A token conservation test for preventing unfair surplus shifting

I believe I have found a vulnerability of the local conservation constraints to an ‘attack’ of sorts, where a user can essentially soak up all the surplus created in a coincidents of wants.

It uses that fact that if a batch consists of two orders trading the same pair in opposite directions, where one order is slightly larger than the other, then the trades will be cleared at whatever price the remaining part of the larger order is matched on chain (it is easy to check this must be true if the local token conservation constraints hold). In other words, the attacker can ensure that they get matched at a maker price, even though they are essentially a taker.

A concrete example could look like this:

Suppose user 1 puts in an order to sell 1 unit of token A for token B. They received a quote promising at least $x$ token $B$ (this is visible in the order book).

Now suppose our attacker observes that the best marginal rate at which token A can be swapped for token B on chain is $y$, where $y>x$. The attacker can force a batch where it sells token B for token A at this rate $y$.

It does so by submitting a sell order for an $x-epsilon$ amount of token B for token A. This just short of enough to fill user order 1, so the solver will need to trade a small (roughly epsilon/y) amount of token A for token B on chain, at a marginal rate of y. This in turn means that the batch must clear at a price that sets the exchange rate for token A to token B to y, given all the surplus to the attacker.

This vulnerability is relatively easy to exploit, as it only requires monitoring the order book. The attacker doesn’t need to know the best marginal rate y precisely. In fact even if a solver finds a better price than y, the solution will adjust to this better price. The only risk is that at solving time, no solver manages to find marginal liquidity at a price better than x (eg due to a sudden price move), in which case the attacker’s order might be executed alone (and therefore doesnt extract any surplus). The time window in which this problem can develop is naturally very small though, and even when it happens the solvers are still optimizing for surplus, so relatively mild overall.

While this strategy doesn’t imply that user 1 gets worse prices than they would have gotten had the attacker not participated at all, I do feel it goes against the notion of fairness we are trying to enforce with the constraints in the first place.

In particular, using the capped surplus idea without the local token conservation constraints could lead to a much fairer outcome in the same situation (ie clearing at a price close to the spot price).