3

AMM | 计算原理

 1 year ago
source link: https://benpaodewoniu.github.io/2022/06/11/defi21/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

AMM | 计算原理 | 犀牛的博客

姑苏城外一茅屋,万树梅花月满天

很多博文都只是浅尝辄止,或者干脆复制黏贴,也没有考虑手续费的变量。

这里以 pancakeswapgetAmountsOut 为例,探究,如何计算 AMM 价格。

经常看到,AMM 的乘积是一个常数,即池子的深度

x∗y=k

其中,K 是常数。然后,x 增加和 y 减少之后

(x−Δx)∗(y+Δy)=k

其里面有一个前提,所谓的 k 不变,是不存在加池子和撤池子的情况,才是恒定 k。仅仅只是交易的话,k 是恒定的,但是,如果进行加池子或者减少池子,则 K 是变化的。

这里参考的是 pancakeswap。

// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'PancakeLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'PancakeLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}

这里解释一下参数

假设,池子是 A , B 两个 token 组成的,这个时候,你想用 A 来换 B

  • amountIn
    • A 的数量
  • reserveIn
    • 池子中 A 的数量
  • reserveOut
    • 池子中 B 的数量

方法中 998,是因为,pancakeswap 的收取费用是 0.2%

但是,pancakeswap 现在的手续费调整为 0.25%,即上面的 998 要变成 997.5 。但是,看公开的代码,这里的手续费用是写死的,不知道 pancakeswap 是怎么变得。

这里按照代码中的 0.2% 的手续费进行计算。

公式代码如下面所示

amountOut=amountIn∗998∗reserveOutreserveIn∗1000+amountIn∗998

这里直接带手续费进行推导。

reserveIn∗reserveOut=(reserveIn+amountIn∗(1−f))∗(reserveOut−amountOut)
reserveIn∗reserveOut(reserveIn+amountIn∗(1−f))=(reserveOut−amountOut)
amountOut=reserveOut−reserveIn∗reserveOut(reserveIn+amountIn∗(1−f))
amountOut=reserveOut∗(reserveIn+amountIn∗(1−f))−reserveIn∗reserveOut(reserveIn+amountIn∗(1−f))
amountOut=reserveOut∗reserveIn+reserveOut∗amountIn∗(1−f))−reserveIn∗reserveOut(reserveIn+amountIn∗(1−f))
amountOut=reserveOut∗amountIn∗(1−f)(reserveIn+amountIn∗(1−f))

这里要说一下,为什么 (reserveIn+amountIn∗(1−f)) ,这里的 1−f 是因为,pancakeswap 要拿走一部分的币作为手续费。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK