# Towards Fairer DEXs on Ethereum

- Channel: [Devcon](https://streameth.org/devcon)
- Date: 2023-10-09
- Duration: 26:07
- Topics: blockchain, smart contracts, distributed ledger, ethereum
- Watch: https://streameth.org/watch/yt-msUvYJSCRjk
- YouTube: https://www.youtube.com/watch?v=msUvYJSCRjk

## Description

Visit the https://archive.devcon.org/ to gain access to the entire library of Devcon talks with the ease of filtering, playlists, personalized suggestions, decentralized access on Swarm, IPFS and more.
https://archive.devcon.org/archive/watch/6/towards-fairer-dexs-on-ethereum/

MEV is inherent to Ethereum and cannot be banned at the core protocol layer. Dapps should therefore carefully assess and reduce the amount of MEV they create. Multi-dimensional batch auctions with just in time competition for order flow offer a fundamentally fairer way of trading on Ethereum. P2P matching reduces the amount of extractable AMM interactions, while best price execution is guaranteed through a network of competing “solvers”.

Speaker(s): Felix Leupold
Skill level: Intermediate
Track: Cryptoeconomics
Keywords: Mechanism Design,MEV,Batch Auctions

Follow us: https://twitter.com/efdevcon, https://twitter.com/ethereum
Learn more about devcon: https://www.devcon.org/
Learn more about ethereum: https://ethereum.org/ 

Devcon is the Ethereum conference for developers, researchers, thinkers, and makers. 
Devcon 6 was held in Bogotá, Colombia on Oct 11 - 14, 2022.
Devcon is organized and presented by the Ethereum Foundation, with the support of our sponsors. To find out more, please visit https://ethereum.foundation/

## Transcript

foreign [Music] my name is Felix I'm working with an awesome team of people at cow Swap and I want to talk to you today about how we can design fera trading mechanisms for ethereum and I want to frame this Vision based upon an idea of just having a single price per token per block and we'll explore a little bit of why we think this is the most Fair Way of trading on ethereum the reason why we're talking about this is if we look at a main adoption of decentralized trading we can see we've made some progress in the last couple of years but we are just seeing the tip of the iceberg here even digital asset trading as a whole including centralized exchanges is many times larger than Dex trading today and when we want to get into more interesting markets like the U.S Securities Market or maybe the Holy Grail of trading Global foreign exchange trading then we really need to step up our game and I think personally that ethereum has as this credible neutral settlement layer the potential of enabled trading of all different parties in across Nations supernational actors so I really think this Global foreign exchange trading is a goal that we can strive for so to talk about how we get there let's first revisit a little bit the brief history honestly that we had um in the in the context of decentralized exchange Trading and I want to frame this history based upon an article from Alvin Roth who is an expert on Market design and won a Nobel prize in economics a while ago who wrote this essay on necessary requirements for a market to function in Harvard Business Review a while ago and he mentions three properties that a market needs to at least fulfill in order to function properly the first one is a good Market needs to be thick thickness just meaning that there is enough liquidity that when a buyer and a seller come or even just one side of them they can actually interact the second point that I will put a lot of focus on is what Alvin calls safety and by safety he means the market has to incentivize its participants to truthfully reveal their preferences they shouldn't be holding behind the bush and haggling and kind of hiding their their their true Revelation their true preferences but instead be incentivized to commit them kind of openly and then the last Point touches more on the scalability aspect which I will not go into much detail here because we know as ethereum as a whole is focused on getting scalability done and we have all these great talks at this conference about ZK VMS sharding and so the hope is that with ethereum figuring out scaling we can basically piggyback on that scaling for Dex trading as well and so if we if we look at how everything started a couple of years ago the first taxes on ethereum where etherdale to idex Oasis basically on chain limit order book dexes and those worked fine for some token pairs like etherus DC maybe worked quite quite well but they had a fundamental flaw which was that they required active Market making participants to constantly update the quotes and the bids and basically keep the market flowing keep the market in sync and with the explosions of tokens in the space it made it very difficult to bootstrap markets for new token participants or for new pairs and so what the problem with Entre limit order books was that it was just eventually very hard to create a thickness create thick markets and this is where amms came along amms really solved the problem of liquidity provision and allowed every one of us to become a liquidity provider just by staking two assets into a smart contract that would then automatically sell them on our behalf based on some um based on some curve based on some preference curve and all of this started in the context of prediction markets way before blockchains were born Robin Hansen had a paper on logarithmic basically amms and then in the context of ethereum we had many different teams pioneering more or less complex functions everyone of course Knows X times y equals K but really the the key thing that amm's brought to the space was overcoming the liquidity bootstrapping problem and creating thick markets even for long tail tokens so what's the problem with amms the problem with amms and again we have heard many talks about this at this conference is Mev or how I would call it in this presentation pay as bit pricing and pay as bit pricing comes from the fact that what you're seeing on for example uni swap if you're trading some tokens is not actually what you are sending into the mempool to be executed this is a trade that actually happened a couple of weeks ago somebody was selling one million dollars on uni Swap and probably so on the UI that they would get 750e but the thing that you need to add on uniswap is a discount to the current fair market Price which is referred to as slippage tolerance and you can think about slippage tolerance as basically how much volatility are you willing to accept in order for your trade to still go through blockchains are asynchronous by Design so there's race conditions and so the moment you click swap on uni swap somebody else might also be clicking swap somewhere else and therefore you need to price that volatility tolerance or slippage tolerance in now the problem with it is if your trade is large enough if the slippage tolerance is large enough the block Builder proposer validator Miner column what you will has an incentive to actually manipulate the prices and execute your trade exactly at your bid at the bid that includes your slippage tolerance and so this is what happened here um the this person got got sandwiched and lost ten thousand five hundred dollar to the in this case it was after the merge to to the to the block producer or validator and so this is really what makes amm's fundamentally unsafe by Design the fact that you cannot be honest about your slippage tolerance you basically have to lie to the amm and say hey um you know just set this small slip Assurance because I know if I really tell you what I'm willing to accept somebody is going to sandwich me and and run over me and so maybe to go a step back and and revisit why is it important to save a a safe mechanism design here a safe Market the first reason is that safe markets are just fundamentally simpler to reason about and make conclusions that basically the system is secure and that the allocations is is optimal and and you find the right answer the second reason why safe markets are better or important is that they're fundamentally more efficient than unsafe markets because if users are incentivized to Rel to reveal their true preferences you can just look at the preference and find the globally socially optimal application in in one round trip rather than doing multiple bits and asks and basically haggle around the haggle around the table and then the last point is maybe a more altruistic argument that safe markets are just fundamentally fairer to the least sophisticated participants Tyrone was talking about stealing from grandmothers I personally think more about people that visit Reddit and find a new coin and then go on uni swap trying to trade it and basically Get Wrecked um and yeah the least sophisticated participants are automatically protected in safe markets and so I agree with Maureen O'Hara who's a professor at Cornell who says especially on this problem of Mev that blockchain is not going to succeed if it's not viewed it's viewed as fared and so let's you know revisit the site that we saw in the very beginning if we want to get larger market adoption we need to design fairer and safer Market mechanisms so how do we build safety on top of amms this is what the second part of this talk will focus on the first thing that I want to kind of revisit is what we think is probably the fundamental root cause of most of the Meb that's out there maybe maybe even all Meb and that is that a single asset today on ethereum can have many different prices within the same block here's an example block from I think a week and a half ago where the most liquid pair that exists on ethereum ethusd was traded 11 times within the same block and at eight different prices the difference between the lowest and the highest price in this block was more than one percent and imagine the block really just happens at a single moment in time that's what blockchains do they they freeze kind of the the state of the world in a specific instant of time and yet that instant of time told people well there's eight different prices for for the most liquid pair and for example latency Arbitrage when you see a price change on binance and you try to Arbitrage it away against an amm that is an example of Mev that comes from have one asset having multiple prices because the first person that gets to trade in the amm still has the outdated price available and then everyone else in the block uh trades at the fair market Price we have one asset many prices the reason that liquidations cause Mev is because that whoever triggers the liquidation gets to trade at a discount whereas the rest of the market trades at a different price rather than using the liquidation volume and put it into the fair price finding and just settle everything at a single price and then the last point the sandwich attacks we saw on the last slide it's very obvious there was three different prices the opening the victim and the sandwich again one asset many prices and that's why we have Med so I argue that any Market structure where prices depend on arbitrary the the block producer can choose it at no um basically at their own will that arbitrary interblock ordering just makes the mechanisms unsafe by Design and so what is the solution well you might have guessed it from how I've started this this this chapter but the solution is to just have one price per token per block and so how would this look like we basically associated with every ethereum block have a price Vector for every asset that is traded in the block and that asset just has a single price at which it can be accessed within well that block and this price here is denominated in dollars it could theoretically be nominated in every in any currency you'd like um but the idea would then be that the participants that are trading in this block would be trading according to this single price clearing so if you're trading eth against Bitcoin in this block you can basically get your exchange rate by just looking up the two values here and that defines what is your exchange rate in this in this block and so this idea of uniform price clearing is very tightly coupled to the idea of um not executing trades sequentially one after the other but batching them together and executing them in one single batch so now I want to talk about how we at Cal swap have built a batch auction system on ethereum we've been live for a year and a half now and yeah you can actually achieve this with everything that ethereum offers today and just six simple steps the first thing that we need to do is we need to stop people from sending raw ethereum transactions because that's just a fundamental limitation of the protocol layer today you cannot when a user signs a raw transaction you cannot open up this transaction batch it together do anything with it the user signed it so it has to be executed at is but trading can also be done on an intent based really what you do when you when you sign a transactional unit swap you're just saying I want to sell token a for token B at a specific limit price and so what we do is we collect users user trades as trade intents rather than as raw transactions and we collect them over many different token pairs so we basically have this multi-dimensional order book of signed trade intents which we then combine with the entirety of on-chain liquidity that exists on ethereum today so all the amms you know about all the RFQ systems you know about and that together creates a thick Market we saw earlier that amms are really responsible for the thickness and so by adding user orders to the to that liquidity pool we have the first criteria which is a fake Market we then go ahead and now trying to find a settlement in which ordering doesn't make any difference in which all at least all user trades are executed according to one single price clearing Vector where each asset just has a single price and so basically we want to find a uniform price clearing and we also need to find a concrete execution path so basically meaning where do the tokens flow so that demand Supply equal and basically that we reach an equilibrium in this case for example the maker token that the first user wanted to sell would flow directly to another user that user would sell their usdc maybe on curve to die and then sell it to give it to the third user and so we can in so-called ring trades mix and match amms together with direct peer-to-peer trading with the only basically the only credit the only constraint that everything has to happen at least everything between those hands has to happen at this uniform price Cream now the problem is that this poses a pretty hard optimization problem it's basically an NP art problem because we're acting over multiple Dimensions not just on a two-dimensional order book but this problem can be quite well approximated or the optimal solution can be quite well approximated if we just maximize the total user Surplus user Surplus is basically the price Improvement you get on the user's limit price so the user was willing to buy either at thirteen hundred dollars and you were delivering it at 12.50 you would have given fifty dollars of surplus to that user and if we sum all the surpluses up together we get one value which we can optimize for and by having this optimization Criterion we can now dispatch this hard problem to a network of what we originally called solvers now we're starting to call it batch Builders we're basically tasked to try to find the most optimal solution to this problem and they could employ it very different strategies or heuristics here we saw the the settlement from the from the previous slide but you could have a solver that just goes and tries to settle every single user trade with the most liquid amm on that pair but by virtue of having this approximate approximation Criterion optimization Criterion we can now rank the different solutions and find the one that settles the user trade at the best possible price and then that solution will get chosen and the proposal for that solution gets a protocol reward and so we kind of moved into a consensus scheme where the leader selection is not based on work not based on stake but based on optimality the UI looks very much similar to what you might be used from your favorite amm front end but here's an example of a batch that we saw I think around 20 days ago where two users were trading in the same so we can see there's one high-level ethereum transaction but in that single transaction we have two people Trading two trade intents so we have one person that is selling the manifold token and another person that is buying the manifold token and the first thing to notice here is that both people were executed at the exact same clearing price whereas if they had gone through a more traditional Dex mechanism one of them would have to go first and get a different price than the second one in this case it was actually better to be the second because the prices the the trades were against one another so you want to First have the the other person move the price in your favor and then trade but basically by matching those at a single uniform clearing price we removed all the games that the people in the batch could have played against one another and made the system more simple fair and safe to reason about the other thing that is cool is that because these tokens were traded exactly in the opposite direction which is what we call a coincidence of once you want the exact opposite of what I have we actually saved about forty thousand dollars in trading volume that we didn't have to send to UNI swap in sushi swap because it could be settled directly peer-to-peer so here we have one person buying 40 000 UCC and one person selling uh 48 000 usdc and so in the specific example we actually not only got fairer pricing we also got a structural price Improvement that only batching people together and trading people peer-to-peer can accomplish because we saved so much money um that didn't have to go to the amm we saved about 800 in reduced LP fees and we also saved about one thousand five hundred dollars in reduced price impact which stems from the fact when you trade against an amm you're moving the price up and then when you sell against it you will move the price down again and so this is how the the solver competition I talked about is looking at the moment we have um as of last week we had 12 servers in production as of this week we have 13 solvers in production that are competing for finding the best solution so we actually have quite a um yeah quite a quite a um heterogeneous landscape of different different solver entities and then there's a an entire presentation from our data engineer Ghent um that was given at depth coin which I highly recommend watching which compares the performance of cow swap in terms of how much slippage can we actually or yeah how much of the slippage can we actually give back to the user compared to other Dex aggregators in the space and we can show that we have substantially better performance compared to some of the other deck segregators so for the last couple of minutes um I want to talk a little bit about proposer Builder separation or kind of the general direction I think that the ecosystem is taking with regards to Mev and why that could be or why I think this is dangerous and I want to start this by quoting one of my um favorite uh columnists the money stuff BBC writer Matt Levine who is from time to time repeating that uh well cryptos in the business of constantly rediscovering the basic ideas of financial history and why this I think this is true specifically for PBS is well I'll talk about this in the next few slides but you might have seen this graph before and this is basically trying to resemble the Meb supply chain going from a user that wants to make a trade and the trade being something like I want to sell UCC for Eve opening their favorite wallet or opening their favorite dab which converts that trade intent into a transaction and sends that transaction and PBS to a network of block builders the transaction will be something concrete like use uni swap to sell one thousand dollars for example and then those block Builders will try to collect transactions from a bunch of different places and propose a block to the actual leader of the consensus protocol the validator for the next block and so the validator is posed with a bunch of choices or blocks that they can pick from and basically the block Builders are bribing the block proposer to accept their block by doing a Max bidding kind of War this meme is from uh from John I have to give credits um so how does a block Builder actually get the money to to perform this bidding basically block Builders try to extract as much Mev from the transaction order flow they they get and then pay back some or most of that uh in this Max bidding or to the block Builder so what might a block Builder do in order to get an edge in this game well they might try to find deals with wallets to get exclusive access to order flow if they are the only one who can extract value or even just you know pose this transaction for its transaction fee into the block that they propose they have an advantage over other block builders and so it could be that the buck the the flow just stops here wallets are starting to receive an extra income that's nice um they might take that that would be very terrible for the user maybe in a slightly better world the wallets will pay some of that uh returns to the user and maybe give the user something like free transactions or commission free trading at least but if we're in this world then we've literally just reinvented traditional Finance because the Brokers Brokers such as Robin Hood received payment from for order flow from market makers or wholesalers just as such as Citadel Securities jump Jane Street but it's just really a handful and then offer commission free trading to their end users and I'm not saying that pfof is bad actually in traditional Finance you know there there could be there's arguments on on each side but what I try to stress here is that we've learned from traditional finance that this mechanism doesn't work in a decentralized Fashions Market maker there's just a handful of them they're highly regulated without the SEC users would be run over there's basically this law that requires a market maker to give people a price Improvement on top of the official bid and ads that they see on NASDAQ and New York Stock Exchange so you require regulation in order to make this Market safe for the user and it is just a centralized system so if we really want to get ethereum to be this neutral credible neutral settlement layer we cannot reinvent the system and and work with traditional Finance the other thing that I hear a lot is you know this narrative around Mev maximization is great we all have to focus on Mev maximization sure we should minimize but we need to maximize the the  of what's out there and I just want to pose the question of these two philosophies Mev maximization and minimization can coexist at the same time because at least in my mind Mev maximization leads to very dangerous incentives for the participants and creates an extremely hard coordination problem that Mev minimizing protocols such as cow swap need to overcome right now we are in a uh you know you could you could think of a Mev reducing protocol or an Mev reducing Builder to having to play a repetitive prisoner's dilemma where in the current status quo everyone is extracting Mev so everyone is making a little profit if you now wear a block Builder that wanted to operate without the rent from Mev you would deflect from the extraction but you would basically not get any rewards from Mev and everyone else would get slightly more and it would require the entire space all Builders to cooperate in order to achieve a new equilibrium in which we'll actually hopefully are all socially better off definitely the the people that are trading because they're not getting wrecked but even the people that are that are validating I'd argue that in this system can make much more money from transaction fees and just adoption but really this requires all Builders to cooperate otherwise we'll not get into this new equilibrium and what we see today is that basically everyone is focusing on the top left corner and the status quo is to fight over the existing Meb that's in there and potentially even um fight against new entrants that are trying to propose Mev reducing protocols because basically that's eating the searcher's lunch and so my call to action here at the end is let's not focus on Mev maximization and split the pie that's out there because it's tiny compared to what we want to unlock let's work together and grow the pie and try to get ethereum to the next order of magnitude of adoption and with that thank you very much there we go all right hey great talk by the way um so I have a kind of a quick question right like what you've done is you've taken a heart problem you have made it an NP hard problem you still you have an NP hard problem which is like this very complicated auction um which brings a bit of a you know difficult situation because NP hard problems kind of by definition are very sensitive to like people kind of manipulating things and adding Solutions and I think by our call correctly bancor had some interesting issues with this um so why not for example you know one simple condition to have one price for many assets or sorry one price for many dexes with or for one for specific assets is just to do optimal routing and optimal routing is a convex problem you can do it efficiently it's very simple to solve why not just do that instead yeah so I think just having one price per token pair per block is I think what you're suggesting that you know would already be a huge Improvement to the status quo and it would be very computationally feasible to solve I totally agree with that I think the reason why we're aiming for a multi-dimensional batch auctions is to make the life of our solver team harder of course but also to because we we know that or we've seen that the token space is just absolutely fragmented right there's no cost for somebody to launch a token and so even if we just look at US Dollars there's 10 or 15 different stable coins that are all trying to resemble the US dollar and so sure we might have then one token per one price per token pair on USD eth and Di and LUSD eat but we would still have this implicit fragmentation and the simplicit Arbitrage and so we think the most efficient way of like you know of arbitraging the if usdc to die is one one and then eth die is 1300 and ethucc is 1200 we still have like some some imbalance on that right and so I mean I agree with you it's it's a good first step maybe but we kind of already aimed for the for the second you know the Holy Grail is re-fragmenting the um re-aggregating the fragmented liquidity space that we have on ethereum and therefore we went multi-dimensional um great talk I think like one question on kind of like seeing liquidity effect rent between l1s and l2s how do you see it kind of like um like is there a way on how Cole swap could settle like cross layer one like cross layer twos because I think like yeah it's probably like the next problem in like every view yeah I mean yeah we are definitely I think one one problem that we're trying to solve rather sooner than later is to just access liquidity on another chain through the solver abstraction so right now if you're for example trading on polygon a large amount you have to potentially bridge to mainnet trade there Bridge back and that's kind of annoying from a user perspective because we already have this abstraction of solvers that can just happen under the hood right the solver can do the bridging swapping bridging back for you and just you know well needs to let you know that you might have to wait a little bit longer but you as a user don't have to worry about it but then of course the the true Holy Grail is to just have one price per token per block across many chains and I think it's an it's a very interesting research problem which we've where we've touched the surface on but not gone super deep yet um synchronicity between chains maybe you have to do some locking of funds like there's actually Mohammed is sitting in the crowd there's actually a hackathon project at Amsterdam that looked a little bit into this but yeah it's very early days for that so so nothing that you could build on right now thank you for leaks thank you
