-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo.js
392 lines (321 loc) · 10.2 KB
/
go.js
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
const Web3 = require("web3");
const fs = require("fs");
const path = require("path");
const decimals = require("./decimals.js");
const pairs = require("./pairs.js");
const uniswapPairAbi = require("./abis/uniswapPair.js");
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
const RIGHT = "right";
const LEFT = "left";
const {
GAS_PRICE_THRESHOLD = 40,
SWAP_AGE_THRESHOLD = 16,
ROUND_TRIP_RATE_THRESHOLD = 1.04,
} = require("./config.js");
const { WEB3_INFURA_PROJECT_ID } = process.env;
const wsUrl = `wss://mainnet.infura.io/ws/v3/${WEB3_INFURA_PROJECT_ID}`;
const {
providers: { WebsocketProvider },
} = Web3;
const wsOptions = {
reconnect: {
auto: true,
delay: 5000,
maxAttempts: 5,
onTimeout: false,
},
};
const wsProvider = new WebsocketProvider(wsUrl, wsOptions);
const web3 = new Web3(wsProvider);
const {
eth: { Contract, getGasPrice },
utils: { fromWei },
} = web3;
const _date = new Date();
const year = _date.getFullYear();
const utcMonth = _date.getUTCMonth();
const month = utcMonth < 11 ? `0${utcMonth + 1}` : utcMonth + 1;
const utcDate = _date.getUTCDate();
const date = utcDate < 10 ? `0${utcDate}` : utcDate;
const mostRecentSwapsFilename = path.join(
__dirname,
`most-recent-swaps/${year}-${month}-${date}-most-recent-swaps.js`
);
const logsFilename = path.join(
__dirname,
`logs/${year}-${month}-${date}-logs.txt`
);
let gasPrice;
const getReadableGasPrice = async () => {
let rawGasPrice;
try {
rawGasPrice = await getGasPrice();
} catch (err) {
console.log("d3168b1936fdda4ea020de441c07bc28", { err });
}
const rawGasPriceInGwei = rawGasPrice && fromWei(rawGasPrice, "gwei");
gasPrice = rawGasPriceInGwei && parseInt(rawGasPriceInGwei, 10);
};
let currentBlockNumber;
setInterval(async () => {
getReadableGasPrice();
}, 30 * 1000);
let mostRecentSwaps = {
/*
[token0]: {
[token1]: {
...swap data
}
}
*/
};
const formatSwap = ({ res, token0, token1 }) => {
const { address, blockHash, blockNumber, returnValues, transactionHash } =
res || {};
const { amount0In, amount1In, amount0Out, amount1Out } = returnValues || {};
const swap = {
address,
amount0In: parseInt(amount0In, 10),
amount1In: parseInt(amount1In, 10),
amount0Out: parseInt(amount0Out, 10),
amount1Out: parseInt(amount1Out, 10),
blockHash,
blockNumber,
transactionHash,
gasPrice,
token0,
token1,
};
return swap;
};
const writeMostRecentSwapsToFile = () => {
const stringifiedMostRecentSwaps = JSON.stringify(mostRecentSwaps, null, 2);
setTimeout(() => {
fs.writeFileSync(
mostRecentSwapsFilename,
`module.exports = ${stringifiedMostRecentSwaps};\n`,
(err) => {
if (err) {
console.log("65bff73107b5116f0246a930ce91a074", { err });
}
}
);
}, 0);
};
const shouldArb = ({ res, token0, token1 }) => {
const swap = formatSwap({ res, token0, token1 });
const { blockNumber: _blockNumber } = res || {};
currentBlockNumber = _blockNumber;
const swapDirection = swap.amount0In > 0 ? RIGHT : LEFT;
let tokenZero;
let tokenOne;
if (swapDirection === RIGHT) {
if (mostRecentSwaps[token0]) {
mostRecentSwaps[token0][token1] = swap;
} else {
mostRecentSwaps[token0] = { [token1]: swap };
}
tokenZero = token0;
tokenOne = token1;
}
if (swapDirection === LEFT) {
if (mostRecentSwaps[token1]) {
mostRecentSwaps[token1][token0] = swap;
} else {
mostRecentSwaps[token1] = { [token0]: swap };
}
tokenZero = token1;
tokenOne = token0;
}
const mostRecentSwapsTokenZero = mostRecentSwaps[tokenZero] || {};
const mostRecentSwapsTokenOne = mostRecentSwaps[tokenOne] || {};
writeMostRecentSwapsToFile();
for (const tokenTwo in mostRecentSwapsTokenOne) {
const mostRecentSwapsTokenTwo = mostRecentSwaps[tokenTwo] || {};
for (const tokenThree in mostRecentSwapsTokenTwo) {
if (tokenThree === tokenZero) {
const zeroToOne = mostRecentSwapsTokenZero[tokenOne];
const oneToTwo = mostRecentSwapsTokenOne[tokenTwo];
const twoToZero = mostRecentSwapsTokenTwo[tokenZero];
const _isTriangularArbOpp = isTriangularArbOpp({
zeroToOne,
oneToTwo,
twoToZero,
});
if (_isTriangularArbOpp) {
// TODO: call the contract
console.log(
"🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐🪐"
);
}
}
}
}
};
const getSwapAmountsAndDirection = ({ swap }) => {
return swap.amount0In > 0
? [swap.amount0In, swap.amount1Out, RIGHT]
: [swap.amount1In, swap.amount0Out, LEFT];
};
const getSwapTokenInAndOut = ({ direction, swap }) => {
return direction === RIGHT
? [swap.token0, swap.token1]
: [swap.token1, swap.token0];
};
const getSwapExchangeRate = ({ amountIn, amountOut, tokenIn, tokenOut }) => {
const { [tokenIn]: tokenInDecimals, [tokenOut]: tokenOutDecimals } =
decimals || {};
const adjustedAmountIn = amountIn * 10 ** (18 - tokenInDecimals);
const adjustedAmountOut = amountOut * 10 ** (18 - tokenOutDecimals);
return adjustedAmountOut / adjustedAmountIn;
};
const isTriangularArbOpp = ({ zeroToOne, oneToTwo, twoToZero }) => {
if (!zeroToOne || !oneToTwo || !twoToZero) {
console.log("your business is all undefined friend");
return false;
}
let tooOld = false;
let tooExpensive = false;
if (zeroToOne.gasPrice > GAS_PRICE_THRESHOLD) {
tooExpensive = true;
}
if (
currentBlockNumber - SWAP_AGE_THRESHOLD > zeroToOne.blockNumber ||
currentBlockNumber - SWAP_AGE_THRESHOLD > oneToTwo.blockNumber ||
currentBlockNumber - SWAP_AGE_THRESHOLD > twoToZero.blockNumber
) {
tooOld = true;
}
const [zeroToOneAmountIn, zeroToOneAmountOut, zeroToOneDirection] =
getSwapAmountsAndDirection({ swap: zeroToOne });
const [zeroToOneTokenIn, zeroToOneTokenOut] = getSwapTokenInAndOut({
direction: zeroToOneDirection,
swap: zeroToOne,
});
const zeroToOneExchangeRate = getSwapExchangeRate({
amountIn: zeroToOneAmountIn,
amountOut: zeroToOneAmountOut,
direction: zeroToOneDirection,
tokenIn: zeroToOneTokenIn,
tokenOut: zeroToOneTokenOut,
});
const [oneToTwoAmountIn, oneToTwoAmountOut, oneToTwoDirection] =
getSwapAmountsAndDirection({ swap: oneToTwo });
const [oneToTwoTokenIn, oneToTwoTokenOut] = getSwapTokenInAndOut({
direction: oneToTwoDirection,
swap: oneToTwo,
});
const oneToTwoExchangeRate = getSwapExchangeRate({
amountIn: oneToTwoAmountIn,
amountOut: oneToTwoAmountOut,
direction: oneToTwoDirection,
tokenIn: oneToTwoTokenIn,
tokenOut: oneToTwoTokenOut,
});
const [twoToZeroAmountIn, twoToZeroAmountOut, twoToZeroDirection] =
getSwapAmountsAndDirection({ swap: twoToZero });
const [twoToZeroTokenIn, twoToZeroTokenOut] = getSwapTokenInAndOut({
direction: twoToZeroDirection,
swap: twoToZero,
});
const twoToZeroExchangeRate = getSwapExchangeRate({
amountIn: twoToZeroAmountIn,
amountOut: twoToZeroAmountOut,
direction: twoToZeroDirection,
tokenIn: twoToZeroTokenIn,
tokenOut: twoToZeroTokenOut,
});
const roundTripRate =
zeroToOneExchangeRate * oneToTwoExchangeRate * twoToZeroExchangeRate;
// TODO: bail earlier if tooOld or tooExpensive -- want to watch for now
const isArbOpp =
roundTripRate > ROUND_TRIP_RATE_THRESHOLD && !tooOld && !tooExpensive;
const newLogEntry = {
time: new Date(),
isArbOpp,
roundTripRate,
ROUND_TRIP_RATE_THRESHOLD,
tooOld,
SWAP_AGE_THRESHOLD,
tooExpensive,
GAS_PRICE_THRESHOLD,
zeroToOneExchangeRate,
oneToTwoExchangeRate,
twoToZeroExchangeRate,
zeroToOne,
oneToTwo,
twoToZero,
};
logArbCalcs({ newLogEntry });
return isArbOpp;
};
const logArbCalcs = ({ newLogEntry }) => {
setTimeout(() => {
console.log(newLogEntry);
const stringifiedNewLogEntry = `${JSON.stringify(
newLogEntry,
null,
2
)}\n===========\n`;
const logsFileExists = fs.existsSync(logsFilename);
if (logsFileExists) {
fs.appendFileSync(logsFilename, stringifiedNewLogEntry, (err) => {
if (err) {
console.log("d34fce835a640873b0c3ba51b55b96ae", { err });
}
});
} else {
fs.writeFileSync(logsFilename, stringifiedNewLogEntry, (err) => {
if (err) {
console.log("d34fce835a640873b0c3ba51b55b96ae", { err });
}
});
}
}, 0);
};
const go = async () => {
const mostRecentSwapsFileExists = fs.existsSync(mostRecentSwapsFilename);
if (mostRecentSwapsFileExists) {
mostRecentSwaps = require(path.resolve(mostRecentSwapsFilename));
}
await getReadableGasPrice();
const pairTokens = {};
for (const _pair of pairs) {
const { pair: pairAddress } = _pair;
const pairContract = new Contract(uniswapPairAbi, pairAddress);
let token0, token1;
await pairContract.methods
.token0()
.call()
.then((_token0) => {
if (token0 !== ZERO_ADDRESS) {
token0 = _token0;
}
})
.catch((err) => console.log("e856a32d0b552e8c64aa08896b1748da", { err }));
await pairContract.methods
.token1()
.call()
.then((_token1) => {
if (token1 !== ZERO_ADDRESS) {
token1 = _token1;
}
})
.catch((err) => console.log("093547cee5726047869efa655ac5e6e1", { err }));
pairTokens[pairAddress] = { token0, token1 };
pairContract.events.Swap((err, res) => {
if (err) {
console.log("bcf23dfcdd1a69adfe495dc96a2af975", { err });
return;
}
const { address } = res || {};
const { token0, token1 } = pairTokens[address] || {};
if (token0 && token1) {
shouldArb({ res, token0, token1 });
} else {
console.log(`uh oh no token0 and token1 for ${address}`);
}
});
}
};
go();