balancer / b-sdk

MIT License
20 stars 8 forks source link

Fix calculate proportional amounts rounding direction for Cow Amm #391

Closed brunoguerios closed 1 month ago

brunoguerios commented 1 month ago

Here’s a bit of context on what this PR fixes:

CowAmm pools use custom maths operations called bdiv and bmul to calculate proportional amounts internally. The problem is that they are not the exact opposite of each other. In other words, when using them: a / b = c but c * b != a This is a problem because we get a referenceAmount (i.e. max user balance) to calculate bptOut and, from there, querying with bptOut as input won't return the same referenceAmount in. Since these behave similar to divUp and mulUp, we end up with a slightly bigger amountIn than the user balance.I created a variation of those maths called bdivDown and bmulDown so we get a slightly smaller bptOut instead, from there we can then use bdiv and bmul to get an exact match on the query amounts. This will leave some dust behind, but at least won't cause the transaction to revert, even with 0% slippage.

brunoguerios commented 1 month ago

I checked with Daniel and this is the desired behavior given the circumstances. I'll merge so it can be used by the FE. Next step is to update AddLiquidityProportional to expect any referenceAmount instead of only bptOut, which will be done in a following PR.