HackMD
  • Beta
    Beta  Get a sneak peek of HackMD’s new design
    Turn on the feature preview and give us feedback.
    Go → Got it
      • Create new note
      • Create a note from template
    • Beta  Get a sneak peek of HackMD’s new design
      Beta  Get a sneak peek of HackMD’s new design
      Turn on the feature preview and give us feedback.
      Go → Got it
      • Sharing Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • More (Comment, Invitee)
      • Publishing
        Please check the box to agree to the Community Guidelines.
        Everyone on the web can find and read all notes of this public team.
        After the note is published, everyone on the web can find and read this note.
        See all published notes on profile page.
      • Commenting Enable
        Disabled Forbidden Owners Signed-in users Everyone
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Invitee
      • No invitee
      • Options
      • Versions and GitHub Sync
      • Transfer ownership
      • Delete this note
      • Template
      • Save as template
      • Insert from template
      • Export
      • Dropbox
      • Google Drive Export to Google Drive
      • Gist
      • Import
      • Dropbox
      • Google Drive Import from Google Drive
      • Gist
      • Clipboard
      • Download
      • Markdown
      • HTML
      • Raw HTML
    Menu Sharing Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Versions and GitHub Sync Transfer ownership Delete this note
    Export
    Dropbox Google Drive Export to Google Drive Gist
    Import
    Dropbox Google Drive Import from Google Drive Gist Clipboard
    Download
    Markdown HTML Raw HTML
    Back
    Sharing
    Sharing Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Note Permission
    Read
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Write
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    More (Comment, Invitee)
    Publishing
    Please check the box to agree to the Community Guidelines.
    Everyone on the web can find and read all notes of this public team.
    After the note is published, everyone on the web can find and read this note.
    See all published notes on profile page.
    More (Comment, Invitee)
    Commenting Enable
    Disabled Forbidden Owners Signed-in users Everyone
    Permission
    Owners
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Invitee
    No invitee
       owned this note    owned this note      
    Published Linked with GitHub
    Like4 BookmarkBookmarked
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Writing a Cowswap Solver > I have been playing with Cowswap API and solvers for some weeks and I wanted to share my findings. Fortunately, I had the cowswap team helping me answering questions. > I hope this post helps you setting up a solver environment and working through the steps as fast as possible. ## Idea I wanted to start with something super basic to understand all the moving pieces. In my example, I am going to build a solver for Yearn tokens. User has a token, let's say, `USDC` and wants to buy `yvUSDC`. Right now, Cowswap would need a LP `USDC/yvUSDC` to settle the trade, but what if the solver understands how to deposit into a yearn vault? :thinking_face: ## The Big Picture Cowswap infrastructure is a lot of services running together, which is a bit intimidating at the beginning. Here's the ELI5 of how cowswap works and it's entities. ### The Orderbook The orderbook is a service that uses a database to stores trades. When you go to https://cowswap.exchange/ and create a trade, the website uses the orderbook API to add the trade to the database. If the trade is ready to go (it might be created but missing a signature), it will be listed in the `solvable_orders` endpoint. ### The Driver The driver is a polling service that queries the orderbook API for orders and tries to settle them using the different solvers. The driver calls different solvers by using an http API. The driver prunes the orderbook `solvable_orders` and sends orders, in json, to the different solvers. If a solver finds a solution to the batch, the driver executes the trade on chain. ### Solver The solver is a standalone service which receives a json with orders and tries to settle them. The settlement can be a list of actions which are executed by the settlement contract on chain. **Warning**: I assume you have rust setup correctly with rustup. ## The most basic setup Let's start simple. Let's first run a solver which solves a json we send by hand with curl. Start by cloning https://github.com/gnosis/cow-dex-solver cow-dex-solver will give you a good idea of how a solver service is architectured. You have a method called `solve()` which receives the batch `orders` and returns a `SettledBatchAuctionModel` aka a solution. To run, exec: ``` cargo run -v ``` Once the service is running you can start throwing jsons at it. I started reading the code and playing with different json setups calling: ``` curl -vX POST "http://127.0.0.1:8000/solve" -H "accept: application/json" -H "Content-Type: application/json" --data "@/Users/user/dev/cow-dex-solver/sample.json" ``` You can get some inspiration from prod examples here: http://gnosis-europe-gpv2-solver.s3-website.eu-central-1.amazonaws.com/index.html#data/prod/2022/01/ Make sure to test what happens when there is a COW :cow: ## Settling Real Orders Once I understood how a solver works, I wanted to solve a real order. To test this out without setting up the orderbook I used a little trick. I created an order in a production orderbook but I setup an impossible limit order. For that I used the staging orderbook in the gnosis-chain. I deployed a yvUSDC vault, and I created an LP USDC/yvUSDC in Honeyswap. You have different options to create a limit oder: - https://docs.cow.fi/tutorials/cowswap-trades-with-a-gnosis-safe-wallet - https://bafybeias5x3tgdshkhj5umriqze2wioy5mjw4fdo2zzp2sl4pacq7rnwtm.ipfs.infura-ipfs.io/?orderbook=https://barn.api.cow.fi/xdai - You call the api by hand Here's the example I created while testing: https://barn.gnosis-protocol.io/gc/orders/0xcc37de3ba70474948f838e8b4af9c6b66577c08202323a4a3060a645b2918dae2813a7e97fd0bc1b80cb63afe136510d940ddc236208633c I am trading 10 USDC for 91.412 yvUSDC, which of course, will never settle by regular solvers since 1 `USDC == 1 yvUSDC` (price per share is 1). Now that we have the real order, the orderbook will return it in the `solvable_orders` endpoint. To consume it, we will need to use the driver. the cow-dex-solver repo now has a nice README.md with an explanation of how to run the driver: https://github.com/gnosis/cow-dex-solver/blob/219ff56d309416bda0d7be4225b95a96711779f6/README.md#how-to-run-simulations-together-with-the-cowswap-official-driver The way I was it running was: ``` cargo run -p solver -- --orderbook-url https://protocol-xdai.dev.gnosisdev.com \ --base-tokens 0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83 \ --node-url "https://rpc.xdaichain.com" \ --cow-dex-ag-solver-url "http://127.0.0.1:8000" \ --solver-account 0x7942a2b3540d1ec40b2740896f87aecb2a588731 \ --solvers CowDexAg \ --transaction-strategy DryRun ``` A small explanation of the parameters: - **orderbook-url**: points to the gnosis staging version - **node-url** connects to gnosis-chain (VERY IMPORTANT, liquidity sources are based on this) - **cow-dex-ag-solver-url** our running solver instance - **solver-account** An address that has permissions to run txs in the settlement contract - **solvers** just use our CowDexAg instance - **transaction-strategy** DryRun will give us a tenderly link after running If you got to this point, you have 99% of stuff you need to write your solver. Until the trade expires, the solver will always find the crazy limit order and send it to your solver. If the solver responds with a solution, the driver will spit out a tenderly link with the execution simulation. ## Full E2E testing Is your solver working and you want to try a more real order? You will need to run your own orderbook. For that, you will need docker. Follow the steps at: https://github.com/gnosis/gp-v2-services/#db-migrationinitialization I run my orderbook with: ``` cargo run --bin orderbook -- \ --skip-trace-api true \ --skip-event-sync \ --base-tokens 0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83 \ --enable-presign-orders true \ --node-url "https://rpc.xdaichain.com" ``` and created an order using https://bafybeias5x3tgdshkhj5umriqze2wioy5mjw4fdo2zzp2sl4pacq7rnwtm.ipfs.infura-ipfs.io/?orderbook=http://localhost:8080 The last step is connecting the driver to the new orderbook local service doing: ``` cargo run -p solver -- --orderbook-url http://localhost:8080 \ --base-tokens 0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83 \ --node-url "https://rpc.xdaichain.com" \ --cow-dex-ag-solver-url "http://127.0.0.1:8000" \ --solver-account 0x7942a2b3540d1ec40b2740896f87aecb2a588731 \ --solvers CowDexAg \ --transaction-strategy DryRun ``` Full process will be: - Orderbook at http://localhost:8080 is returning your oder in the `solvable_orders` endpoint - Driver will fetch orders from your orderbook and query your - Solver at http://localhost:8000 ## My solver code I forked cow-dex-solver and wrote my first lines of rust. You can checkout my solver's code at: https://github.com/poolpitako/cow-dex-solver/pull/1 ## Conclusion While there are several services you need to run for an e2e testing, I gotta say I enjoyed developing this prototype. I believe that in the future Cowswap will not only be used for regular trades but it will be used for settling positions. Want to add liquidity to a curve pool in a single click? Go to Cowswap. Want to swap your DAI for two yearn vault positions, go to Cowswap. :cow2: :cow2: :cow2: :cow2: :cow2: :cow2: :cow2:

    Import from clipboard

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lost their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template is not available.


    Upgrade

    All
    • All
    • Team
    No template found.

    Create custom template


    Upgrade

    Delete template

    Do you really want to delete this template?

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Tutorials

    Book Mode Tutorial

    Slide Mode Tutorial

    YAML Metadata

    Contacts

    Facebook

    Twitter

    Feedback

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions

    Versions and GitHub Sync

    Sign in to link this note to GitHub Learn more
    This note is not linked with GitHub Learn more
     
    Add badge Pull Push GitHub Link Settings
    Upgrade now

    Version named by    

    More Less
    • Edit
    • Delete

    Note content is identical to the latest version.
    Compare with
      Choose a version
      No search result
      Version not found

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub

        Please sign in to GitHub and install the HackMD app on your GitHub repo. Learn more

         Sign in to GitHub

        HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Available push count

        Upgrade

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Upgrade

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully