Felix Leupold: CowSwap – Tackling the Shortcomings of AMMs #399

12 Jul 2021 · 1:09:34

Epicenter hosts Brian Fabian Crain and Sunny Aggarwal talk with Felix Leupold, a software developer at Gnosis, about CowSwap and its approach to fixing shortcomings in automated market makers. Leupold explains how CowSwap's solver model works, how it reduces the effects of MEV for traders, and the protocol's upcoming integration with Balancer V2.

Speakers

Topics

Transcript

this is app center episode 399 with guest felix leupold welcome to epicenter the podcast where we interview crypto founders builders and fault leaders i'm brian frogman crane and i'm here with sunny agarwal so today we're going to speak with felix leupold he's a software engineer at gnosis he's working there on a project called cow swap and gnosis has done a lot of very innovative work around amms decentralized exchanges there's been various iterations and cow swap is

kind of the latest of those so we're going to speak about that speak about amms more generally but before we get to the episode we'd like to tell you a little bit about some of our sponsors so one of our first sponsors for this week is solana so solana is a next generation blockchain with lightning fast blocks and fees that are less than a cent per transaction right now scalability is one of the biggest challenges facing crypto obviously and you know solana i think is one of the best when it comes to really solving scalability by tackling the throughput that a single blockchain can tackle and they've done this through a number of really interesting innovations so go to solano.com epicenter to learn more

and this episode is also brought to you by exodus so exodus is an easy to use wallet that supports hundreds of different crypto assets it has native applications for like all the platforms including ios android desktop app and it's a fully non-custodial wallet so you know you can keep your keys and that's very much at the core of their philosophy they've been around for a very long time use a lot you can also directly swap different coins uh from v next this so go check it out go give exodus a try so it's at exodus.com and with that let's get into episodes so felix thank you much for joining us today maybe just tell us a little bit like what

has your personal journey into uh blockchain bin and how did he end up working at gnosis and on uh cow swap it's great to be here thanks for the invitation i joined gnosis as a software engineer about about three years ago and i kind of directly started working on decentralized exchange protocols within gnosis and before i'd been following the ethereum ecosystem for a couple of years i was at uh defcon zero actually or there was definitely one in london where there was a very inspiring talk for the project that we are now working on on batch auctions to be used in blockchains actually there but then i was working as a software

engineer at facebook at the time working on end-to-end encryption and privacy so always kind of interested in cryptography and then yeah about three years ago i took the leap and and joined gnosis and since then we've been working on well applying batch auctions to as a trading mechanism to the decentralized exchange landscape and and that's what cow swap our latest product uh is doing in a kind of me and fun fun way you know i i had this joke that i used to make a year ago where gnosis is building all the fundamental infrastructure of ethereum except for prediction markets uh so i mean obviously since then i think you guys actually did have released some uh prediction market projects uh

products with you know like you had the it's called open dot so tell me about like gnosis you know especially for like a lot of the longtime listeners of the podcast you know last time we had martin well last time we had martin on was actually for circles but you know the previous time was about you know still about prediction markets and so it seems to me that like gnosis has taken this big shift away from the prediction markets and working on every other important piece of infrastructure for ethereum so can you tell us a little bit about how did that why did that happen yeah so one thing that is maybe not super intuitive is that decentralized exchange mechanisms are a fundamental part of actually bringing prediction markets of efficient prediction markets onto the

blockchain and so in a way like how i would see it is that gnosis has actually is actually done implementing the you know basic prediction market contract where you have positions that then at some point when the unknown event in the future can be resolved perform a payout to whoever holds the outcome token that happens to represent the correct event but then there's kind of two hard parts in prediction markets and one of them is the oracle problem which i've noticed we've always taken a quite an agnostic approach towards we said kind of well you can plug in any oracle that you'd like in our prediction market smart contract framework so really like it's up to you what you would like to

use as an oracle and then we've traditionally kind of focused more on the second hard problem for prediction markets which is actually making these outcome tokens liquid and tradable before the event happens before the certainty has arrived and well you can just redeem them in the underlying smart contract and this is where where i would say gnosis protocol or today the application on top of this protocol and called cow swap started because in prediction markets you tend to have very fragmented or illiquid tokens and so having a traditional kind of classic continuous limit order book is usually well it's very tough to get a to get a dense or

to get a to get a good bit ask spread for events that maybe not a lot of people care about like your local soccer league or something something like that and so when thinking about prediction markets and how to bring that to kind of mass adoption we also had to think about well effective trading mechanisms and that's where kind of our idea of batch auctions or in general discrete discrete time mechanisms um started so you know you guys iterated over a series of many different types of decentralized exchanges like you guys worked on like a lot of batch auction systems you had this gnosis protocol i feel like maybe cow swap is one of the first times when you guys are really diving into amms specifically or you know maybe that's the first time you know because you guys

are one of the first ones to ever come up with amms back like four or five years ago why this return to like focused on amm based infrastructure or dex infrastructure so what we've realized with gnosis protocol version one which we launched about a little bit more than a year ago it was in april april 2020 was that with kind of a closed system or kind of in well yeah with this the gnosis protocol v1 we were not open to tap into any of the other kind of on-chain liquidity sources that there are so one fundamental thing about batch auctions is that they are kind of a method like or they're kind of a mechanism that is that

is not open necessarily to the public so it's well it's okay let me let me rephrase this actually um so so one thing about batch auctions is that it requires a certain auctioneer or some form of in our system it's called solver to actually settle the auction on chain and so while um this auctioneer could theoretically tap into any of the on-chain liquidity sources it's not like uni swap for example where any other protocol can tap into that specific liquidity source so for um diagnosis protocol it's not that the orders that are placed as part of our batch auction are publicly available on like this atomic liquidity pool um and can be tapped in by anyone

maybe just to take a little bit of a step back and can you explain on like on a high level like what are the different attempts that nurses have made in creating decentralized exchanges and what are the key you know learnings you've had of things of like oh this is really working or this is like not the right way to go yeah for sure so the the very first auction mechanism that we've built was probably for our own token sale back in 2017 uh where instead of doing an english auction or a fixed price token sale we went with a dutch auction because even at that time kind of martin the ceo and stefan they kind of foresee this problem foresaw this

