-
Notifications
You must be signed in to change notification settings - Fork 0
/
Flashboy.sol
434 lines (376 loc) · 19.3 KB
/
Flashboy.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//SPDX-License-Identifier: MIT
//
//.......for people asking, yes this is 'one of those arbitrage bots'
//
// ↓ ↓ ↓ ↓ ↓ ↓
//USE THIS AT YOUR OWN RISK
//IF USED INCORRECTLY THIS CAN RESULT IN 100% LOSS
// ↑ ↑ ↑ ↑ ↑ ↑
//
//FORKED SPDX
//......NOW WORKS ON BSC LOL!
//
//⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣤⠤⣄⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
//⠀⠀⠀⠀⠀⠀⠀⣀⠴⠚⠉⠁⠀⠀⠀⠀⠀⠈⠉⠳⢤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀
//⠀⠀⠀⠀⠀⣠⠚⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⣆⠀⠀⠀⠀⠀⠀⠀⠀
//⠀⠀⠀⢀⡞⡥⠀⠀⠀⠀⣠⠴⢀⣠⠤⢦⡀⠀⠀⠀⠀⠀⠈⣆⠀⠀⠀⠀⠀⠀⠀
//⠀⠀⢠⡞⢸⠁⠀⠀⣠⢚⡥⠚⠉⠀⠀⠘⣗⡄⠀⠀⢰⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀
//⠀⠀⢾⠇⡎⠀⠀⣰⡳⠋⠀⠀⣠⣤⠶⠢⡿⣸⣆⠀⠈⣧⣄⢸⠁⠀⠀⠀⠀⠀⠀
//⠀⠀⢸⡄⢳⣠⣾⡟⠓⠆⠀⠘⠙⢀⣤⣶⢿⣤⣹⡅⠀⣿⠈⣿⡇⠀⠀⠀⠀⠀⠀
//⠀⠀⠀⡇⠸⡇⣾⡛⣶⡦⠀⠀⠀⠛⢱⢼⣷⠸⠋⢣⠀⡇⣹⠛⡇⠀⠀⠀⠀⠀⠀
//⠀⠀⠀⢱⠀⠹⣏⠉⢟⣻⣀⠀⠀⠀⠐⠛⠛⠐⠀⠘⣴⡽⣇⠀⢸⡀⠀⠀⠀⠀⠀
//⠀⠀⠀⠈⢇⠀⠘⡄⠀⠀⢸⡁⠀⠀⠀⠀⠀⠀⠀⠀⣿⢀⢹⡀⠈⣧⠀⠀⠀⠀⠀
//⠀⠀⠀⠀⠈⢦⠀⢻⢦⡀⠈⠰⠶⠒⠂⠀⠀⢀⡤⠀⡇⢘⡆⢇⠀⠸⣷⠀⠀⠀⠀
//⠀⠀⠀⠀⠀⠀⠳⡼⡀⣟⡶⢄⡀⠀⢀⡠⠖⠁⠀⢀⡇⢸⢻⠸⡀⠀⣿⢇⠀⠀⠀
//⠀⠀⠀⠀⠀⠀⢠⠏⢳⠟⢀⠷⠈⣹⡇⠀⠀⠀⠀⣼⢣⡞⢸⠀⡇⢰⣼⢸⠀⠀⠀
//⠀⠀⠀⠀⠀⢀⠎⣠⠋⢀⡼⠟⠊⠟⠀⠀⠀⠀⠀⣿⠀⠑⢯⣀⣇⣎⢏⡞⠀⠀⠀
//⠀⠀⠀⢀⡠⠾⠔⠓⢞⣁⣀⣀⠀⠀⠀⠀⠀⠀⠀⢻⣀⣀⣀⡈⠛⠿⠯⣀⠀⠀⠀
//⠀⠀⢠⠋⠀⠀⠀⠀⠀⠀⠀⠀⠉⠁⠐⠉⠉⠉⠉⠉⣧⡀⠀⠀⠀⠀⠀⠀⠑⡄⠀
//⠀⠀⢻⠀⠀⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠧⠀⠀⠀⠀⠀⠀⠀⢹⡆
//⠀⠀⢸⠀⠀⡼⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣤⠀⠀⠀⠀⠀⠀⡼⠃
//⠀⠀⠘⡤⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⡀⠀⠀⠀⠀⢠⠇⠀
//⠀⣠⠎⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢣⠀⠀⠀⠀⡎⠀⠀
//⢠⠇⣠⡂⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⢀⠀⠀⠘⡄⠀⠀⡸⠀⠀⠀
// .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------.
//| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |
//| | _________ | || | _____ | || | __ | || | _______ | || | ____ ____ | || | ______ | || | ____ | || | ____ ____ | |
//| | |_ ___ | | || | |_ _| | || | / \ | || | / ___ | | || | |_ || _| | || | |_ _ \ | || | .' `. | || | |_ _||_ _| | |
//| | | |_ \_| | || | | | | || | / /\ \ | || | | (__ \_| | || | | |__| | | || | | |_) | | || | / .--. \ | || | \ \ / / | |
//| | | _| | || | | | _ | || | / ____ \ | || | '.___`-. | || | | __ | | || | | __'. | || | | | | | | || | \ \/ / | |
//| | _| |_ | || | _| |__/ | | || | _/ / \ \_ | || | |`\____) | | || | _| | | |_ | || | _| |__) | | || | \ `--' / | || | _| |_ | |
//| | |_____| | || | |________| | || ||____| |____|| || | |_______.' | || | |____||____| | || | |_______/ | || | `.____.' | || | |______| | |
//| | | || | | || | | || | | || | | || | | || | | || | | |
//| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
//
//
//
//Tom_D v0.14
pragma solidity ^0.7.0;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/EnumerableSet.sol';
import 'hardhat/console.sol';
import './interfaces/IUniswapV2Pair.sol';
import './interfaces/IWETH.sol';
import './libraries/Decimal.sol';
struct OrderedReserves {
uint256 a1; // base asset
uint256 b1;
uint256 a2;
uint256 b2;
}
struct ArbitrageInfo {
address baseToken;
address quoteToken;
bool baseTokenSmaller;
address lowerPool; // pool with lower price, denominated in quote asset
address higherPool; // pool with higher price, denominated in quote asset
}
struct CallbackData {
address debtPool;
address targetPool;
bool debtTokenSmaller;
address borrowedToken;
address debtToken;
uint256 debtAmount;
uint256 debtTokenOutAmount;
}
contract FlashBot is Ownable {
using Decimal for Decimal.D256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
// ACCESS CONTROL
// Only the `permissionedPairAddress` may call the `uniswapV2Call` function
address permissionedPairAddress = address(1);
// WETH on ETH or WBNB on BSC
address immutable WETH;
// AVAILABLE BASE TOKENS
EnumerableSet.AddressSet baseTokens;
event Withdrawn(address indexed to, uint256 indexed value);
event BaseTokenAdded(address indexed token);
event BaseTokenRemoved(address indexed token);
constructor(address _WETH) {
WETH = _WETH;
baseTokens.add(_WETH);
}
receive() external payable {}
/// The callback function on different DEX are not same, so use a fallback to redirect to uniswapV2Call
fallback(bytes calldata _input) external returns (bytes memory) {
(address sender, uint256 amount0, uint256 amount1, bytes memory data) = abi.decode(_input[4:], (address, uint256, uint256, bytes));
uniswapV2Call(sender, amount0, amount1, data);
}
function withdraw() external {
uint256 balance = address(this).balance;
if (balance > 0) {
payable(owner()).transfer(balance);
emit Withdrawn(owner(), balance);
}
for (uint256 i = 0; i < baseTokens.length(); i++) {
address token = baseTokens.at(i);
balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
// do not use safe transfer here to prevents revert by any shitty token
IERC20(token).transfer(owner(), balance);
}
}
}
function addBaseToken(address token) external onlyOwner {
baseTokens.add(token);
emit BaseTokenAdded(token);
}
function removeBaseToken(address token) external onlyOwner {
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
// do not use safe transfer to prevents revert by any shitty token
IERC20(token).transfer(owner(), balance);
}
baseTokens.remove(token);
emit BaseTokenRemoved(token);
}
function getBaseTokens() external view returns (address[] memory tokens) {
uint256 length = baseTokens.length();
tokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
tokens[i] = baseTokens.at(i);
}
}
function baseTokensContains(address token) public view returns (bool) {
return baseTokens.contains(token);
}
function isbaseTokenSmaller(address pool0, address pool1)
internal
view
returns (
bool baseSmaller,
address baseToken,
address quoteToken
)
{
require(pool0 != pool1, 'Same pair address');
(address pool0Token0, address pool0Token1) = (IUniswapV2Pair(pool0).token0(), IUniswapV2Pair(pool0).token1());
(address pool1Token0, address pool1Token1) = (IUniswapV2Pair(pool1).token0(), IUniswapV2Pair(pool1).token1());
require(pool0Token0 < pool0Token1 && pool1Token0 < pool1Token1, 'Non standard uniswap AMM pair');
require(pool0Token0 == pool1Token0 && pool0Token1 == pool1Token1, 'Require same token pair');
require(baseTokensContains(pool0Token0) || baseTokensContains(pool0Token1), 'No base token in pair');
(baseSmaller, baseToken, quoteToken) = baseTokensContains(pool0Token0)
? (true, pool0Token0, pool0Token1)
: (false, pool0Token1, pool0Token0);
}
// Borrow base token by using flash swap from lower price pool and sell them to higher price pool
function getOrderedReserves(
address pool0,
address pool1,
bool baseTokenSmaller
)
internal
view
returns (
address lowerPool,
address higherPool,
OrderedReserves memory orderedReserves
)
{
(uint256 pool0Reserve0, uint256 pool0Reserve1, ) = IUniswapV2Pair(pool0).getReserves();
(uint256 pool1Reserve0, uint256 pool1Reserve1, ) = IUniswapV2Pair(pool1).getReserves();
// Calculate the price denominated in quote asset token
(Decimal.D256 memory price0, Decimal.D256 memory price1) =
baseTokenSmaller
? (Decimal.from(pool0Reserve0).div(pool0Reserve1), Decimal.from(pool1Reserve0).div(pool1Reserve1))
: (Decimal.from(pool0Reserve1).div(pool0Reserve0), Decimal.from(pool1Reserve1).div(pool1Reserve0));
// get a1, b1, a2, b2 with following rule:
// 1. (a1, b1) represents the pool with lower price, denominated in quote asset token
// 2. (a1, a2) are the base tokens in two pools
if (price0.lessThan(price1)) {
(lowerPool, higherPool) = (pool0, pool1);
(orderedReserves.a1, orderedReserves.b1, orderedReserves.a2, orderedReserves.b2) = baseTokenSmaller
? (pool0Reserve0, pool0Reserve1, pool1Reserve0, pool1Reserve1)
: (pool0Reserve1, pool0Reserve0, pool1Reserve1, pool1Reserve0);
} else {
(lowerPool, higherPool) = (pool1, pool0);
(orderedReserves.a1, orderedReserves.b1, orderedReserves.a2, orderedReserves.b2) = baseTokenSmaller
? (pool1Reserve0, pool1Reserve1, pool0Reserve0, pool0Reserve1)
: (pool1Reserve1, pool1Reserve0, pool0Reserve1, pool0Reserve0);
}
console.log('Borrow from pool:', lowerPool);
console.log('Sell to pool:', higherPool);
}
function flashArbitrage(address pool0, address pool1) external {
ArbitrageInfo memory info;
(info.baseTokenSmaller, info.baseToken, info.quoteToken) = isbaseTokenSmaller(pool0, pool1);
OrderedReserves memory orderedReserves;
(info.lowerPool, info.higherPool, orderedReserves) = getOrderedReserves(pool0, pool1, info.baseTokenSmaller);
// this must be updated every transaction for callback origin authentication
permissionedPairAddress = info.lowerPool;
uint256 balanceBefore = IERC20(info.baseToken).balanceOf(address(this));
// avoid stack too deep error
{
uint256 borrowAmount = calcBorrowAmount(orderedReserves);
(uint256 amount0Out, uint256 amount1Out) =
info.baseTokenSmaller ? (uint256(0), borrowAmount) : (borrowAmount, uint256(0));
// borrow quote token on lower price pool, calculate how much debt we need to pay demoninated in base token
uint256 debtAmount = getAmountIn(borrowAmount, orderedReserves.a1, orderedReserves.b1);
// sell borrowed quote token on higher price pool, calculate how much base token we can get
uint256 baseTokenOutAmount = getAmountOut(borrowAmount, orderedReserves.b2, orderedReserves.a2);
require(baseTokenOutAmount > debtAmount, 'Arbitrage fail, no profit');
console.log('Profit:', (baseTokenOutAmount - debtAmount) / 1 ether);
// can only initialize this way to avoid stack too deep error
CallbackData memory callbackData;
callbackData.debtPool = info.lowerPool;
callbackData.targetPool = info.higherPool;
callbackData.debtTokenSmaller = info.baseTokenSmaller;
callbackData.borrowedToken = info.quoteToken;
callbackData.debtToken = info.baseToken;
callbackData.debtAmount = debtAmount;
callbackData.debtTokenOutAmount = baseTokenOutAmount;
bytes memory data = abi.encode(callbackData);
IUniswapV2Pair(info.lowerPool).swap(amount0Out, amount1Out, address(this), data);
}
uint256 balanceAfter = IERC20(info.baseToken).balanceOf(address(this));
require(balanceAfter > balanceBefore, 'Losing money');
if (info.baseToken == WETH) {
IWETH(info.baseToken).withdraw(balanceAfter);
}
permissionedPairAddress = address(1);
}
function uniswapV2Call(
address sender,
uint256 amount0,
uint256 amount1,
bytes memory data
) public {
// access control
require(msg.sender == permissionedPairAddress, 'Non permissioned address call');
require(sender == address(this), 'Not from this contract');
uint256 borrowedAmount = amount0 > 0 ? amount0 : amount1;
CallbackData memory info = abi.decode(data, (CallbackData));
IERC20(info.borrowedToken).safeTransfer(info.targetPool, borrowedAmount);
(uint256 amount0Out, uint256 amount1Out) =
info.debtTokenSmaller ? (info.debtTokenOutAmount, uint256(0)) : (uint256(0), info.debtTokenOutAmount);
IUniswapV2Pair(info.targetPool).swap(amount0Out, amount1Out, address(this), new bytes(0));
IERC20(info.debtToken).safeTransfer(info.debtPool, info.debtAmount);
}
/// @Calculate how much profit we can by arbitraging between two pools
function getProfit(address pool0, address pool1) external view returns (uint256 profit, address baseToken) {
(bool baseTokenSmaller, , ) = isbaseTokenSmaller(pool0, pool1);
baseToken = baseTokenSmaller ? IUniswapV2Pair(pool0).token0() : IUniswapV2Pair(pool0).token1();
(, , OrderedReserves memory orderedReserves) = getOrderedReserves(pool0, pool1, baseTokenSmaller);
uint256 borrowAmount = calcBorrowAmount(orderedReserves);
// borrow quote token on lower price pool,
uint256 debtAmount = getAmountIn(borrowAmount, orderedReserves.a1, orderedReserves.b1);
// sell borrowed quote token on higher price pool
uint256 baseTokenOutAmount = getAmountOut(borrowAmount, orderedReserves.b2, orderedReserves.a2);
if (baseTokenOutAmount < debtAmount) {
profit = 0;
} else {
profit = baseTokenOutAmount - debtAmount;
}
}
/// alculate the maximum base asset amount to borrow in order to get maximum profit during arbitrage
function calcBorrowAmount(OrderedReserves memory reserves) internal pure returns (uint256 amount) {
// we can't use a1,b1,a2,b2 directly, because it will result overflow/underflow on the intermediate result
// 1. divide all the numbers by d to prevent from overflow/underflow
// 2. calculate the result by using above numbers
// 3. multiply d with the result to get the final result
// Note: this workaround is only suitable for ERC20 token with 18 decimals, which I believe most tokens do
uint256 min1 = reserves.a1 < reserves.b1 ? reserves.a1 : reserves.b1;
uint256 min2 = reserves.a2 < reserves.b2 ? reserves.a2 : reserves.b2;
uint256 min = min1 < min2 ? min1 : min2;
// choose appropriate number to divide based on the minimum number
uint256 d;
if (min > 1e24) {
d = 1e20;
} else if (min > 1e23) {
d = 1e19;
} else if (min > 1e22) {
d = 1e18;
} else if (min > 1e21) {
d = 1e17;
} else if (min > 1e20) {
d = 1e16;
} else if (min > 1e19) {
d = 1e15;
} else if (min > 1e18) {
d = 1e14;
} else if (min > 1e17) {
d = 1e13;
} else if (min > 1e16) {
d = 1e12;
} else if (min > 1e15) {
d = 1e11;
} else {
d = 1e10;
}
(int256 a1, int256 a2, int256 b1, int256 b2) =
(int256(reserves.a1 / d), int256(reserves.a2 / d), int256(reserves.b1 / d), int256(reserves.b2 / d));
int256 a = a1 * b1 - a2 * b2;
int256 b = 2 * b1 * b2 * (a1 + a2);
int256 c = b1 * b2 * (a1 * b2 - a2 * b1);
(int256 x1, int256 x2) = calcSolutionForQuadratic(a, b, c);
// 0 < x < b1 and 0 < x < b2
require((x1 > 0 && x1 < b1 && x1 < b2) || (x2 > 0 && x2 < b1 && x2 < b2), 'Wrong input order');
amount = (x1 > 0 && x1 < b1 && x1 < b2) ? uint256(x1) * d : uint256(x2) * d;
}
/// solution of quadratic equation: ax^2 + bx + c = 0, only return the positive solution
function calcSolutionForQuadratic(
int256 a,
int256 b,
int256 c
) internal pure returns (int256 x1, int256 x2) {
int256 m = b**2 - 4 * a * c;
// m < 0 leads to complex number
require(m > 0, 'Complex number');
int256 sqrtM = int256(sqrt(uint256(m)));
x1 = (-b + sqrtM) / (2 * a);
x2 = (-b - sqrtM) / (2 * a);
}
/// Newton’s method for caculating square root of n
function sqrt(uint256 n) internal pure returns (uint256 res) {
assert(n > 1);
// The scale factor is a crude way to turn everything into integer calcs.
// Actually do (n * 10 ^ 4) ^ (1/2)
uint256 _n = n * 10**6;
uint256 c = _n;
res = _n;
uint256 xi;
while (true) {
xi = (res + c / res) / 2;
// don't need be too precise to save gas
if (res - xi < 1000) {
break;
}
res = xi;
}
res = res / 10**3;
}
// copy from UniswapV2Library
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// copy from UniswapV2Library
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
}