Decentralized Exchange

Public blockchains have the potential to act as a potent equalizing force for the world by democratizing access to financial services in the same way that the internet has democratized access to information. Decentralized exchange technology will play a key role in accelerating our transition to a financial system where people can transact directly, on a peer-to-peer basis, with no middlemen required.

To understand how decentralized exchanges work we must first understand what blockchains are and how they function at a conceptual level. Blockchain explainers tend to emphasize their elegant inner-workings rather than the practical details that make them useful; let’s review some of the practical details first.

Blockchains

A blockchain is a peer-to-peer (“p2p”) network where each node maintains an identical copy of a transaction ledger by synchronizing with other nodes on a regular cadence. A p2p network is just a bunch of computers — called nodes — running software that allows them to find and communicate with each other. The ledger is just a list of past transactions (“Alice sent Bob X units of asset Y at time Z”) that may be used to keep track of everyone’s respective balances of the blockchain’s underlying cryptocurrency.

The ledger is the sole reason for why a blockchain exists, everything that follows — all of the computer science stuff — is just there to make sure every node has an identical and up-to-date copy of that ledger.

In practice, blockchain networks can reach tremendous scale. Today, the Bitcoin network consists of approximately 10,000 nodes spread out across the globe. One can spin up a Bitcoin node (latest version here) and plug into the network to get a reasonably accurate view of the global distribution of nodes.

Figure 1: a map showing the global distribution of 9,659 reachable Bitcoin nodes over 24 hours (August 28, 2018).

Centralized cryptocurrency exchanges

Cryptocurrency exchanges are for-profit businesses that allow customers to move between different cryptocurrencies and, sometimes, fiat currencies. Exchanges for traditional financial products such as securities and derivatives tend to be highly regulated in the US and other developed countries, with extensive rules intended to protect customers from market manipulation and other misconduct. By contrast, substantially fewer regulations have been adopted specifically to apply to cryptocurrency exchanges. The preexisting regulatory regimes that do apply, such as money transmission licensing, were not designed with cryptocurrencies in mind and don’t comprehensively address the activities that cryptocurrency exchanges conduct.

Until recently, all popular cryptocurrency exchanges have been centralized services that require customers to trust the exchange operator and the security practices used to safeguard deposited funds. As we will see later, customer trust is often misplaced.

To trade on a centralized cryptocurrency exchange, a customer must deposit their funds into a pooled wallet that is controlled by the exchange operator, who then credits the customer with a “trading balance.” This balance is simply an entry within a centralized database that the exchange operator is tasked with updating as the customer completes trades.

Cryptocurrency exchanges also maintain some or all of these pooled customer funds in a so-called “hot” wallet, which means that the wallet is connected to a network. This enables exchanges to fulfill customer withdrawal requests quickly. But anything connected to a network is vulnerable to hacking, thus creating a greater risk to customer funds. It is possible to store cryptocurrency in so-called “cold” storage, which means that the wallet is maintained entirely offline, and thus remote from external hackers. While some cryptocurrency exchanges store a portion of customer funds in cold storage as an added security measure, a substantial amount of exchange-held customer funds remain in hot wallets. Finally, while hot wallets are far more vulnerable to external hacking, cold storage is also not free from risk. Internal company actors, such as rogue employees, can misappropriate funds in cold storage if they have access to the requisite wallet keys.

Figure 2: when depositing cryptocurrency into a centralized exchange, you are giving up custody and control to a third party that can irreversibly lose your funds.

This centralized model that exchanges use to custody customer funds is problematic for several significant reasons. Since cryptocurrency transactions are irreversible, unless the exchange’s security practices are flawless, their wallet or web infrastructure can be irreparably compromised by hackers or rogue employees. To make matters worse, popular cryptocurrency exchanges tend to have many thousands of customers, whose assets — when pooled into the exchange’s address — can represent incredibly large sums, the perfect target for a hacker. To see one of these centralized exchange wallets live, take a look at this address used by Binance to store a chunk of user funds worth >$200mm as of the date of this writing; you may also notice deposit and withdrawal transactions happening every few seconds. If a hacker is able to gain access to a wallet such as this, they can steal thousands of customers’ funds in one fell swoop. Losses of this scale not only effect an exchange’s customers, they can also create systemic risks within cryptocurrency networks that use the stolen digital asset to drive consensus or community governance processes.

