2xic / optimistic-cfd

"synth protocol that somewhat ressembles CFDs" - norswap
https://github.com/2xic/optimistic-cfd/issues/1
10 stars 2 forks source link

Simplify Pool Balancing #3

Open norswap opened 2 years ago

norswap commented 2 years ago

Hey there! Great work on the repo!

When looking at the code, I spotted that the pool balancing logic is much more complex than it needs to be.

Currently, you manually adjust every single position. If there are a lot of users, this will cost a ton of gas.

In reality, it suffices to transfer tokens from one side of the pool to the other, and to adjust the protocol's position.

Assume we're doing an ETH synth with long token cfdETH, short token scfdETH and our stablecoin si $C. If we define the following variables:

Than, when the pools are balanced we want to preserve the following invariants:

To do that when the pool is perfectly balanced (protocol neither long nor short):

That's the gist of it!

Of course there are other scenarios, mainly when users purchase cfdETH / scfdETH or redeem. Again, the procedure to follow is dictated by preservation of the invariants above!

I'm wondering if we can't write a single pool rebalancing function. We'd perform the transfer of interest (purchase, redemption, or side transfer after a price change) then call this function. It would lookup the current ETH price and rebalance the pool in order to satisfy the invariants.

One open question I have is whether we want to represent the protocol stake in each pool as an explicit variable (a bit more effective, probably more gas efficient too) or the balance of a "normal" address (the contract's address).

2xic commented 2 years ago

Thanks for taking a look, and for another well formulated + in depth write-up!

The design you describe does sound like a more efficient design both in terms of the code structure, and the gas usage!

I will refactor the code to use this new design over the coming days. If you want to, I can mention this issue when the code has been refactored to the new design, and then you can take a new look!

Sounds good ?