problem of front running and basically when there is a good that everyone wants and basically a price that is increasing uh over time it well basically is is a mechanism that is that is prone to whoever has the best kind of making well the best hardware or the best uh algorithm to to to get in as fast as possible and so for the gnosis token say what they wanted to do is actually have a descending auction so they started at a very high price per token that was decreasing as a function of time and that mechanism is called a dutch auction which worked extremely well for the gno token sale and so one of the ideas was even though we were already thinking about batch auctions at the

time well let's just implement dutch auctions as a product and and give other people access to use this kind of auction because it has been working so well for our for our use case and so we've built um dutch x as a product and we kind of thought well this might take three to six months and so it's a nice interim step the first product to launch it turned out to take much longer much more than a year i think and yeah kind of the problem that we saw that when when applying dutch auctions kind of on regular trading is that people are not comfortable with kind of these long wait times so in dutch x i think an auction was running up to 12 hours it was expected to clear within six hours and

people just are not really really not comfortable to you know start a trade at you know some point in time but only know that their trade will be executed at a certain price a couple of hours later and the other thing that was really hard about dutch auctions was the concept of teaching people that the price you would be getting is a function of the time and not a function of what you're actually you know of a bid or something that you're putting in at the moment um and that concept was was really just hard for people to to to grasp and understand um and so other market mechanisms that were more direct where you actually could execute a swap directly and once your transaction is mined you have your you have your tokens and you can

use them freely um gotten got an edge over over over dutch x and so from there on we then circled back and said well we had this more general idea for how trading on the blockchain could become more fair and less frontrunning prone and just that would be within a single ethereum block there should never be two assets traded in two separate transactions with a different price because well blockchains are inherently discrete in terms of every 12-15 seconds we get a new block and then all the information in that block is kind of happening at the very same instant in the very same millisecond nanosecond fewish and so having these price time priority mechanisms

on chain like uni-swap for example seemed problematic to us at the time and so we started looking into batch auction with uniform clearing prices just briefly you you called it the price time priority mechanism can you explain that yeah so the maybe in layman's term would be first come first served but basically that even within a single block the ordering in which your transactions are executed matter because the underlying mechanism uses some state within the system so in unisop amms it would be the reserve values to give you a price and so if somebody trades the first

index of a block they see the current reserve value and they change them with their trade and so whoever gets second will get a slightly or sometimes significantly different price and that kind of opens the the door to these to these games that are being played on the on ethereum today with with maximally extractable value where if you have a trade that would um affect unisop amm significantly and you actually are you happen to set high slippage tolerance so you're actually okay with receiving a significantly worse price what somebody can do is they can just try to get right in front of you to move the current amm price all the way down to your reserve to your limit

price then your transaction will go through at the at your pain point basically at the at the last price that you're willing to accept and then that other person uh could just reverse their own trade and well because they initially bought at a low price you traded so you raised the price they are now selling at a high price and uh buying low sell high is is usually a good strategy and yeah that's kind of what i mean by price time priority now let's talk about solana we all know that scalability is one of the most important issues facing the blockchain industry today the solana blockchain has been engineered from the ground up optimizing for performance and scalability the network supports thousands of transactions a second with 600 millisecond block times and over 500

different validators it's not a shorter blockchain but a single blockchain hyper optimized for performance and that makes it easy to maintain composability between the apps on solana so they work together seamlessly the solana ecosystem is growing at a rapid pace and it's a great place to build your project and get involved with the community so go to solana.com epicenter to learn more so you mentioned dutch x so i don't remember the launch i think we actually also did the episode at the time on epicenter about that now dodge x didn't really like get the traction uh of course it makes a lot of sense right that the user experience is just like it's not what people are used to right to put in training and wait six hours or

wait 12 hours and they don't know what happens and is it going to clear or not where does gnosis protocol and then kyle's web come in and maybe also like what's the relationship between gnosis protocol and cow swap so gnosis protocol in its first version was cutting down the expected trading time from six hours to five minutes um so we would collect orders over the course of a five minute period which we could would call a batch and then we would settle it we would settle all the orders that we had received in that batch at a uniform clearing price now and that's kind of what i tried to say earlier with this idea of being closed is that all the orders that are

submitted into a single batch can basically could in version one only be settled against one and another we had no access to kind of any any other on-chain liquidity and what i would say is now kind of the breakthrough mechanism agnostic protocol version two is that in the settlement we can trade orders against one another kind of peer-to-peer if you wish but we can also take whatever we cannot settle within a single batch and what we sometimes refer to as the excess amounts and settle those excess amounts against any on-chain liquidity that we can find which allows us to significantly reduce the batch sizes so before we said well we need to wait at least five minutes to have

enough trades in one batch that that we can make a settlement that actually something can happen but now because we can basically if there's no overlap in in trade intents we can still just go and settle with the best on-chain liquidity we can cut batches much much shorter and so at the moment we are waiting for 30 seconds to collect user orders but theoretically we could cut this down and actually have a single batch per block and by this hopefully at some point ensure that people that are trading in the same block will get cleared at a uniform clearing price and then yeah the question was about the relationship with cow swap english protocol um so the i would say the trading mechanism uh using batch options with uniform

clearance prices that is kind of the core value proposition and the core idea of gnosis protocol so the trading mechanism in itself and then cow swap is our first application built on top of that protocol so it's our first trading user interface that we've built and we've taken a lot of inspiration and even some of the front-end code from unison version two just to make it a very playful and very um easy to use experience because that was also something we learned from nurses protocol v1 is that well people were not getting the hang of our user experience and so kind of for v2 we thought let's start at the exact opposite let's take something that works that everybody understands and

let's try to make the minimum amount of changes to it to make it work with a new dex mechanism um and so this is what caused basically is playful and meaningful so when you say cow swap you're referring specifically to sort of the front end portion of it and the actual sort of batching algorithm and everything that would fall under your classification of the gnosis protocol now right so gnosis protocol works basically with off-chain signatures which are just expressing intents to trade for for the people that are using it and cow swap is just one source for these intents to trade so if you

