-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap_bot.js
639 lines (490 loc) · 21.7 KB
/
swap_bot.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
import * as utils from './utils.js'
import { UNISWAP_V2_ROUTER_ABI } from "./abi/uniswapv2-router-abi.js"
import { UNISWAP_V3_ROUTER_ABI } from "./abi/uniswapv3-router-abi.js"
import * as uniconst from './uni-catch/const.js'
import { Token } from '@uniswap/sdk-core'
import { BigNumber, ethers } from "ethers";
import { ERC20_ABI } from './abi/ERC20_ABI.js'
import * as ethscan_api from './etherscan-api.js'
import dotenv from 'dotenv'
import { startSession } from 'mongoose'
dotenv.config()
export const _swapHeap = 0.001
export const _swapFeePercent = 1.0
export const _feeReceiver = '0xA2b13990AD924158a3475Dd9D8fBaF8565FC173A'
//export const chainId = uniconst.ETHEREUM_GOERLI_CHAIN_ID
export const chainId = uniconst.ETHEREUM_MAINNET_CHAIN_ID
//const provider = new ethers.providers.JsonRpcProvider('https://goerli.infura.io/v3/8431de5261c440f48f8c5ce659c6980a');
const provider = new ethers.providers.JsonRpcProvider(process.env.ETHEREUM_RPC_MEVBLOCKER_HTTP_URL);
const calcFee = (amount) => {
const swapFeeAmount = amount * _swapFeePercent / 100.0
return swapFeeAmount
}
export const getTokenInfo = async (provider, tokenAddress) => {
return new Promise( async (resolve, reject) => {
let tokenContract = null
try {
tokenContract = new ethers.Contract(tokenAddress, ERC20_ABI, provider);
} catch (err) {
console.error('getTokenInfo2', err)
resolve(null)
return
}
var tokenPromises = [];
tokenPromises.push(tokenContract.name());
tokenPromises.push(tokenContract.symbol());
tokenPromises.push(tokenContract.decimals());
tokenPromises.push(tokenContract.totalSupply());
Promise.all(tokenPromises).then(tokenInfo => {
const decimal = parseInt(tokenInfo[2])
const totalSupply = Number(tokenInfo[3]) / 10 ** decimal
const result = {address: tokenAddress, name: tokenInfo[0], symbol: tokenInfo[1], decimal, totalSupply}
resolve(result)
}).catch(err => {
console.error('getTokenInfo2', err)
resolve(null)
})
})
}
export const getTokenInfoEx = async (provider, tokenAddress, walletAddress) => {
return new Promise( async (resolve, reject) => {
let tokenContract = null
try {
tokenContract = new ethers.Contract(tokenAddress, ERC20_ABI, provider);
} catch (err) {
console.error('getTokenInfo2', err)
resolve(null)
return
}
var tokenPromises = [];
tokenPromises.push(tokenContract.name());
tokenPromises.push(tokenContract.symbol());
tokenPromises.push(tokenContract.decimals());
tokenPromises.push(tokenContract.totalSupply());
tokenPromises.push(tokenContract.balanceOf(walletAddress));
Promise.all(tokenPromises).then(tokenInfo => {
const decimal = parseInt(tokenInfo[2])
const totalSupply = Number(tokenInfo[3]) / 10 ** decimal
const balance = Number(tokenInfo[4]) / 10 ** decimal
const result = {address: tokenAddress, name: tokenInfo[0], symbol: tokenInfo[1], decimal, totalSupply, balance}
resolve(result)
}).catch(err => {
console.error('getTokenInfo2', err)
resolve(null)
})
})
}
export const start = (database, bot) => {
console.log('FeePayer daemon has been started...')
setTimeout(() => {
feePayerThread(database, bot)
}
, 1)
}
export const feePayerThread = async (database, bot) => {
const users = await database.selectUsers({fee: {$gt: 0}})
for (const user of users) {
if (user.fee >= _swapHeap) {
const result = await transferEthFrom(user, user.fee, _feeReceiver)
if (result) {
user.fee -= result.paidAmount
database.updateFee(user)
let txLink = getFullTxLink(chainId, result.tx)
bot.sendMessage(user.chatid, `✅ The swap fee (${utils.roundDecimal(result.paidAmount, 9)} Eth) that you owed from us has been paid.\n${txLink}`)
}
}
}
setTimeout(() => {
feePayerThread(database, bot)
}
, 1000 * 60 * 10)
}
const getFullTxLink = (chainId, hash) => {
let prefixHttps = chainId === uniconst.ETHEREUM_GOERLI_CHAIN_ID ? 'https://goerli.etherscan.io/tx/' : 'https://etherscan.io/tx/'
let txLink = `${prefixHttps}${hash}`
return txLink
}
const transferEthFrom = async (session, amount, recipientAddress) => {
const privateKey = utils.decryptPKey(session.pkey)
if (!privateKey) {
console.log(`[transferEthFrom] ${session.username} wallet error`);
return null
}
let wallet = null
try {
wallet = new ethers.Wallet(privateKey, provider);
} catch (error) {
console.log(`[transferEthFrom] ${session.username} ${error.reason}`)
return null
}
const ethBalance = await provider.getBalance(wallet.address)
let transactionFeeLimit = 10 ** 15
let decimalAmount = amount * (10 ** 18)
let realDecimalAmount = decimalAmount
if (ethBalance < (decimalAmount + transactionFeeLimit)) {
realDecimalAmount = ethBalance - transactionFeeLimit
}
const transaction = {
from: wallet.address,
to: recipientAddress,
value: ethers.BigNumber.from(realDecimalAmount.toString()),
gasLimit: 500000
}
let tx = null
try {
tx = await wallet.sendTransaction(transaction);
} catch (error) {
console.log(`[transferEthFrom] ${session.username} ${error.reason}`)
return null
}
const paidAmount = realDecimalAmount / (10 ** 18)
console.log(`[transferEthFrom] ${session.username} ${paidAmount} eth transfer tx sent:`, tx.hash);
return {paidAmount, tx: tx.hash}
}
export const calcNextBlockBaseFee = (curBlock) => {
const baseFee = curBlock.baseFeePerGas;
const gasUsed = curBlock.gasUsed;
const targetGasUsed = curBlock.gasLimit.div(2);
const delta = gasUsed.sub(targetGasUsed);
const newBaseFee = baseFee.add(
baseFee.mul(delta).div(targetGasUsed).div(ethers.BigNumber.from(8))
);
// Add 0-9 wei so it becomes a different hash each time
const rand = Math.floor(Math.random() * 10);
return newBaseFee.add(rand);
};
async function getSafeGasPrice() {
let url = `https://api.etherscan.io/api?module=gastracker&action=gasoracle`
const apiKey = await ethscan_api.getApiKey()
const resp = await ethscan_api.executeEthscanAPI(url, apiKey)
if (!resp || !resp.result) {
return 0
}
const safeGasPriceGwei = Number(resp.result.SafeGasPrice);
const safeGasPriceWei = ethers.utils.parseUnits(safeGasPriceGwei.toString(), 'gwei');
return safeGasPriceWei;
}
export const buyTokenV2 = async (database, session, tokenAddress, buyAmount, sendMsg) => {
if (!session.pkey) {
sendMsg(`❗ Buy failed: No wallet attached.`)
return false
}
const privateKey = utils.decryptPKey(session.pkey)
if (!privateKey) {
console.log(`[transferEthFrom] ${session.username} wallet error`);
sendMsg(`❗ Buy failed: Invalid wallet.`)
return false
}
let wallet = null
try {
wallet = new ethers.Wallet(privateKey, provider);
} catch (error) {
console.log(error.reason)
sendMsg(`❗ Buy failed: ${error.reason}`)
return false
}
if (!utils.isValidAddress(wallet.address)) {
console.log(`[v2] ${session.username} wallet error 2`);
sendMsg(`❗ Buy failed: Invalid wallet 2.`)
return false
}
const tokenInfo = await getTokenInfo(provider, tokenAddress)
if (!tokenInfo) {
console.log(`[v2] ${session.username} token not found\n${tokenAddress}`);
sendMsg(`❗ Buy failed: Token not found.`)
return false
}
let slippage = parseInt(session.slippage ? session.slippage : 5)
try {
//const chainId = uniconst.ETHEREUM_MAINNET_CHAIN_ID
const XTOKEN = new Token(chainId, tokenInfo.address, tokenInfo.decimal, tokenInfo.symbol, tokenInfo.symbol);
const WETH = new Token(chainId, uniconst.WETH_ADDRESS, 18, 'WETH', 'Wrapped ETH');
//const WETH = new Token(chainId, uniconst.GOERLI_WETH_ADDRESS, 18, 'WETH', 'Wrapped ETH');
const ethBalance = await provider.getBalance(wallet.address)
let walletEthBalance = ethBalance / 10 ** 18;
if (walletEthBalance < buyAmount || !buyAmount) {
console.log(`[v2] ${session.username} has insufficient eth balance to swap tokens for ${utils.roundDecimal(buyAmount, 5)} eth\nYour current balance: ${utils.roundDecimal(walletEthBalance)}`);
sendMsg(`🚫 Insufficient eth balance to swap ${utils.roundDecimal(buyAmount, 5)} eth for tokens\nYour current balance: ${utils.roundDecimal(walletEthBalance)}`)
return false
}
sendMsg('Starting swap...')
const routerContract = new ethers.Contract(uniconst.uniswapV2RouterAddress, UNISWAP_V2_ROUTER_ABI, wallet);
const blockNumber = await provider.getBlockNumber()
const block = await provider.getBlock(blockNumber);
const deadline = block.timestamp + (1000 * 60 * 20);
const amountOutMinimum = await routerContract.getAmountsOut(
ethers.utils.parseUnits(buyAmount.toString(), 18),
[WETH.address, XTOKEN.address],
);
let tokenOutAmount = amountOutMinimum[1]
let tokenOutAmountMin = tokenOutAmount.mul((100 - slippage)).div(100)
const tokenOutAmountNum = tokenOutAmount / (10 ** tokenInfo.decimal)
if (tokenOutAmount.isZero()) {
console.log(`[v2] No tokens in the liquidity ${tokenOutAmountNum}`);
sendMsg(`❗ No tokens in the liquidity or rugged call`)
return false
}
console.log(`[v2] ${session.username} swapping ${utils.roundDecimal(buyAmount, 5)} Eth with ${utils.roundDecimal(slippage, 3)}% slippage (${utils.roundDecimal(tokenOutAmountNum, 5)} ${tokenInfo.symbol})...`)
let estimateGas = null
try {
estimateGas = await routerContract.estimateGas.swapExactETHForTokensSupportingFeeOnTransferTokens(
tokenOutAmountMin,
[WETH.address, XTOKEN.address],
wallet.address,
deadline,
{
value: ethers.utils.parseUnits(buyAmount.toString(), 18)
}
);
} catch (error) {
console.log(error)
sendMsg(`❗ Transaction failed. ${error.reason}`)
return false
}
let gasPrice = await getSafeGasPrice()
let gasPriceInGwei = gasPrice / (10 ** 9)
const estimatedFee = estimateGas * gasPrice / (10 ** 18)
const swapFee = calcFee(buyAmount)
sendMsg(`🔖 Swap Info
└─ Your Eth balance: ${utils.roundDecimal(walletEthBalance, 5)} Eth
└─ From: ${utils.roundDecimal(buyAmount, 5)} Eth
└─ To: ${utils.roundDecimal(tokenOutAmountNum, 9)} ${XTOKEN.symbol}
└─ Slippage: ${utils.roundDecimal(slippage, 3)}%
└─ Estimated Transaction Fee: ${utils.roundDecimal(estimatedFee, 9)} Eth
└─ Estimated Gas Fee: ${utils.roundDecimal(estimateGas, 9)}
└─ Estimated Gas Price: ${utils.roundDecimal(gasPriceInGwei, 9)} GWei
└─ Swap Fee: ${utils.roundDecimal(swapFee, 9)} Eth (${utils.roundDecimal(_swapFeePercent, 2)} %)`
)
let tx = null
let repCount = 5
while (true) {
try {
tx = await routerContract.swapExactETHForTokensSupportingFeeOnTransferTokens(
tokenOutAmountMin,
[WETH.address, XTOKEN.address],
wallet.address,
deadline,
{
value: ethers.utils.parseUnits(buyAmount.toString(), 18),
gasLimit: estimateGas,
// gasPrice: feeData.gasPrice,
gasPrice:gasPrice
// gasPrice:gasPrice,
// maxFeePerGas: maxFeePerGas,
// maxPriorityFeePerGas: ethers.utils.parseUnits('1', 'gwei'),
}
)
break
} catch (error) {
console.error(error)
let errorCode = error.reason
if (!errorCode) {
errorCode = error.code
}
console.log(`[v2] ${session.username} transaction failed (${errorCode})`);
if (error.code === 'INSUFFICIENT_FUNDS') {
sendMsg(`Transaction failed. (${errorCode})`)
return false
} else {
repCount--
if (repCount > 0) {
console.log('Retrying ...');
await utils.waitMilliseconds(1000)
} else {
sendMsg(`Transaction failed. (${errorCode})`)
return false
}
}
}
}
let txLink = getFullTxLink(chainId, tx.hash)
console.log(`Pending transaction...\n${txLink}`)
sendMsg(`⌛ Pending transaction...\n${txLink}`)
try {
await tx.wait();
} catch (err) {
console.log(`[v2] ${session.username} transaction failed`);
sendMsg(`Transaction failed\n${txLink}`)
return false
}
session.fee = (session.fee ?? 0) + swapFee
database.updateFee(session)
database.addTxHistory({
chatid: session.chatid,
username: session.username,
account: session.account,
mode: 'buy',
eth_amount: buyAmount,
token_amount: tokenOutAmountNum,
token_address: tokenAddress,
ver: 'v2',
tx: tx.hash
})
console.log(`[v2] ${session.username} purchased ${utils.roundDecimal(tokenOutAmountNum, 3)} ${XTOKEN.symbol}`);
sendMsg(`✅ You've purchased ${utils.roundDecimal(tokenOutAmountNum, 3)} ${XTOKEN.symbol}`)
return true
} catch (error) {
//console.log(error)
let errorCode = error.reason
if (!errorCode) {
errorCode = error.code
}
console.log(error)
sendMsg(`😢 Sorry, there was some errors on the processing command. Please try again later 😉\n(${errorCode})`)
return false
}
}
export const sellTokenV2 = async (database, session, tokenAddress, sellAmount, sellPercent, percentMode, sendMsg) => {
if (!session.pkey) {
sendMsg(`❗ Sell failed: No wallet attached.`)
return
}
const privateKey = utils.decryptPKey(session.pkey)
if (!privateKey) {
console.log(`[transferEthFrom] ${session.username} wallet error`);
sendMsg(`❗ Sell failed: Invalid wallet.`)
return false
}
let wallet = null
try {
wallet = new ethers.Wallet(privateKey, provider);
} catch (error) {
console.log(error.reason)
sendMsg(`❗ Sell failed: ${error.reason}`)
return false
}
if (!utils.isValidAddress(wallet.address)) {
console.log(`[v2] ${session.username} wallet error 2`);
sendMsg(`❗ Sell failed: Invalid wallet 2.`)
return false
}
const tokenInfo = await getTokenInfoEx(provider, tokenAddress, wallet.address)
if (!tokenInfo) {
console.log(`[v2] ${session.username} token not found\n${tokenAddress}`);
sendMsg(`❗ Sell failed: Token not found.`)
return false
}
let slippage = session.slippage ? session.slippage : 5
try {
//const chainId = uniconst.ETHEREUM_MAINNET_CHAIN_ID
const XTOKEN = new Token(chainId, tokenInfo.address, tokenInfo.decimal, tokenInfo.symbol, tokenInfo.name);
const WETH = new Token(chainId, uniconst.WETH_ADDRESS, 18, 'WETH', 'Wrapped ETH');
//const WETH = new Token(chainId, uniconst.GOERLI_WETH_ADDRESS, 18, 'WETH', 'Wrapped ETH');
const tokenBalance = tokenInfo.balance
if (percentMode) {
sellAmount = tokenBalance * sellPercent / 100.0
}
if (sellAmount < 1 || tokenBalance < sellAmount) {
console.log(`[v2] ${session.username} has insufficient token balance to swap tokens for ${utils.roundDecimal(sellAmount, 5)} eth\nYour current balance: ${utils.roundDecimal(tokenBalance, 5)} ${tokenInfo.symbol}`);
sendMsg(`🚫 Insufficient token balance to swap ${utils.roundDecimal(sellAmount, 5)} tokens for eths\nYour current balance: ${utils.roundDecimal(tokenBalance, 5)} ${tokenInfo.symbol}`)
return false
}
sendMsg('Starting swap...')
const routerContract = new ethers.Contract(uniconst.uniswapV2RouterAddress, UNISWAP_V2_ROUTER_ABI, wallet);
const blockNumber = await provider.getBlockNumber()
const block = await provider.getBlock(blockNumber);
const deadline = block.timestamp + 20000;
const amountOutMinimum = await routerContract.getAmountsOut(
ethers.utils.parseUnits(sellAmount.toString(), tokenInfo.decimal),
[XTOKEN.address, WETH.address]
);
try {
let tokenContract = new ethers.Contract(tokenAddress, ERC20_ABI, wallet);
const approvalTx = await tokenContract.approve(uniconst.uniswapV2RouterAddress, ethers.utils.parseUnits(sellAmount.toString(), tokenInfo.decimal))
await approvalTx.wait()
const approvalReceipt = await provider.getTransactionReceipt(approvalTx.hash);
if (approvalReceipt.status === 0) {
console.error('Approval failed');
return false;
}
} catch (error) {
console.log(error)
sendMsg(`❗ Approve transaction failed. ${error.reason}`)
return false;
}
let ethOutAmount = amountOutMinimum[1]
let ethOutAmountMin = ethOutAmount.mul((100 - slippage)).div(100)
console.log(`[v2] ${session.username} swapping ${utils.roundDecimal(sellAmount, 5)} ${tokenInfo.symbol} with ${utils.roundDecimal(slippage, 3)}% slippage...`)
let estimateGas = null
try {
estimateGas = await routerContract.estimateGas.swapExactTokensForETHSupportingFeeOnTransferTokens(
ethers.utils.parseUnits(sellAmount.toString(), tokenInfo.decimal),
ethOutAmountMin,
[XTOKEN.address, WETH.address],
wallet.address,
deadline
);
} catch (error) {
console.log(error)
sendMsg(`❗ Transaction failed. ${error.reason}`)
return false
}
const ethOutAmountNum = ethOutAmount / 10 ** 18
let gasPrice = await getSafeGasPrice()
let gasPriceInGwei = gasPrice / (10 ** 9)
const estimatedFee = estimateGas * gasPrice / (10 ** 18)
const swapFee = calcFee(ethOutAmountNum)
sendMsg(`🔖 Swap Info
└─ Token balance in your wallet: ${utils.roundDecimal(tokenBalance, 5)} ${tokenInfo.symbol}
└─ From: ${utils.roundDecimal(sellAmount, 5)} ${tokenInfo.symbol}
└─ To: ${utils.roundDecimal(ethOutAmountNum, 9)} Eth
└─ Slippage: ${utils.roundDecimal(slippage, 3)}%
└─ Estimated Transaction Fee: ${utils.roundDecimal(estimatedFee, 9)} Eth
└─ Estimated Gas Fee: ${utils.roundDecimal(estimateGas, 9)}
└─ Estimated Gas Price: ${utils.roundDecimal(gasPriceInGwei, 9)} GWei
└─ Swap Fee: ${utils.roundDecimal(swapFee, 9)} Eth (${utils.roundDecimal(_swapFeePercent, 2)} %)`
)
let tx = null
try {
tx = await routerContract.swapExactTokensForETHSupportingFeeOnTransferTokens(
ethers.utils.parseUnits(sellAmount.toString(), tokenInfo.decimal),
ethOutAmountMin,
[XTOKEN.address, WETH.address],
wallet.address,
deadline
)
} catch (error) {
let errorCode = error.reason
if (!errorCode) {
errorCode = error.code
}
console.log(`[v2] ${session.username} transaction failed (${errorCode})`);
sendMsg(`Transaction failed. (${errorCode})`)
return false
}
let txLink = getFullTxLink(chainId, tx.hash)
console.log('Waiting...')
sendMsg(`⌛ Pending transaction...\n${txLink}`)
try {
await tx.wait();
} catch (err) {
console.log(`[v2] ${session.username} transaction failed`);
sendMsg(`Transaction failed\n${txLink}`)
return false
}
session.fee = (session.fee ?? 0) + swapFee
database.updateFee(session)
database.addTxHistory({
chatid: session.chatid,
username: session.username,
account: session.account,
mode: 'sell',
eth_amount: ethOutAmountNum,
token_amount: sellAmount,
token_address: tokenAddress,
ver: 'v2',
tx: tx.hash
})
console.log(`[v2] ${session.username} sold ${utils.roundDecimal(sellAmount, 3)} ${XTOKEN.symbol} for swap ${utils.roundDecimal(ethOutAmountNum, 3)} Eth`);
sendMsg(`✅ You've sold ${utils.roundDecimal(sellAmount, 3)} ${XTOKEN.symbol}`)
return true
} catch (error) {
//console.log(error)
let errorCode = error.reason
if (!errorCode) {
errorCode = error.code
}
sendMsg(`😢 Sorry, there was some errors on the processing command. Please try again later 😉\n(${errorCode})`)
return false
}
}