CoW 🛠️ How to Add Pre & Post Interactions to your Swaps
ETHGlobal·Wed, Oct 9, 2024, 12:00 AM
Join us for a CoW workshop! From November 17-19 2023, ETHGlobal welcomed developers from around the globe to take part in shaping the future of Ethereum at ETHGlobal Istanbul. Over $600,000 USD in prizes were given away at the prestige Istanbul Congress Center... thanks for an amazing weekend hackers! ----------------- Follow us: https://x.com/ETHGlobal?s=20 Check us out: https://ethglobal.com/ Email us at: hello@ethglobal.com
Transcript
[Music] hello everyone Welcome to our uh Pro C protocol workshop on for the hackathon and we are going to talk about um a feature that we launched recently C protocol hooks which allow you to upgrade um the intent expression language of uh your C protocol orders Beyond just um swap intense uh there's also another um project or another type of feature that we are sponsoring which is programmatic orders I won't have time to go into that into detail but I have a link at the end and you're welcome to stop by our booth and we can explain you everything about programmatic orders as well uh maybe just quick show of hand so I know how much I should spend on kind of the intro part versus the demo part um who here is not familiar with cowo or has you know doesn't really know what it's doing no one everyone knows okay sorry should I speak in this okay um so I can keep it very short maybe just for the recording um so you know KW kind of invent well invented as a strong word but kind of pioneered intense I would say um in in in the Dex aggregator space back in the days let's say 2019 2018 um the way that trading would happen on chain is people would sign a specific ethereum transaction saying concretely I want to go to this Unis swap pool um and Swap this asset for that asset and hand that directly to to the minor which exposed them to revert risk uh they wouldn't get best execution because the price would change maybe to a different venue while they were you know waiting for their transaction to get mined they would pay a failed gas cost and you know the the overall experience was quite harsh if we think that we can we want to get you know blockchain into the hands of you know retail users and people that are not um trading experts uh so C protocol kind of re um shaped that um that that trading model by making users just sign abstract messages limit if you will in its most basic form and handing that over to a thirdparty um Network that we call solver Network which compete for executing uh the user order at the best possible um price solvers can um protect the user much better from Price swings and you know also me than than the average retail user can um it means that the the retail user doesn't need to pay their Network fee in the native token they can just um pay in the cell token um and the other thing that uh this kind of intent based system allows is for batching multiple trade intents together so instead of just matching every user individually one trade per transaction cop allows for the solver to combine different um trade intents and settle them um in one Atomic transaction and this has the nice advantage of allowing to pay uh to to to basically execute Traders peer-to-peer so if you are buying ether and I'm selling ether then instead of going to Unis swap paying 0.3 basis point points of um LP fee and potential price impact we can just meet in the middle and um trade at the spot price uh there's some other advantages of batch auctions which you know kind of fundamentally um lower the amount of me that that we expose in the in the system because we can add constraints to the solution such as every token should just have one price within a batch or within a block and then there's no more opportunity for example a block Builder um or some other entity to uh Buy an asset low and sell the asset High atomically within the same block so we really fundamentally reduce the amount of Meb that we expose Beyond just maybe um what a clumsy user might expose when they set um too large slippage tolerance but okay um well the last Point here actually is that cow protocol is not just um executing batch auctions on individual token pairs uh but instead we aggregate all uh intents that come into the system across all possible token pairs which allow us to find these Coincidence of once or peer-to-peer trades also in multiple Dimensions um and that gives rise to what we call ring trades and helps generally to reaggregate the fragmented liquidity space that we see on chain today if you look at um you know e staking derivatives if you look at stable coins you can find you know multiple different tokens which are basically trying to represent the same underlying asset and you'll have different fragmented markets for those um and by you know virtue of having these multidimens ditional batch auctions we can actually reaggregate that space and and make um give structural price improvements and make the market more efficient but okay that was just basic you know what is what is the idea behind cow swap now let's um talk about uh the feature we recently launched cow hooks um for this uh we let's let's just revisit quickly how the life cycle of a cow order um you know is in the old system where we didn't have or I mean where where hooks were not yet um activated and then we see how it how it changes when when the user actually specifies some hooks uh here for Simplicity we're just looking at a single order batch so there's no coincidence of once and um we basically have a solver that initiates the settlement transaction by calling into our settlement contract the settlement contract then um validates the users's intent making sure that they actually wanted to make the trade that the solver is claiming to execute on their behalf as a second step we transfer the sell tokens from the trader into the settlement contract just so that we have something to work with basically we can convert the sell tokens into the buy tokens uh the solver together with the uh user intent also submits a recipe if you want to call it like that how to execute um the swap intent on chain using the best um onchain liquidity if there were multiple orders in the badge they could also um find Coincidence of once or they could use uh their own private liquidity uh so as a third step the settlement contract execut Utes that that recipe those we call them interactions and then as a last step we transfer out the buy tokens and the trader can um kind of go home with their proceeds now when we hook this cow order basically we have now a hooked cow order there's um One Step before everything we saw so far and one step after we saw everything so far um so before we validate the signature we basically execute all the preh hooks of the orders that are in the PCH and pre hooks are just arbitrary contract calls that can be specified by the trader that is making um that is making the Swap and so as a pre hook you could imagine anything that prepares your swap anything that you need to do for your swap to be valid it could be pulling in some funds maybe from an LP position where you have your token staked it could be you set an allowance just in time you could potentially even you instantiate a contract in a pre hook that is needed for whatever reason to execute the um the trade we then go through the um entire process so everything is is executed and at the end the trader has the option to um specify a set of pre of post hooks that they want to execute in order to clean up after theel themselves uh in a post hook you could for instance uh send your tokens to another contract and have those bridged over you could rake um the asset if you wanted to um if you had like bought an LP position you could restake that LP position um or anything else you want to do kind of you know after um after your trade is executed um just one more kind of diagram over the uh how the just the the kind of control flow um goes for for these hook executions um because that's a question we get quite often uh the TX origin of the settlement contract is the solver who calls into our settlement contract that contract itself holds allowances and fees and a bunch of other balances so it's not safe to let the user kind of execute arbitrary calls from within that settlement contract the user could for instance then you know take funds out solvers are allowed to do um interactions within that context because they're heavily bonded um but we don't want our traders to require um heavy bonds and so what we do instead is we call into a trampoline contract like a a neutral um unprivileged context which then calls into the Target that the user specifies um and so just for you to know if you build a hook your message. sender will be um basically a glorified um multi-end Library um but you know it's kind of an unprivileged uh and shared context across all hooks so you shouldn't really you know um yeah put too much too much faith in it um the hook also specifies a gas limit and then of course the call data so really um basically you can call into any contract and do anything as part of your pre- and post hooks you can also have multiple pre Hooks and multiple post hooks that's important and um we'll go through a live demo um in a minute but just kind of uh very high level how do we specify these pre- and post hooks they're actually just um metadata that is uploaded to ipfs if you have signed a cwap order in the past using metamask for instance you might have come across this app data hash here and you know just looks like random gibberish data but what it actually is is a pointer to an ipfs hosted file where you can find a Json that um gives you more metadata about this order and so for hooks we basically just um Extended this Json and said okay um the user can specify a list of preh hooks and a list of post hooks upload that metadata file to ipfs and you know of course if you do that on a UI that will be all extracted away from the user um and then basically we just put that um that hash on on the order that we sent into the system so now let's uh let's go through a through a live example we also have um a really nice video and step by step tutorial on our documentation page with the code that I'll be using um to make it you know very easy to follow along the um example even has a post hook for now because of time constraints we're just looking to pre hooks um so yeah check that out afterwards if if um if you want to kind of reproduce what we're doing the um use case that I'm going to look at is uh we're going to have an account or nosis chain which has received one usdc but which was a fresh account that has never been um you know seeded with any native token so it's it's literally a completely empty account it doesn't have any gas money so it would be hard in the you know previous systems it's quite quite hard to to do anything with this account until you maybe fund it with some native token from an exchange or or some other wallet which would then link the two wallets together so you know it's kind of maybe for privacy reasons you you've received one usdc from whatever source and now you would like to actually swap that um token without linking that account to any other um account and we can do this because USC implements a feature called permit um so we can well swaps are already gasless we said that earlier like swaps are just sign messages the one step that we normally need when you trade on cow swap is you need to set an allowance for the token that you want to trade so that the settlement contracts can use the token on your behalf and for that you usually need gas so um before if you received some token in your account you needed to se it um but because usdc implements ERC 20 permit we can now actually use a post hook to give an allowance to the settlement contract via this offchain permit signature and make this account swap the underlying UCC without needing any native token and so for this um I've taken the the code from the um from the example and um kind of simplified it a little bit made it made it work um Native Le young nois chain because yeah mayet has been become quite expensive uh lately um but basically what we do here is we um okay in instantiate some some contracts that we need for um C protocol settlement contract the contract that eventually needs the allowance uh the token that we want to buy will be cow the token that we want to sell will be USC and then we just create our order basically selling um selling usdc for cow sending the proceeds into the wallet that we're working with so the the wallet that I just showed you and um the important part here is that we now need to encode the permit call that we want to attach as a pre hook um Erp 12 2612 um defines kind of the the arguments that that permittable tokens take um and those are specified here so we allow the Vault relayer to use um an um the exact cell amount so one usdc on behalf of our user um and we make that permit signature kind of not expire so it can be used for um you could put an expiry date on there but um in this example the permit doesn't expire we then um encode the permit signature into uh call data this is what happens here um and then basically specify our hook the Target contract will be usdc which takes the permit signature and basically sets the approval for our vault relayer contract uh the call data is the um permit call that we've just created here and then we estimate how much gas will be needed and specify that as a gas limit for this pre hook um we then create our app data as I showed you before the app data is just a Json where we now have metadata with a hooks field and then the encoded preh hook um and we then go to our API and get a quote for um our order if it's important to note that this uh gas limit needs to be specified and needs to be accurately reflected because the quote will compute how much gas does your hook need and put the network fee that the solver will incur for executing the hook as a you know extra fee on your order so if you just put a very large number in there then the fee that your user might have to pay um as a network fee might become very high we receive the quote and then um we sign the order that we received and we place it uh on our API so I know this you know was quite quick like I I recommend checking out the tutorial and reading the code step by step um I think we can um run this example here so we can see that um the account on nosis chain is encoding this specific permit hook it is then receiving a quote from our API and it's then placing this order in our API so now if we go and check out um this order we can see that it um is found in um in our back end it is not yet settled will take maybe 30 seconds or a minute um for it to settle but once it does once it does we'll see that it has converted the usdc into cow without requiring um any G here we go we've lost three cents in um in price impact or in like um LP fees on this on this trade and but basically what we see now is that the um yeah contract no longer holds ustc but instead holds hold cow if we go and inspect that settlement um we can also see what is happening under the hood I'm using tenderly to ulate or to to kind of analyze the trace of um what was going on in this transaction and basically yeah what we see here is that um before the signature was recovered here in this in this line we actually executed some interactions before and those are the pre- interactions or pre hooks um and here we will be able to see that um we're calling basically um permit might not be the contract I think is not verified on nois chain but um you here you can see it's a permittable token that some message selectors called on and that's actually the permit message we that is being called um before the uh signature verification and before the transfers from the user address um so this is so much for the live demo um I have only four minutes left um I think on the slide deck I have just a few more ideas on what you could build with hooks so we just walked over the um the permit and um some other ideas are yeah you could unstake LP tokens just in time to sell them you could deploy a safe and so you could really have like a stealth contract that you know has some tokens and and then just in time deploys a safe which could even be a programmatic order so not a standard limit order but maybe a stop loss or good after time or t-up order something more complex and then for post hooks um it would be nice to look at you know generalized Bridge Solutions uh we have an example for bridging togn nois chain and the polygon team also worked on an example for bridging to polygon but maybe we can actually find a solution that Bridges to you know any other chain as a post hook um you could restate your LP tokens and you know the ideas are endless you can really connect your swaps with anything you want to do before and after you trade and with that let me just the gas I will not go through but um let me just end here um these are the references for our docs we have our old docs version one which are a little bit hard to read maybe and we're redoing them as a version two which can be found at beta. d.c.
uh for those we would like to have feedback so please come to our booth if anything is unclear we are still actively working on them we're have a lot of Engineers on the ground that are happy to sit with you and and work together with you on something um we also have documentation about the other bounty we have programmatic orders um and then here's again the QR code for the tutorial on Hooks and now I have like three minutes for questions Ben could you just briefly describe the difference yeah so programmatic orders is um not doing anything before or after an order it is this so to me hooks extend the intent expression language of cwap to allow you to do more things before and after you trade whereas programmatic orders allow you to be more dynamic or programmatic in a way um about what the order the actual swap you're trying to do wants so in the traditional system every swap is a limit order so I really have to say sell this token for this token at this price with a programmatic order I can now let the solver or any other entity propose um a concrete swap to me and all that my smart contract needs to decide is do I want the swap yes or no so instead of making a concrete swap proposal I just need basically an acceptance function an acceptance Oracle that says given this trait do I like it or not and so this upgrades your you know what type of swap you want to do the intent expression language for what type of swap you want to do whereas hooks allow you to do anything before and after so it's kind of the actions um the action space is expanded can then you combine yes and very much any other questions yeah yeah test net suggestion is um I I mean we are on gly and so girley would work we don't we are trying to get on seoa but it's not it's not live yet um I personally like to test on nosis chain because with like you know $ onear you you you can basically test for the entire week and uh it works quite well because your pools have more liquidity there's more protocols and it's less you know maybe unexpected Behavior whereas on no on girly I sometimes feel um you know things it's just play money so so it's hard to find like deep liquidity and other things yeah it's very cheap to test agnosis yeah um but yeah gir agnosis is what I would suggest I think osis also has bounties so maybe you can combine some bounties if you test CH examp like not like uh so it depends actually on your chain so interesting agnos chain all Bridge tokens Implement permit if I understand correctly um on ethereum mainnet it's just the I would say the more modern tokens um but I think any token that has been launched recently supports it um or if they don't then it's kind of Clowny but yeah it's it's only a subset of us20 that's that's correct cool um if you have more questions we have our booth um in the main hall on the right um we have a lot of as I said Engineers on the ground to help you hack and uh I'd love to see what you're building thank you very much
Automatic transcript — names and jargon may be misspelled.