if you create an order on cow swap you're actually not creating an ethereum mainnet transaction but you're actually just signing a message with your private key and then that message is handed over to nosis protocol which allows these so-called solvers that perform the settlement on your behalf to then enforce things that the protocol wants for example uniform clearing prices aggregating orders together but theoretically these orders could come from any front end they could be coming from dex aggregators they could be coming from metamask directly from balancers front end like we are really agnostic for the source of these intents to trade so maybe we should start to dive into a

little bit about so so this whole cow meme like you know it's an acronym for coincidence of wants uh can you tell us a little bit about what is this entire concept and what what what is household really trying to solve here with this coincidence of wants so while we think that this kind of concept of having batch auctions with uniform clearing prices is our long-term vision for how trading should happen on on ethereum one thing that to us is a very clear use case or a very clear argument why this is actually a better mechanism is that today two people trade the same asset in opposite directions so let's say i'm trying to buy eth for usdc and you're trying to sell eth for uscc then we would both be trading against

let's say the most liquid amm on chain in the very extreme case we would be even maybe trading roughly the same amounts so the price of the two assets we are trading would not even change because you're just moving the amm up slightly and i'm moving the amm down slightly but at the end of the block the amm hasn't changed but it has still generated fees for whoever provided liquidity for it so in in some sense the amm acts like a sponge on chain like an intra block sponge that is not really needed because if we meet in the same block at the same time we could just trade directly against one another i give you my eighth you get you know i get your usdc and we just basically trade otc or peer-to-peer if you wish and so this this

phenomenon when two parties um want the exact opposite of one another i want exactly what you are trying to sell and you want exactly what i'm trying to sell that is what is called coincidence of wants in the literature and so coincidence of one's short is a cow and you know we're looking for something that is easy to to build a community or build a meme around and so yeah cow swap seemed like a very good very good candidate for this so can can you explain how cow swap works from a user perspective so you said that you're you know you're not trading directly on chain right now creating an on-chain transaction but you're kind of like delegating you

signing a message and sort of delegating this trade execution so like how does that work right so the first thing that we need to get users to do is instead of um kind of signing their own ethereum transactions and and executing the trades by themselves in a single transaction on chain we need to actually get them so if we want to be able to batch them together and create these cows we need to get users to pass on this right to settle the transaction on chain to a third party and in the context of mev or this maximal extractable value this actually makes a lot of sense because if you give the miner your transaction directly today

they're most likely going to try to extract as much value from that transaction as possible because well they have no incentive to act in your best interest you're assigning them a transaction you're giving them a transaction fee and they can artificially order that transaction in the block as they as they would like and so from user perspective it actually makes a lot of sense to think about well who should like giving your transaction to a third party that can protect you from minor extractable value in and of itself is is something that we see more and more people doing with the adoption of mavgath and flashbots and this is also kind of a prerequisite that we need to even implement batch auctions and so and so this is kind of the high level idea on on cow swap is that when you go and

click click the swap button you won't actually see a meta mask pop up with a transaction but you'll just see some message that you're signing which basically says i'm willing to trade this token for that token at a specific limit price and there's also a deadline involved like up until when this trade is valid and then this kind of intent to trade is being sent to our back end which collects all the orders that are happening kind of roughly at the same time and then about every 30 seconds we have one of these passes that or one of these runs that we call a solver run where a bunch of independent algorithms or even well at the moment they're mostly run by us but eventually they should be decentralized and run also by different

parties but a bunch of different solvers look at the intents that have been submitted to the back end basically listing what do people want to trade at the moment and then they're trying to find the best possible way of matching those and of course first they will they will check can i match subsets of these trades directly with one another because in that case i can save amm fees i can save private market maker fees i can just make the most effective trade directly peer-to-peer and then they will check kind of whatever is left and look at all the on-chain liquidity that is available and try to find the best path for kind of the leftover the excess um to settle that using the best exergator or using

a portion of it with balancer a portion of it with curve kind of theoretically the protocol is completely agnostic to the underlying liquidity that is being used then all these solvers kind of come to a come to a result like this is my proposed solution and then we have a ranking in place that compares the different solutions in terms of which solution serves the user best and that serves the user best as something that we can go into in a little bit more detail but just kind of to come to an end here um the the solver that provides the best solution based on the criterion is then eligible to actually send this transaction on chain and because it's a third party it's a professional entity that that entrance admission is also done the

user is much better protected from mev uh by that professional solution submission because it can use things like mavget or flashbots directly it can watch the mempool for race conditions and see oh now my solution is no longer valid or i need to reorder the mempool in this way so that the solution can go through and it can also set very tight slippage bounds on the underlying protocols that it uses even in and of itself even if you're just trading by yourself a professional solver will likely protect you much better from mev than you could with your with your metamask extension i think that's a very interesting piece to dive into of like you know this ranking what is the utility function that the solver

are trying to optimize over what is is it to minimize the fees that users will have to pay is it to decrease the slippage that users have to pay and when you say like you know what's best for the users i mean the hard part is here we have a multi-party system and what's good for some users might be bad for other users so how how does the solvers take these into account right um and and just to maybe um pre prefix this we don't necessarily we're not confident that we found the very best solution to this yet and this is ongoing kind of discussion and work in progress and i'm super happy to talk about our thought process and but if somebody has great ideas on how to improve this we're definitely still still also researching this and working with also known researchers on this topic but

so basically the idea is that whenever you have batch auctions so whenever you kind of go away from this traditional continuous limit order book you stop having kind of these traditional graphs if you've seen a limit order book you've probably seen this this graph that kind of diverges almost kisses each other in the middle you have the bit curve and the ass curve and then in the middle there's a little gap hopefully it's very tiny and that is your bid ask spread but they will never overlap because the moment that something would overlap in a continuous limit order book it would just execute right away and the overlap would be gone however in batch auctions because you're collecting orders over time you might have the the situation where somebody is willing to sell a certain good

