欢迎光临
我们一直在努力

Uniswap学习笔记

简介

v1版本,基于恒定乘积做市商模型(

x

×

y

=

k

x\\times y = k

x×y=k) v2版本,包含Core和Periphery

  • Factory 管生(创建池子)
  • Pair 管养(存钱、算价、交易)
  • Router 管用(让用户方便地操作)

其支持预言机机制,TWAP(Time-Weighted Average Price)时间加权平均价格 v3版本

  • 增加集中流动性
  • 费率分层:支持0.05%/0.30%/1.00%
  • 非同质化流动性
  • 高级预言机:优化了 TWAP 的计算方式,支持更高效的价格查询

增强关系式

L

=

x

y

P

=

y

x

L

=

Δ

y

Δ

P

\\begin{align*}L &= \\sqrt {x y} \\\\ \\sqrt{P}&= \\sqrt {\\frac{y}{x}}\\\\ L&= \\frac{\\Delta y}{\\Delta \\sqrt{P}} \\end{align*}

LP

​L​=xy

​=xy​

​=ΔP

​Δy​​

V2

Core核心

主要有

  • UniswapV2Factory
  • UniswapV2Pair

UniswapV2Pair

比较使用

k

b

e

f

o

r

e

≤

k

a

f

t

e

r

k_{before} \\le k_{after}

kbefore​≤kafter​ v2交易对,其主要成员有 reserve0/reserve1:表示交易对的两种代币的储备金量 totalSupply:表示所有用户的LP代币总数量 factory:表示创建交易对的工厂合约 token0/token1:表示交易对的两种代币合约地址 price0CumulativeLast/price1CumulativeLast:表示TWAP预言机的核心变量,是对“边际价格 × 持续时间”进行连续积分,其计算公式为

p

r

i

c

e

0

C

u

m

u

l

a

t

i

v

e

L

a

s

t

=

∑

r

e

s

e

r

v

e

1

∗

2

112

r

e

s

e

r

v

e

0

∗

Δ

t

price0CumulativeLast=\\sum{\\frac{reserve1 * 2^{112}} {reserve0}} * \\Delta t

price0CumulativeLast=∑reserve0reserve1∗2112​∗Δt

p

r

i

c

e

1

C

u

m

u

l

a

t

i

v

e

L

a

s

t

=

∑

r

e

s

e

r

v

e

0

∗

2

112

r

e

s

e

r

v

e

1

∗

Δ

t

price1CumulativeLast =\\sum{\\frac{reserve0 * 2^{112}}{reserve1}} * \\Delta t

price1CumulativeLast=∑reserve1reserve0∗2112​∗Δt 其中

Δ

t

=

b

l

o

c

k

T

i

m

e

s

t

a

m

p

L

a

s

t

−

b

l

o

c

k

T

i

m

e

s

t

a

m

p

L

a

s

t

l

a

s

t

\\Delta t = blockTimestampLast – blockTimestampLast_{last}

Δt=blockTimestampLast−blockTimestampLastlast​ blockTimestampLast:表示上次计算连续积分时的区块时间戳对

2

32

2^{32}

232的模 关键操作

名称说明
mint 增加流动性
burn 减少流动性
swap 实现资产交换

mint:对于初次增加流动性,其流动性计算公式为

a

m

o

u

n

t

0

∗

a

m

o

u

n

t

1

−

10

3

\\sqrt{amount0 * amount1} – 10^3

amount0∗amount1

​−103追加情况时计算公式为

min

⁡

{

a

m

o

u

n

t

0

r

e

s

e

r

v

e

0

∗

t

o

t

a

l

S

u

p

p

l

y

,

a

m

o

u

n

t

1

r

e

s

e

r

v

e

1

∗

t

o

t

a

l

S

u

p

p

l

y

}

\\min \\{ \\frac{amount0}{reserve0} *totalSupply, \\frac{amount1}{reserve1} * totalSupply \\}

min{reserve0amount0​∗totalSupply,reserve1amount1​∗totalSupply} 其中amount0/amount1为存入的交易对代币值 如果设置了要收协议费,即factory的feeTo()接收地址不为0,协议费计算公式为

k

−

k

l

a

s

t

5

k

+

k

l

a

s

t

∗

t

o

t

a

l

S

u

p

p

l

y

\\frac{k – k_{last}}{5k + k_{last}} * totalSupply

5k+klast​k−klast​​∗totalSupply 其中

k

