Output Amount Calculation

Our collection of Uniswap math formulas lacks a final piece: the formula for calculating the output amount when selling ETH (that is: selling token ). In the previous milestone, we had an analogous formula for the scenario when ETH is bought (buying token ):

This formula finds the change in the price when selling token . We then added this change to the current price to find the target price:

Now, we need a similar formula to find the target price when selling token (ETH in our case) and buying token (USDC in our case).

Recall that the change in token can be calculated as:

From this formula, we can find the target price:

From this, we can find using basic algebraic transformations:

Knowing the target price, we can find the output amount similarly to how we found it in the previous milestone.

Let’s update our Python script with the new formula:

# Swap ETH for USDC
amount_in = 0.01337 * eth

print(f"\nSelling {amount_in/eth} ETH")

price_next = int((liq * q96 * sqrtp_cur) // (liq * q96 + amount_in * sqrtp_cur))

print("New price:", (price_next / q96) ** 2)
print("New sqrtP:", price_next)
print("New tick:", price_to_tick((price_next / q96) ** 2))

amount_in = calc_amount0(liq, price_next, sqrtp_cur)
amount_out = calc_amount1(liq, price_next, sqrtp_cur)

print("ETH in:", amount_in / eth)
print("USDC out:", amount_out / eth)

Its output:

Selling 0.01337 ETH
New price: 4993.777388290041
New sqrtP: 5598789932670289186088059666432
New tick: 85163
ETH in: 0.013369999999998142
USDC out: 66.80838889019013

This means that we’ll get 66.8 USDC when selling 0.01337 ETH using the liquidity we provided in the previous step.

This looks good, but enough of Python! We’re going to implement all the math calculations in Solidity.