at a very low price but somebody else is willing to buy it at a very high price and so you have this overlap and kind of willingnesses to pay and the question is how do you how do you find the the clearing price in this overlap that is the fairest and the first kind of metric that that we define is what we call the trader surplus and the trader surplus is basically the difference between the limit order that you placed so let's say you were willing to buy one each at two thousand dollars and then the price you ended up getting eventually so let's say you you if this our solver decided well the price of these is 1900 in this batch so you actually get to buy your one eat at 1900 and so your surplus is the difference between your limit price

and the price that um you actually got so in this case it would be a hundred dollars that that would be your individual trader surplus and now kind of the basic idea was well let's just maximize trader surplus over all orders and let's try to just find the globally maximal trader surplus and that's also kind of what we did in gnosis protocol v1 one issue with that is that you can actually lie about your surplus in certain ways um so you can say this is my limit price and you set your limit price very low and so you can boost your surplus in some ways and then if you combine this with maybe some tokens that are particularly illiquid or where you control all the liquidity some token that you created for example

there are actually ways in which you can manipulate this this mechanism and and and boost your individual trader surplus to make the the best solution choose a path that favors you over other people and so for gnosis protocol v2 what we implemented was a mechanism that also says well whatever prices the the solver proposes um there has to be and that's a concept called envy freeness um there has to be basically if if i decide ether is trading at 1900 and you had your order in you were willing to buy it at 2 000 then it means that i cannot leave your your order out of the system um it means i have to trade your order because your limit price was actually

above the clearing price and if i told you you're not getting match you would say like but why i had a price that was actually higher and so you would be jealous or you would have envy and so the the concept of envy freeness meaning that if we select a price that is better than your limit order we we also have to match you um and this kind of ensures that even with fake tokens i can maybe lie about my personal utility but i cannot manipulate batches in a way that i would basically make you not trade eventually let's get to our sponsor exodus exodus is a fantastic cryptocurrency wallet that strikes the right balance between ease of use security and great features you can get exodus on the iphone

desktop app web app android whatever platform you use it's a non-custodial wallet and that is so critical because what's the point of crypto if you don't control your own assets with exodus you always do they're old school and they've been around since 2015 over 1.2 million users rely on exodus so you know that they've stood the test of time they have support for over 100 different crypto assets and from within exodus you can easily change one different asset to the other they also allow you to buy crypto with fiat and they even have a great offer where you can buy up to five hundred dollars worth of crypto through their ios app and pay just one dollar in fee

so go to exodus.com epicenter and check out their wallet we want to thank exodus for their amazing support of app center with these solvers are there some kind of economic incentives around providing solutions and do you think that a market is going to emerge around this we very much hope so at the moment our intention so basically yes there is an economic incentive and kind of at least probably at the high level we will just charge one fee for orders and that is kind of what solvers will be paid from but just kind of on a theoretically level how this fee should be chosen

because solvers perform the actual transaction submission for you they need to pay gas or and maybe get the minor bribe on your behalf so they actually have a cost for settling your transactions and so we at least need to give them back kind of what you would have paid if you had settled your trade by yourself as a as a high level ethereum transaction and then on top of that we think that we can charge a small very small percentage as kind of a protocol fee and we are not yet entirely sure if this will be just a flat rate on your volume that you're trading or something that we could also do is we could even make it dependent

on the trader surplus that we get for you so we could actually look at what value do we provide for users how much do we improve their limit price compared to what would they be maximally willing to pay and then that is the the real value that is added by the protocol and we could just charge a percentage of that value added um so these are kind of our two thought processes but yeah the um the solvers will be rewarded with um basically with an equivalent of at least what they have to pay in gas on top of some kind of protocol fee for providing the service are they going to be also rewarded based off of like the effectiveness of their solution according to whatever metrics it is and also how are these metrics measured

yeah how do we make sure that people aren't just submitting bad solutions and they're getting like rewarded right uh so there is a bunch of kind of soft criterions that the protocol can also enforce on a solution and if you think about kind of the solvers in and of themselves to become a solver you have to provide a bond to the protocol so that in case if you if you misbehave if you're for example censoring people's orders or if you're maybe even just well submitting your solution although you didn't provide the best objective criterion if you're just basically not respecting the rules of the competition then the

protocol can slash you and there can be a penalty that can then be paid back to the users that took harm from this but how do you detect that someone is it an automated thing or is it like some sort of a governance-based thing so at the moment it's uh it's solvers are kind of trusted by authentic the code is is written or reviewed by us so we we are just enforcing that that no malicious behavior happens by kind of auditing the code but um of course in the near future we want to make this permissionless and just happen decode i mean this is off chain right so you cannot actually see what code they're running right i mean it depends if we are running the solvers then we can look at yeah sure but in the in the very like

in the kind of our decent our road to decentralization would be to have a protocol dow enforce these slashing well these slashing events but also enforce the the rules under which slashing can happen and so one of the rules that this dow might agree to enforce for example would be that no clearing price even though if it maximizes trader surplus may be a way maybe off from let's say the most liquid on-chain liquidity source let's say unisof v3 etheusdc is kind of your reference price for what's the price of ether and you could say well no even if your solution is the best you cannot submit a solution where your price or your price is off the reference price by more than let's say 0.3

or 0.5 meaning that if you want to settle a trade that is far away from uniswork liquidity you need to at least use as much liquidity from units to move that price onto the your target basically onto that that bound in which you're kind of free to to diverge and then of course just by the sheer fact of having a competition of having multiple servers submitting solutions against one another uh if another solver finds a better settlement one that well gives more surplus to the traders than that that solver is chosen to perform the the settlement so that's another protection mechanism just by having this competition

doesn't this just shift the mev from the miner towards these solvers like you know now the solvers have the ability to extract mvv essentially because you know if they have the ability to censor transactions for example they can like move the slippage price you know the execution price to be wherever they want and there's probably a lot of mev to be extracted by doing this so there's definitely a censoring problem and so kind of another part of the decentralization is to have a data availability layer with consensus on which orders are part of a of a batch at a certain time and so that the dow can then also decide well this solver didn't use this specific order although it would have improved the