=

r

e

s

e

r

v

e

0

∗

r

e

s

e

r

v

e

1

k=\\sqrt{reserve0 * reserve1}

k=reserve0∗reserve1

​,

k

l

a

s

t

k_{last}

klast​表示上一次计算的

k

k

k swap:由Router来调用,其传的参数amount0Out和amount1Out其中一个必定为0,采用了“乐观转账(Optimistic Transfer)”模式,主要承担三件职责

  • 资产交割:根据输入的参数,将代币从流动性池(Pair)转移至目标地址(to)
  • 数学验证:在转账后,通过余额反推输入金额,并验证扣除 0.3% 手续费后的乘积是否不小于交易前的乘积
  • 状态同步:更新储备金余额和时间戳,为 TWAP(时间加权平均价格)预言机提供数据。

交换时需要满足

x

×

y

≥

k

x \\times y \\ge k

x×y≥k。闪电贷是通过swap来实现的,uniswapV2Call 中实现偿还贷款及费用

function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');

uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 – amount0Out ? balance0 – (_reserve0 – amount0Out) : 0;
uint amount1In = balance1 > _reserve1 – amount1Out ? balance1 – (_reserve1 – amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}

_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}

Periphery外围

主要包含

  • UniswapV2Migrator
  • UniswapV2Router01(已废弃)
  • UniswapV2Router02

#mermaid-svg-tB6VqopYdWaCiKr7{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-tB6VqopYdWaCiKr7 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-tB6VqopYdWaCiKr7 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-tB6VqopYdWaCiKr7 .error-icon{fill:#552222;}#mermaid-svg-tB6VqopYdWaCiKr7 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-tB6VqopYdWaCiKr7 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-tB6VqopYdWaCiKr7 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-tB6VqopYdWaCiKr7 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-tB6VqopYdWaCiKr7 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-tB6VqopYdWaCiKr7 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-tB6VqopYdWaCiKr7 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-tB6VqopYdWaCiKr7 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-tB6VqopYdWaCiKr7 .marker.cross{stroke:#333333;}#mermaid-svg-tB6VqopYdWaCiKr7 svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-tB6VqopYdWaCiKr7 p{margin:0;}#mermaid-svg-tB6VqopYdWaCiKr7 g.classGroup text{fill:#9370DB;stroke:none;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:10px;}#mermaid-svg-tB6VqopYdWaCiKr7 g.classGroup text .title{font-weight:bolder;}#mermaid-svg-tB6VqopYdWaCiKr7 .cluster-label text{fill:#333;}#mermaid-svg-tB6VqopYdWaCiKr7 .cluster-label span{color:#333;}#mermaid-svg-tB6VqopYdWaCiKr7 .cluster-label span p{background-color:transparent;}#mermaid-svg-tB6VqopYdWaCiKr7 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-tB6VqopYdWaCiKr7 .cluster text{fill:#333;}#mermaid-svg-tB6VqopYdWaCiKr7 .cluster span{color:#333;}#mermaid-svg-tB6VqopYdWaCiKr7 .nodeLabel,#mermaid-svg-tB6VqopYdWaCiKr7 .edgeLabel{color:#131300;}#mermaid-svg-tB6VqopYdWaCiKr7 .edgeLabel .label rect{fill:#ECECFF;}#mermaid-svg-tB6VqopYdWaCiKr7 .label text{fill:#131300;}#mermaid-svg-tB6VqopYdWaCiKr7 .labelBkg{background:#ECECFF;}#mermaid-svg-tB6VqopYdWaCiKr7 .edgeLabel .label span{background:#ECECFF;}#mermaid-svg-tB6VqopYdWaCiKr7 .classTitle{font-weight:bolder;}#mermaid-svg-tB6VqopYdWaCiKr7 .node rect,#mermaid-svg-tB6VqopYdWaCiKr7 .node circle,#mermaid-svg-tB6VqopYdWaCiKr7 .node ellipse,#mermaid-svg-tB6VqopYdWaCiKr7 .node polygon,#mermaid-svg-tB6VqopYdWaCiKr7 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-tB6VqopYdWaCiKr7 .divider{stroke:#9370DB;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 g.clickable{cursor:pointer;}#mermaid-svg-tB6VqopYdWaCiKr7 g.classGroup rect{fill:#ECECFF;stroke:#9370DB;}#mermaid-svg-tB6VqopYdWaCiKr7 g.classGroup line{stroke:#9370DB;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5;}#mermaid-svg-tB6VqopYdWaCiKr7 .classLabel .label{fill:#9370DB;font-size:10px;}#mermaid-svg-tB6VqopYdWaCiKr7 .relation{stroke:#333333;stroke-width:1;fill:none;}#mermaid-svg-tB6VqopYdWaCiKr7 .dashed-line{stroke-dasharray:3;}#mermaid-svg-tB6VqopYdWaCiKr7 .dotted-line{stroke-dasharray:1 2;}#mermaid-svg-tB6VqopYdWaCiKr7 #compositionStart,#mermaid-svg-tB6VqopYdWaCiKr7 .composition{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #compositionEnd,#mermaid-svg-tB6VqopYdWaCiKr7 .composition{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #dependencyStart,#mermaid-svg-tB6VqopYdWaCiKr7 .dependency{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #dependencyStart,#mermaid-svg-tB6VqopYdWaCiKr7 .dependency{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #extensionStart,#mermaid-svg-tB6VqopYdWaCiKr7 .extension{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #extensionEnd,#mermaid-svg-tB6VqopYdWaCiKr7 .extension{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #aggregationStart,#mermaid-svg-tB6VqopYdWaCiKr7 .aggregation{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #aggregationEnd,#mermaid-svg-tB6VqopYdWaCiKr7 .aggregation{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #lollipopStart,#mermaid-svg-tB6VqopYdWaCiKr7 .lollipop{fill:#ECECFF!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 #lollipopEnd,#mermaid-svg-tB6VqopYdWaCiKr7 .lollipop{fill:#ECECFF!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-tB6VqopYdWaCiKr7 .edgeTerminals{font-size:11px;line-height:initial;}#mermaid-svg-tB6VqopYdWaCiKr7 .classTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-tB6VqopYdWaCiKr7 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-tB6VqopYdWaCiKr7 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-tB6VqopYdWaCiKr7 :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}

