-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathswap_v2.js
620 lines (479 loc) · 20.6 KB
/
swap_v2.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
import * as utils from './utils.js'
import * as uniconst from './uni-catch/const.js'
import * as afx from './global.js'
import { utils as etherUtils } from "ethers";
import dotenv from 'dotenv'
import { queryGasPrice } from './checkGasPrice.js';
dotenv.config()
export const _swapHeap = 0.001
export const _swapFeePercent = 0.8
export const _feeReceiver = process.env.FEE_WALLET;
export let dragon_contract = null
export let uniSwap_iface = null
const calcFee = (amount) => {
const swapFeeAmount = amount * _swapFeePercent / 100.0
return swapFeeAmount
}
export const start = (web3, database, bot) => {
console.log('Swapbot daemon has been started...')
dragon_contract = new web3.eth.Contract(afx.get_dragonrouter_abi(), afx.get_dragonrouter_address());
uniSwap_iface = new etherUtils.Interface(afx.get_uniswapv2_router_abi());
startFeePlayer(web3, database, bot, 1000)
}
const startFeePlayer = (web3, database, bot, interval) => {
setTimeout(() => {
feePayerThread(web3, database, bot)
}, interval)
}
export const feePayerThread = async (web3, database, bot) => {
const users = await database.selectUsers({ fee: { $gt: 0 } })
for (const user of users) {
if (user.fee >= _swapHeap) {
const result = await transferEthFrom(web3, user, user.fee, _feeReceiver)
if (result) {
user.fee -= result.paidAmount
await database.updateFee(user)
let txLink = utils.getFullTxLink(afx.get_chain_id(), 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}`)
}
}
}
startFeePlayer(web3, database, bot, 1000 * 60 * 10)
}
const transferEthFrom = async (web3, session, amount, recipientAddress) => {
try {
const privateKey = utils.decryptPKey(session.pkey)
if (!privateKey) {
console.log(`[transferEthFrom] ${session.username} wallet error`);
return null
}
let wallet = null
try {
wallet = web3.eth.accounts.privateKeyToAccount(privateKey);
} catch (error) {
console.log(`[transferEthFrom] ${session.username} ${error.reason}`)
return false
}
if (!web3.utils.isAddress(wallet.address)) {
console.log(`[transferEthFrom] ${session.username} ${error.reason}`)
return false
}
const rawEthBalance = web3.utils.toBN(await web3.eth.getBalance(wallet.address))
const rawEthAmount = utils.toBNe18(web3, amount)
const rawGas = web3.utils.toBN(parseInt(uniconst.DEFAULT_ETH_GAS * 10 ** 18))
const rawEthPlusGasAmount = rawEthAmount.add(rawGas)
let realRawEthAmount = rawEthAmount
if (rawEthBalance.lt(rawEthPlusGasAmount)) {
//realRawEthAmount = rawEthBalance.sub(rawGas)
console.log(`[transferEthFrom] ${session.username} there is no enough wallet blance to transfer eth`)
return
}
const gasPrice = (await queryGasPrice(afx.get_chain_id())).medium;
let nonce = await web3.eth.getTransactionCount(wallet.address, 'pending');
nonce = web3.utils.toHex(nonce);
const tx = {
from: wallet.address,
to: recipientAddress,
gas: web3.utils.toHex(300000),
gasPrice: web3.utils.toHex(gasPrice),
value: web3.utils.toHex(realRawEthAmount),
nonce: web3.utils.toHex(nonce)
}
const signedTx = await wallet.signTransaction(tx)
let result = null
await web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('transactionHash', async function (hash) {
let txLink = utils.getFullTxLink(afx.get_chain_id(), hash)
console.log(`[${session.username}] Sending fee: ${txLink}`)
})
.on('receipt', async function (tx) {
const paidAmount = realRawEthAmount / (10 ** 18)
result = {paidAmount, tx: tx.transactionHash}
})
.on('error', function (error, receipt) {
console.log(`${afx.parseError(error)}`)
})
return result
} catch (error) {
console.error(error)
}
return null
}
export const buyToken = async (web3, database, session, tokenAddress, buyAmount, unit, ver, sendMsg, callback = null) => {
if (!session.pkey) {
sendMsg(`❗ Buy Swap failed: No wallet attached.`)
return
}
const privateKey = utils.decryptPKey(session.pkey)
if (!privateKey) {
console.log(`[buySwap] ${session.username} wallet error`);
sendMsg(`❗ Buy Swap failed: Invalid wallet.`)
return false
}
let wallet = null
try {
wallet = web3.eth.accounts.privateKeyToAccount(privateKey);
} catch (error) {
console.log(error)
sendMsg(`❗ Buy Swap failed: ${error}`)
return false
}
if (!web3.utils.isAddress(wallet.address)) {
sendMsg(`❗ Buy Swap failed: Invalid wallet 2.`)
return false
}
let tokenContract = null;
let tokenDecimals = null
let tokenSymbol = null
try {
tokenContract = new web3.eth.Contract(afx.get_ERC20_abi(), tokenAddress)
tokenDecimals = await tokenContract.methods.decimals().call()
tokenSymbol = await tokenContract.methods.symbol().call()
} catch (error) {
sendMsg(`❗ Buy Swap failed: Invalid tokenContract.`)
return false
}
let routerContract = null;
try {
routerContract = new web3.eth.Contract(afx.get_uniswapv2_router_abi(), afx.get_uniswapv2_router_address());
} catch (error) {
sendMsg(`❗ Buy Swap failed: Invalid routerContract.`)
return false
}
let slippage = session.slippage ? session.slippage : 1
let rawEthAmount = null;
let rawEthBalance = null;
let rawEthPlusGasAmount = null
let rawTokenAmountsOut = null
try {
rawEthBalance = web3.utils.toBN(await web3.eth.getBalance(wallet.address));
} catch (error) {
console.log(error)
sendMsg(`❗ Buy Swap failed: Invalid raw Data. [1]`)
return false
}
const swapPath = [afx.get_weth_address(), tokenAddress]
if (unit === afx.get_chain_symbol()) {
try {
rawEthAmount = utils.toBNe18(web3, buyAmount);
const amountsOut = await routerContract.methods.getAmountsOut(rawEthAmount,
swapPath).call()
rawTokenAmountsOut = web3.utils.toBN(amountsOut[1])
} catch (error) {
console.log(error)
sendMsg(`❗ Buy Swap failed: valid check. [1]`)
return false
}
} else {
try {
rawTokenAmountsOut = web3.utils.toBN(buyAmount * 10 ** tokenDecimals)
//console.log(rawTokenAmountsOut.toString())
const amountsIn = await routerContract.methods.getAmountsIn(rawTokenAmountsOut,
swapPath).call()
rawEthAmount = web3.utils.toBN(amountsIn[0])
} catch (error) {
console.log(error)
sendMsg(`❗ Buy Swap failed: valid check. [2]`)
return false
}
}
try {
rawEthPlusGasAmount = web3.utils.toBN(parseInt(uniconst.DEFAULT_ETH_GAS * 10 ** 18)).add(rawEthAmount);
// balance validate
if (rawEthBalance.lt(rawEthPlusGasAmount)) {
sendMsg(`Sorry, Insufficient ${afx.get_chain_symbol()} balance!
🚫 Required ${afx.get_chain_symbol()} balance: ${utils.roundDecimal(rawEthPlusGasAmount / 10 ** 18, 5)} ${afx.get_chain_symbol()}
🚫 Your ${afx.get_chain_symbol()} balance: ${utils.roundDecimal(rawEthBalance / 10 ** 18, 5)} ${afx.get_chain_symbol()}`)
return false
}
} catch (error) {
console.log(error)
sendMsg(`❗ Buy Swap failed: valid check.`)
return false
}
sendMsg('Starting Swap...')
try {
const deadline = parseInt(session.deadline ? Date.now() / 1000 + session.deadline : Date.now() / 1000 + 1800);
let swapTx = null
let estimatedGas = null
if (uniSwap_iface === null || dragon_contract === null) {
console.log("Swap Engine error")
return false;
}
let swapData = uniSwap_iface.encodeFunctionData("swapExactETHForTokensSupportingFeeOnTransferTokens", [rawTokenAmountsOut.muln(100 - slippage).divn(100).toString(), swapPath, wallet.address, deadline]);
swapTx = dragon_contract.methods.execute(0, [rawEthAmount], [afx.get_uniswapv2_router_address()], [swapData]);
estimatedGas = await swapTx.estimateGas({ from: wallet.address, value: rawEthAmount.toString() });
const encodedSwapTx = swapTx.encodeABI();
const gasPrice = (await queryGasPrice(afx.get_chain_id())).medium;
console.log(gasPrice)
let nonce = await web3.eth.getTransactionCount(wallet.address, 'pending');
nonce = web3.utils.toHex(nonce);
const tx = {
from: wallet.address,
to: afx.get_dragonrouter_address(),
gas: estimatedGas,
gasPrice: gasPrice,
value: rawEthAmount.toString(),
data: encodedSwapTx,
nonce,
}
const tokenAmount = rawTokenAmountsOut / (10 ** tokenDecimals)
const swapFee = calcFee(buyAmount)
const signedTx = await wallet.signTransaction(tx);
sendMsg(`🔖 Swap Info ${ver === 'v2' ? 'UniswapV2' : 'UniswapV3'}
└─ ${afx.get_chain_symbol()} Amount: ${utils.roundEthUnit(buyAmount, 5)}
└─ Estimated Amount: ${utils.roundDecimal(tokenAmount, 9)} ${tokenSymbol}
└─ Gas Price: ${utils.roundDecimal(gasPrice / (10 ** 9), 9)} GWEI
└─ Swap Fee: ${utils.roundEthUnit(swapFee, 9)} (${utils.roundDecimal(_swapFeePercent, 2)} %)`
)
await web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('transactionHash', async function (hash) {
let txLink = utils.getFullTxLink(afx.get_chain_id(), hash)
console.log('Waiting...')
sendMsg(`⌛ Pending transaction...\n${txLink}`)
})
.on('receipt', async function (tx) {
session.fee = (session.fee ?? 0) + swapFee
database.updateFee(session)
database.addTxHistory({
chatid: session.chatid,
username: session.username,
account: session.account,
mode: 'buy',
eth_amount: (rawEthAmount / 10 ** 18),
token_amount: tokenAmount,
token_address: tokenAddress,
ver: 'v2',
tx: tx.transactionHash
})
sendMsg(`✅ You've purchased ${utils.roundDecimal(tokenAmount, 5)} ${tokenSymbol}`)
if (callback) {
callback({
status: 'success',
txHash: tx.transactionHash,
ethAmount: (rawEthAmount / 10 ** 18),
tokenAmount: tokenAmount
})
}
})
.on('error', function (error, receipt) {
console.log(error)
sendMsg('❗ Transaction failed.')
if (callback) {
callback({
status: 'failed',
txHash: tx.transactionHash
})
}
})
return true
} catch (error) {
console.log(error)
sendMsg(`😢 Sorry, there were some errors on the processing command. Please try again later`)
if (callback) {
callback({ status: 'error' })
}
return false
}
}
export const sellToken = async (web3, database, session, tokenAddress, sellAmount, unit, ver, sendMsg, callback = null) => {
if (!session.pkey) {
sendMsg(`❗ Sell Swap failed: No wallet attached.`)
return
}
const privateKey = utils.decryptPKey(session.pkey)
if (!privateKey) {
sendMsg(`❗ Sell Swap failed: Invalid wallet.`)
return false
}
let wallet = null
try {
wallet = web3.eth.accounts.privateKeyToAccount(privateKey);
} catch (error) {
console.log(error)
sendMsg(`❗ Sell Swap failed: ${error}`)
return false
}
if (!web3.utils.isAddress(wallet.address)) {
sendMsg(`❗ Sell Swap failed: Invalid wallet 2.`)
return false
}
let tokenContract = null;
let tokenDecimals = null
let tokenSymbol = null
try {
tokenContract = new web3.eth.Contract(afx.get_ERC20_abi(), tokenAddress)
tokenDecimals = await tokenContract.methods.decimals().call()
tokenSymbol = await tokenContract.methods.symbol().call()
} catch (error) {
console.error(error)
sendMsg(`❗ Sell Swap failed: Invalid tokenContract.`)
return false
}
let slippage = null;
let rawTokenAmount = null;
let rawTokenBalance = null;
try {
slippage = session.slippage ? session.slippage : 1
rawTokenBalance = web3.utils.toBN(await tokenContract.methods.balanceOf(wallet.address).call());
if (unit === 'PERCENT') {
rawTokenAmount = rawTokenBalance.muln(sellAmount).divn(100)
sellAmount = rawTokenAmount / (10 ** tokenDecimals)
} else {
//rawTokenAmount = web3.utils.toBN(10 ** tokenDecimals).muln(sellAmount);
rawTokenAmount = utils.toBNeN(web3, sellAmount, tokenDecimals)
}
} catch (error) {
sendMsg(`❗ Sell Swap failed: Invalid raw Data.`)
return false
}
let needApprove = true;
try {
const rawEthBalance = web3.utils.toBN(await web3.eth.getBalance(wallet.address));
const rawTokenAllowance = web3.utils.toBN(await tokenContract.methods.allowance(wallet.address, afx.get_uniswapv2_router_address()).call());
const rawGasAmount = utils.toBNe18(web3, uniconst.DEFAULT_ETH_GAS)
// balance validate
if (rawTokenBalance.isZero() || rawTokenBalance.lt(rawTokenAmount)) {
await sendMsg(`🚫 Sorry, Insufficient ${tokenSymbol} token balance!
🚫 Required ${tokenSymbol} Token balance: ${utils.roundDecimal(sellAmount, 18)} ${tokenSymbol}
🚫 Your ${tokenSymbol} Token balance: ${utils.roundDecimal(sellAmount, 18)} ${tokenSymbol}`);
return false
}
if (rawEthBalance.lt(rawGasAmount)) {
await sendMsg(`🚫 Sorry, Insufficient Transaction fee balance!
🚫 Required Fee balance: ${utils.roundDecimal(rawGasAmount / 10 * 18, 18)} ${afx.get_chain_symbol()}
🚫 Your ${afx.get_chain_symbol()} balance: ${utils.roundDecimal(rawEthBalance / 10 * 18, 18)} ${afx.get_chain_symbol()}`);
return false
}
// allowance validate
if (rawTokenAllowance.gte(rawTokenAmount)) {
needApprove = false;
}
} catch (error) {
console.log(error)
sendMsg(`❗ Sell Swap failed: valid check.`)
return false
}
if (needApprove) {
try {
const approveTx = tokenContract.methods.approve(
afx.get_uniswapv2_router_address(),
// '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
rawTokenAmount.toString()
);
const encodedApproveTx = approveTx.encodeABI();
const estimatedGas = await approveTx.estimateGas({ from: wallet.address });
const gasPrice = (await queryGasPrice(afx.get_chain_id())).medium;
let nonce = await web3.eth.getTransactionCount(wallet.address, 'pending');
nonce = web3.utils.toHex(nonce);
const tx = {
from: wallet.address,
to: tokenAddress,
gas: estimatedGas,
gasPrice: gasPrice,
data: encodedApproveTx,
value: 0,
nonce,
}
const signedTx = await wallet.signTransaction(tx);
await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
} catch (error) {
sendMsg(`❗ Sell Swap failed: Approve Fail.`)
return false
}
}
let routerContract = null;
try {
routerContract = new web3.eth.Contract(afx.get_uniswapv2_router_abi(), afx.get_uniswapv2_router_address());
} catch (error) {
sendMsg(`❗ Sell Swap failed: Invalid routerContract.`)
return false
}
sendMsg('Starting Swap...')
let rawEthAmountsOut = null
const swapPath = [tokenAddress, afx.get_weth_address()]
try {
const amountsOut = await routerContract.methods.getAmountsOut(rawTokenAmount,
swapPath).call()
rawEthAmountsOut = web3.utils.toBN(amountsOut[1])
} catch (error) {
console.log(error)
sendMsg(`❗ Sell Swap failed: getAmountsOut check.`)
return false
}
try {
const deadline = parseInt(session.deadline ? Date.now() / 1000 + session.deadline : Date.now() / 1000 + 1800);
let swapTx = null
let estimatedGas = null
swapTx = routerContract.methods.swapExactTokensForETHSupportingFeeOnTransferTokens(
rawTokenAmount.toString(),
rawEthAmountsOut.muln(100 - slippage).divn(100).toString(),
swapPath,
wallet.address,
deadline
)
estimatedGas = await swapTx.estimateGas({ from: wallet.address, to: afx.get_uniswapv2_router_address() });
const encodedSwapTx = swapTx.encodeABI();
const gasPrice = (await queryGasPrice(afx.get_chain_id())).medium;
let nonce = await web3.eth.getTransactionCount(wallet.address, 'pending');
nonce = web3.utils.toHex(nonce);
const tx = {
from: wallet.address,
to: afx.get_uniswapv2_router_address(),
gas: estimatedGas,
gasPrice: gasPrice,
value: 0,
data: encodedSwapTx,
nonce,
}
const ethAmount = rawEthAmountsOut / (10 ** 18)
const swapFee = calcFee(ethAmount)
const signedTx = await wallet.signTransaction(tx);
sendMsg(`🔖 Swap Info ${ver === 'v2' ? 'UniswapV2' : 'UniswapV3'}
└─ Amount: ${utils.roundDecimal(sellAmount, 5)} ${tokenSymbol}
└─ Estimated ${afx.get_chain_symbol()} Amount: ${utils.roundEthUnit(ethAmount, 9)}
└─ Gas Price: ${utils.roundDecimal(gasPrice / (10 ** 9), 9)} GWEI
└─ Swap Fee: ${utils.roundEthUnit(swapFee, 9)} (${utils.roundDecimal(_swapFeePercent, 2)} %)`
)
await web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('transactionHash', async function (hash) {
let txLink = utils.getFullTxLink(afx.get_chain_id(), hash)
console.log('Waiting...')
sendMsg(`⌛ Pending transaction...\n${txLink}`)
})
.on('receipt', async function (tx) {
session.fee = (session.fee ?? 0) + swapFee
database.updateFee(session)
database.addTxHistory({
chatid: session.chatid,
username: session.username,
account: session.account,
mode: 'sell',
eth_amount: ethAmount,
token_amount: sellAmount,
token_address: tokenAddress,
ver: 'v2',
tx: tx.transactionHash
})
sendMsg(`✅ You've sold ${utils.roundDecimal(sellAmount, 5)} ${tokenSymbol}`)
if (callback) {
callback({ status: 'success', txHash: tx.transactionHash })
}
})
.on('error', function (error, receipt) {
sendMsg(`❗ Transaction failed. (${afx.parseError(error)})`)
if (callback) {
callback({ status: 'failed', txHash: tx.transactionHash })
}
})
return true
} catch (error) {
console.log(error)
sendMsg(`😢 Sorry, there were some errors on the processing command. Please try again later`)
// sendMsg(`😢 Sorry, there were some errors on the processing command. Please try again later 😉\n(${afx.parseError(error)})`)
if (callback) {
callback({ status: 'error' })
}
return false
}
}