The ability to swap tokens is critical to web3 and decentralized finance (DeFi). Swapping allows you to exchange one token for another, allowing you to leverage the diverse opportunities that many DeFi protocols offer.
In this article, we will look at how to swap tokens, how smart contracts work behind the scenes, what the critical terms around swapping mean (such as liquidity and liquidity pools), and how to protect yourself against the risks of token swapping.
By the end, you’ll be ready to swap tokens confidently and dive into DeFi. This is your swaps primer for Wave 3 of the Linea DeFi Voyage.
Token swapping means exchanging one cryptocurrency (or token) directly for another.
Token swapping is similar to how you might exchange US dollars for yen at a currency exchange. Except in web3 you are exchanging blockchain tokens instead of fiat, can use a decentralized on-chain exchange (DEX), and instead of dozens of currencies, there are thousands of tokens you can potentially swap.
Token swapping is critical to DeFi. A large percentage of web3 projects (and DeFi protocols) have their own token. These tokens are foundational to the protocols—they might give you the ability to use the protocol, give you a discount on services or access to specific features, govern the protocol, and more. However, a large percentage of these tokens are not available for direct onboarding from fiat. Instead, you will need to onboard into a major cryptocurrency (such as ETH) and then swap that token for your desired token.
Because swapping on a Layer 1 (L1) network is often very slow, Layer 2s (L2s) like Linea have become an important component of token swapping. On an L1, by the time your requested swap is processed, token prices may have changed, causing your swap to execute at a lower-than-expected price (or even to fail). If you want to have your transaction go through quickly to avoid these issues, you will need to pay high gas fees.
Linea, however, is built to be fast and cheap. So swaps on Linea execute quickly and at a much lower cost.
Liquidity is important to all financial markets. Liquidity is how easy it is to sell an asset without affecting its market price. For example, stocks usually have high liquidity and art usually has low liquidity. When something has low or no liquidity, trading an asset can be difficult, prices can drop, and markets become highly inefficient. It is difficult to sell a Picasso. It is easy to sell General Motors stock.
Just like other markets, web3 requires liquidity for users to swap tokens efficiently. For these token swaps, most of web3 relies on liquidity pools—a web3 innovation that does not exist in traditional markets.
Liquidity pools can be complex, but what they do is straightforward. If a user wants to trade Token X for Token Y, the user trades using an X/Y liquidity pool that holds both tokens. The user deposits some number of Token X into the liquidity pool and gets back the equivalent value of Token Y from the pool.
The exchange rate of X to Y is fluid and changes with each trade to a market value. In the example above, since there is now more of Token X and less of Token Y, the price of Token Y (in terms of X) goes up. It is basic supply and demand.
To fund these liquidity pools, tokens are deposited and “locked” by users (called liquidity providers or LPs). These LPs supply the liquidity, take on risk by locking up their capital, and are usually rewarded appropriately. Some protocols charge a small fee for the swap which is then distributed to the LPs. Some protocols reward LPs with that protocol’s token. Some do both.
Behind the scenes, liquidity pools are smart contracts. That means they run on a blockchain and execute automatically and without a central authority—which makes the token-swapping protocol decentralized.
Another type of smart contract involved in token swaps is automated market makers (AMMs). These are smart contracts that rely on liquidity pools to execute trades and set the rules for how the liquidity pools, tokens, and LPs all work together.
When a trade occurs, the AMM algorithm automatically adjusts the quantities of the tokens in the pool to maintain constant liquidity. This process is called pool balancing. For example, if you buy Token X , the supply of Token X in the X/Y pool decreases, while the supply of Token Y increases. The AMM algorithm then automatically increases the price of Token X and reduces the price of Token Y.
However, some external factors can make the pool unbalanced. For example, if a large number of users sell Token X for Token Y, it will lead to an excess of Token X in the pool and a shortage of Token Y in the pool. This unbalances the pool and changes the relative price of the tokens.
Another important player that helps create liquidity in token swaps is aggregators. Aggregators gather liquidity from multiple DEXs and offer users the best price for their trade. The way aggregators work is that a user initiates a trade, let’s say sell Token X for Token Y. The aggregator splits the trade into smaller parts and routes these parts through different DEXs. Each DEX executes the trade for its part and routes it back to the aggregator.
The aggregator can then compare the rates for the trade offered by each DEX, and routes the remaining parts of the trade to the DEX with the best price. This allows the aggregator to offer the user the best price for their trade.
A recent innovative idea in the world of token liquidity is ve(3,3) DEX. It is unique in the sense that it aims to balance out the incentives for providing liquidity between LPs, token holders, DEXs, and users. It is designed in a way to incentivize users to provide liquidity for their tokens, and reward them on the basis of the amount of liquidity they provide, rather than the rewards from LPs. How it works is that the protocol buys liquidity from users in return for their native token OHM. And it does so at an average discount of 7%. The tokens bought from the users are then staked, for a set amount of time with the minimum being a week. While the users benefit as they get a discounted token, the protocol benefits because they add a token to their treasury own liquidity in a pool.
When you execute a swap, what Token Y is worth in Token X can vary widely across protocols. Some exchanges, for example, might have much higher liquidity of a trading pair than others, which in turn can cause a wide price difference.
To help create price stability across protocols, arbitrage traders trade among the protocols (often with bots), taking advantage of price discrepancies between the exchanges. This not only rewards the arbitrage traders with profits, but also helps to keep the price consistent and stable across exchanges.
Cryptocurrencies (also known as tokens) are the digital currencies used on blockchains.
Stablecoins are cryptocurrencies designed to keep a stable value, as opposed to most cryptocurrencies which tend to have high volatility. The value of a stablecoin is usually pegged (tied) to a more stable asset such as the US dollar or gold.
Wrapped Tokens (such as WBTC and wETH) are tokens that have been “wrapped” in a new contract, allowing them to be used on a blockchain where they normally wouldn’t be available.
Protocol Tokens give holders the ability to participate in the protocol. For example, holders of a protocol’s token might be able to participate in governance, run a node, stake, and earn or pay fees. Examples are ETH for Ethereum and UNI for Uniswap.
Liquid Staking Tokens (LSTs) are tokens that represent a staked asset. For example, users often stake their ETH (the native token of Ethereum) in order to help support the network as part of running a node. But staking ETH locks the ETH into a contract so that it's no longer tradable. Some protocols issue users an LST (for example Lido issues stETH) that represents, and is redeemable for, the locked ETH—but is still tradeable. LSTs allow users to stake their tokens yet still maintain liquidity.
Real-world Asset Tokens (RWAs) are tokens that represent real-world, non-digital assets such as real estate, commodities, and stocks. RWAs represent these assets as digital tokens on a blockchain, allowing them to be traded and used in DeFi.
Non-Fungible Tokens (NFTs) are tokens that are unique and not fungible, meaning they are not interchangeable. If you trade one NFT for another NFT, you end up with something different. In contrast, if you trade an ETH token, which is fungible, for another ETH token, you have exactly the same thing. NFTs are often used to represent ownership of artwork, music, and collectibles.
To swap tokens on Linea, you can use a decentralized exchange** (DEX)—a decentralized protocol** that allows you to swap tokens using smart contracts on a blockchain as we covered above. Examples of a DEX include Uniswap, SushiSwap, or even aggregators that look for the best prices among other DEXs such as the swap feature in MetaMask. On these sites, you use your web3 wallet to approve the trade and you retain control of your funds at all times.
Let us look at some of the risks of swapping tokens on Linea.
Slippage - In traditional finance, the trading platform matches buyers and sellers at a certain price. However, since there is no central authority in DeFi, trades are executed automatically by the AMM against the liquidity pools. This means that under some situations (low liquidity), your trade might not be completed at the price you expect. You might get fewer tokens than expected. You might get significantly less. This is because if there aren’t many tokens in the liquidity pool (again, low liquidity) a large trade can cause an imbalance, causing the price to change quickly and wildly. This movement in price between when a swap is placed and when it is confirmed is called slippage, and it can wreck a trade.
Liquidity Risk - If you buy and sell tokens that aren’t popular, you might get stuck with a token that has little to no liquidity. This happens more often on L2s like Linea, where there can be many versions of a token on Linea, causing what little liquidity there is to be spread even thinner across Linea and token variations.
Smart Contract Bugs - Of course, as with all of web3, there is always the risk of a bug appearing in the smart contract. It might accidentally lock your funds permanently so that you can never get them back, open a window a hacker can use to steal your funds, or simply cause the smart contract to not work as expected.
What are some of the mitigation strategies you can use to guard against these risks?
Token swaps are one of the most important aspects of DeFi. Without token swaps, you could not participate in many of the groundbreaking protocols that drive web3. But be sure to understand how token swaps work, their risks, and the best practices you need to succeed.
You can explore this concept in more detail, and other aspects of DeFi, by participating in the Linea DeFi Voyage. The six-week Voyage is designed to give all levels of web3 users an opportunity to explore DeFi, in an intuitive, immersive, and educational manner.