uniswapv3怎么通过公式得到正确的输出价格和数量

下面是根据uniswap v3原理构建的python代码,用于计算正确的输出价格和数量,但是计算出的结果是错误的(接近)

我得到的结果

image.png

而dex上面显示的结果

image.png

我得到是1个sns1可以得到40.59059566个ICP,而dex确是40.46949104个ICP 请问这个哪里出问题了呢?

具体代码如下:

import math

q96 = 2**96

 icp  =  10**8

def price_to_tick(p):
    return math.floor(math.log(p, 1.0001))

def price_to_sqrtp(p):
    return int(math.sqrt(p) * q96)

def sqrtp_to_price(sqrtp):
    return (sqrtp / q96) ** 2

def tick_to_sqrtp(t):
    return int((1.0001 ** (t / 2)) * q96)

def liquidity0(amount, pa, pb):
    if pa > pb:
        pa, pb = pb, pa
    return (amount * (pa * pb) / q96) / (pb - pa)

def liquidity1(amount, pa, pb):
    if pa > pb:
        pa, pb = pb, pa
    return amount * q96 / (pb - pa)

def calc_amount0(liq, pa, pb):
    if pa > pb:
        pa, pb = pb, pa
    return int(liq * q96 * (pb - pa) / pb / pa)

def calc_amount1(liq, pa, pb):
    if pa > pb:
        pa, pb = pb, pa
    return int(liq * (pb - pa) / q96)

liq=115619824967
sqrtp_cur=12401388481691991086552029889
amount_in = 1 * icp
price_diff = (amount_in * q96) // liq
price_next = sqrtp_cur + price_diff
print("Now price:", (sqrtp_cur / q96) ** 2)
print("Now tick:", price_to_tick((sqrtp_cur / q96) ** 2))

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_amount1(liq, price_next, sqrtp_cur)
amount_out = calc_amount0(liq, price_next, sqrtp_cur)

print("sns1 in:", amount_in / icp)
print("icp out:", (amount_out / icp))
请先 登录 后评论

3 个回答

癞蛤蟆
请先 登录 后评论
仗剑走天涯
请先 登录 后评论
赵逸 - 区块链开发
请先 登录 后评论
  • 3 关注
  • 0 收藏,2451 浏览
  • Charm 提出于 2023-04-30 08:55