New Ethereum talks, every Monday. The week's conference uploads by event, in your inbox.

Loading player…

Unstoppable CoWs 🛠 How to leverage EIP-1271 to place all sorts of smart orders on CowSwap

ETHGlobalMon, Oct 9, 2023, 12:00 AM

Join Felix Leupold from Unstoppable CoWs for a workshop titled "How to leverage EIP-1271 to place all sorts of smart orders on CowSwap." Thank you to everyone who joined us for ETHBogotá 🇨🇴 and helped us kick off Devcon Week. With over 1400 attendees from 62 different countries, ETHBogotá was our biggest hackathon in Latin America ever! ----------------------------------------- Follow us: https://twitter.com/ETHGlobal​ Check us out: https://ethglobal.co​m Email us at: hello@ethglobal.com #ethereum #web3 #blockchain #eth

Transcript

foreign [Applause] [Music] hello welcome everyone um my name is Felix lopard I'm here giving the talk that actually my colleague Nick was supposed to give so apologies if it's not as smooth or rounded as he would have given it um and in particular we're going to talk today about ERC or eip1271 and how we can Leverage The the smart order smart contract order signature concept for building all kinds of really cool use cases on cow protocol um I hope you guys are roughly familiar with cup protocol we are a metadex aggregator where users Place orders just by signing off-chain messages and then those off-chain messages get batched together and sent off to a network of solvers that compete for that order flow and try to find the best possible solution um for the user orders matching them together in what we call Coincidence of wants whereas the name Cow protocol comes from and yeah protecting users from Mev and giving a significantly better user experience but that's kind of the background happy to talk also at the booth over like the advantages of cow swap in particular today this talk will will cover uh really ERC 1271 smart contract signatures and we'll first cover a little bit the basics how Cloud protocol orders work usually and and why this doesn't really work for smart contracts we'll then talk about the easy case of smart contracts that just want to place trades on cow Swap and then go one step further where we explore this concept of smart orders so even more than just placing a boring old limit order smart contracts can actually Place really cool and advanced concepts and there's a little demo at the end and there's some code in the GitHub repository if you're willing to hack we have a five thousand dollar bounty on the best integration of a smart contract order into Cloud protocol for the sackathon so it might be worth your time to check out this repo at the end and and start hacking so let's begin with the basics how how do orders in color protocol work um here you can see the general struct that describes an order it's really like what what you would expect on a when you're making a trade you have to specify a cell token a buy token you can send the proceeds to some other receiver you have a sell amount and a buy amount that's basically your limit price you have an expiry date you have a fee it can be a seller or buy token so you have a bunch of fields that represent an order on cup protocol and then the way that it normally works with externally owned accounts with your metamask is that the order that you're willing to sign gets hashed according to um the Erp I think said 712 is the is the EIP gets hashed into a um into a typed typed order hash and then you with your externally owned account can go ahead and consign this commitment to the order that you're willing to place and the way that signatures work with externally owned accounts is by using some fancy math ellipt curve cryptography you know you don't have to really understand it in detail but um basically you're you know taking two points on a curve and then um have your private and your public key and with your private key you can basically prove that you're in possession of that private key without revealing it and what ends up um being generated is this triple RSV it also doesn't really matter what this specifically means just there is a way of how externally owned accounts can use their private key to attest that they are actually willing to make this trade now the problem is that smart contracts cannot do that because smart contracts on ethereum don't have a private key so they cannot do any ecdsa they cannot um you know sign an order given elliptic curve signatures so another signature scheme is needed and that's why the ethereum I mean Community has created what is known as EAP 1271 I think Nick is really strict on that it's technically an ERC and not an EIP because it doesn't need any protocol changes but the basic way that smart contracts can prove that they are okay with um you know with with something happening the way that they prove that they are validating a signature is by just implementing this very simple method is valid signature and that method takes a bytes 32 hash this is basically the order hash we saw in slide 304. and then an arbitrary byte array of what can be interpreted as a signature and that by the way can really be anything it can be some eoa signature that maybe is the owner of the smart contract or maybe a delegate of the smart contract that is signing the hash on the smart contract's behalf it could be just more information that the smart contract needs to then maybe check an oracle or check some other state to decide if it's actually willing to accept the hash that is being passed into but basically what you can think of this off is a Boolean response am I okay with this hash or am I not okay with this hash now the return type is not Boolean it's some magic bytes forward value which has some some yeah detailed history of why it's not just a Boolean but you can think of it you know it's a method that says yes or no given a hash is the Smart contract okay executing this um the signature and so yeah basically if we go back to the order struct we um again take our concrete order that we want to sign we compute the hash and then the thing that gets passed into our smart contract is we basically invoke signer is valid signature with that hash and whatever we decide to pass in as a signature and so how do smart contract wallets implement this so for example Argent or nose is safe you know pick your favorite smart contract wallet they don't have private keys so they also need to implement ERC 1271. and the implementation can be specific to each individual wallet um you know some wallets might use a might require the user to First send a transaction that says I am a testing that this hash is okay so you might think of it as like a bitmap that for each hash you have a is signed or is not signed and then is valid signatures there's checks for the hash if the the bit is set to yes you could also just blindly trust signatures from certain domains so you could say if um you know certain I guess member of an ens Community or whatever has signed this then I'm okay with it or the way that the nose is safe and I also think Arjun does it is you could um you know go smart contracts usually have an owner they have multiple signers you could just use those signers as delegates and verify the signatures by just checking have enough signers have enough EOS that own the smart contract while they've signed for the hash and this is for example how diagnostic does it so concretely because it knows to say if it's also a project very close to our hearts we care a lot about having calcium work nicely with nursesafe and the way that that the signature verification on their end works is again you have this order struct that gets compressed into a hash that you need to sign and then um yeah the save interface has like a certain again named struct for for its signatures where then each owner can basically use their externally owned account to create a good old um 712 like a good old eoa signature a good old you know ecdsh signature and then what the save does it basically Waits um for enough owners to have created their own individual signatures so if you have a three out of five say for example you need to collect signatures from at least three owners you concatenate all those three signatures together and then the safe will say is valid signature true true if enough signers have signed for that hash so this is again just a recap of how it works for the safe you collect all the signatures you encode them into bytes you concatenate them together Insight is valid signature it just deconcatinates them and then checks for each signature are you an owner if so increment the count of owners that have signed and if at the end the number of signatures that have been signed by owners is greater than the threshold is valid signature returns true and this works in cow swap Nick implemented a little script that you can use to actually place these gasless orders from your nose is safe already today here's here's a proof on Gurley that this works so you can actually use Nosa safe today to place gasless or you know without having to pay gas orders into into cow swap and that's already quite cool that's that's you know a very good use case of of ERC 1271 but there's even a sorry yeah go ahead uh so it's gasless because um you can use your eoa to just sign the message and hand that message off to cow Swap and then Council will pay for the gas basically so you use sign you basically sign with your UA that you want your smart computers you know so save to trade one ether for 1300 and then you send this message off chain to our API and our API will then send it to the solvers and the solvers will take it and settle it on chain and they will still take some fee from your sell amount so it's not that you can trade on call Swap and don't pay anything right like you will still pay whatever the gas would be in eth but in US dollars from your sell amount it just means you don't your UA doesn't need to have doesn't need to have any eth um right you can just use the signature you don't need to fund your UA okay so this is already pretty cool to use your safe with a gases manner to to do trades but then the real power comes when we um you know you know I don't know any plan to have this climax but in the beginning you had decks then you had decks aggregators then you had cow swap as The Meta decks aggregators and today we're going to introduce smart orders the next Paradigm in this uh you know crazy climax okay so um the idea of smart orders is that you implement ERC 1271 similar how you just saw this that the safe does it but you can do it with arbitrary logic you don't actually have to check that there is a some signer that has signed for it using an UA you can theoretically use arbitrary logic you can check in an oracle that you want to investigate that you basically you're always okay to trade if the price is better than what chain link reports or some other logic that that is completely independent of of any actual UA signature and so the way that these smart orders usually work is you create a smart contract you deposit some tokens into it and then that smart contract implements this is valid signature method in some way or the other so yeah you have custom on chain logic and that's it and so one example that we're gonna go through today in this Workshop is a good after time order good after time orders only become valid after a certain timestamp so you can basically place an order today that becomes valid tomorrow and you could place a second one today that becomes about the day after and so you could use good after time orders to implement something like a daily cost average strategy for example and right now in the very native cow protocol order format this is not supported we have an expiry date valid two but we don't have a field valid from and so it would require to change the native cow order format it would require to update the contracts and so it's you know it's very painful to add this to Cloud protocol in its current form but you can just write a smart contract order that basically implements this Behavior and the way you would do that is you just Implement is valid signature in a way that it checks what is the current block time stamp and when that block timestamp is past a certain Target block you say is valid signature true and if it's not you say no it's not yet valid and so you can place this order into the order book the order book will constantly try to check is this order now valid or not and once it becomes valid it will automatically um you know take it into the current batch and ship it to the solvers and it will get matched automatically so let's walk over the code and we'll also see it in real life in a minute but let's just walk over the code that's that's required here so this is um this is actually not this is like this the construct for a good after time order but at this point it doesn't do much at this point it just takes in the Constructor and Order hash that you want to be executing and then if um is valid signature just checks that whatever the settlement contract is trying to execute is actually the thing that we have pre-signed here so this is not yet doing good after time this is just the very basic format you you basically say here's an order hash that I'm okay executing um and then as well as signature just checks that we are indeed executing that so now um let's add cancellation because with good after time you also don't know maybe the price changes a lot you know from today to tomorrow and your order might no longer be satisfying its limit price so you might have a way you might need a way to actually cancel this order and get your funds back out so here's just you know some random scaffolding or some small scaffolding to allow the owner of that contract to regain the tokens that they have deposited into it and then this is actually the part that adds the good after time into the to the smart contract so we add this valid from field we set it in the Constructor saying that this order is only valid after a certain maturity date and then in the is valid from implementation we just check that block.timestamp is passed valid from if that's not the case we revert and if it's the case we set this magic value which basically means we return true the other thing we need to remember is that the smart contract needs to have the the cow protocol settlement contract approved so the way that cloud protocol works is it needs an approval from whoever is authoring the trade so that it can actually take the the sell tokens from the author of the trade and then send it back the buy tokens so we need to set an approval and then we're good to go this is the entire code I think it's like you know 30 or 35 lines of smart contract code and you have a good after time order implemented the one thing that we added here is a factory because right now every user that wants to implement a good after time order needs to deploy their own instance of that order and so Nick also built a a small Factory contract that anyone can now call with um yeah basically a raw order struct and and some sort just to make it not replayable and then that factory contract will actually deploy the actual good after time contract and also do the transfer of the in amounts and and basically return the the the the order ID that has been created it's not super important you don't have to implement this if you want to use uh um smart orders you could just deploy every order um again and again and maybe some orders don't need to be deployed if you're looking into building an amm or so you just need to deploy it once but if you have something that every user would have to redeploy maybe a factory contract makes sense all the code is in this GitHub repo we don't have to really go through it in in depth but yeah so this is then the the general the general flow um the trader would approve the good after time Factory contract call the place function which then does all the magic basically creates this good after time order instance uh transfers all the tokens in sets developed from parameter and the order is ready then we just have to wait for the timestamp to be reached um so this okay yeah this is then the last step that is needed right now um our back end doesn't automatically identify when an order is placed on chain so you also have to tell our backend separately hey there exists an order please start tracking this order and please start checking once this order become valid um start settling it we are working towards making this step Obsolete and just having an event emitted inside the smart contract that our backend can automatically pick up but right now you still need to um call our um yeah call our API here here's how it will hopefully very soon look like you don't have to call our API anymore then you just emit an event and our backend will automatically pick up that there's a new order in the system that needs to be tracked okay I think this is maybe now good for a demo this should be demo time now so um we have the repository here um I I had to clone it um just because it was made for your rinky B and and rinky B doesn't work anymore so now it's made for girly and so if you check out my GitHub and check for the depcon 2022 smart orders repo there's the readme with the four steps you have to run um but basically what we are going to run is the place order script which does exactly what we discussed so in this repo you will find the the good after time in the contracts uh repository here you'll find the good after time orders which has all the smart contract code that we showed I'm happy to talk about the details of that also at the booth if you have specific questions and then what we're going to do right now is we're going to place one of these orders um we're going to sell with and we're going to buy cow on Gurley and we're going to set the field valid from to be starting now plus two minutes so basically when we place this order it won't be valid but two minutes later it will become valid yeah yeah you can do I mean you can do you can you can Fork from it you can start um you can start from scratch like uh really like I mean this is just one example I'll have a few more examples on the last slide but basically and we can also use the remaining time to bring some ideas I really think there's like an endless amount of design space that you can do with this anything like that's basically expressible in solidity okay so we're going to place an order using some old account that I that I have um that is going to create an instance of this good after time order and then the script is gonna print out the order ID of the good after time order so we can track it in our in our car explorer okay so this is the order and we should check the time 153 um so in here we can check the order it's open but it won't match right away because it's not yet valid in fact we can actually check our API and we can see that right now the auction is empty so that there there's right now no orders that are allowed to be settled and this is because is valid signature returns reverts in the current state because the block time hasn't Advanced far enough yet and so now we need to kill a minute and a half of time to see this uh become valid another packet yeah um so the back end basically has a set of orders that attracts and it just checks are these orders valid like do the um order creators have enough um balance have they given allowance um in this smart contract order case is the is valid signature does it return true and so it builds periodically every 15 seconds it builds an auction with all the valid orders that are currently in the system and sends it off to this network of solvers who would then go ahead and try to settle the current batch and the solvers return back kind of their proposal of how they would settle the batch and then the back end decides basically measures what is the best solution in terms of price Improvement for the user and the one that had the biggest price Improvement gets the right to then execute that settlement on chain and so um let's start looking at the API this should in a few seconds we should start seeing the order here because it will have become there we there it is so this is our order it's now valid so solvers can start trying to figure out how to settle it and then hopefully um this will turn into a field very soon suspense foreign seconds never felt so long no no this isn't so the order has been yeah it has been filled this there this ERC is five years old it just got finalized last this year or so like it it had some minor changes really annoying minor changes which made it not backwards compatible but still you know it didn't change fundamentally um but it got finalized this year so we're now pretty certain that that this is going to last uh for the for the future and yeah so basically here now we can see the order got filled um you know we get a nice Surplus this is like our normal cost of orders would work um but yeah basically you had this this logic that made it good after time here's some other cool ideas and just like you know just the tip of the iceberg of what um we could Implement with it uh stop loss orders is is one other example so stop loss orders means you're not buying when a certain minimum price is is uh or sorry you're not you're not buying um you're not buying so well no but you can always place it basically you normally you're selling eth when the price goes up right you're saying I want to sell ether when it's like at 1500 that's a normal limit sell order a stop loss order would be I want to exit my eighth position I want to sell it if it goes below 1 000 because then I think we're all doomed and we go to zero so stop loss orders allows you to basically um take the other side of like cut your losses and and exit if you feel like oh now we're about to go to zero and so you could use an unchain Oracle it's a chain link or something to check what is the current price of course some trust in that price Oracle is kind of you know needs to be considered in the design and then decide I say is valid signature yes if um the price is below that and then I'm basically trying to exit my position and cut my losses Advanced good after time use cases would be this um daily cost average or time weighted average pricing where you basically allow for example a dow to sell or buy tokens little by little over the course of a month um but you can also think of other you know cool ideas you could for example Implement an amm in a smart contract order where the smart contract has two balances two tokens and then a constant and you just allow trades as long as x times Y is still larger or equal to K and this way you've built an amm into Cal swap which gets settled at the same uniform clearance prices as all the other users so you would have built an amm that can actually capture Surplus from trades uh you know unlike uni swap where basically you get settled exactly on your on your x times y equals K curve and cow swap you would have amms that can actually capture price Improvement and capture Surplus uh but yeah basically most of these smart contracts don't require any special integration if you're the thing that you're expressing becomes a little bit too complex you might also have to talk to one of those solvers so that they can actually understand what do I have to what do I have to do in order to activate the smart contract order um but for the vast majority of use cases you know you don't even need that you basically just have this on-chain contract that follows ERC 1271 and it will just work out of the box um so this is kind of the the wrap-up of the talk and I will go to the references the first thing that we talked about of how to place a gasless orders using notice safe is in the safe cow order repo from Nick and then the adjusted uh smart good after time order prototype is in uh in my GitHub repository and yeah if you have any more questions as well let's let's talk at the booth and I think we have maybe a few minutes for questions yeah maybe like I don't know one or two questions if you have anything at the top of your head but um yeah yeah it's essentially I mean yeah so basically I mean cow swap's main value country proposition is that it protects you from Mev so basically a keeper you have to pay the keeper a you know some fee that it basically um it takes your order and then it might take it at your limit price you you're not guaranteed and the keeper system necessarily that you're getting price Improvement whereas in cow swap you have everyone that is in the batch gets the same uniform clearing price um and by virtue of having to solve a competition and the more price improvements the solver give to you the more likely it is that they win you have this guarantee that there's actually somebody fighting for you getting the best price and um and yeah and but basically yeah there's there's other Concepts as well we personally think that or I mean we as a company think that that cow swap is a uh you know very good way for Dallas to easily you know of course somebody has to write this down um DCA order but then it can be reused by many dials over and over again and the dial can just say okay we want to buy we want to build a position over the next month let's do it automatically whereas right now you have to build this um I looked at the at buntec did a very nice example of such a keeper contract but you basically have to customize it for your company you then have to find a some flashbots Miner or like some Searcher to actually execute it for you so I think there's some user inter like user experience benefits and then also this idea of you know benefiting from other retail traders that might take the other side so basically a view where you earn and you wanted to do a buyback of yfi tokens you shouldn't be doing necessarily the Wi-Fi buyback against uni swap you can just absorb cell pressure whenever a user wants to sell a Wi-Fi why don't you just buy it as a as a solver so they sound like some of the ideas cool um we are on the Upper Floor in the corner on the left we'll have people on the booth most of the time and happy to also help people that are interested in hacking this where we have again uh two bounties uh five thousand dollars for the best smart order or smart contract order integration and then another five thousand dollars for the best UI integration built on cloud swap can be combined of course if you build a really nice smart contract order with a UI then of course you can also um have two both bounties which are five thousand dollars each and uh yeah happy hacking and hope to see you around thank you

Automatic transcript — names and jargon may be misspelled.