paint-brush
Understanding Decentralized Exchangesby@dominiek
35,342 reads
35,342 reads

Understanding Decentralized Exchanges

by Dominiek Ter HeideFebruary 8th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Most of the world’s cryptocurrency trading is done through centralized exchanges such as <a href="http://coinbase.com/" target="_blank">Coinbase/GDax</a>, <a href="http://binance.com/" target="_blank">Binance</a>, <a href="http://bittrex.com/" target="_blank">Bittrex</a>, etc. These exchanges manage a person’s capital (and private keys) and facilitate trading. In the <a href="http://fortune.com/2018/01/31/coincheck-hack-how/" target="_blank">past weeks</a> and <a href="https://bravenewcoin.com/news/mtgox-btc-e-and-the-missing-coins-a-living-timeline-of-the-greatest-cyber-crime-ever/" target="_blank">years</a> there have been some high profile hacks in which a large amount of funds were stolen. It is unlikely that this problem will get solved anytime soon and I would argue that the problem will only get worse. The increase of software and hardware complexity will result in more severe security vulnerabilities such as the recent <a href="https://medium.com/@mattklein123/meltdown-spectre-explained-6bc8634cc0c2" target="_blank">Meltdown and Spectre exploits</a> in Intel’s CPU firmware.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coins Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Understanding Decentralized Exchanges
Dominiek Ter Heide HackerNoon profile picture

Photo by Scott Rodgerson on Unsplash

Most of the world’s cryptocurrency trading is done through centralized exchanges such as Coinbase/GDax, Binance, Bittrex, etc. These exchanges manage a person’s capital (and private keys) and facilitate trading. In the past weeks and years there have been some high profile hacks in which a large amount of funds were stolen. It is unlikely that this problem will get solved anytime soon and I would argue that the problem will only get worse. The increase of software and hardware complexity will result in more severe security vulnerabilities such as the recent Meltdown and Spectre exploits in Intel’s CPU firmware.

Decentralized Exchanges — also known as DEX’s — are a new technology that facilitate cryptocurrency trading on a distributed ledger. These exchanges shift back control of funds and trades to the user and they eliminate the single point of failure. A secondary effect is that government taxation or fund confiscation can become nearly impossible. This can arguably have profound long term consequences to macro-economic and geopolitical landscape.

DEX technology however, is still young and there are still quite some shortcomings including certain attack vectors. In this post, we’ll examine the inner workings of a decentralized exchange.

EtherDelta and 0x

There’s a popular project out there called 0x (Zero X). The aim of the project is to provide an open protocol for decentralized exchanges on top of Ethereum. They’ve also done a token sale of the $ZRX token that’s trading at a $542M market cap currently. (Disclosure: I own some). The purpose of the token is to provide governance mechanisms in for smart contracts and protocols.

0x has some excellent ideas, open source code implementation and documentation. I’m not sure however, how 0x plans to monetize decentralized exchanges and how a $542M market cap can be sustained.

When you read the 0x white paper it is basically an eloquent description of the EtherDelta decentralized exchange. EtherDelta is one of the first decentralized exchanges that has gained some traction out there. It runs mostly on Ethereum and there is about $1.4BN USD in the most recent version of its smart contract. This is pretty phenomenal given the state of their user interface which is difficult to use for even the most tech savvy users.

The EtherDelta UI

Understanding how the EtherDelta exchange works will give us a thorough understanding of the current state of decentralized exchanges and how 0x will work. 0x at it’s essence is EtherDelta with better code and additional capabilities.

The EtherDelta Smart Contract

Ethereum smart contracts are pieces of code that can be executed on the Ethereum blockchain in a distributed and immutable fashion. The core logic of EtherDelta and Ethereum-based exchanges resides in these smart contracts. Compared to conventional programming, implementing these smart contracts is like launching a rocket. They need to be ultra secure and robust, because any bug can result in huge monetary losses.