Centralized exchange hacks have been occurring every few months since the business model first emerged – most notably with Mt. Gox in 2011 – and there is little evidence that the frequency of these hacks is slowing down. Figure 3 provides a non-exhaustive list of hacks that have occurred over the years and the amount of customer funds lost in each case.

Figure 3: centralized cryptocurrency exchange hacks. Source.

While there are certainly risks associated with centralized cryptocurrency exchanges, they also provide some unique benefits. Centralized exchanges can serve as fiat on-ramps, allowing customers to deposit funds directly from their bank account in order to purchase cryptocurrency in a trusted and compliant way. In addition, centralized cryptocurrency exchanges are able to offer high performance trading capabilities and other advanced tools that may appeal to institutional investors. Further, centralized exchanges can potentially be held legally accountable should any issues occur.

Decentralized exchanges

Numerous groups are focused on developing decentralized exchange (“DEX”) technology and a number of different approaches have emerged over the years. What all of these approaches have in common is that they remove users’ need to give up custody of their cryptocurrency or digital asset to a third party. In other words, DEXs allow cryptocurrency holders to exchange with each other directly, on a peer-to-peer basis, without needing to trust an intermediary or each other. No DEX can yet trade between a cryptocurrency and fiat currency (setting aside tokens backed by fiat balances held by a trusted intermediary) because fiat currencies inherently require a trusted central party to record account balances. Aside from fiat pairs, peer-to-peer exchanges are easiest to accomplish when the traded tokens or cryptocurrencies both use the same public blockchain to record transactions (and we’ll discuss this below) but cross-blockchain exchanges, say between Bitcoin and Ethereum, are also possible using cross-chain atomic swaps.

CROSS-CHAIN ATOMIC SWAPS

Cross-chain atomic swaps are actively being developed as a means of trading cryptocurrencies that exist on distinct blockchains, such as Bitcoin and Litecoin. Figure 4 provides a visual representation of a cross-chain atomic swap and how they work conceptually. The trading process is broken into four transactions. In transactions #1 and #2, the two parties that are interested in entering into a trade coordinate with each other to lock their respective assets into a trustless escrow using something called a Hashed Time-Locked Contract. To redeem the proceeds from one leg of the trade (transaction #3), the redeemer must reveal a secret that allows their counterparty to redeem the proceeds for the other leg of the trade (transaction #4). Either both legs of the trade are completed successfully or neither are.

Figure 4: cross-chain atomic swaps allow trustless exchange of cryptocurrencies that exist on distinct blockchains.

Cross-chain atomic swaps have only recently become feasible for the largest cryptocurrency networks. The first BTC/LTC (testnet) and BTC/DCR swaps occurred in 2017, but have seen little subsequent adoption due to their cost, high latency, and technical complexity. Further, differences in how blockchains are designed lead to limited compatibility in terms of the existing cryptocurrencies one may trade between. For these reasons, cross-chain atomic swaps are most feasible for large, infrequent trades between sophisticated parties that are trading specific pairs of cryptocurrency. To get a detailed look at the transactions underlying a cross-chain atomic swap, this is a good reference.

Note: There are blockchains specifically designed to address compatibility limitations for the purposes of swaps. Blockchains such as Blocknet or Komodo act as hubs that facilitate swaps between a variety of other blockchains.

TOKENIZATION

Over the past 2 years, the Ethereum blockchain has become the de facto platform for issuing digital assets. Ethereum’s ledger not only keeps track of users’ ether (ETH) balances, it can also store and execute tiny programs called smart contracts. Smart contracts can own, custody, manipulate and/or be digital assets depending upon what they are programmed to do. Often, smart contracts serve as sub-ledgers for digital assets called tokens.