UniswapV2Router02

UniswapV2Factory

UniswapV2Router02

通过amountIn计算amoutOut公式为

r

e

s

e

r

v

e

0

⋅

r

e

s

e

r

v

e

1

=

(

r

e

s

e

r

v

e

0

+

0.997

⋅

a

m

o

u

n

t

I

n

)

⋅

(

r

e

s

e

r

v

e

1

−

a

m

o

u

n

t

O

u

t

)

reserve0 \\cdot reserve1 = (reserve0 + 0.997 \\cdot amountIn) \\cdot (reserve1 – amountOut)

reserve0⋅reserve1=(reserve0+0.997⋅amountIn)⋅(reserve1−amountOut) 即

a

m

o

u

t

O

u

t

=

0.997

⋅

r

e

s

e

r

v

e

1

⋅

a

m

o

u

n

t

I

n

r

e

s

e

r

v

e

0

+

0.997

⋅

a

m

o

u

n

t

I

n

amoutOut = \\frac{0.997 \\cdot reserve1 \\cdot amountIn}{reserve0 + 0.997 \\cdot amountIn}

amoutOut=reserve0+0.997⋅amountIn0.997⋅reserve1⋅amountIn​

函数说明
swapExactTokensForTokens path中的第一个为输入token,即根据一个amoutIn,批量计算amoutOut
swapTokensForExactTokens path中的最后一个为输出token,即根据一个amoutOut批量计算amoutIn

UniswapV2Library

函数说明
getAmountOut 根据amountIn计算amountOut
getAmountIn 根据amoutOut计算amoutIn
getAmountsOut 批量计算amountOut
getAmountsIn 批量计算amoutIn
getReserves 返回代币对的储备量
quote 计算LP代币的价值

V3

core核心

主要有

  • UniswapV3Factory
  • UniswapV3Pool