price and that user basically now has envy because well they had a better limit price they would have liked to trade at the settle at the clearing price that was announced um but envy freeness would not was not guaranteed um and just like a kind of hacky way of achieving this data availability for us would be to lose like to use like a either a test network or a low fee kind of side chain uh to to kind of broadcast these orders at the same time but of course eventually um we could also have the dow run kind of a gossip network and kind of get to consensus which orders form a batch at any any any given time at that point why not just build a new l2 for this sure that so in a way i mean people were asking also if gnosis protocol isn't

in some form in l2 just because we have this off chain order book and then we settle like we do a transaction on chain we kind of don't really see it as an l2 because we are really tightly integrated with layer one and every settlement moves funds from one account to one another and we're like directly using the liquidity of of layer one at least in this in this very first version um or in the second v2 but in this in the current version we could envision a future in which we also have kind of a miracle root of balances inside the protocol and then it would probably become more of like a layer two solution we're actively looking into how we can use

liquidity on other layer twos and combine them and maybe become like a meta protocol to aggregate and get arbitrage freeness even across different l2 solutions but yeah that's a very technically challenging problem we haven't found a great solution to that how do you uh sort of compare the when it comes to this algorithm like this coincidence of wants mechanism is only taking the the flow at any given time without taking into account any of the like liquidity that exists into these pools so so for context one of the things that so i'm working on a project called osmosis and we're doing a lot of batching stuff as well uh but and so we actually have a very specific notion

of like the goals of our batching mechanism which is to create fairness and how we define fairness is if you take all the orders and randomize them infinite times the execution price is the average of all of these like random permutations this basically removes the meb so that there's no ordering games that can be done because no matter what order this is the most fair price possible but to do this we actually have to take into account the available liquidity in the pool how would you compare this versus something more like what you guys are doing with coincidence of wants i think i think what maybe the solution that you ex described solves kind of more practically is the is this

this issue of compute computational feasibility of solving these kind of batch auction as a multi-dimensional order book discrete order book with with multi-dimensional uniform clearing prices which in itself is a very hard problem um so like even harder than np complete and definitely uh very challenging to solve for a large amount of orders that being said kind of we are we have pretty good algorithms that can that can find reason good solutions or even like optimal solutions for still a reasonable amount of problem sizes at least for ethiopia today and kind of under that premise to us it feels that having no ordering whatsoever basically giving every trade within

a block within a batch the exact same uniform clearing price it's just the purest kind of mechanism or the fairest mechanism in itself um but i mean i i'm more than happy to also research the project that you mentioned a little bit more it sounds like a very practical approach to kind of also get um yeah basically order independent execution prices one of the reasons i like trading on an amm instead of an order book right is when i'm in an order book i always have this like notion of like oh am i getting screwed by being on this order book you know i why am i putting these market orders i should be putting these limit orders instead and like you know just all this mental overhead and what's nice with an amm is like market orders only i submit it and i'm

pretty sure i'm going to be getting a reasonably fair price and the slippage bound is just this mechanism to like you know it's a fail-safe mechanism where it's like all right if if something's really out of whack you know have my slippage like kill it but with with this model it feels more like once again like it's an order book where now i have to be very cognizant of the maximum best price i'm willing to accept because you know then you take that into account in your surplus calculations and it's like now i feel like i have to start gaming and thinking about like okay what should i put as the surplus should i overestimate my surplus just so i can get a better estimate uh return for myself and this just becomes a harder cognitive

load for the users have you run into this being an issue i think one thing that maybe the the average user doesn't doesn't realize as such and maybe also in the in the kind of purest form of how unisoft should work uh sure they they are basically placing a market order but under the hood what they're actually doing with the slippage tolerance they are in fact placing a limit order and kind of with mevgeth or and with mev and flashbots kind of rising and just the fact that miners are playing these games at the end of the day you are you are making a mistake today when you place an order directly on unit swap with a large slippage tolerance because you are actually going to get your order filled exactly at your limit and not at

a fair market price and so that that's kind of why why we think well we can we can take the unisfork trading experience where it feels like we give you a quote this is your market order you have somewhere in the settings the slippage criterion that maybe i don't know five percent ten percent of users understand what it actually means and it feels like you're getting a fair market price and we want to give the same experience to people on cow swap which is why we have kind of done the same the same user experience and under the hood just in the very basic case and that's today is most of the cases you will be the only person that is trading in a batch and we will actually go and execute your batch against the best on-chain liquidity and when which then kind of resolves

back to you having chosen to trade on unisop directly with this you know market or fair market order just with the difference that you go through the solver which can actually protect you from mev and which can actually under the hood make sure that while you personally are fine with a 0.5 percent slippage tolerance the actual transactions that hits ethereum just uses zero point one percent or even zero percent slippage tolerance uh because it makes sure that the transaction is not front runner but not front running your your intents and then one other thing that we are working on which of course is a big endeavor but the best thing about a mechanism would be if it had like a true revelation principle where we could prove that it's the best strategy for all players to just give us their true willingness to pay and say well

here's my limit price and there's no games to be played by over or under reporting your your um your preference um but yeah that that is ongoing research and ongoing work and and something that the best mechanisms have and we hope we can get to this um also with by choosing the right objective criterion by maybe doing some more simplifications to the mechanism but fundamentally having better options where true revelation is the optimal stretch one so there's a new version of kyle swap coming up where you're integrating a balancer can you explain a little bit like you know what what is the change that's coming up and how is that balancer integration gonna

work so basically the balancer version 2 works with the concept of a vault and so you can you can trade just the old way that you do at the moment also with uni swap where you basically take your balances that are in your wallet and you swap them for any other token but you also have kind of former professional or more frequent traders the option to actually keep your balance inside the balancer protocol and have the balancer smart contract manage your wallets erc tokens for you so it's basically just a matter of custody to do the tokens are they in the storage of your wallet or are they in the storage