Figure 5: the Ethereum ledger contains tiny programs called smart contracts that can be programmed to behave as sub-ledgers (tokens). It is worth noting that the Bitcoin ledger can support similar, crude abstractions called colored coins.

There are over 115,000 tokens on the Ethereum blockchain today and this number is rapidly increasing. While, to date, tokens have primarily been used as a fundraising mechanism for initial coin offerings, there are a number of innovative use cases for tokens that extend beyond fundraising, especially when taken in combination with other smart contract systems that are being built on the Ethereum blockchain. Some of these use cases include globally accessible prediction markets, stable coins, p2p debt instruments and derivatives, decentralized organizations, p2p networks for file storage/compute/bandwidth, digital collectibles and the tokenization of traditional assets. As these use cases are explored, the number of tokens on Ethereum could grow by orders of magnitude. For this reason, we believe that a majority of DEX trading activity will take place on Ethereum or similar smart contract platforms.

DECENTRALIZED EXCHANGE IN THE CONTEXT OF TOKENS ON THE ETHEREUM BLOCKCHAIN

There are a number of different approaches to decentralized exchange on the Ethereum blockchain, though predominantly, DEXs use variations of an approach termed off-chain order relay with on-chain settlement. In this approach, one party (the “maker”) generates an “order,” which is just a chunk of data that defines the terms of a trade that the maker would like to enter into. The chunk of data adheres to a specific message format, such as the 0x protocol v1.0 format, which takes the following form:

"order":{

"maker":"0xaa40e9f4dadabef71c6864b04e4fbc4c01563601",

"taker":"0x0000000000000000000000000000000000000000",

"makerFee":"0",

"takerFee":"0",

"makerTokenAmount":"1000000000000000000000",

"takerTokenAmount":"1000000000000000000000",

"makerTokenAddress":"0xd0a1e359811322d97991e03f863a0c30c2cf029c",

"takerTokenAddress":"0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570",

"expirationUnixTimestampSec":"1546329600",

"feeRecipient":"0x0000000000000000000000000000000000000000",

"Salt":"79191593431936512524324195543585235073888075871061193308019521801915927235481",

}

Figure 6: example order generated by Ethereum account 0xaa40…3601.

The order is cryptographically signed by the maker, providing verifiable proof of its authenticity. Figure 7 shows the cryptographic signature corresponding to the example order in Figure 6; while it appears to be a random sequence of numbers and letters, it is actually a unique proof that cannot be forged and that can be authenticated by both humans and smart contracts alike.

"signature":{

"0x1bfc0aece5f6d6515881230757339348ca0117b8304d246f95413113d69b3431df2e4b316e2f4798af80632f348d3c0e8150dba9b36634429878283678960ec13c03"

}

Figure 7: cryptographic signature corresponding to the example order. No other sequence of numbers and letters can represent a valid signature for the example order.

Once the maker has created and signed an order, all that is left for the maker to do is find someone to act as their counterparty (the “taker”). If the maker has a specific counterparty in mind, they can simply send the signed order to the desired counterparty via email, text message, or any other communication medium. If the maker doesn’t care who fills their order, they can broadcast it to a large number of people however they want; even a social network like Twitter or Facebook could work. In any case, once the maker successfully communicates their order to an interested taker, the taker may execute a trade by injecting the order into a corresponding smart contract on the Ethereum blockchain which verifies the order’s cryptographic signature and transfers the trade proceeds between the two parties at the specified exchange rate.

Figure 8: two parties exchanging distinct tokens that exist on the Ethereum blockchain. The maker (node F) generates an order to exchange 3 units of Token A for 7 units of Token B. The maker then sends the order (red arrow) to the taker (node G), who subsequently fills the order at block N+1. Balance updates that occur during trade settlement are directly reflected on each token’s sub-ledger.

While the previous steps may sound complex, most of the ugly details can be hidden away. For example, you can act as a taker and fill the example order from Figure 6 by following this link.