#mermaid-svg-poa9KYBYaNViT7xD{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-poa9KYBYaNViT7xD .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-poa9KYBYaNViT7xD .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-poa9KYBYaNViT7xD .error-icon{fill:#552222;}#mermaid-svg-poa9KYBYaNViT7xD .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-poa9KYBYaNViT7xD .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-poa9KYBYaNViT7xD .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-poa9KYBYaNViT7xD .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-poa9KYBYaNViT7xD .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-poa9KYBYaNViT7xD .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-poa9KYBYaNViT7xD .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-poa9KYBYaNViT7xD .marker{fill:#333333;stroke:#333333;}#mermaid-svg-poa9KYBYaNViT7xD .marker.cross{stroke:#333333;}#mermaid-svg-poa9KYBYaNViT7xD svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-poa9KYBYaNViT7xD p{margin:0;}#mermaid-svg-poa9KYBYaNViT7xD g.classGroup text{fill:#9370DB;stroke:none;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:10px;}#mermaid-svg-poa9KYBYaNViT7xD g.classGroup text .title{font-weight:bolder;}#mermaid-svg-poa9KYBYaNViT7xD .cluster-label text{fill:#333;}#mermaid-svg-poa9KYBYaNViT7xD .cluster-label span{color:#333;}#mermaid-svg-poa9KYBYaNViT7xD .cluster-label span p{background-color:transparent;}#mermaid-svg-poa9KYBYaNViT7xD .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-poa9KYBYaNViT7xD .cluster text{fill:#333;}#mermaid-svg-poa9KYBYaNViT7xD .cluster span{color:#333;}#mermaid-svg-poa9KYBYaNViT7xD .nodeLabel,#mermaid-svg-poa9KYBYaNViT7xD .edgeLabel{color:#131300;}#mermaid-svg-poa9KYBYaNViT7xD .edgeLabel .label rect{fill:#ECECFF;}#mermaid-svg-poa9KYBYaNViT7xD .label text{fill:#131300;}#mermaid-svg-poa9KYBYaNViT7xD .labelBkg{background:#ECECFF;}#mermaid-svg-poa9KYBYaNViT7xD .edgeLabel .label span{background:#ECECFF;}#mermaid-svg-poa9KYBYaNViT7xD .classTitle{font-weight:bolder;}#mermaid-svg-poa9KYBYaNViT7xD .node rect,#mermaid-svg-poa9KYBYaNViT7xD .node circle,#mermaid-svg-poa9KYBYaNViT7xD .node ellipse,#mermaid-svg-poa9KYBYaNViT7xD .node polygon,#mermaid-svg-poa9KYBYaNViT7xD .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-poa9KYBYaNViT7xD .divider{stroke:#9370DB;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD g.clickable{cursor:pointer;}#mermaid-svg-poa9KYBYaNViT7xD g.classGroup rect{fill:#ECECFF;stroke:#9370DB;}#mermaid-svg-poa9KYBYaNViT7xD g.classGroup line{stroke:#9370DB;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5;}#mermaid-svg-poa9KYBYaNViT7xD .classLabel .label{fill:#9370DB;font-size:10px;}#mermaid-svg-poa9KYBYaNViT7xD .relation{stroke:#333333;stroke-width:1;fill:none;}#mermaid-svg-poa9KYBYaNViT7xD .dashed-line{stroke-dasharray:3;}#mermaid-svg-poa9KYBYaNViT7xD .dotted-line{stroke-dasharray:1 2;}#mermaid-svg-poa9KYBYaNViT7xD #compositionStart,#mermaid-svg-poa9KYBYaNViT7xD .composition{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #compositionEnd,#mermaid-svg-poa9KYBYaNViT7xD .composition{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #dependencyStart,#mermaid-svg-poa9KYBYaNViT7xD .dependency{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #dependencyStart,#mermaid-svg-poa9KYBYaNViT7xD .dependency{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #extensionStart,#mermaid-svg-poa9KYBYaNViT7xD .extension{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #extensionEnd,#mermaid-svg-poa9KYBYaNViT7xD .extension{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #aggregationStart,#mermaid-svg-poa9KYBYaNViT7xD .aggregation{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #aggregationEnd,#mermaid-svg-poa9KYBYaNViT7xD .aggregation{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #lollipopStart,#mermaid-svg-poa9KYBYaNViT7xD .lollipop{fill:#ECECFF!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD #lollipopEnd,#mermaid-svg-poa9KYBYaNViT7xD .lollipop{fill:#ECECFF!important;stroke:#333333!important;stroke-width:1;}#mermaid-svg-poa9KYBYaNViT7xD .edgeTerminals{font-size:11px;line-height:initial;}#mermaid-svg-poa9KYBYaNViT7xD .classTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-poa9KYBYaNViT7xD .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-poa9KYBYaNViT7xD .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-poa9KYBYaNViT7xD :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}

UniswapV3Factory

«interface»

IUniswapV3Factory

«interface»

IUniswapV3Pool

UniswapV3PoolDeployer

UniswapV3Pool

P

(

i

)

=