of the balancer vault contract but you can still of course use them as you please and this concept of having these internal balances actually makes um trading at least for frequent users significantly cheaper because they can save one entire erc20 transfer which costs a significant amount of gas depending on which erc20 token you use and so um yeah balancer version 2 will for frequent traders hopefully be more gas efficient than traditional amms and then we basically spoke with balancer and we really liked their v2 architecture and they really liked the idea of using coincidence of ones and giving better prices to the user and well basically we decided to do a

partnership and integrate the balancer vault as a source for where your balance come from can come from when you trade using gnosis protocol so they can of course still come from your wallet from kind of any smart contract or your eoa but they can now also come directly from the internal balance that you have inside the balancer vault and now if you use the balancer amms through gnosis protocol that in itself will be even more gas efficient because we don't have to trade funds from the source wallet into our settlement contract then perform the swaps and have to pay them back out we can actually leave everything inside the balancer vault and perform the swaps directly just using balancer and so all things

equal if balancer has the comparable price than uni swap solving your order viagnosis protocol the uh amount of gas that would be used should be less for balancer and so they will have a structural advantage okay so that that makes sense right so basically what you have is like today you know a cow swap is is plugging into different liquidity sources and that's still going to be the case in the future it's going to be more gas efficient if you have your tokens already in bouncer and so then can safeguard costs and and i guess we'll be uh also driving some liquidity there i think it's also more gas efficient if

you're using external balances just because balancer performs better for multiple swaps um kind of if if you have to go from let's say dial to width and then from width to gno that is more efficient inside the balancer world because it just happens in one call and so also there and the tight integration that we have with the balancer world will make these kind of swaps more gas efficient than using let's say uni swap or curve one question i had back about the mev side was so like okay so we have this like high amount of trust in the solvers to not do mev so you know i spent a lot of time thinking about how to solve muban ethereum as well and the challenge i kept running into

was i can build a channel that's like very muv resistant which is kind of what you guys are doing with cow swap but if people can just bypass that channel and jump in front of like so what's to stop someone from you know looking at the giant batch trade that's happening on cow swap or on gnosis protocol and seeing hey there's this front running opportunity let me just hit you to swap or hit balancer directly let me just front run the batch itself so unless you have an amm that only allows execution via cow swap how does that did you actually solve anything from mev just as a kind of side effect like a side note we are actually thinking about having some form of amms that are

kind of not private but that are kind of privileged for gnosis protocol but at the moment this is not the case for sure we are only hitting um on-chain liquidity which in that interaction by itself is front runnable as you said but there again kind of the mev protection in cow swab is is twofold the first protection comes from these coincidences of once or this peer-to-peer matching where we trade one person directly against one another and there the level of mav protection is basically similar to when you have these zero x request for quote kind of orders when you do otc trading because the solver agrees on a price um and the price doesn't depend on your ordering within the settlement and then it just sends the amounts back

and forth and then it is that interaction itself it doesn't matter where it happens in the block it is not front runnable so by creating more and more cows and getting people to actually use gnosis protocol together we can fight mev kind of in a collaborative form but then even for this access and you're totally right this interaction in itself is prone to front running um however there our idea is that solvers are professional entities which can for example run meb guests themselves and make sure that they submit their settlement in a bundle and for example even just take everyone that is not trading on nurses protocol let's say everyone that is still trading on sushi swap or uni swap and they can arrange those trades in the perfect manner so that our settlement

actually fits in kind of nicely and all the ones well basically that that we use all the other liquidity to to to make our trade more profitable um but even just in the base case when you have a professional solver that says i'm setting a very tight slippage on this interaction um it actually becomes very hard to to sandwich you um if you're setting zero percent or 0.1 percent slippage on your on your unisoft interactions it's still possible if you're if the price moves extremely in your favor while your transaction is waiting to be mined because then what was zero slippage at the time of submission becomes actually a significant slippage but we are actually running continuous analysis of our solver address and except for one case where we

basically introduced a bug and did a very bad trade ourselves um there has not been any significant sandwiching opportunity i think the total sandwiching is a bit more than a thousand dollars on um more than 100 million dollar trading volume so it seems to be working and and end users seem to be quite well protected from mev even if they are not trading in these coincidence of ones so two more questions about the algorithm one is what you do when let's say there's a more demand in one side so there's a million dollars i want to buy some asset and only 500k that wants to sell it the 500k that ends up hitting the liquidity pool do you give an equal price to everyone in the cap that like

participated in the cow exactly so one of the and it's theoretically something that we could even enforce on the smart contract layer um that we say the the price at which every single trade is settled is a uniform clearing price there's just one price no matter which which trade you are um just the way it's just a technicality at the moment a malicious solver could submit a batch or could submit a solution where they actually give slightly different prices to different orders but that would then of course also be a slashing criterion and so yes um we effectively give uh everyone that submitted their order via cow swap the same clear price if they're trading the same asset and then the other one was one of the

things that i remember you guys were very focused on especially in the earlier version of the gnosis protocol was this idea of ring trades and ring trades are you know they're like multi-dimensional cows right like multi-dimensional coincidence of wants instead of just saying hey here's a bilateral one can we create like you know someone wants to sell bitcoin for e someone wants to sell eth for atoms and someone wants to sell atoms for bitcoin there's no bilateral currencies of one but if you take all three together you have a cow is that something that the cow swap handles right now it does and it was actually a relatively big design decision at the beginning we were thinking about starting easy just building kind of a giving people uni swap but better prices

this was kind of one of our first ideas but just you know we'll always write to uni swap but if we have a coincidence of once we'll just take that um but then we did some analyzers and we actually found that the amount of potential coincidence of ones we can find by looking at not just the direct you know buy and sell token that people send but actually by dissecting their trades into this you know little sub hops so for example if you're trading curve for you for usdc today you will go via weath in the middle so you'll actually do two hops and by dissecting all the traits that happen in a just a random block today into their you know atomic paths we are actually able to generate a much more like a significant larger share of coincidence of once and