Note: the example order is only valid on Ethereum’s “Kovan” test network, it may have already been filled by a previous reader and, if not, the order will expire at 12:01am on January 1, 2020 UTC. Try partially filling the example order so that others may participate.

In the context of 0x protocol, third parties (“relayers”) can help makers and takers find each other by establishing online meeting places to share and aggregate orders. While relayers can optionally charge a fee for the convenience they provide, they never custody users’ funds or operate proprietary infrastructure for trade execution and/or settlement; the blockchain takes care of all of these processes. In this sense it would not be accurate to characterize a relayer as a cryptocurrency exchange; relayers are more comparable to digital bulletin boards such as Craigslist. Interestingly enough, one of the first relayers to emerge was the internet message board shown in Figure 9 (left) which was created by an unknown group of netizens to facilitate over-the-counter trades. Today relayers provide highly refined web applications that can rival centralized cryptocurrency exchanges in terms of ease of use. While all relayers are non-custodial, some relayers may host a may host a centralized order-book or store other exchange-related data on private servers. When using these relayers, users may be sacrificing an element of decentralization in order to receive a more controlled and simplified user experience.

Figure 9: relayers help makers and takers find each other. Any digital medium can serve as a relayer, whether it is an internet message board such as the /r/tokentrade subreddit (left) or DDEX‘s custom web application (right) which provides a more traditional trading interface.

REGULATING A NEW PARADIGM

As demonstrated in the previous section: p2p exchange technologies make exchanging digital assets as simple as sending an email. All that is required is an Ethereum wallet and an internet connection. Further, any digital medium can now serve as a meeting place for buyers and sellers. This new paradigm leads to perplexing questions about the nature of exchange in the p2p context. By disseminating the example order in Figure 6 to readers, is this backgrounder subject to regulation for facilitating an exchange of assets? If so, does it make sense that the regulation should differ based on whether the token being traded represents a security or not?

The fact that public blockchains such as Ethereum are innately permissionless and globally accessible may lead one to believe that tokens and p2p exchange technologies cannot comply with existing regulations. This is not the case. When someone conducts p2p trades or other activity on Ethereum that is subject to existing regulations, they should be able to comply with corresponding requirements to the same extent as someone using legacy technology. In fact, the programmable nature of smart contracts make it simple to build systems that ensure compliance where necessary. This is because compliance rules can be directly encoded into Ethereum smart contracts. Companies such as Harbor make it possible to, for instance, issue securities in the form of Ethereum tokens that automatically enforce all requisite KYC/AML, accreditation, and Reg D securities requirements on each transaction. The Ethereum smart contracts used within the 0x protocol can also be extended to support compliant p2p trading using a concept we refer to as permissioned liquidity pools. And since all activity on the Ethereum blockchain is transparent, it is possible for regulators and market participants to inspect trading activity more closely than with centralized cryptocurrency exchanges or traditional financial markets, which use private databases to record trades.

Final thoughts

At 0x, we envision a world in which all forms of value are tokenized on public blockchains, including fiat currencies, stocks, bonds, commodities, debt instruments, real estate, video game items, digital collectibles, software licenses, voting rights, reputation, and much more. Combined with p2p exchange technology and other complementary building blocks, we can create a global financial system that is more efficient, transparent, and equitable than any system that has existed in the past.

Special thanks to Joshua Boehm and Jason Somensatto for providing thoughtful feedback while this article was being drafted.

About the author:

Will Warren is Co-founder and CEO at ZeroEx Inc., which is developing the 0x protocol to serve as public infrastructure for peer-to-peer exchange on the Ethereum blockchain. After receiving a B.S. in Mechanical Engineering from UC San Diego, Will worked as a graduate research assistant at Los Alamos National Laboratory conducting applied physics research. Will spent two years in UC San Diego’s doctoral program before dropping out to pursue an interest in Ethereum full time. Since its launch in August 2017, the 0x protocol has been used to exchange over $300mm in notional value and produced at least five venture-backed startups, one of which was acquired by Coinbase.