← Back

The story behind PolySwap

In this post, I'll tell you how PolySwap started, how it became the live beta running today, how Polymarket works under the hood, and how conditional orders work on CoW Protocol.

The story

PolySwap started as a hackathon project at ETHGlobal Bangkok 2024.

The idea hasn't changed since: make it possible to execute a swap based on the live odds of Polymarket, a prediction market. Prediction markets were known (and in my opinion, still are) for giving really good live data about people's sentiment, better than a regular poll. And that sentiment can be used as trading information.

But before PolySwap, if you wanted to trade on Polymarket odds, you had to watch the market yourself 24/7, then sign and execute the swap at the moment you felt the sentiment meant something worth trading on.

PolySwap does all of this for you: it automatically executes the swap you set up beforehand, as soon as the odds cross the threshold you chose, on any market available on Polymarket!

At the hackathon, we won 2nd place in CoW Protocol's programmatic orders prize πŸŽ‰. The CoW team was really interested in the idea and its use cases, so they told us that if we wanted to keep building it (we did), they would probably accept it for a grant.

Spoiler: they did πŸ”₯ PolySwap was funded by a CoW Protocol grant.

Polyswap illustration

How conditional orders work on CoW Protocol

Now that you know the story, let's dive into how it all works.

A normal CoW Swap order

When you swap on CoW Swap, you don't send a transaction:

  1. You sign an intent to trade, not the trade itself, and send it to the order book, which is off-chain.
  2. Solvers compete to find you the best swap and execute it on-chain.
  3. There, the settlement contract checks your signature and that the trade respects everything you asked for: tokens, amounts, the minimum you accept to receive (set by your slippage)…

What a conditional order changes

With a conditional order, your wallet registers the order in a contract called ComposableCoW. It gives it three things:

  • the address of a handler contract;
  • a random salt, so two identical orders stay different;
  • a staticInput: all the classic parameters (tokens, amount, slippage, expiry date…), encoded for the handler.

ComposableCoW only stores a hash of these, and only the handler knows how to read the staticInput. The handler is responsible for checking one specific condition!

The handler has to implement a specific interface. Here is a simplified version:

solidity
abstract contract BaseConditionalOrder is IConditionalOrderGenerator {
    function verify(...) external view { ... }

    function getTradeableOrder(...) public view virtual returns (GPv2Order.Data memory);

    function supportsInterface(bytes4 interfaceId) external view returns (bool) { ... }
}

getTradeableOrder is called to check whether the condition is met. If it is, it returns the order to trade (a GPv2Order.Data). If not, it reverts with a specific error.

This is the part you write yourself, so you can build any condition you can imagine. I'll show you the PolySwap handler later on.

verify is already written for you in BaseConditionalOrder: it calls getTradeableOrder and checks that the order being settled is exactly the one it returns (more on that in the Safe part).

The watch tower

Your order is now registered on-chain and points to your handler. But how does it get executed?

A service run by CoW, the watch tower, listens for the ConditionalOrderCreated events that ComposableCoW emits when an order is registered. Then it checks each order's condition every block until it is met or the order expires.

Remember the revert error? It tells the watch tower what to do next:

  • PollTryNextBlock: try again on the next block;
  • PollTryAtBlock or PollTryAtEpoch: come back at a given block or time;
  • OrderNotValid or PollNever: drop the order and stop trying.

Once the condition is met, the watch tower posts the order to the order book itself. It gets it from ComposableCoW.getTradeableOrderWithSignature(), which returns the order and a "signature" that isn't a real one: it holds the conditional order's parameters. So you don't have to sign anything new, your wallet checks the order on-chain (that's the next part).

Why it needs a Safe

Final step: how can the swap execute without a transaction coming from your wallet?

I've hidden a detail until now. When we built the beta, only Safe wallets worked with conditional orders (more precisely, smart contract wallets: a Safe through its ExtensibleFallbackHandler, or any contract that inherits ComposableCoW's ERC1271Forwarder). That's not the case anymore, and I'll explain the flow with a regular (EOA) wallet in a future post. Stay tuned!

Why only Safe wallets? Because the wallet needs a programmatic way to approve the swap when it executes, without a new signature from the user.

Here is a little schema to explain it:

The settlement contract calls the Safe, which calls the ExtensibleFallbackHandler, then ComposableCoW, then the conditional handler that checks the condition
  1. The solver calls the settlement contract.
  2. The settlement contract asks the Safe whether the order's signature is valid (isValidSignature(), from the ERC-1271 standard).
  3. The Safe passes the call to its fallback handler, the ExtensibleFallbackHandler (EFH).
  4. The EFH sees that the order comes from CoW Protocol, and forwards the check to the contract registered for it: ComposableCoW (isValidSafeSignature()).
  5. ComposableCoW checks that the Safe really registered this conditional order, then calls the handler's verify().
  6. verify() calls getTradeableOrder() again and checks that the order being settled is exactly the one it returns. If the condition isn't met anymore, or the order is different, it reverts and the settlement fails.

We don't do it in PolySwap, but a handler can return a different order each time. For example, a TWAP handler returns an order for only a part of the total amount, and each part is checked the same way.

So for conditional orders to work, your Safe needs two settings:

  • the ExtensibleFallbackHandler as its fallback handler, which lets the Safe hand off signature checks to other contracts;
  • ComposableCoW as the contract that checks CoW Protocol orders (the EFH calls it a domain verifier).

After that, the swap executes exactly like a normal one!

Hope you're still with me after all of this 😁

How Polymarket works

Now let's quickly look at how Polymarket works.

Polymarket is a prediction market: people buy Yes or No shares on a specific question. A share's price is between $0 and $1, and the Yes and No prices always add up to about $1. When people buy Yes, the Yes price goes up and the No price goes down. So if everyone thinks the answer is Yes and buys Yes shares, the Yes price gets closer to $1.