so make the protocol much more useful and that's why we decided to actually go this route of multi-dimensionality and say um well we can trade any token for any other token in the same batch and then make sure that we model them in kind of a graph or kind of a multi-dimensional order book if you wish and and make use of these rings if they happen and then one classic example for this would be stable coins where we have a highly fragmented market of like 10 or 15 tokens that all represent the u.s dollar and so there might always be very liquid liquidity between each stable token pair but then you might be willing to buy your project token with usdt and i might be willing to sell my project token for usdc and then we can actually form a ring

by using that let's say curve liquidity that connects usdc and usdt quite quite efficiently yeah one thing that will be really nice is like you know on a lot of dex aggregators i wish they had an option to let me choose like you know i don't really care whether i'm trying to sell something i don't care whether i'm getting usdc or usdt i'm just like give me whichever one has a better price and that would be like a sort of a nice feature that i guess you're saying is that it's somehow somewhat built in already into uh cow swap which is cool right that is actually another kind of an idea that we had very early on and it's far from being implemented but the um the concept of kind of giving a bit more specialized preferences of what you would like to receive and

one extreme case of this would be basket orders where you say look here's a here's a bag of tokens i have and here's like a bag of tokens that i want and then you know i don't really care what gets traded for what or but just you know at the end of the day i would like to change my position that i have today into some target position and yeah just the idea of having more expressiveness in your orders is something that we would also like in the future to bring to to ethereum wouldn't this massively decrease the uh returns for lps because like you know lps are sort of very heavily dependent on fees to you know subsidize their il but now if you're trying to starting to match things against each other

the lps are not really earning and you're not giving the fees to the lps isn't this like is this almost like potentially existential to like the sustainability of a lot of these amms and to a way you know on top of that it's like i feel like there's this notion where yes it's the lps are not being executed anymore so maybe they is it kind of weird to give them fees if they're not being executed against but i think the existence of the lps is what's enabling this trading to even happen like the fact that you're able to find these coincidence of wants the only reason people are trading right now on these dexes on chain is because they know that those liquidity providers are there as a backstop and so isn't it fair to somehow

still give them some sort of fees to like compensate them yes so maybe i mean maybe maybe we can start by just saying like who are the winners and who are the losers in this model um in a way so there are some some some people that profit from this protocol and some people that should not profit and kind of the people that we would like to see profit are the actual traders the retail traders that are just wanting to swap tokens for one another and today pay significant fees to liquidity providers or then even arbitragers or front-runners or basically people miners that eventually extract them and so on the losing side well we have abi treasures if if we actually get the majority of people trading on noses protocol given

that there's no at least risk-free arbitrage within a single block because every every trade gets kind of the same uniform clearing price we will take hopefully a lot of kind of the value that is extracted today from arbitragers or provided to make the market more efficient depending on which site you take and pay that back to to retail traders the other part of course is liquidity providers on on amms today and potentially there well there is a chance that there will be a significant cut to to to their um trading volume however i think at least for now in the foreseeable futures gnosis protocol in itself relies heavily on the liquidity that is being provided by these amms and so by making trading

on ethereum more fair and actually more accessible to retail users you could also argue that you know in a way i mean most of the time we will trade against the best on-chain liquidity source just because coincidence of ones while they exist they are still not the majority of kind of trades that that happen on chain um and then the other kind of counter argument maybe against that is that at least with uni uni swap v3 you could argue that that even today you can see there's there's i think one address last week that has been called out for adding liquidity just at the current market price when it makes sense when they see a lot of volume being traded in the order book and then they add very very concentrated liquidity just at that specific market price to basically capture most of the

fee and that also goes at the expense of kind of the normal passive uniform liquidity provider that just has a high range that they passively provide liquidity to and there you could say well if this exists via me we get then it's it's kind of a sign that there is kind of this there is this effective way of matching people directly against past against active market makers on chain via a more effective mechanism than you know trying to sandwich uh adding liquidity removing liquidity in between some trades and so we hope with nosis protocol v2 we can actually be that layer um and well if this kind of you know if there's people that want to take the opportunity and and and reduce the amount of trading that or the amount of fees that get paid

to these large-scale passive liquidity providers then that would happen regardless of moses protocol v2 or not and we are just hopefully the most effective way to match active market makers and retail traders on chain so where is cow swap today and like what's the what's the road map ahead yeah so today we have kind of we have three main liquidity sources integrated natively into our kind of batch enabled algorithm that can find coincidence of ones which are uni-swap version 2 sushi swap and we're very close to finalizing our balancer integration and so well that is kind of the the base

liquidity that we have in our own native solver but of course we see with kind of the rise of other liquidity like unisport b3 launched recently and there's other protocols coming up we kind of need a more diversified landscape for solving and it some you know it takes us more time to integrate new liquidity sources than it takes new projects to provide protocols and so one of the things that we've been doing recently that we've been doing recently was to also integrate dex aggregators into our solver landscape and so kind of as a fallback or as kind of another way to solve instances we now um use one inch power swap and matcha to just check what is the best way of

solving our trades individually in case there's no cow there's no coincidence of ones what would be the best trade what's best pass to match them on chain um and so well even if there's a cow but you know just other protocols have a much better price then our ranking ensures that each order is actually traded at the at the best possible path and so what this leads to cow swap um also being at least at the moment is kind of a meta dex aggregator where you can place your order and you can place it you know at some point in time let's say you're a multi-sig or a dao you could even place your order a couple of you know it could take it could take you potentially hours from initiating your order to collecting all the signature or completing the vote to actually

submit your order and then the best route that gets taken on chain if you're using power swap or if you're using univ3 or balancer that can then be decided by our solver infrastructure and so um yeah cow swap is well kauswap and it can trade peer-to-peer and match your coincidence of once but it's also in a way a meta dex aggregator that makes sure that between one inch power swap matcha whatever other sources we might integrate in the future you always get the best price at execution time do you think that uh aggregators will try to build their own in-house versions of this so i'm thinking about like for example one inch right like or i feel like dex aggregators are this like very hard to defend business model right

