0x Project: The Future of Cryptocurrency Exchanges
0x Project: The Future of Cryptocurrency Exchanges. Cryptocurrencies are all the rage right now and as FOMO spreads far and wide more and more people want to be a part of this economic revolution. However, this is where we hit a snag. In order to join this revolution, people need to go through centralized exchanges which have immense problems of their own.
0x Project: The Future of Cryptocurrency Exchanges
This is why decentralized exchanges and the 0x Project in particular, are so important. In this guide, we will explore how the 0x Project works. However, before that, let’s look at what exchanges, in general, are.
What is a Cryptocurrency Exchange?
Image Credit: Bite my Coin
The exchange serves one of the most critical functions in the crypto ecosystem. It basically acts as a portal between the Fiat world and the crypto world. There are usually two types of exchanges:
- Fiat to Crypto.
- Crypto to Crypto.
Fiat to Crypto
Fiat to Crypto exchanges helps you buy Cryptocurrencies in exchange for Fiat money. Coinbase is a perfect example of this kind of exchange. Coinbase helps you buy BTC, BCH, LTC, and ETH in exchange for Fiat currency.
Crypto to Crypto
Then we have the Crypto to Crypto exchanges. These exchanges help you exchange certain cryptos like BTC, ETH, BCH etc. for other cryptocurrencies. Binance is a fine example of a crypto-to-crypto exchange.
While they do offer pretty valuable services, the problem is that they are all centralized, which makes them vulnerable. This is an extremely risky proposition when you consider the sheer amount of money that these exchanges deal with each and every single day. Let’s look at the 24-hour volume of the top 5 exchanges in the world:
Image Credit: Coin Codex.
That’s nearly 10 billion USD! And that’s how much money they are processing every single day! That’s just absolutely ridiculous. Now, keeping in mind that centralized exchanges are vulnerable to a plethora of problems, do you really feel safe keeping your money with these entities?
The Problem with Centralized Exchanges
Let’s take a look at some of the problems plaguing centralized exchanged:
#1 Vulnerability to Hacks
Centralized exchanges will always be vulnerable to hackers. Two years ago, in 2016, Hong Kong based cryptocurrency exchange platform, Bitfinex, was hacked for 120,000 BTC which was worth $72 million back then was stolen.
The price of Bitcoin went for a tumble and fell nearly 20%. One BTC went as low as $480 before it managed to recover.
Image Credit: CoinDesk
#2 Subject to Mismanagement
How can we forget the infamous Mt. Gox hack? Back then, it was the biggest hack in history with bitcoins worth ~$500 million USD getting robbed. The exchange suffered from a number of issues.
However, if we were to surmise all of them, it all comes down to one thing:
Highly incompetent and childish management
Andreas Antonopoulos, in a very scathing report, had this to say:
“Magic The Gathering Online Exchange (Mt. Gox) is a systemic risk to bitcoin, a death trap for traders and a business run by the clueless.”
Those are some very harsh words, but there is so much truth in that statement. The thing is that the Mt. Gox owner, Max Karpeles, was more of an idealistic programmer than a businessman. While he could code, he could never have the acumen needed to run a company. And, unfortunately, because of this, a huge disaster happened.
#3 Volume Problems
Another huge problem that most centralized exchanges suffer is that they just don’t know how to deal with a sudden increase in demand.
On 12th November there was a sudden surge of demand and most trading platforms just couldn’t cope with the spike in volume. In fact, Bithumb, one of the biggest platforms in the world, suffered a minimum downtime of 90 mins during peak trading period. They lost 60,000 BTC worth of trade volume.
What were the after effects of this? Bitcoin Cash’s value nearly halved as a result. In fact, you can see the dip in the chart below:
#4 Subject to The Whims of the Government
The Centralized crypto exchanges have their companies registered in a country. This means that they can be directly affected by any policies that the government of that country wishes to enact.
Will you be comfortable with not having an ounce of control on your money?
Can Decentralized Exchanges be a Solution?
So what are Decentralized Exchanges or DEXs?
DEXs enable crypto exchange on a shared ledger which facilitates trustless trading without being dependent on a third party. In every sense, DEXs are the future of trading for several reasons.
- Firstly, they provide stronger security. Since there are third parties, there are no single points of failures.
- Secondly, there won’t be possible of a malicious exchange running away with all the funds.
- Thirdly, DEXs are not dependent on government regulations.
EtherDelta is one of the first DEXs that got some sort of attention. In fact, $1.4 billion is tied up in the latest version of its smart contract, which is extremely impressive.
The pic above, taken from this hackernoon article, shows the Ether Delta UI.
So, before we get into the 0x Project, it is important to learn how Ether Delta works. This will give us a grasp on DEXs in general.
How does Ether Delta Work?
Smart contracts are automated contracts. They are self-executing with specific instructions written on its code which get executed when certain conditions are made.
When someone wants to get a particular task done in Ethereum they initiate a smart contract with one or more people.
Smart contracts are a series of instructions, written using the programming language “solidity”, which work on the basis of the IFTTT logic aka the IF-THIS-THEN-THAT logic. Basically, if the first set of instructions are done then execute the next function and after that the next and keep on repeating until you reach the end of the contract.
So, Ether Delta also has a smart contract and we are going to be focusing our attention on two key areas:
- Fund Management.
- Trading Logic.
Since EtherDelta is a DEX, the funds are completely in control of the users. The funds work in the following ways:
- To use EtherDelta, one must move the funds to a smart contract.
- The funds are pooled together in a smart contract whilst staying on a distributed ledger.
- At any point, any user can withdraw or deposit their funds.
Image Credit: Hackernoon
The diagram above gives you a general idea of how EtherDelta works. The new market orders are stored on-chain or off-chain. A person, i.e. the maker, submits buy or sell orders. Another person, the taker, chooses to execute on this order.
Let’s get a general overview of how EtherDelta functions:
- The Maker creates an order and hashes it using SHA 3.
- Maker signs the hash with their Ethereum private key.
- The order and signature is then sent off-chain.
- If a Taker wants to trade, the signature and order is sent to the trade function of the smart contract.
- The smart contract then verifies the signature to make sure that it is valid.
- The order goes through
The Flaws with Ether Delta
While Ether Delta provides a rather serviceable DEX, it, unfortunately, has some glaring issues.
- Slow: There is a high latency in order book processing. Plus, along with that cancellation is extremely slow as well .
- Blockchain Bloat: The on-chain order book results in transactions that consume network bandwidth and bloat the blockchain.
- High gas costs: Because of the latency in the order book processing, Takers may not know what the other Taker is ordering for. This in turn causes a sense of competition within the Takers on the same orders which drives up the gas costs. Plus, makers are forced to spend gas every single time they post, modify, or delete their order.
- Upgradation issues: Because of its architecture, the entire system comes to a standstill during upgradation. Also, the users are forced to take their money out the smart contracts and give them to a trusted third party. This defeats the purpose of a decentralized system.
Introducing the 0x Project
According to their website, “0x is an open, permissionless protocol allowing for ERC20 tokens to be traded on the Ethereum blockchain” and will be used for “powering decentralized exchange.”
NOTE: The V2 of 0x will support more than just ERC20. More on this later.
0x came about in October 2016. Co-founders Will Warren and Amir Bandeali had a vision of a future where all kinds of assets, stocks, currencies, precious metals, could be traded publicly on the blockchain as tokens.
The 0x Team
0x has one of the most dedicated and respected teams in the community.
The faces of the project are undoubtedly the two co-founders Will Warren and Amir Bandeali. Will Warren did applied physics at Los Alamos Nat Lab and mechanical engineering at UC San Diego.
Amir Bandeali, on the other hand, was previously a fixed-income trader at DRW. He studied finance at the University of Illinois.
This project is financially backed by a number of companies such as Pantera Capital, Fintech Blockchain Group, Blockchain Capital and Jen Advisors
Now that we have introduced ourselves to the team let’s get into the nitty-gritty of the project. There are still some basics that we need to understand before we get into anything.
0x and Ether Delta. Bridging the Gap
0x works pretty similarly to Ether Delta but there are some major differences.
- 0x has a group of participants called relayers (more about them later) and anyone among those can become an exchange. Ether Delta has only one unique entity which can become an exchange.
- 0x has its own token ZRX which is used to pay transaction and governance fees.
Most of Ether Delta’s major flaws were surrounding its on-chain order book and scalability. This is why, in order to create something like 0x, two important innovations needed to be done.
#1 AMM Smart Contracts
Automated market maker (AMM) smart contracts came about as an alternative to the traditional on-chain order book. The AMM brings a price-adjustment model in which an asset’s price adjusts in accordance with market forces and market participants on either side of the trade.
AMM price adjustment makes sure that the price doesn’t vary wrt to liquidity. It imposes self-inflicted restraints on supply to make sure that assets remain insensitive to market liquidity.
#2 State Channels
What are state channels?
A state channel is a two-way communication channel between participants which enable them to conduct interactions, which would normally occur on the blockchain, off the blockchain. What this will do is that it will decrease transaction time exponentially since you are no longer dependent on a third party like a miner to valid your transaction.
So what are the requirements to do an off-chain state channel?
- A segment of the blockchain state is locked via multi-signature or some sort of smart contract, which is agreed upon by a set of participants.
- The participants interact with each other by signing transactions with each other without submitting anything to the miners.
- The entire transaction set is then added to the blockchain.
The state channels can be closed at a point which is predetermined by the participants according to Slock.it founder Stephan Thual. It could either be:
- Time lapsed eg. the participants can agree to open a state channel and close it after 2 hours.
- It could be based on the total amount of transactions done eg. close the chain after $100 worth of transactions have taken place.
Image Courtesy: Stephan Tual Medium Article
So, in the image above. We have a car which directly interacts with the charger and does a total of $39.19 worth of transactions. Finally, after a series of interactions, the entire transaction chunk is added to the blockchain. Imagine how much time it would have taken if they had to run every single transaction through the blockchain!
0x decided to do a hybrid implementation which is referred to as “off-chain order relay with the on-chain settlement.” The idea is to combine the efficiency of state channels with the near-instant settlement of on-chain order books.
Using this method, one can cryptographically sign orders and broadcast off the blockchain. Anyone interested can use one or more of these orders into a smart contract to execute trustless trading directly on the blockchain.
This method greatly decreases the gas costs for the Makers.
Most of the work that they need to do is completely off-chain. Since they don’t need to deal with the blockchain so much, their gas costs are greatly cut down.
Overview of The Process
The diagram above shows the general architecture of the 0x protocol. Let’s look at how the process works. Suppose Maker wants to trade their Token A for Token B.
- Maker firstly approves the DEX smart contract.
- Maker creates order to exchange token A for token B specifying the desired exchange rate, expiration time and signs off with their private key.
- Maker broadcasts the order.
- Taker intercepts the order and decides to go for it.
- Taker submits the Makers order to the DEX which proceeds to verify the signature.
- The transfer between the Maker and Taker takes place at the specified exchange rate.
Types of Orders
There are two types of orders in 0x:
In point-to-point orders, two parties can directly exchange tokens between them using any communication method they prefer for message relaying. The order is made of packets of data containing a few hundred bytes of hex. It can be sent through Facebook messages, whisper, email, etc. Anyone who eavesdrops won’t be able to access the order since it can only be filled by the specified Taker address.
This order format consists of the following:
The second kind of orders in the 0x protocol are Broadcast orders. This is the more common form of exchange orders. For any exchange to work, there must be a public order book where buyers and sellers can post their orders. In the 0x protocol, there are entities called “Relayers” who “facilitate signaling between market participants by hosting and propagating an order book that consists of generic messages.”
The Relayers do not execute any trades, they merely facilitate trades between Makers and Takers. Think of it as a group of participants and any of them can become an exchange.
The message format of broadcast orders has 2 major changes as compared to simple point-to-point messages.
- Broadcast orders included don’t specify a taker address. This means that anyone who intercepts the order can fill it in.
- Secondly, broadcast orders include feeA (maker fees), feeB (taker fees), and feeRecipient (relayer address) parameters. These basically calculate the total fees that the Relayer will get upon transaction completion in their address.
The message format looks like this:
Now, let’s do an overview of the whole process:
- The Relayer declares their fees and the address which they are using to collect fees.
- Maker creates order by setting feeA, feeB values. The feeRecipient value is set to the Relayer’s address.
- The maker then sends the signed order to the Relayer.
- Relayer validates the order. If it is not satisfactory then the order is rejected. If satisfactory then the Relayer adds the order to their order book.
- Takers receive an updated version of the order book that includes Maker’s order.
- Taker fills the Maker’s order.
The 0x Smart Contract
The entire 0x smart contract has approximately 100 lines of code and costs ~90k gas to fill in an order. There are four main components to this smart contract:
- Signature Authentication.
- Fills and Partial Fills.
- Expiration Time.
- Canceling Orders
The first part of the smart contract that one must pay attention to is the Signature Authentication. The contract is able to validate the Maker signature via the ecrecover function. The function does the following:
- Takes a hash and signature of the has as arguments.
- Returns the public key that produced the signature.
- If the public key returned is equal to the maker address, the signature is authentic.
address publicKey = ecrecover( hash, signature( hash ) );
if (publicKey != maker ) throw;
Fills and Partial Fills
In order to stop the repetitiveness of orders, the smart contract stores a reference to each previously filled order. The references are stored as a SHA 3 Keccak hash. Since the hash for a particular input is unique, it makes sure that repetitive orders aren’t filled.
A Taker may partially fill an order by specifying an additional argument, valueFill, when calling the exchange smart contract’s fill function. Multiple partial fills may be executed on a single order so long as the sum of the partial fills does not exceed the total value of the order.
Every order in the 0xProtocol has an expiration time as specified by the Maker which is specified at the time that the order is signed. The value of the expiration time can’t be changed once it has been signed.
An unfilled order can be canceled before its expiry date by the associate Maker via the cancel function. Canceling an order costs gas and, therefore, the cancel function is only intended to serve as a fallback mechanism. Typically, Makers are expected to avoid on-chain transactions by setting their order expiration times to match the frequency with which they intend to update their orders
The 0x Whitepaper notes one case where the cancel function may create an issue:
“One issue with this approach is that it can create situations where a Maker attempts to cancel their order at roughly the same time a Taker is attempting to fill that same order. One of the two parties transactions will fail, wasting gas, depending upon the sequence in which the two transactions are mined. Uncertainty regarding the sequence in which transactions are mined could lead to undesirable outcomes at times. This uncertainty could increase if the Ethereum blockchain were to experience a significant backlog of pending transactions.”
Governance in The 0x Protocol
One of the biggest issues with Ether Delta is the downtime during upgradation. It is impossible for it to upgrade without causing issues to its participants. 0x aims to use their native ZRX tokens to upgrade securely. Plus, seeing how critical governance is for an entity like 0x, it is important to learn exactly how that will work in the system.
0x is envisioned as a pipeline of smart contracts (check diagram below for the visual) wherein each segment of the pipeline can be taken out and upgraded without the system coming to a halt.
Image Credit: Will Warren Medium blog.
The 0x team wanted to create a governance system which:
- Ties in the ZRX token for voting purposes.
- Has sound governance mechanics.
In order to create a system wherein all 0x stakeholders are represented fairly and equally, an implementation roadmap was conceptualized. The roadmap looks like this:
There are three main phases of this governance system:
- Community managed token registry.
- Community veto power.
- Liquid Democracy.
Community Managed Token Registry
0x uses a token registry contract to store a list of ERC20 tokens with associated metadata. The registry basically is an official on-chain reference that maybe used by participants to verify token addresses and exchange rates before going through with the trade.
The registry, for now, is centrally managed by the 0x core team, however, they plan to convert that into a community managed on-chain registry. This is the first phase of the governance system.
Community Veto Power
Before the core team hands over governance completely to token holders, they want to make sure that the system is properly vetted. The way they plan to do that is by launching a system where the core team proposes various upgrades and the ZRX holders have the power to veto.
The final phase is liquid democracy.
So, how does it work?
Image Credit: Medium.
- People can vote on their policies directly.
- People can delegate their voting responsibilities to a delegate who can vote on their policies for them.
- The delegates themselves can delegate their voting responsibilities to another delegate who can vote on their behalf. This property wherein a delegate can appoint their own delegate is called transitivity.
- If a person, who has delegated their voting doesn’t like the vote that their delegates have chosen, then they can simply take back their vote and vote on the policy themselves.
This fluid transition from direct democracy to representative democracy and back is called liquid democracy.
It won’t be a stretch to say that 0x protocol could be the future of cryptocurrency exchanges. The really fascinating part of it is the sheer amount of flexibility it provides. They are about to release a V2 version soon where:
- Any and all token standards will be supported. Currently, 0x only supports ERC20 tokens. So with v2 implementation, you can trade a cryptokitty with a ZRX token.
- It will be easier and simpler to write your own external smart contracts that plug into 0x. Eg. you can now have a whitelist of people that can trade on your exchange.
- Implementation of EIP 712 to make users less susceptible to possible scams.
- Support for signature types of Trezor hardware wallet.
- Support for adding multiple orders together.
It will be fascinating to see how this brilliant project pans out in the future.