Author: Alyssa Chen
As we have covered previously in Exchanges & Trading, a smart contract is a piece of code that facilitates the execution of a digital contract. DEXs are built on top of blockchain technology, and orders are processed through smart contracts on the blockchain. Users connect to DEXs using a Web3 wallet (i.e. Metamask, Rainbow, or Coinbase wallet) and orders are matched based on predefined rules executed via the smart contract.
The following is an example of how an order is executed on a DEX:
The user places an order on the DEX.
The order is broadcasted to the entire blockchain network.
The smart contract matches the buyer and seller based on predefined rules.
Once the order is matched, the smart contract automatically executes the trade.
Assets are exchanged between the two parties.
DEX’s provide transparency and security, which enable users to retain control of their own funds and trade 24/7 without relying on a central party. However, there are some risks associated with DEXs. First, liquidity can be lower compared to that of a CEX, leading to wide bid-ask spreads and higher slippage. Trade executions may also be slower, as trades need to be first confirmed on the blockchain. Other than the smart contract code, there is limited regulatory oversight, which can expose smart contract vulnerabilities to higher risk of hacks— which is why is critical for smart contract code to be engineered thoroughly.
Order-book DEXs are similar to CEXs. They allow users to place limit orders and specify the price and amount they are willing to buy or sell an asset for. The user will usually place an order, which is then broadcasted to the network. The smart contract will then record the order on an order book, allowing other users to be able to fulfill the other side of the trade.
Another type of DEX is an automated market maker (AMM), which uses a liquidity pool to facilitate trades between different assets. The main difference here, is that instead of fulfilling trades via an order book, AMMs utilize a pool. This pool operates according to an algorithmic formula, which determines the price of each asset based on the ratio of assets in the pool— its formula maintains a constant balanced ratio of assets in the pool and allows users to trade assets almost instantly.
In AMMs, liquidity providers (LPs) deposit assets into the pool, and are able to earn a portion of the trading fees by doing so. These fees are distributed based on the percentage of liquidity provided by each LP. Below is an example of how a trade might occur on an AMM:
Liquidity providers deposit funds (cryptocurrencies or tokens) into a liquidity pool
User places a trade
Trade is executed instantly based on liquidity in the pool
Liquidity providers earn portion of trading fees
An assets price is rarely the same on every exchange— this is because each AMM uses their own liquidity pools with a different algorithmic formula. Arbitrageurs typically buy assets from DEXs with lower prices and sell into DEXs with higher prices, averaging the price between the two pools. As trades are executed, the ratio of assets in the pool may change. This alters the price of the pool’s tokens, which may result in impermanent loss, which occurs when the value of assets in the pool changes relative to each other over time. This can result in a loss for liquidity providers.
Let’s say a liquidity pool contains 10 units of token , and 20 units of token . 1 unit of token is worth 2 units of token as determined by the pool (). If a user purchases 5 units of token for 2.5 units for token , then the pool’s ratio will shift. Now, the pool contains 12.5 units of token and 15 units of token , so one unit of token is now worth 1.2 units of token .
Now, as a user on a decentralized exchange, how can you ensure you are getting the best price for an asset? The naive answer may be to manually check various platforms to see which offers the best price. Would there be a way to unify all this information to access liquidity across various DeFi platforms?
Similar to how Expedia displays flight prices from many different airlines, DEX aggregators are a type of platform that allows users to access multiple DEXs from a single interface. Users can place orders on multiple DEXs at once, and the aggregator will route the order to the DEX with best price/liquidity.
Typical aggregators will look at all the different DEXs and display the best possible exchanges that are offered, while smart order routing will split up the users desired trade amongst many DEXs— maximizing the overall trade not solely based on platform.
Code audits are a critical security measure for DEX operators. Often times, DEXs will hire reputable security firms to review their codebases and identify potential vulnerabilities— this helps DEX operators identify and address issues before launching their platform. Having these security measures are a good way to reduce risk of hacks or smart contract vulnerabilities, and give users confidence that the DEX operator takes security seriously.
Bug bounty programs are another security measure that incentivizes security researchers to find and report vulnerabilities in the DEX platform. These programs offer rewards for identifying and reporting issues, and a great way to encourage responsible disclosure of vulnerabilities. This allows DEX operators address potential issues before they are exploited by malicious actors, and helps to increase the overall security of the platform and improve user trust.
Cold storages offer a method of storing cryptocurrency private keys in an offline medium (such as a USB drive or a hardware wallet) to help prevent funds from being stolen in the event of a hack of security breach. A drawback to using cold storages is that it can make it more difficult to access user funds quickly. Hardware wallets are small portable devices that store private keys offline and require physical authentication to access funds— they are often considered the most secure form of cold storage.
Muli-signature (multisig) wallets are wallets that require multiple signatures to authorize the movement of funds, which reduces the risk of a single point of failure— however, these wallets can still be hacked. Some examples of multi-sig wallets are Electrum, Arbitrum, and Guarda. The concept behind multi-signature schemes are explored more in this paper on Blockchain at Berkeley’s Mirror.
Lastly, governance, which is the process of decision-making in DeFi protocols, can be used to maintain integrity of the protocol, resolve disputes, and upgrade protocols. Governance allows engagement with users and the broader community, in order to identify and address potential security issues. DEX operators can participate in forums, social media, and other platforms where users can report issues or ask questions.
Uniswap is an Ethereum-based DEX which utilizes an AMM model to execute smart contracts that manage liquidity pools. Users are able to trade tokens instantly by adding or removing liquidity from pools, and the price of each token is determined by the constant product formula, where represent the respective quantity of each token in the pool and acts as the product of the two token’s reserve balances.
Uniswap v2’s transition to Solidity allowed for the direct trade of ERC-20 tokens, which is a programming standard that describes the function interfaces required to integrate a token with the rest of the blockchain. Uniswap also implemented new features such as price oracles and flash swaps. Uniswap’s price oracle is determined by dividing assets at specified time and several things are resigned to improve on the oracle’s functionality. At the beginning of each block, keeping track of the cumulative sum makes it more difficult for attackers to manipulate the prices at the end of each block.
To measure asset prices, Uniswap v2 tracks both the price of asset in terms of asset and vice versa, allowing more flexibility to the user to choose their preferred unit. Additionally, to prevent oracle manipulation while ensuring accurate pricing, Uniswap v2 caches its own reserves after each interaction, using these caches to update the oracle to protect against potential attacks.
V2 also introduces a new way for trading with its concept of flash swaps– allowing users to send and receive assets before payment, given the payment takes place in the same atomic transaction. This swap will then issue a callback to check for sufficient funds, otherwise reverting the purchase transaction.
Trading Technicalities: The swap function allows users to exchange one token for another, while the callback contract is a temporary smart contract which is triggered when a user makes a trade. This contract is used to verify the transaction, and is deleted shortly after the transaction is completed.
Security and Recovery Mechanisms: Smart contracts on Uniswap are publicly audited by multiple independent security firms. Trail of Bits, Quantstamp, and ConsenSys Diligence are some examples.
Uniswap also has two recovery mechanisms:
sync(), which updates reserves to match current balances in the case that the token’s real-time balance does not match the reserves of the parent contract.
skim(), used to update reserves and recover excess tokens.
Uniswap has several pros: namely, it is decentralized and non-custodial— users have full control over their funds and don't need to trust a third party. Uniswap charges a 0.3% fee on trades, compared to the 0.1% - 0.5% fees typically charged by CEX’s. Additionally, anyone can create a trading pair or list a token on Uniswap, and all transactions and liquidity pools are publicly visible on Ethereum. Uniswap is also highly resistant to downtime or outages, as it is run by a network of nodes rather than a single central server.
However, liquidity providers may experience impermanent loss if the prices of the tokens in the pool diverge significantly, and trades may result in higher slippage than on centralized exchanges due to the algorithmic pricing model. It may also be important to consider user error, for example, users may make mistakes when adding or removing liquidity, resulting in losses or other issues. Uniswap's smart contracts can also be subject to bugs or vulnerabilities that could be exploited by attackers, as mentioned previously. Uniswap, along with many other decentralized exchanges are often being updated and improved. To keep up with these changes, we recommend to stay connected through their blogs and Twitter!
If you’re interested in learning more about decentralized finance— including exchanges, stablecoins, derivatives, MEV and more… stay tuned for Blockchain at Berkeley’s Fundamentals of DeFi article series!
In the next week, we will be covering stablecoins and lending!
This series is based off Blockchain at Berkeley’s DeFi lecture series. Credits to Tiffany Liu, Riteka Murugesh, Aditya Bhandari, Nate Pola, Daniela Fajardo, Jaylem Brar, and other previous contributors.