-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.js
201 lines (158 loc) · 7.9 KB
/
main.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
require('dotenv').config();
const Web3 = require('web3');
const BigNumber = require('bignumber.js');
const { performance } = require('perf_hooks');
const FlashswapApi = require('./abi/index').flashswapv2;
const BlockSubscriber = require('./src/block_subscriber');
const Prices = require('./src/prices');
let FLASHSWAP_CONTRACT = process.env.CONTRACT_MAIN;
let FLASHSWAP_CONTRACT_OWNER = process.env.OWNER_MAIN;
const TransactionSender = require('./src/transaction_send_main');
const fs = require('fs');
const util = require('util');
var log_file = fs.createWriteStream(__dirname + '/log_arbitrage_main.txt', { flags: 'w' });
var log_stdout = process.stdout;
console.log = function (d) {
log_file.write(util.format(d) + '\n');
log_stdout.write(util.format(d) + '\n');
};
const web3 = new Web3(
new Web3.providers.WebsocketProvider(process.env.WSS_BLOCKS, {
// Enable auto reconnection
reconnect: {
auto: true,
delay: process.env.DELAY, // ms
maxAttempts: process.env.MAX_ATTEMPTS,
onTimeout: false
}
})
);
const { address: admin } = web3.eth.accounts.wallet.add(process.env.MAINNET_KEY);
const prices = {};
const flashswap = new web3.eth.Contract(FlashswapApi, FLASHSWAP_CONTRACT);
const pairs = require('./src/pairs-main').getPairs();
for (let i = 0; i < pairs.length; i++) {
console.log(`pair ${[i]}: ${pairs[i].name}`);
}
const init = async () => {
// console.log('starting: ', JSON.stringify(pairs.map(p => p.name)));
const transactionSender = TransactionSender.factory(process.env.WSS_BLOCKS.split(','));
let nonce = await web3.eth.getTransactionCount(admin);
let gasPrice = await web3.eth.getGasPrice();
setInterval(async () => {
nonce = await web3.eth.getTransactionCount(admin);
}, 1000 * 19);
setInterval(async () => {
gasPrice = await web3.eth.getGasPrice()
}, 1000 * 60 * 3);
const owner = FLASHSWAP_CONTRACT_OWNER;
console.log(`started: wallet ${admin} - gasPrice ${gasPrice} - contract owner: ${owner}`);
let handler = async () => {
const myPrices = await Prices.getPrices();
if (Object.keys(myPrices).length > 0) {
for (const [key, value] of Object.entries(myPrices)) {
prices[key.toLowerCase()] = value;
}
}
};
await handler();
setInterval(handler, 1000 * 60 * 5);
const onBlock = async (block, web3, provider) => {
const start = performance.now();
const calls = [];
const flashswap = new web3.eth.Contract(FlashswapApi, FLASHSWAP_CONTRACT);
pairs.forEach((pair) => {
calls.push(async () => {
const check = await flashswap.methods.check(pair.tokenBorrow, pair.tokenPay, new BigNumber(pair.amountTokenPay * 1e18), pair.sourceRouter, pair.targetRouter).call();
const profit = check[0];
let s = pair.tokenPay.toLowerCase();
const price = prices[s];
if (!price) {
console.log('invalid price: ', pair.tokenPay);
return;
}
const profitUsd = profit / 1e18 * price;
const percentage = (100 * (profit / 1e18)) / pair.amountTokenPay;
console.log(`[${block.number}] [${new Date().toLocaleString()}]: [${provider}] [${pair.name}] Arbitrage checked! Expected profit: ${(profit / 1e18).toFixed(3)} $${profitUsd.toFixed(2)} - ${percentage.toFixed(2)}%`);
if (profit > 0) {
console.log(`[${block.number}] [${new Date().toLocaleString()}]: [${provider}] [${pair.name}] Arbitrage opportunity found! Expected profit: ${(profit / 1e18).toFixed(3)} $${profitUsd.toFixed(2)} - ${percentage.toFixed(2)}%`);
const tx = flashswap.methods.startArbitrage(
block.number + process.env.BLOCK_NUMBER,
pair.tokenBorrow,
pair.tokenPay,
new BigNumber(pair.amountTokenPay * 1e18),
pair.sourceRouter,
pair.targetRouter,
pair.sourceFactory,
);
let estimateGas
try {
estimateGas = await tx.estimateGas({from: admin});
} catch (e) {
console.log(`[${block.number}] [${new Date().toLocaleString()}]: [${pair.name}]`, 'gasCost error', e.message);
return;
}
const myGasPrice = new BigNumber(gasPrice).plus(gasPrice * process.env.GAS_MULTIPLIER).toString();
const txCostBNB = Web3.utils.toBN(estimateGas) * Web3.utils.toBN(myGasPrice);
let gasCostUsd = (txCostBNB / 1e18) * prices[BNB_MAINNET.toLowerCase()];
const profitMinusFeeInUsd = profitUsd - gasCostUsd;
if (profitMinusFeeInUsd < process.env.EFFECTIVE_PROFIT) {
console.log(`[${block.number}] [${new Date().toLocaleString()}] [${provider}]: [${pair.name}] stopped: `, JSON.stringify({
profit: "$" + profitMinusFeeInUsd.toFixed(2),
profitWithoutGasCost: "$" + profitUsd.toFixed(2),
gasCost: "$" + gasCostUsd.toFixed(2),
duration: `${(performance.now() - start).toFixed(2)} ms`,
provider: provider,
myGasPrice: myGasPrice.toString(),
txCostBNB: txCostBNB / 1e18,
estimateGas: estimateGas,
}));
}
if (profitMinusFeeInUsd >= process.env.EFFECTIVE_PROFIT) {
console.log(`[${block.number}] [${new Date().toLocaleString()}] [${provider}]: [${pair.name}] and go: `, JSON.stringify({
profit: "$" + profitMinusFeeInUsd.toFixed(2),
profitWithoutGasCost: "$" + profitUsd.toFixed(2),
gasCost: "$" + gasCostUsd.toFixed(2),
duration: `${(performance.now() - start).toFixed(2)} ms`,
provider: provider,
}));
const data = tx.encodeABI();
const txData = {
from: admin,
to: flashswap.options.address,
data: data,
gas: estimateGas,
gasPrice: new BigNumber(myGasPrice),
nonce: nonce
};
let number = performance.now() - start;
if (number > 1500) {
console.error('out of time window: ', number);
return;
}
console.log(`[${block.number}] [${new Date().toLocaleString()}] [${provider}]: sending transactions...`, JSON.stringify(txData))
try {
await transactionSender.sendTransaction(txData);
} catch (e) {
console.error('transaction error', e);
}
}
}
})
})
try {
await Promise.all(calls.map(fn => fn()));
} catch (e) {
console.log('promise error', e)
}
let number = performance.now() - start;
if (number > 1500) {
console.error('warning to slow', number);
}
if (block.number % 40 === 0) {
console.log(`[${block.number}] [${new Date().toLocaleString()}]: alive (${provider}) - took ${number.toFixed(2)} ms`);
}
};
BlockSubscriber.subscribe(process.env.WSS_BLOCKS.split(','), onBlock);
}
init();