feat: increase coverage of spot prices function #152
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Context
Some protocols, like BalancerV3 do not have the PriceFunction capability. This PR enhances the coverage of Spot Prices function, proposing an alternative way of calculating spot prices.
The code calculates a marginal price between token pairs using a numerical approximation of the derivative of the exchange function. Here's how it works:
It takes two tokens (t0 and t1) and calculates:
x1
: A small sell amount (1% of the sell limit)x2
: A slightly larger sell amount (1.01% of the sell limit)It performs two swap simulations:
y1
: The amount of t1 received when selling amountx1
of t0y2
: The amount of t1 received when selling amountx2
of t0It calculates the marginal price as the ratio of the difference:
num = y2 - y1
: The incremental output amountden = x2 - x1
: The incremental input amountmarginal_price = (y2 - y1) / (x2 - x1)
It applies a decimal correction to account for different token decimal places:
token_correction = 10^(sell_token_decimals - buy_token_decimals)
final_price = marginal_price * token_correction
This numerical derivative approach approximates the instantaneous exchange rate at the given point on the AMM curve, which is more accurate than using average prices for larger amounts.
This function was already extended on Python's adapter (https://github.com/propeller-heads/tycho-simulation/pull/126/files)