-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
290 lines (256 loc) · 10.4 KB
/
index.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
// Require packages
require('dotenv').config();
const { Wallet, ethers, providers } = require('ethers');
const { FlashbotsBundleProvider, FlashbotsBundleResolution } = require('@flashbots/ethers-provider-bundle');
// Require ABIs and Bytecode
const { UniswapAbi, UniswapBytecode, UniswapFactoryAbi, UniswapFactoryBytecode, pairAbi, pairBytecode, erc20Abi, erc20Bytecode, uniswapV3Abi } = require('./abi');
// User configurable variables
const BRIBE_TO_MINERS = ethers.utils.parseUnits('20', 'gwei');
const BUY_AMOUNT = ethers.utils.parseUnits('0.1', 'ether');
const CHAIN_ID = 5;
// Providers
const httpProvider = new ethers.providers.JsonRpcProvider(process.env.HTTP_PROVIDER_URL);
const wsProvider = new ethers.providers.WebSocketProvider(process.env.WS_PROVIDER_URL);
// Set up contracts and providers
const signingWallet = new Wallet(process.env.PRIVATE_KEY).connect(wsProvider);
const uniswapV3Interface = new ethers.utils.Interface(uniswapV3Abi);
const uniswapFactory = new ethers.ContractFactory(UniswapFactoryAbi, UniswapFactoryBytecode, signingWallet).attach(process.env.UNISWAP_FACTORY_ADDRESS);
const erc20Factory = new ethers.ContractFactory(erc20Abi, erc20Bytecode, signingWallet);
const pairFactory = new ethers.ContractFactory(pairAbi, pairBytecode, signingWallet);
const uniswap = new ethers.ContractFactory(UniswapAbi, UniswapBytecode, signingWallet).attach(process.env.UNISWAP_ADDRESS);
// Decode uniswap universal router transactions
const decodeUniversalRouterSwap = (input) => {
const abiCoder = new ethers.utils.AbiCoder();
const decodedParameters = abiCoder.decode(['address', 'uint256', 'uint256', 'bytes', 'bool'], input);
const breakdown = input.substring(2).match(/.{1,64}/g);
let path = [];
let hasTwoPath = true;
if (breakdown.length != 9) {
const pathOne = '0x' + breakdown[breakdown.length - 2].substring(24);
const pathTwo = '0x' + breakdown[breakdown.length - 1].substring(24);
path = [pathOne, pathTwo];
} else {
hasTwoPath = false;
}
return {
recipient: parseInt(decodedParameters[(0, 16)]),
amountIn: decodedParameters[1],
minAmountOut: decodedParameters[2],
path,
hasTwoPath,
};
};
// Set up initial checks
const initialChecks = async (tx) => {
let transaction = null;
let decoded = null;
let decodedSwap = null;
try {
transaction = await httpProvider.getTransaction(tx);
} catch (error) {
console.error(error);
return false;
}
if (!transaction || !transaction.to) {
return false;
}
if (!transaction.maxPriorityFeePerGas) {
return false;
}
if (Number(transaction.value) == 0) return false;
if (transaction.to.toLowerCase() != process.env.UNIVERSAL_ROUTER_ADDRESS.toLowerCase()) return false;
try {
decoded = uniswapV3Interface.parseTransaction(transaction);
} catch (error) {
console.error(error);
return false;
}
// check to make sure the swap is for uniswapV2
if (!decoded.args.commands.includes('08')) return false;
let swapPositionInCommands = decoded.args.commands.substring(2).indexOf('08') / 2;
let inputPosition = decoded.args.inputs[swapPositionInCommands];
decodedSwap = decodeUniversalRouterSwap(inputPosition);
if (!decodedSwap.hasTwoPath) return false;
if (decodedSwap.recipient === 2) return false;
if (decodedSwap.path[0].toLowerCase() != process.env.WETH_ADDRESS.toLowerCase()) return false;
return {
transaction,
amountIn: transaction.value,
minAmountOut: decodedSwap.minAmountOut,
tokenToCapture: decodedSwap.path[1],
};
};
// Calculate amount out
const getAmountOut = (amountIn, reserveIn, reserveOut) => {
if (amountIn <= 0) {
console.log('Insufficient Input Amount');
return false;
}
if (reserveIn <= 0 || reserveOut <= 0) {
console.log('Insufficient Liquidity');
return false;
}
const amountInWithFee = amountIn.mul(997);
const numerator = amountInWithFee.mul(reserveOut);
const denominator = reserveIn.mul(1000).add(amountInWithFee);
return numerator.div(denominator);
};
// Process transaction
const processTransaction = async (tx) => {
const checksPassed = await initialChecks(tx);
if (!checksPassed) return false;
const { transaction, amountIn, minAmountOut, tokenToCapture } = checksPassed;
// Get and sort the reserves
const pairAddress = await uniswapFactory.getPair(process.env.WETH_ADDRESS, tokenToCapture);
const pair = pairFactory.attach(pairAddress);
let reserves = null;
try {
reserves = await pair.getReserves();
} catch (error) {
console.error(error);
return false;
}
let a;
let b;
if (process.env.WETH_ADDRESS < tokenToCapture) {
a = reserves._reserve0;
b = reserves._reserve1;
} else {
a = reserves._reserve1;
b = reserves._reserve0;
}
// Get fee costs. for simplicity we'll add the user's gas fee
const maxGasFee = transaction.maxFeePerGas ? transaction.maxFeePerGas.add(BRIBE_TO_MINERS) : BRIBE_TO_MINERS;
const priorityFee = transaction.maxPriorityFeePerGas.add(BRIBE_TO_MINERS);
// Buy using amount in and calculate amount out
let firstAmountOut = getAmountOut(BUY_AMOUNT, a, b);
const updatedReserveA = a.add(BUY_AMOUNT);
const updatedReserveB = b.add(firstAmountOut);
let secondBuyAmount = getAmountOut(amountIn, updatedReserveA, updatedReserveB);
if (secondBuyAmount.lt(minAmountOut)) return console.log('Victim would get less than the minimum');
const updatedReserveA2 = updatedReserveA.add(amountIn);
const updatedReserveB2 = updatedReserveB.add(secondBuyAmount);
let thirdAmountOut = getAmountOut(firstAmountOut, updatedReserveB2, updatedReserveA2);
// Prepare first transaction
const deadline = Math.floor(Date.now() / 1000) + 60 * 60; //1 hour from now
let firstTransaction = {
signer: signingWallet,
transaction: await uniswap.populateTransaction.swapExactETHForTokens(firstAmountOut, [process.env.WETH_ADDRESS, tokenToCapture], signingWallet.address, deadline, {
value: BUY_AMOUNT,
type: 2,
maxFeePerGas: maxGasFee,
maxPriorityFeePerGas: priorityFee,
gasLimit: 300000,
}),
};
firstTransaction.transaction = {
...firstTransaction.transaction,
chainId: CHAIN_ID,
};
// Prepare second transaction
const victimsTransactionWithChainId = {
chainId: CHAIN_ID,
...transaction,
};
const signedMiddleTransaction = {
signedTransaction: ethers.utils.serializeTransaction(victimsTransactionWithChainId, {
r: victimsTransactionWithChainId.r,
s: victimsTransactionWithChainId.s,
v: victimsTransactionWithChainId.v,
}),
};
// Prepare the third transaction
const erc20 = erc20Factory.attach(tokenToCapture);
let thirdTransaction = {
signer: signingWallet,
transaction: await erc20.populateTransaction.approve(process.env.UNISWAP_ADDRESS, firstAmountOut, {
value: '0',
type: 2,
maxFeePerGas: maxGasFee,
maxPriorityFeePerGas: priorityFee,
gasLimit: 300000,
}),
};
thirdTransaction.transaction = {
...thirdTransaction.transaction,
chainId: CHAIN_ID,
};
// Prepare the fourth transaction
let fourthTransaction = {
signer: signingWallet,
transaction: await uniswap.populateTransaction.swapExactTokensForETH(firstAmountOut, thirdAmountOut, [tokenToCapture, process.env.WETH_ADDRESS], signingWallet.address, deadline, {
value: '0',
type: 2,
maxFeePerGas: maxGasFee,
maxPriorityFeePerGas: priorityFee,
gasLimit: 300000,
}),
};
fourthTransaction.transaction = {
...fourthTransaction.transaction,
chainId: CHAIN_ID,
};
const transactionsArray = [firstTransaction, signedMiddleTransaction, thirdTransaction, fourthTransaction];
const signedTransactions = await flashbotsProvider.signBundle(transactionsArray);
const blockNumber = await httpProvider.getBlockNumber();
console.log('simulating...');
const simulation = await flashbotsProvider.simulate(signedTransactions, blockNumber + 1);
if (simulation.firstRevert) {
return console.log('Simulation error', simulation.firstRevert);
} else {
console.log('Simulation success', simulation);
}
// Send transactions with flashbots
let bundleSubmission;
flashbotsProvider
.sendRawBundle(signedTransactions, blockNumber + 1)
.then((_bundleSubmission) => {
bundleSubmission = _bundleSubmission;
console.log('Bundle submitted', bundleSubmission.bundleHash);
return bundleSubmission.wait();
})
.then(async (waitResponse) => {
console.log('Wait response', FlashbotsBundleResolution[waitResponse]);
if (waitResponse == FlashbotsBundleResolution.BundleIncluded) {
console.log('---------------------------------------------');
console.log('---------------------------------------------');
console.log('-------------- Bundle Included --------------');
console.log('---------------------------------------------');
console.log('---------------------------------------------');
} else if (waitResponse == FlashbotsBundleResolution.AccountNonceTooHigh) {
console.log('The transaction has been confirmed already');
} else {
console.log('Bundle hash: ', bundleSubmission.bundleHash);
try {
console.log({
bundleStats: await flashbotsProvider.getBundleStats(bundleSubmission.bundleHash, blockNumber + 1),
userStats: await flashbotsProvider.getUserStats(),
});
} catch (error) {
console.error(error);
return false;
}
}
});
};
// Create the start function to listen to transactions
const start = async () => {
flashbotsProvider = await FlashbotsBundleProvider.create(httpProvider, signingWallet, process.env.FLASHBOTS_URL);
console.log('Listening for transactions on chain ID #', CHAIN_ID);
wsProvider.on('pending', (tx) => {
console.log('TX: ', tx);
processTransaction(tx);
});
};
start();
// Next steps:
// - Calculate gas costs
// - Estimate the next base fee
// - Calculate amounts out locally
// - Use multiple block builders besides flashbots
// - Reduce gas costs by using an assembly yul contract
// - Use multiple cores from your computer to improve performance
// - Calculate the transaction array for type 0 and type 2 transactions
// - Implement multiple dexes like uniswap, shibaswap, sushiswap and others
// - Calculate the pair address locally with a function without a blockchain request
// - Calculate the exact amount you'll get in profit after the first, middle and last trade without a request and without loops