# 算法

## 恒定乘积做市商模型

交易所如果要去中心化、也不使用挂单 order book，就需要靠算法自动算出交易标的的数量与价格，而 Uniswap 使用名为恒定乘积的演算法，其来源可追溯自 Vitalik 的这篇 [文章](https://ethresear.ch/t/improving-front-running-resistance-of-x-y-k-market-makers/1281)。

公式非常的简单：x *y = k。令交易的两加密货币为 X 和 Y，各自数量为 x 和 y，两货币数量的乘积 x* y 恒等于 k，k 值是由第一笔注入的流动性所决定。

因此，用 ∆x 数量的 X 币来购买 Y 币所能得到的数量 ∆y、或是为了购买 ∆y 需要付出的 ∆x 数量，依照此公式进行计算：(x+∆x)(y-∆y) = k，而交易的价格就是两币量 ∆x 和 ∆y 的比。

以下公式用 α = ∆x /x 和 β = ∆y /y 来表示 ∆x 和 ∆y 及 X Y 两币在交易发生后的新均衡数量：

![](https://assets.exincdn.com/images/exinswap/algorithm/jrnj6lw.png)

## 计入手续费

在 Uniswap 进行的每一笔交易都会被收取 ρ = 0.003 / 0.3% 的手续费回馈给流动性提供者 liquidity provider ，因此要将手续费纳入公式的考量：

![](https://assets.exincdn.com/images/exinswap/algorithm/gaj6fd1.png)

上图的公式或许不太直觉，建议不要从 x’ρ 及 y’ρ 开始理解，而是从 ∆x 和 ∆y 两值开始：手续费 ρ = 0.3% 的意思是会从付款中扣掉 0.3 %，也就是从 ∆x 扣。在有手续费的情况下 ∆x 就变成了 (1-ρ)∆x ，若令 γ = 1-ρ 则为 γ∆x。因此，将图一中的 ∆x 换成 γ∆x，就会得到以下公式：

![](https://assets.exincdn.com/images/exinswap/algorithm/w26x21b.png)

将等号左方的 γ 移到右方后就得到了图二中的 ∆x。同理，由于 ∆y 中的 α = ∆x /x ，用 γ∆x 代换 ∆x 就会得到图二中的 ∆y (有 α 的地方乘上 γ)。而 x’ 还有 y’ 就可以由 ∆x 和 ∆y 推演出来了。然而，将图二中得到的 x’ 和 y’ 相乘，会得到：

![](https://assets.exincdn.com/images/exinswap/algorithm/mz0xjxk.png)

也就是说，当有手续费使得 γ != 1 /ρ != 0，x’ρ *y’ρ 的值其实会稍微和 xy = k 不同：在实际上 γ = 0.997 / ρ = 0.003，因此 1/γ-1 ≒ 0.003。β = ∆y /y 代表的是换得的 Y 币占总量的比例，即使最大值为 1，误差也只有 1* 0.003，故可知手续费 = 0.3% 对于 k 值的影响极小。

## Uniswap 白皮书

如果您想了解 Uniswap 的更多细节，可以参考 Uniswap 白皮书。

链接：<https://uniswap.org/whitepaper.pdf>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://support.exinswap.com/zh/algorithm.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
