When, in a given instant i, a trade is initiated and the contract will check the following parameters to proceed:
Trade direction (from token A to token B or the opposite).
The number of tokens the user wants to buy or sell ( exactAInput orexactBoutput ). The amounts considered in the trade will be called Ai and Bi , and they will be represented with the sign of the trade from the pool's point of view. If purchases options tokens, Ai will be negative (options tokens are leaving the pool), and Biwill be positive (stablecoins are entering the pool).
The total price slippage the user allows.
Owner.
Once the contract gathered this information, it will start performing the following trade functions:
1. Calculate factors
1.1 Calculate Option Unit Theoretical Price
The contract will supply our BS implementation with the following data:
the current spot price of the underlying asset
time to maturity
strike price
risk-free rate
last sigma (IVi−1)
And will get in return the updated option price (Pi) based on the current market scenario.
inside _calculateNewABPrice function on optionAMMPool
1.2 Calculate total price based on the transaction amount
a) Calculate pool amounts for each token:
poolAmountA=min{TBA;PiTBB}
poolAmountB=min{TBB;TBA⋅Pi}
_getPoolAmounts at OptionAMMPool.sol
b) Calculate product constant
k=poolAmountA∗poolAmountB
c) Calculate total transaction price, in terms of B
Bi=(poolAmountA−tradeAmountA)k−poolAmountB
d) Calculate new option unit price (aka target price)
The target price will be the input for the SigmaGuesser contract.
TargetPricei=poolAmountA+AipoolAmountB−Bi
Note that on the contract level, for each of our 4 trade functions (exactAInput / exactAOutput / exactBInput / exactBOutput) the functions above are slightly different.
3. Find new IV correspondent to the new unit price
At this point, the pool's inventory changed, and it represents a new "virtual price." The IV corresponding to this new virtual price reflects market information of supply and demand for this option.
So the AMM will input the new target price in the Black Scholes formula and find the new correspondent IV for this price. It uses a specific numerical method applied to Black Scholes. If you want to deep dive into how it works, explore Find next IV.
The IV found will be stored in the contracts to later feed the Weighted Average with 25% weight.
newIV variable on any of the trade functions at OptionAMMPool
4. Updates
4.1 Update Total Balances
This step will update the pool's new total balances, considering the trade that just happened.
TBAi=TBAi−1+Ai
TBBi=TBBi−1+Bi
At the contract level, Ai are usually exactAmountIIn or exactAmountAOut and Bi is amountBIn / amountBOut since we do not handle negatives numbers on solidity.
Note that the trade function won't update the DB nor the Fv factor.