The Road Towards Efficient On-Chain Swaps
On-chain swaps for DAPPS are hard! We explore the latest and greatest about; on-chain swaps, current best practices, and highlighting the importance of decentralization in this core DeFi primitive.
TLDR
On-chain swaps are crucial for decentralized finance (DeFi) but come with challenges like vulnerability to Maximum Extractable Value (MEV).
Introducing a trusted party for pricing can create a single point of failure and is not a recommended solution. DeFi has evolved to allow complete decentralization, making the introduction of trusted entities counterproductive.
Key considerations for on-chain swaps include security, performance, execution time, and gas consumption.
We’ve identified four on-chain swap categories: Fixed paths, On-chain Aggregation, ySwap from Yearn, and Intent Swaps.
CowSwap and Uniswap X are two protocols that utilize Intent Swaps, a novel approach to on-chain swapping.
Uniswap V4's RFQ model may usher in order flow toxicity, deterring passive LPs and risking liquidity, which calls for a balanced order routing approach.
CowSwap has proven its model with over $15 billion in transaction volume and employs a Request For Quote (RFQ) system.
Uniswap X, still in beta, offers both RFQ and Dutch auctions, adding a layer of decentralization to the process.
Intent Swaps could revolutionize on-chain swaps by offloading the complexity to specialized market makers, potentially offering better rates.
The article concludes by highlighting the need for future research in areas like data collection, implementation options, and UX design.
Introduction
The aim of this report is to assess the cutting-edge developments in on-chain swap technology broadly. These on-chain swaps facilitate trades through self-executing, trust-minimized smart contracts.
Vaults represent a typical application for on-chain swaps. For instance, when a vault deploys a single asset into a dual-asset liquidity pool (LP), a swap is needed to convert the deposited token into the LP's secondary token. The following image illustrates how this process would work in the case of a USDC vault deploying into a USDC/DAI liquidity pool.
In addition to initial deployments, on-chain swaps are also essential during vault harvests and auto-compounding events.
However, on-chain swaps present unique vulnerabilities, most notably to Maximum Extractable Value (MEV) (Read more about MEV). Because these transactions are publicly visible in the mempool before confirmation, they become targets for MEV bots. These bots can front-run or sandwich the swap transactions to siphon off value, a concern that warrants careful consideration given its potentially severe impact, which can range from minor financial losses to the complete depletion of a vault.
One solution that is often employed is introducing a trusted party to price the swap off-chain, however, introducing a trusted party is a common but flawed solution. While this approach might appear to streamline the process, it effectively introduces a single point of failure into the system. Worse, it adds an element of uncertainty, as the trusted party could offer unfavorable pricing or even engage in deceptive practices like sandwich attacks. Shielded by privacy technology, this entity could execute such schemes and conveniently attribute them to coding errors, thus avoiding accountability.
The principle that a protocol is only as secure as its weakest link is acutely relevant here. Imagine painstakingly constructing a house with insulation and energy-efficient materials to keep it warm during winter, only to negate all that effort by leaving a window open. That's exactly what happens when you introduce a trusted party into a decentralized finance (DeFi) environment.
DeFi technology has evolved to a point where it's possible to decentralize every aspect of a network stack, from user interfaces and web clients to node hosting. This allows for a completely decentralized and trustless interaction with the network. Introducing a trusted entity into this well-calibrated machine not only undermines the inherent security but also leaves users vulnerable, effectively squandering the robustness and independence that decentralized systems are designed to offer.
Considerations
The primary considerations for on-chain swaps are security, performance, execution time, and gas consumption.
Security
Here we ask the questions:
Is there a trusted party? What power do they have to exploit the protocol?
What’s the contract risk? Is it battle-tested? How complex is it?
Note, here, we ignore the security of the particular network the protocol is deployed on, though this should be considered closely when building a product.
Performance
Focuses entirely on the price achieved by the swap. MEV plays a role here; limiting MEV and accessing the best on-chain liquidity is the goal.
Execution Time
How fast does this particular swap need to occur? The answer to this differs for different applications. Whether the swap is asynchronous or synchronous also affects execution time.
Synchronous swaps occur on demand within the desired transaction; these are more flexible and can be executed faster.
Asynchronous swaps occur within a timeframe, and often their transaction won't be submitted by the protocol but rather a relay of sorts.
Gas Consumption
If the transactions are frequent, this is particularly important, but for most use cases, this is the least important requirement.
On-chain Swap Options
We’ve categorized 4 on-chain swap categories, which we will explore. These categories are Fixed paths, On-chain Aggregation, ySwap from Yearn, and Intent Swaps.
This section explores each of these categories, evaluating each and comparing them.
Fixed paths
The fixed paths approach is the simplest of the options and also the most gas-efficient. The swap will always use the same router and the same path; there are no price optimizations, and it’s up to the devs to choose the most suitable path when deploying or upgrading the contract. The contract developers simply hard-code the swap path for each required swap.
A common approach used (often in Yearnv2 strategies), is to calculate the path on the fly, as detailed in the snippet below.
This simple algorithm checks if either of the tokens is ETH; if so, there will likely be a pool between ETH and the other token, so it returns a path of length 2. If neither is ETH, it sandwiches ETH between the two tokens in the path, which is also likely to have suitable liquidity.
This approach is most suitable when there is an obvious source of liquidity for a swap, which is often the case for governance tokens; hence, fixed paths are often used for harvesting farming rewards.
If the swaps begin to be a significant portion of the LP, the MEV incentives increase. A good source of price, like an oracle, is desirable. Even with an oracle MEV, the difference between the market price and the oracle is still possible. This should be considered closely; you will need confidence in your oracle.
On-chain Aggregation
Modern dex aggregation is calculated entirely off-chain. This is because the algorithms to solve for the best path are complex and computationally expensive; they require solving multiple differential equations on the fly. Computation on blockchains is expensive, which is why On-chain Dex Aggregation has run its course.
OneSplit, or 1Split, was an innovation of its time and where 1inch started. It attempted to plug into all available on-chain liquidity and find the LP that would produce the best rate for a given swap. This was no joke; it plugged into Curve, Uniswapp, Uniswap, Mooniswap, Kyber, and many others while calculating some complex equations on chain, on the fly.
It was popular, Yearn V1 used it, and while gas was cheap and MEV wasn’t so prevalent, it worked well.
ySwap
ySwap is an interesting approach to the problem. Yearn has many strategies, and for each, they find to source swap liquidity for harvests, deployments, liquidations, etc. They devised a method to make this generic and portable, improving the developer experience and giving the Yearn team more flexibility to source liquidity while maintaining decentralization.
Yearn’s built Swappers for on-chain protocols, each following a common interface. Strategies then plug into ySwap and can specify which swapper the strategy desires to use for its swap. This is novel to change where a strategy sources liquidity; they need to change which swapper the strategy is using. Also, each time they build a new Swapper, it can be reused by any other strategy that might benefit from the Swapper.
ySwap also introduces the concept of Synchronous and Asynchronous swaps. The synchronous swap will occur within the strategy transaction, most commonly a liquidation for withdrawal or a harvest that requires just-in-time (JIT) liquidity to report profits. However, many strategies do not need JIT liquidity; they can support a delay. In these circumstances, the Asynchronous swap can be used; this is where an external EOA triggers the swap and can specify the most suitable Swapper off-chain. The EOA is permission, but that account only has the flexibility to specify which pre-approved Swapper should be used for the Swap.
ySwap has seen a lot of use from Yearn, which fits many requirements. However, I suspect they will migrate to intent swaps in the future for Asynchronous swaps, given they’re already using CowSwap for their treasury swaps.
Intents Swaps
There are few intent swap protocols; however, this report will focus on the new and the less-new (aka battle-tested), Uniswap x, and CowSwap.
Intents
“Informally, an intent is signed a set of declarative constraints which allow a user to outsource transaction creation to a third party without relinquishing full control to the transacting party.”
When submitting a transaction, users specify the exact computational path. When submitting an intent, users specify the goal and some constraints, and a matchmaking process decides the computational path to be taken. Source: Paradigm
Intent Swaps introduce a completely different approach to on-chain swaps, utilizing intents to help users receive the best prices for on-chain swaps. Rather than users signing a swap transaction and broadcasting the transaction on-chain, they utilize intents to swap and broadcast to a group of Solvers or Fillers (Platform dependent terminology) who can bid match to match the swap, paying for the transaction gas along with matching the order. The example below shows the user's intent to swap 1000USDC for 0.5ETH. Two fillers bid to match the order, but only the best bid will win.
Fillers (AKA Solvers) complete the matchmaking process & complete the swap for the user. Where are fillers getting the liquidity? Well, that’s completely up to them. They could use on-chain liquidity sources in the same transaction, be it on one chain, multiple DEX actions, multiple chains, or even off-chain liquidity. The point is that the intent Swap platform doesn’t care; the user wants liquidity, and the fillers behave as market makers.
Why does this matter for On-chain Swaps?
intent Swaps have the potential to play a large role in DeFi. In the context of On-chain Swaps, the benefit is the rates. Given that the Fillers are competing to win the auction, there’s a race to the bottom on the premium the market-makers are taking. This offloads the complexity of finding the best on-chain liquidity from the protocols to the fillers. The fillers are specialized market-makers in constant competition, so they will be much better than the average protocols for finding the best liquidity and accessing off-chain sources.
Trusted Entities
In the worst case, a user finds themselves in a position where a single party executes intents, such as the monopolist block builder from the section above. In such a world, the monopolist block builder could extract rents, and any new proposal for how intents should be processed would be denied traction if not adopted by the builder. In the face of a monopolist, individual users lose negotiating power, which is exacerbated when users use intents to give additional degrees of freedom to middlemen. Source: Paradigm
Intent Swaps Protocols
Two protocols bubble to the top, CowSwap, and Uniswap X. CowSwap has been live for over 1 year, and Uniswap X is currently in an opt-in beta. There are other Intent Swap protocols, and I expect there will be more, though for this report, we will dive into CowSwap and Uniswap X to understand if and how on-chain intension swaps could work.
CowSwap
CowSwap was launched in April 2021, with over $15 Billion in volume since launch, often reporting more than 10% of the DEX aggregator market share.
The contracts are relatively simple, with audits completed by Hacken & G0 Group. With CowSwap, the majority of the complexity is offloaded to the solvers. It’s quite elegant, really.
CowSwap API
CowSwap employs a Request For Quote (RFQ) system to match orders with the winning solver.
Users submit signed orders via CowSwaps API
The API server bundles orders into a batch
The API server polls each of the registered solvers for their bid (the best prices they can offer for the batch)
The API server informs the winner of the auction
The winning solver settles the batch on-chain
API Server
The CowSwap API server is responsible for enforcing the rules of the auction and publishing which solver won the auction, instructing them to submit the settlement transaction. (Note: I am not 100% sure about this because the API is private). The CowSwap API is centralized, so users are relying on CowSwap and Solvers to act on their behalf, though they are incentivized to do so.
Solvers
Solvers are trusted 3rd parties. They are individually approved by CowSwap governance. They are permitted to call the `settle` function on the settlement CowSwap contract; however, there are assertions to ensure the user's tokens cannot be stolen by a Solver. All solvers have fronted a bond or entrusted by someone who has fronted it on their behalf. Source: CowSwap Docs
Liquidity
CowSwap is designed to access liquidity on-chain predominately. Liquidity is sourced by executing an array of “intents”, which will contract interactions with on-chain DEXs (Solvers cannot access private liquidity). They
Swapping via Contracts
CowSwap supports ERC1271, which means contracts can interact with the protocol by approving EOAs to sign transactions on their behalf.
Batching
CowSwap supports batching, which has the potential to be more gas-efficient and return a better swap price for its users.
Milkman
Milkman deserves a notable mention; it’s a free, open-source project that enables on-chain CowSwap swaps with little developer overhead. The most common use-case is large Multisig treasury swaps; for example, AAVE and Yearn use it.
References
Uniswap X
Uniswap X was introduced to the public by Hayden Adams from Uniswap in July. It’s now available in a public opt-in beta via the Uniswap application. The protocol has a lot of similarities to CowSwap; for example, they offer a Request For Quote (RFQ) system that performs much like CowSwap, but something new they’ve introduced is on-chain Dutch auctions for settlement.
Request For Quote
“In order to incentivize this network of fillers to offer their best possible price, UniswapX allows orders to specify a filler that receives the exclusive right to fill the order for a brief duration, after which the Dutch auction begins and any filler is able to execute the order.”
Uniswap X whitepaper
The specifics of the RFQ aren’t clear at this stage; the API Docs only cover the endpoints for the Dutch Auctions. Aspiring Quoters need to apply to become a quoter, though there are plans to increase the transparency.
However, from reading the docs, this is the flow I expect:
User Submits Order to Uniswaps RFQ API
Uniswap polls each of the registered Quoters for their best price
Uniswap’s API server selects the best quoter, permitting that quoter to settle the order on-chain (with a short expiry)
Uniswap V4's Request For Quote (RFQ) model aims to refine trading efficiency. However, an unintended outcome might be the emergence of order flow toxicity. In this model, off-chain solvers handle non-toxic order flow, while on-chain liquidity providers (LPs) deal with the remaining, often toxic, order flow. Over time, this could drive away passive LPs due to the unfavorable flow, eroding last-resort liquidity and veering towards centralization. This shift could potentially impact execution improvement for swappers adversely. The scenario underscores the need for a balanced approach in order routing to uphold decentralization, inviting further community engagement to address this nuanced challenge.
Dutch Auctions
The other option to trade with Uniswap X is using their Dutch auctions. This approach is particularly interesting because it eliminates the need for a centralized body (Uniswap) to enforce the auctions.
Uniswap X Dutch Auction Orders API
A user constructs an order, specifying the start amount, end amount, and the decay start and end (among other properties).
The user signs the order and submits it via the Uniswap X API
Fillers poll the Uniswap X API for orders.
As time progresses and blocks roll in, the offer price of the order decreases. Once one of the fillers is willing to match the order, they construct and submit a transaction to fill the order.
Given there are no special privileges granted to fillers, and the API server isn’t responsible for enforcing the auction, anyone could run a Uniswap X API server. This enables private order books to be used for AML regulation and opaque order-flow.
Liquidity
Like CowSwap, the Fillers can execute arbitrary functions within settlement (using the ReactorCallback function). Since Uniswap X uses a callback function, Filler can access private on-chain liquidity, unlike CowSwap. This is what enables off-chain and cross-chain liquidity sources. It’s a minor detail in the contracts but has a big impact on practice.
Swapping via Contracts
Uniswap also supports ERC1271, which means contracts can interact with the protocol by approving EOAs to sign transactions on their behalf.
Intent Swaps Comparison
Below is a summary of the differences between the protocols
References
Summary
Below, we have an attempt to rate each of the on-chain swap options for various considerations: 1 is poor, and 5 is best-in-class. This is entirely our own judgment and should not be used to make architectural design or financial decisions.
Conclusion
The landscape of on-chain swaps in the decentralized finance (DeFi) sector is continuously evolving, with new innovations like intent swaps adding layers of complexity and opportunities for users. CowSwap and Uniswap X represent two remarkable approaches to utilizing intents in on-chain swaps. Both have their unique features and benefits, offering traders varying levels of decentralization, flexibility, and efficiency.
For synchronous swaps, where immediacy is crucial, ySwaps appear to be the most promising approach in this report. Developed by Yearn, ySwap offers a unique blend of efficiency, flexibility, and security, albeit requiring a trusted party to add Swappers. However, as the technology matures, ySwaps may likely yield intent swaps for asynchronous transactions, considering the latter's inherent advantages.
CowSwap, with its trusted Solvers and Request For Quote system, is an established player, proving the model's feasibility with over $15 billion in transaction volume since its launch.
Uniswap X, still in its opt-in beta phase, offers a blend of centralized and decentralized features. Its RFQ system mirrors CowSwap, but its Dutch auctions add a layer of decentralization. Uniswap X's architecture also allows for greater flexibility in liquidity sources.
Both protocols represent technological advancements and a paradigm shift in how users interact with DeFi protocols. Instead of being mere transaction senders, users become more like clients specifying certain goals and constraints, which the protocols strive to fulfill in the most efficient way possible.
A pressing concern remains the influence of trusted entities, particularly when a single, monopolistic organization gains dominance over the network. In such cases, the negotiating power of individual users is likely to be severely curtailed, highlighting the critical need for decentralized governance.
In summary, intent swaps can revolutionize on-chain swaps by offloading the complexity of finding the best liquidity sources to specialized market makers, thereby potentially offering users better rates. As DeFi continues to evolve, these protocols could significantly shape its future landscape, offering traders more choices and control than ever before.
Whether you're a trader looking for the best rates or a developer considering integrating one of these protocols into your project, it's crucial to understand the nuances of each to make an informed decision. This report should serve as a starting point in exploring what could very well be the next frontier in DeFi.
Future Research
As the landscape of on-chain swaps continues to evolve, several research avenues promise to deepen our understanding and improve the efficacy of existing technologies. The following are key areas for future exploration:
Collect On-Chain Swap Data
A comprehensive data collection initiative should be undertaken to gauge the performance and prevalence of various on-chain swap methods. This would involve crawling various blockchain networks to collect relevant metrics on swap methods, including but not limited to success rates, costs, and speed. Analyzing this data can help us identify the strengths and weaknesses of existing solutions.
Implementation Options for Asynchronous Swaps
This report overviews the various high-level options available for on-chain swaps. Still, it stops short of diving into the granular specifics of how developers might implement intent-based swaps on-chain. Milkman has gained noteworthy recognition as a leading option currently in production for asynchronous swaps. However, this domain has ample room for further research and enhancements. For instance, no Milkman equivalent is available specifically for Uniswap, highlighting an area that could benefit from additional study.
By exploring new implementation strategies, the DeFi community can move closer to offering more robust, secure, and efficient asynchronous swap options across various protocols.
UX Design Updates for Asynchronous Interactions
User experience (UX) plays an essential role in the adoption and usability of any technology, especially something as intricate as on-chain swaps. Future research could explore UX design improvements that enable asynchronous interactions without hampering user experience. This would allow more prevalent use of intent swaps in on-chain products.
Each of these research areas could significantly contribute to advancing on-chain swap technology, making it more efficient, secure, and accessible to a broader audience.
Special thanks to Robolabs.
Robolabs has been of great help in writing this report. They are our resources for R&D, and I highly recommend them.
Good report. Thanks Leviathan for recommend.