Several new decentralized exchanges have recently launched on Tezos, which has inspired me to discuss the peculiarities of building DEXs on Tezos. This article is a bit technical, but I hope that you will still enjoy it.
What Is AMM?
All the decentralized exchanges that will be covered in this article are Automated Market Makers. AMM is a protocol that determines asset prices based on the following mathematical formula, where the price is only allowed to move along a predefined curve.
The best-known pioneer of AMM development is Uniswap. Simply, their smart contracts can be described as the system of three components: Factory, Pair, and Router.
Pair is the Automated Market Maker for two particular ERC20 tokens. It allows underlying assets to be deposited in the pool to earn swap fees by minting liquidity pool tokens(LP). the withdrawal of them by burning LP shares, and, of course, tokens to be swapped in both directions.
Factory, as the name suggests, stores bytecode for the Pair contract and lets anyone use it for any two ERC20 tokens. The only restriction is that for any two assets, only one pair can exist. To enforce this rule consistently, it has a lookup table (called “mapping” in Solidity) that matches a pair address to its tokens’ addresses. It doesn’t need to perform the backward mapping of the tokens to their pair address since the address can be calculated anytime as the pairs are deployed with create2 opcode.
The router is the periphery contract that makes the interaction with pairs easier. It is worth noting that the Pair contract is pretty bare, and interacting with it directly without a proxy smart contract is a real pain. Essentially, Router does all the dirty work for the user such as figuring out the pair address, wrapping ETH into the ERC20 Wrapped ETH, transferring and approving token transfers in the correct order, making calculations for multi-trades, and so on.
Tezos Implementation Challenges
Despite such cool architecture, the exact reimplementation of Uniswap is not fully possible on Tezos. Let’s look at some of the reasons behind it.
Baking rewards are a carrot and a stick at the same time
One of the main perks of the Tezos blockchain is its consensus algorithm called Liquid Proof-of-Stake. It basically means that anyone can vote for a baker with their Tez and earn baker rewards while still being able to transfer or receive Tez. There are no restrictions or unbounded periods, unlike under other variations of the POS consensus. Of course, certain rules apply when funds actually start working and you become eligible for baker rewards. The general idea is that no matter whether the Tez is delegated or not, the balance is liquid, and if it is delegated, the reward will be paid out to the delegator someday.
This means that the decentralized exchanges that support XTZ token pairs and hold XTZ should have the mechanics to choose the baker and handle receiving rewards.
An important point to mention is that the rewards distribution is out of the protocol’s control and is solely the baker’s burden. They can distribute rewards at any time, and this is treated as a regular XTZ transfer to the account. Some of the bakers do this in advance, some only after receiving the rewards for the producing block, and others may do this at any other arbitrary time. This uncertainty complicates rewards tracking in smart contracts and makes it hard to distribute rewards fairly, especially if the exchange protocol assigns the rewards to the liquidity providers according to their shares.
There is no fair Wrapped Tezos (yet)
Looking at Uniswap with their Wrapped ETH, you may consider using some kind of Wrapped Tez to mitigate the above challenge. However, none of the existing solutions have succeeded in creating a token that would cost exactly 1 Tez that also allows investors to earn baker rewards, and enables DeFi to omit the voting and logic of receiving rewards.
The main reason is that while you are holding the token, you don’t receive baker rewards, but some contract that holds your Tez maybe does. This then leads to many other problems, namely: how to vote for a baker, how to distribute rewards, how to handle transfers to other accounts, how to keep a 1:1 price, and so on. Something worth highlighting is that none of the existing versions of the Wrapped Tez have come up with an idea of how to distribute the rewards in a way that other DeFi protocols wouldn’t need to care about them.
Tezos has 2 token standards
During the time of dinosaurs, which I remember well, there was only one standard for tokens – FA1.2, and many old but essential projects launched their tokens according to it. Even now, some awkward guys still deploy such tokens. But the standard is very narrow-minded, gas costly, developer-unfriendly, and not suitable for the growing ecosystem. As a result, the FA2 standard emerged. A notable difference between these standards is the interactions with tokens.
Now DEXs are expected to support both of them (and + XTZ). So, there are three entirely different approaches to processing assets that should be implemented in the great exchange.
There is a lack of view methods
Unlike in Ethereum, the Tezos Virtual Machine doesn’t support read-only calls (so-called on-chain views) to other contracts. It may be difficult to comprehend, but in order to read data from another contract, these contracts should implement a method (e.g., getBalance) where one of the arguments is the entry point of their contract where the response should be sent (e.g., a callback). Such a call is a regular internal operation.
Imagine that the contract needs to make some calculations, then requests the balances of 2 tokens, and then continues the calculations. At first, after the calculations are completed, they must be stored somewhere together with the current call arguments if they will be needed later, otherwise, they will be lost between internal calls. The contract then generates three internal operations: two for the tokens and one for itself to continue execution. Both tokens will send the responses to the contract with the balance. The contracts must have entry points with the correct type and logic to store this information before the three internal operations are executed. During the third operation, the data can finally be read from the storage and processed. And, of course, the contract must ensure that any unexpected calls that can break the logic aren’t done between the internal calls.
Insane stuff. Fortunately, adequate on-chain views are promised in the upcoming Hangzhou protocol update.
There is no way to calculate the address of the contract
One of the smallest challenges on the list is that there is no analog for EVM create2 opcode in Tezos. That’s why if the Uniswap architecture (with pairs as separate contracts) is reimplemented, there must be a registry (e.g., inside the Factory analog) that will map the tokens to their pair address. In order to enable on-chain re-routing, it must have a view function that will send the address to the provided contract that will process the response in a desirable way. This makes the whole system much heavier.
There were strict gas, operation, and type limits in the past
Even if it is not the case right now, looking at the exchanges that were developed in the earliest days, it is worth mentioning that the limits were much lower and operation costs were significantly higher than now.
This has a huge impact on the architecture since finding a single line that should be removed or simplified could be a huge achievement that lets the code be deployed or executed without limit errors. The solution had to be as concise as possible.
Tezos is a fascinating ecosystem full of challenges and enthusiasts with creative solutions. The trickiest obstacles relating to the building of DEXs on Tezos are:
- Processing baker rewards;
- Unfair Wrapped Tezos models;
- Two token standards;
- Lack of the view methods;
- Lack of some smart opcodes;
- Strict gas, operation, and type limits (in the past).
However, the brave teams of Dexter, Quipuswap, Plenty, Spicyswap, Vortex, and Aliens have approached it from the other side and addressed the issues in their own, authentic ways to make the platform better and the ecosystem richer. Due to Tezos on-chain voting, the new protocols try to mitigate common difficulties, leaving them in the past and ensuring smooth development. Hopefully, we will soon see more and more competitive exchanges on Tezos.