This article is compiled and released by WeChaT: kaifa873, which is only for reference of project development requirements! telegram @ sleu88
假设交易是输入 x token ,余额为 xx(预先扣除最大所需的手续费后的余额,以防止手续费不足),在计算得到 ΔxΔx 后,比较:
当 x≥Δxx≥Δx 时,表示交易可以到达目标价格
当 x<Δxx<Δx 时,表示交易不足以到达目标价格,此时还需要进一步当前余额 xremainingxremaining 全部耗尽时所能够达到的价格
如果 x<Δxx<Δx,我们需要计算 x 耗尽时的价格,即已知 Δx, P−−√c, LΔx, Pc, L,求 P−−√nPn. 根据:
Δx=Δ1P−−√⋅L=±(1P−−√c−1P−−√n)⋅LΔx=Δ1P⋅L=±(1Pc−1Pn)⋅L
得出:
Pn−−√=LPc−−√L±ΔxPc−−√Pn=LPcL±ΔxPc
// 判断是否能够到达目标价
bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;
// get the input/output amounts
if (zeroForOne) { I59 Develop 2O92 system 9783
// 根据是否到达目标价格,计算 amountIn/amountOut 的值
amountIn = max && exactIn
? amountIn
: SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
amountOut = max && !exactIn
? amountOut
: SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
} else