-
Notifications
You must be signed in to change notification settings - Fork 38
/
lib.js
95 lines (80 loc) · 2.39 KB
/
lib.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
const fs = require('fs');
const log = (message, ...optionalParams) => {
if (process.env.ENABLE_LOGGING === 'true') {
console.log(message, ...optionalParams);
}
};
const aToBProfit = (
flashFee,
amountIn,
highestPlatform,
lowestPlatform,
network = null,
baseToken = null
) => {
let trade1Ratio = highestPlatform.ratio;
let trade2Ratio = lowestPlatform.ratio;
if (trade1Ratio < trade2Ratio) {
console.error('Logic failure, trade1Ratio is less than trade2Ratio');
return -1;
}
trade1Ratio = trade1Ratio * amountIn; // token1
let amountAfterTrade2 = trade1Ratio * (1 / trade2Ratio); // token0
const amountOut = amountAfterTrade2 - flashFee * amountIn; // token0
const profit = amountOut - amountIn; // token0
log(
`Potential profit (${highestPlatform.name} in, ${lowestPlatform.name} out):`,
profit
);
if (profit > 0) {
if (highestPlatform && lowestPlatform && baseToken) {
const filePath = process.env.LOG_FILE;
if (filePath && filePath !== '') {
const data = `${network},${highestPlatform.name},${lowestPlatform.name},${baseToken},${flashFee},${amountIn},${trade1Ratio},${amountAfterTrade2},${amountOut},${profit}\n`;
// check if file exists
if (!fs.existsSync(filePath)) {
fs.writeFileSync(
filePath,
'network, highestPlatform,lowestPlatform,baseToken,flashFee,amountIn,amountAfterTrade1,amountAfterTrade2,amountOut,profit\n'
);
}
fs.appendFile(filePath, data, { flag: 'a+' }, (err) => {
if (err) {
console.error('Failed to save opportunity:', err);
}
});
}
}
}
// Return the profit
return profit;
};
const getOppositPlatforms = (cache) => {
if (Object.keys(cache).length < 2) {
return null;
}
// Compare all items in cache
let highest = 0;
let highestPlatform = null;
for (const platform in cache) {
if (cache[platform] > highest) {
highest = cache[platform];
highestPlatform = platform;
}
}
// Now get lowest
let lowest = Infinity; // Initialize with Infinity so any number will be lower
let lowestPlatform = null;
for (const platform in cache) {
if (cache[platform] < lowest) {
lowest = cache[platform];
lowestPlatform = platform;
}
}
return { highestPlatform, lowestPlatform };
};
module.exports = {
aToBProfit,
getOppositPlatforms,
log,
};