1.0001

i

×

2

96

\\sqrt{P(i)} = \\sqrt{1.0001^i} \\times 2^{96}

P(i)

​=1.0001i

​×296,其中

i

i

i表示tick的索引 UniswapV3Pool的主要成员有

成员说明
slot0 池子的“仪表盘”
ticks 记录每个 Tick 边界上流动性变化的账本
tickBitmap 这是一张位图(Bitmap),用于快速寻找“下一个有流动性的 Tick”
positions 非同质化的仓位账本,是以地址+下界+上界作为key。position即头寸,即一个区间相关的信息

struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the most-recently updated index of the observations array
uint16 observationIndex;
// the current maximum number of observations that are being stored
uint16 observationCardinality;
// the next maximum number of observations to store, triggered in observations.write
uint16 observationCardinalityNext;
// the current protocol fee as a percentage of the swap fee taken on withdrawal
// represented as an integer denominator (1/x)%
uint8 feeProtocol;
// whether the pool is locked
bool unlocked;
}

mapping(int24 => Tick.Info) public override ticks;
mapping(int16 => uint256) public override tickBitmap;
mapping(bytes32 => Position.Info) public override positions;
//Tick.Info
struct Info {
// the total position liquidity that references this tick
uint128 liquidityGross;
// amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),
int128 liquidityNet;
// fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
// only has relative meaning, not absolute — the value depends on when the tick is initialized
uint256 feeGrowthOutside0X128;
uint256 feeGrowthOutside1X128;
// the cumulative tick value on the other side of the tick
int56 tickCumulativeOutside;
// the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)
// only has relative meaning, not absolute — the value depends on when the tick is initialized
uint160 secondsPerLiquidityOutsideX128;
// the seconds spent on the other side of the tick (relative to the current tick)
// only has relative meaning, not absolute — the value depends on when the tick is initialized
uint32 secondsOutside;
// true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0
// these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks
bool initialized;
}
//Position.Info
struct Info {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
// the fees owed to the position owner in token0/token1
uint128 tokensOwed0;
uint128 tokensOwed1;
}

主要方法有

方法说明
mint 流动性提供者(LP)向特定价格区间注入资金
burn 移除流动性,实际没有把钱转给用户,只是销毁账本上的流动性记录
collect 把钱转给用户
swap zeroForOne为true表示用 token0 买 token1即抛售token0,买入token1会导致价值下降,为false时表示用token1买token0即抛售token1买入token0会导致价值上升 amountSpecified正数表示知道需要花多少输入代币,负数表示知道需要收到多少输出代币

mint主要步骤为

  • 修改position信息(_modifyPosition)
    • 检查tickLower和tickUpper的有效性,要求tickLower小于tickUpper,tickLower不能小于TickMath.MIN_TICK, tickUpper不能大于TickMath.MAX_TICK
    • 更新positions,ticks和tickBitmap信息(_updatePosition),在ticks[tickLower]处增加流动性(liquidityNet)同时增加liquidityGross,在ticks[tickUpper] 处减少流动性,更新 positions映射,主要包含以下数据
      • liquidity:头寸拥有的流动性数量
      • feeGrowthInside0LastX128​ :上一次你与该头寸交互时,token0 在该价格区间内的每单位流动性累积手续费快照
      • feeGrowthInside1LastX128:上一次你与该头寸交互时,token1在该价格区间内的每单位流动性累积手续费快照
      • tokensOwed0:已经结算但尚未提取的 token0 手续费
      • tokensOwed1:已经结算但尚未提取的 token1 手续费
    • 如果slot0中的当前tick正好在这个区间内,会增加池子的流动性liquidity
    • 如果当前tick在区间内,你需要提供两种代币,如果tick在区间下方,只提供token0,如果tick在区间上方,只提供token1
  • 回调索取资金uniswapV3MintCallback,乐观记账,事后索偿

swap的步骤为

  • 找下一tick(nextInitializedTickWithinOneWord)
  • 算该步可以换多少(computeSwapStep)
  • 处理穿越(cross)
  • 更新全局状态,即slot0中的sqrtPriceX96和tick以及池中的流动性liquidity
  • 池子帐转为用户帐,即作转帐safeTransfer
  • 执行回调uniswapV3SwapCallback
  • 资料

    Uniswap V2 Book Uniswap V3 开发手册

    赞(0)
    未经允许不得转载:171主机测评 » Uniswap学习笔记
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址