Smart Contracts — which are typically written in a human readable language called Solidity — are compiled down to Ethereum Virtual Machine instructions. These EVM instructions are practically unreadable by humans. Some projects choose to never share the Solidity code of a smart contract in an attempt to create security by obscurity. For example, the Crypto Kitties genetic diversity smart contract is “closed source”. That said, in theory one can always piece together the original workings of a smart contract so always be weary of closed source smart contracts.

The Solidity code for the EtherDelta contract is freely available on Etherscan here. We’ll analyze the two most important areas of the contract: Funds Management & Trading Logic.

Fund Management

EtherDelta leaves control of funds completely in control of the users. That said, in order to use EtherDelta funds need to be moved into the smart contract. Funds are essentially pooled together in the smart contract, but yet it’s all done on a distributed ledger. Confusing I know. The bottom line is that at any point in time a user can withdraw or deposit funds without any third party intervention.

As you can see in the above snippet there are two mechanisms for moving funds. One is for moving ETH — the native currency of Ethereum. The other is for moving ERC20 tokens. Most ICOs and tradable tokens these days are in fact ERC20 tokens on the Ethereum blockchain. Ethereum provides specific mechanisms for handling these standardized tokens.

In the code above you may notice that only one of the methods is marked as payable. This is a safety mechanism in Solidity to explicitly allow sending of ETH funds for that given call. The depositToken requires an additional step to be implemented for any client to authorize the movement of ERC20 tokens.

Trading Logic

In EtherDelta new market orders can be stored “on-chain” or “off-chain”. On chain means they are stored in the smart contract, off-chain means a third party like a central server. In practice, no orders are stored on-chain for EtherDelta due to the cost and speed implications. Instead the following mechanism is used.

A person can submit open buy or sell orders for a given ERC20 token — in exchange terminology this person is the Maker. Another trader can browse these orders and choose to execute on them — this is called the Taker.

Now, the special sauce that makes off-chain order books work comes right from the heart of blockchain — an Elliptic Curve Digital Signature Algorithm — or ECDSA for short. This is a particular variation of asymmetric cryptography which allows for public and private key encryption as well as signature verification — all in a computational friendly way.

At a high-level, this is how it works in EtherDelta:

  1. Maker creates a new order: ERC20 token, the amount, the ETH amount in return and whether it’s a buy or sell order.
  2. Maker creates a cryptographic hash of that order (using SHA3)
  3. Maker then uses their Ethereum private key to sign the order hash (using ECDSA and in particular the Secp256k1 implementation which is also used in Bitcoin)
  4. Maker sends order off chain together with the signature (In EtherDelta this is accomplished via a set of servers all communicating JSON messages via WebSockets)
  5. When Taker wants to trade against the order, the signature and order information is send to the smart contract’s trade function.
  6. The smart contract verifies that the signature originated from Maker
  7. The smart contract makes sure order is not expired or filled.
  8. Funds are transferred and fees are taken.

Steps 5 through 7 all happen in the following crucial bit of contract code:

On line 5 of the above code, a hash is generated for the specific order amount, price, expiration and a one time random number called nonce. This hash — a 32 byte sequence — represents a unique market order.

Line 7 is where first the on-chain order book is checked (which is unused) and then if there are no on-chain orders, a verification is done on the signature.

This signature verification takes the order has that was signed by the Maker — and verifies whether it originated from the Maker’s account address. If any change is made to the order parameters, the hash will require a different signature.

Once validation completes the tradeBalances function moves around the money and charges fees:

It should be noted that this is done in a way where money is taken from the (active) Taker first and only credited to the Taker at the end. I think this is crucial to the security of the contract, because it’s possible to send (and validate) a malformed user address. If this is attempted, it will simply cause the Taker to lose money. This shows how tricky and challenging it is to secure software like this.

Conclusion

We’ve now walked through the essentials of a DEX on Ethereum. The 0x project has a lot of additions to this, like open standards for off-chain order management, well tested and documented smart contracts, more types of trading mechanisms, etc. But at the very core of the DEX the same fundamental flows and cryptographic principles are used.

In next posts, I’ll dive deep into some related topics around DEX’s and Ethereum smart contracts. Stay tuned!