So you can read the price as a probability: a Yes share at $0.75 means the market gives Yes a 75% chance!

When the question is resolved, each share of the winning side is worth $1 and each share of the losing side is worth $0. Your profit is the difference between $1 and the price you paid.

The answer is decided by an oracle, UMA. It's a really interesting thing to discover, so I encourage you to take a look. It's exactly what I rebuilt for gno.land (an optimistic oracle)! I may write a post about it.

As you can see, the UMA oracle is on-chain, because Polymarket is only partly on-chain:

On-chain Off-chain
The resolution (UMA oracle) The order book
The share mechanism The live odds
All the tokens The market data

You can't match your Polymarket orders on-chain yourself: the exchange contract only accepts matches sent by Polymarket's backend.

How PolySwap works

You now have almost all the pieces. Maybe you've already spotted the problem in my explanations.

The big issue

The live Polymarket odds aren't on-chain! There's no way to read them on-chain, except the final result, once the market is resolved and one side is at 100%. That doesn't work for us: the goal is to trade on a sentiment before the event happens, and a market is usually resolved long after the news is confirmed.

Running our own oracle wasn't an option either. We wanted PolySwap to be as permissionless as possible, and we didn't want to be responsible for people's funds through our own oracle.

So we were stuck for a long time, until Baptiste Florentin (shout-out to him for his help on the project) found a workaround.

The workaround: a limit order as a trigger

We place a Polymarket limit order at the price of the chosen odds. When the market reaches that threshold, the limit order is matched on-chain, and that's how we check, without any oracle, that the threshold was reached!

The PolySwap handler

Here is the part of the PolySwap handler that checks the condition:

solidity
abstract contract PolyswapBase is BaseConditionalOrder {
    uint256 internal constant MIN_FILL_BPS = 1000; // 10%, in basis points

    function getTradeableOrder(
        address,
        address,
        bytes32,
        bytes calldata staticInput,
        bytes calldata
    ) public view override returns (GPv2Order.Data memory order) {
        // The swap and trigger order params, registered with the order
        PolyswapOrder.Data memory data =
            abi.decode(staticInput, (PolyswapOrder.Data));
        order = PolyswapOrder.orderFor(data);

        // How much of the trigger order has been used,
        // read from Polymarket's exchange contract
        (bool filled, uint256 remaining) =
            _getOrderStatus(data.polymarketOrderHash);
        uint256 makerAmount = data.polymarketMakerAmount;
        uint256 consumed = remaining == 0
            ? (filled ? makerAmount : 0)
            : (makerAmount > remaining ? makerAmount - remaining : 0);

        // Under 10% used: not reached yet, try again next block
        if (consumed * 10_000 < makerAmount * MIN_FILL_BPS) {
            revert IConditionalOrder.PollTryNextBlock(CONDITION_NOT_MET);
        }
        // Otherwise, `order` is returned and the swap can execute
    }
}

A little detail I haven't talked about until now: the handler doesn't wait for the limit order to be completely filled. It considers the threshold reached once at least 10% of it is filled.

We found out later that a Polymarket limit order can be filled at a better price than the one asked. When that happens, the order is matched but some of its amount is never used, so a check waiting for a complete fill never passed, and the swap never executed.

So now the threshold counts as reached as soon as 10% of the tokens we're willing to spend on shares have been used:

  1. The conditional order stores the limit order's original amount (polymarketMakerAmount).
  2. Polymarket's exchange contract gives us the remaining amount and, on its latest version, whether the order is filled.
  3. From these two, we compute the share of tokens used. Under 10%, the handler reverts with PollTryNextBlock, and the watch tower tries again on the next block.

The choices we made

To make the UX as easy and smooth as possible, we couldn't ask users to create the limit order with their own wallet. That would be a very bad UX: they would need a specific token on Polygon, place the limit order themselves, and give us the order ID.

So we place the limit order ourselves. It stays pretty safe for the user: in the worst case, the limit order is cancelled and their swap never executes. And since it's a limit order, we don't need the funds until it's matched, so we can handle a lot of orders at the same time with only $5 in the wallet. We just need to sell the shares as fast as possible once the order is matched, to lose as little money as possible.

Putting it all together

Here is the full life of a PolySwap order:

  1. You choose a market, an outcome, a threshold and the swap you want.
  2. We prepare the trigger limit order at your threshold price, and your Safe registers the conditional order on ComposableCoW, pointing to the PolySwap handler and to that limit order.
  3. Once the conditional order is registered on-chain, we place the limit order on Polymarket.
  4. Every block, the watch tower asks the handler whether your order can be traded, and the handler reads the limit order on Polymarket's exchange contract.
  5. When at least 10% of the limit order is filled, the watch tower posts your order to the CoW order book, and solvers execute your swap.
  6. We sell the shares the limit order bought.

The rest of the stack

That's it, you now know how PolySwap works. The last missing parts:

  • We fetch new Polymarket markets every hour and save them in our database, so the dapp can display them with filters and a recommendation algorithm.
  • A listener continuously checks whether the Polymarket limit orders are matched, to update the UI.
  • It also checks on-chain whether each conditional order is valid, and if not, why, so we can show the right error to the user.
  • When an order is created, we check that it's registered on-chain before placing the limit order on Polymarket.

As this is still a personal project, I only use free plans for RPC providers and other services. So I had a hard time optimising the number of RPC and Polymarket data API calls, and the CI/CD, to run the listener's Docker image on a 2 vCPU / 4 GB RAM server without it crashing πŸ˜….

You now have the whole story of this project, I hope it wasn't too long. If you still have questions, don't hesitate to contact me.

See you πŸ‘‹