where like it's it's very hard to find a moat and i and so you know i think that one inch tried to do this via their moonie swap product and you know they're like all right can we like build a lot of liquidity in-house and that will be like one of our remotes and it turned out that didn't work but it seems like building their own cow mechanism would be a very powerful way for them to like you know they have all this order flow already and to build a moat using their order flow how are you guys incentivizing these aggregators to like be part of gnosis protocol rather than build their own in-house versions right maybe uh one thing to to start off um we

it is actually not trivial to be a dex aggregator first of all um modeling all the liquidity that there is catching up with like all the protocols and then even just solving a single order optimally is not it's a solvable problem but not a trivial problem so uh being an exergator is definitely not not a trivial task as we also learned and and just trying with our kind of cow enabled more advanced mechanism but that being said we would of course very much like one inch or power swap or any other team that already has some expertise in this field to provide solutions to gnosis protocol and the fact that the protocol in itself enables hopefully soon permissionless solvers but for now i mean for now we kind of

hypnosis now actually um white lists the the available solvers we we can we can integrate a one-inch uh version that can settle multiple or powershot version that settles multiple trades at the same time and tries to find cows within them and that would be wonderful they would be great and we would love to work together with strong teams in the field to make sure we have this act of competition and well the reward would be coming from the protocol fee that is that is hope that would be that would be earned and the reason why teams should be doing it is that as you said it's it's very important to get this order flow and in order to really maximize the value of the user we need to get a significant chunk of order flow from ethereum routed to this

protocol so that we can actually maximize the amount of cows and the amount of value and so we think that by just providing this base layer protocol and then incentivizing um parties around it that can actually be beneficial it's a win-win situation for for protocols as well rather than trying to build their own yeah just in-house in-house matching just on their own order flow so zooming out maybe a little bit before we wrap up so the the entire space of amms and like on-chain decentralized exchanges has exploded you know not long ago there was like you know ether delta which was this automate or the book

based exchange on ethereum that you know was had terrible user experience that didn't really have volume and you know it was almost sort of like looked at oh well these these amms they are decentralized exchanges like far away can't really compete with centralized exchanges well then uni swap and others came and had like tremendous success and now we are seeing like you know an explosion of different things so so two questions on that first of all with regards to order book based exchanges versus amms i know there is for example also the ftx and serum team right where they're building this order book based exchange on solana and there was also binance

chain building an order book based exchange on on finance chains and both of those uh teams basically argued that well the reason why all the book-based exchanges aren't like working on ethereum is because you know transactions are too expensive blocks are too slow uh but you know really it's a superior design to amms and you know once these technical issues are sort of resolved and like you know that will prevail like what's your stance on that do you agree or like what do you think is the future of all the book based exchanges yeah it's definitely a very interesting question and also a question where we where our opinions differ i would say within the team we're not we're not at all sure how it will play

out what i think what we what we might see in the near term is more expressive amms and kind of where it's not just x times y equals k but i mean curve has started to go a little bit in that direction balancer as well but just having people express their preference curves as functions is definitely an innovation that has aided passive liquidity providers to play a game and to play to take part in this game and to provide liquidity on ethereum so i don't think we will see this go away in the in the near future to the question whether fundamentally order books are more effective i would say probably yes and this is kind of also why we are working very hard to prove that point

and to try to show that well we can maybe eventually get even some active market makers to provide liquidity off chain on nose protocol to even further remove the necessity necessity to go to on-chain protocols and so basically create some more cows even if they are somewhat artificial but yeah i mean it's it's definitely uh yeah it's a very interesting space and we we kind of try to take an agnostic approach to it and especially within those protocol being able to tap into all on-chain liquidity we kind of want to stay away from the the protocol the amm innovation space and just say you know whatever is the newest and latest and greatest protocol on chain we will just integrate it and we are happy to take whatever

um people come up with and um and just amend it with coincidence of wants and batch options and try to make give the user the best price at the end of the day i think it'll be really interesting to see how that works out because you know i i think with osmosis we have a slightly different thesis where we think that like mev reduction and amm design are like and like the protocol design are like so intertwined that it is a little bit hard to disentangle them and it's hard like you know you can build the best mev reduction system when you have control over the amms themselves but um i i think it's really interesting to see how how the like sort of approaches will sort of differ and like and i i think there's value in providing what's like you know

if there is already so much liquidity that exists on like a lot of these ethereum decisions so what's the best mev reduction that we could provide on top of them there's also one other aspect about amms that we think is really interesting and that kind of plays out maybe between unison v3 and balancer v2 at the moment which is kind of cooperative liquidity provision where there's competitive liquidity provision and yeah so on balancer v2 you're still joining a pool everyone in the pool gets the same amount of fees and even though you can like there's maybe an oracle that decides what is the current best fee to be chosen it is still kind of you're all in it together you have like a cooperative approach to things whereas in unison v3 you now have these independent kind of well liquidity management strategies

and it becomes a bit of more of a competition like is your strategy better than mine or is mine better than yours and we kind of we kind of would like to um take this cooperative approach and kind of apply it to traders instead of liquidity providers and basically say well if you go on cow swap you're putting you you're cooperating with other traders you're coming together to this marketplace where we act in your best interest where we try to match your peer-to-peer if we can and if we can't then we will give you the best sunshine price that that we can find otherwise so we want to get this cooperative kind of mindset um to to to retail trading as well yeah cool well thanks so much felix for joining us it's really cool to hear about cowswap and to you know sort of see where the

protocol is going to go so thanks so much thank you for everyone it was great great to talk to you guys thank you for joining us on this week's episode we release new episodes every week you can find and subscribe to the show on itunes spotify youtube soundcloud or wherever you listen to podcasts and if you have a google home or alexa device you can tell it to listen to the latest episode of the episode podcast go to epicenter.tv subscribe for a full list of places where you can watch and listen and while you're there be sure to sign up for the newsletter so you get new episodes in your inbox as they're released if you want to interact with us guests or other podcast listeners you can follow us on twitter and please leave us a review on itunes it helps people find the show and we're

always happy to read them so thanks so much and we look forward to being back next week you