Try   HackMD

Flashloan fee of Uniswap v2

tags: uniswap flashloan fee uniswap-v2

Refer to Uniswap v2 Whitepaper, each swap should satisfy following formula:

(1)(x10.003xin)(y10.003yin)x0y0

To simplify the calculation on-chain:

(2)(1000x13xin)(1000y13yin)1000000x0y0

When we flash loan from Uniswap v2 pair, what is the amount including fee we should repay?

Suppose we flash loan amount of token

y:
yout
.

xin and
yin
are the amount of token
x
and token
y
to repay.

x0 and
x1
are the balance of token
x
before and after flash loan, respectively,
y0
and
y1
are the balance of token
y
before and after flash loan.

The problem is to calculate

yin using
yout
.

Since we don't flash loan token

x, so
xin=0
,
xout=0
,
x0=x1
, we can simplify formula (2):

(3)1000y13yin1000y0

(4)y1y031000yin

The relation between

yin and
yout
is:

(5)yin=y1(y0yout)

Using formula (4) and (5):

(6)yinyout31000yin

We can calculate

yin:

(7)yin1000997yout

In Solidity contract, to avoid rouding down error, we should add 1 to round up:

uint256 repayAmount = amountOut.mul(1000).div(997).add(1)

where repayAmount is

yin, amountOut is
yout
.

So the flashloan fee of Uniswap v2 is:

(8)100099710.00300902710.30090271%