forked from CryptoGnome/LimitSwap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LimitSwap.py
executable file
·1677 lines (1411 loc) · 77.9 KB
/
LimitSwap.py
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from web3 import Web3
from time import sleep, time
import json
from decimal import Decimal
import os
from web3.exceptions import ABIFunctionNotFound, TransactionNotFound, BadFunctionCallOutput
import logging
from datetime import datetime
import sys
import requests
import cryptocode, re, pwinput
# global used to track if any settings need to be written to file
settings_changed = False
failedtransactionsamount = 0
# color styles
class style(): # Class of different text colours - default is white
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
def timestamp():
timestamp = time()
dt_object = datetime.fromtimestamp(timestamp)
return dt_object
"""""""""""""""""""""""""""
//PRELOAD
"""""""""""""""""""""""""""
print(timestamp(), "Preloading Data")
f = open('./settings.json', )
settings = json.load(f)[0]
f.close()
directory = './abi/'
filename = "standard.json"
file_path = os.path.join(directory, filename)
with open(file_path) as json_file:
standardAbi = json.load(json_file)
directory = './abi/'
filename = "lp.json"
file_path = os.path.join(directory, filename)
with open(file_path) as json_file:
lpAbi = json.load(json_file)
directory = './abi/'
filename = "router.json"
file_path = os.path.join(directory, filename)
with open(file_path) as json_file:
routerAbi = json.load(json_file)
directory = './abi/'
filename = "factory2.json"
file_path = os.path.join(directory, filename)
with open(file_path) as json_file:
factoryAbi = json.load(json_file)
directory = './abi/'
filename = "koffee.json"
file_path = os.path.join(directory, filename)
with open(file_path) as json_file:
koffeeAbi = json.load(json_file)
directory = './abi/'
filename = "pangolin.json"
file_path = os.path.join(directory, filename)
with open(file_path) as json_file:
pangolinAbi = json.load(json_file)
directory = './abi/'
filename = "joeRouter.json"
file_path = os.path.join(directory, filename)
with open(file_path) as json_file:
joeRouter = json.load(json_file)
"""""""""""""""""""""""""""
//ERROR LOGGING
"""""""""""""""""""""""""""
log_format = '%(levelname)s: %(asctime)s %(message)s'
logging.basicConfig(filename='./logs/errors.log',
level=logging.INFO,
format=log_format)
logger1 = logging.getLogger('1')
logger1.addHandler(logging.FileHandler('./logs/exceptions.log'))
logging.info("*************************************************************************************")
logging.info("For Help & To Learn More About how the bot works please visit our wiki here:")
logging.info("https://cryptognome.gitbook.io/limitswap/")
logging.info("*************************************************************************************")
"""""""""""""""""""""""""""
//NETWORKS SELECT
"""""""""""""""""""""""""""
if settings['EXCHANGE'].lower() == 'pancakeswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
print(timestamp(), 'Using custom node.')
else:
my_provider = "https://bsc-dataseed4.defibit.io"
if not my_provider:
print(timestamp(), 'Custom node empty. Exiting')
exit(1)
if my_provider[0].lower() == 'h':
print(timestamp(), 'Using HTTPProvider')
client = Web3(Web3.HTTPProvider(my_provider))
elif my_provider[0].lower() == 'w':
print(timestamp(), 'Using WebsocketProvider')
client = Web3(Web3.WebsocketProvider(my_provider))
else:
print(timestamp(), 'Using IPCProvider')
client = Web3(Web3.IPCProvider(my_provider))
print(timestamp(), "Binance Smart Chain Connected =", client.isConnected())
print(timestamp(), "Loading Smart Contracts...")
if settings['EXCHANGEVERSION'] == "1":
routerAddress = Web3.toChecksumAddress("0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F")
factoryAddress = Web3.toChecksumAddress("0xbcfccbde45ce874adcb698cc183debcf17952812")
elif settings['EXCHANGEVERSION'] == "2":
routerAddress = Web3.toChecksumAddress("0x10ED43C718714eb63d5aA57B78B54704E256024E")
factoryAddress = Web3.toChecksumAddress("0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c")
base_symbol = "BNB"
rugdocchain = '&chain=bsc'
modified = False
if settings['EXCHANGE'].lower() == 'traderjoe':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://api.avax.network/ext/bc/C/rpc"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "AVAX Smart Chain Connected =", client.isConnected())
print(timestamp(), "Loading Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0x60aE616a2155Ee3d9A68541Ba4544862310933d4")
factoryAddress = Web3.toChecksumAddress("0x9Ad6C38BE94206cA50bb0d90783181662f0Cfa10")
routerContract = client.eth.contract(address=routerAddress, abi=joeRouter)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7")
base_symbol = "AVAX"
rugdocchain = '&chain=avax'
modified = True
elif settings['EXCHANGE'].lower() == 'pinkswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
print(timestamp(), 'Using custom node.')
else:
my_provider = "https://bsc-dataseed4.defibit.io"
if not my_provider:
print(timestamp(), 'Custom node empty. Exiting')
exit(1)
if my_provider[0].lower() == 'h':
print(timestamp(), 'Using HTTPProvider')
client = Web3(Web3.HTTPProvider(my_provider))
elif my_provider[0].lower() == 'w':
print(timestamp(), 'Using WebsocketProvider')
client = Web3(Web3.WebsocketProvider(my_provider))
else:
print(timestamp(), 'Using IPCProvider')
client = Web3(Web3.IPCProvider(my_provider))
print(timestamp(), "Binance Smart Chain Connected =", client.isConnected())
print(timestamp(), "Loading PinkSwap Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0x319EF69a98c8E8aAB36Aea561Daba0Bf3D0fa3ac")
factoryAddress = Web3.toChecksumAddress("0x7d2ce25c28334e40f37b2a068ec8d5a59f11ea54")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c")
base_symbol = "BNB"
rugdocchain = '&chain=bsc'
modified = False
elif settings['EXCHANGE'].lower() == 'apeswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://bsc-dataseed4.defibit.io"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "Binance Smart Chain Connected =", client.isConnected())
print(timestamp(), "Loading ApeSwap Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0xcF0feBd3f17CEf5b47b0cD257aCf6025c5BFf3b7")
factoryAddress = Web3.toChecksumAddress("0x0841BD0B734E4F5853f0dD8d7Ea041c241fb0Da6")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c")
busd = Web3.toChecksumAddress("0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56")
base_symbol = "BNB"
rugdocchain = '&chain=bsc'
modified = False
elif settings["EXCHANGE"].lower() == 'uniswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://pedantic-montalcini:[email protected]"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "Uniswap Chain Connected =", client.isConnected())
print(timestamp(), "Loading Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D")
factoryAddress = Web3.toChecksumAddress("0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")
base_symbol = "ETH"
rugdocchain = '&chain=eth'
modified = False
elif settings["EXCHANGE"].lower() == 'kuswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://rpc-mainnet.kcc.network"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "Kucoin Chain Connected =", client.isConnected())
print(timestamp(), "Loading KuSwap Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0xa58350d6dee8441aa42754346860e3545cc83cda")
factoryAddress = Web3.toChecksumAddress("0xAE46cBBCDFBa3bE0F02F463Ec5486eBB4e2e65Ae")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0x4446Fc4eb47f2f6586f9fAAb68B3498F86C07521")
base_symbol = "KCS"
rugdocchain = '&chain=kcc'
modified = False
elif settings["EXCHANGE"].lower() == 'koffeeswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://rpc-mainnet.kcc.network"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "Kucoin Chain Connected =", client.isConnected())
print(timestamp(), "Loading KoffeeSwap Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0xc0fFee0000C824D24E0F280f1e4D21152625742b")
factoryAddress = Web3.toChecksumAddress("0xC0fFeE00000e1439651C6aD025ea2A71ED7F3Eab")
routerContract = client.eth.contract(address=routerAddress, abi=koffeeAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0x4446Fc4eb47f2f6586f9fAAb68B3498F86C07521")
base_symbol = "KCS"
rugdocchain = '&chain=kcc'
modified = True
elif settings["EXCHANGE"].lower() == 'spookyswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://rpcapi.fantom.network"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "FANTOM Chain Connected =", client.isConnected())
print(timestamp(), "Loading Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0xF491e7B69E4244ad4002BC14e878a34207E38c29")
factoryAddress = Web3.toChecksumAddress("0x152eE697f2E276fA89E96742e9bB9aB1F2E61bE3")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83")
base_symbol = "FTM"
rugdocchain = '&chain=ftm'
modified = False
elif settings["EXCHANGE"].lower() == 'spiritswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://rpcapi.fantom.network"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "FANTOM Chain Connected =", client.isConnected())
print(timestamp(), "Loading Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0x16327E3FbDaCA3bcF7E38F5Af2599D2DDc33aE52")
factoryAddress = Web3.toChecksumAddress("0xEF45d134b73241eDa7703fa787148D9C9F4950b0")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83")
base_symbol = "FTM"
rugdocchain = '&chain=ftm'
modified = False
elif settings["EXCHANGE"].lower() == 'quickswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://polygon-rpc.com"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "Matic Chain Connected =", client.isConnected())
print(timestamp(), "Loading Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff")
factoryAddress = Web3.toChecksumAddress("0x5757371414417b8c6caad45baef941abc7d3ab32")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270")
base_symbol = "MATIC"
rugdocchain = '&chain=poly'
modified = False
elif settings["EXCHANGE"].lower() == 'waultswap':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://rpc-waultfinance-mainnet.maticvigil.com/v1/0bc1bb1691429f1eeee66b2a4b919c279d83d6b0"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "Matic Chain Connected =", client.isConnected())
print(timestamp(), "Loading Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0x3a1D87f206D12415f5b0A33E786967680AAb4f6d")
factoryAddress = Web3.toChecksumAddress("0xa98ea6356A316b44Bf710D5f9b6b4eA0081409Ef")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270")
base_symbol = "MATIC"
rugdocchain = '&chain=poly'
modified = False
elif settings["EXCHANGE"].lower() == 'pangolin':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
else:
my_provider = "https://api.avax.network/ext/bc/C/rpc"
client = Web3(Web3.HTTPProvider(my_provider))
print(timestamp(), "AVAX Chain Connected =", client.isConnected())
print(timestamp(), "Loading Smart Contracts...")
routerAddress = Web3.toChecksumAddress("0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106")
factoryAddress = Web3.toChecksumAddress("0xefa94DE7a4656D787667C749f7E1223D71E9FD88")
routerContract = client.eth.contract(address=routerAddress, abi=pangolinAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7")
base_symbol = "AVAX"
rugdocchain = '&chain=avax'
modified = True
def get_password():
global settings_changed
setnewpassword = False
# Check to see if the user has a version of the settings file before private key encryption existed
if 'ENCRYPTPRIVATEKEYS' not in settings:
response = ""
settings_changed = True
while response != "y" and response != "n":
print ("\nWould you like to use a password to encrypt your private keys?")
response = input("You will need to input this password each time LimitSwap is executed (y/n): ")
if response == "y":
settings['ENCRYPTPRIVATEKEYS'] = "true"
setnewpassword = True
else:
settings['ENCRYPTPRIVATEKEYS'] = "false"
# If the user wants to encrypt their private keys, but we don't have an encrypted private key recorded, we need to ask for a password
elif settings['ENCRYPTPRIVATEKEYS'] == "true" and not settings['PRIVATEKEY'].startswith('aes:'):
print ("\nPlease create a password to encrypt your private keys.")
setnewpassword = True
# Set a new password when necessary
if setnewpassword == True:
settings_changed = True
passwords_differ = True
while passwords_differ:
pwd = pwinput.pwinput(prompt="\nType your new password: ")
pwd2 = pwinput.pwinput(prompt="\nType your new password again: ")
if pwd != pwd2:
print ("Error, password mismatch. Try again.")
else:
passwords_differ = False
# The user already has encrypted private keys. Accept a password so we can unencrypt them
elif settings['ENCRYPTPRIVATEKEYS'] == "true":
pwd = pwinput.pwinput(prompt="\nPlease specify the password to decrypt your keys: ")
else:
pwd = ""
if not pwd.strip():
print ()
print ("X WARNING =-= WARNING =-= WARNING =-= WARNING =-= WARNING =-= WARNING=-= WARNING X")
print ("X You are running LimitSwap without encrypting your private keys. X")
print ("X Private keys are stored on disk unencrypted and can be accessed by X")
print ("X anyone with access to the file system, including the Systems/VPS administrator X")
print ("X and anyone with physical access to the machine or hard drives. X")
print ("X WARNING =-= WARNING =-= WARNING =-= WARNING =-= WARNING =-= WARNING=-= WARNING X")
print ()
return pwd
# RUGDOC CONTROL IMPLEMENTATION
# Honeypot API details
honeypot_url = 'https://honeypot.api.rugdoc.io/api/honeypotStatus.js?address='
# Rugdoc's answers interpretations
interpretations = {
"UNKNOWN": (style.RED + '\nThe status of this token is unknown. '
'This is usually a system error but could \n also be a bad sign for the token. Be careful.'),
"OK": (style.GREEN + '\nRUGDOC API RESULT : OK \n'
'√ Honeypot tests passed. RugDoc program was able to buy and sell it successfully. This however does not guarantee that it is not a honeypot.'),
"NO_PAIRS": (style.RED + '\nRUGDOC API RESULT : NO_PAIRS \n'
'⚠ Could not find any trading pair for this token on the default router and could thus not test it.'),
"SEVERE_FEE": (style.RED + '\nRUGDOC API RESULT : SEVERE_FEE \n'
'/!\ /!\ A severely high trading fee (over 50%) was detected when selling or buying this token.'),
"HIGH_FEE": (style.YELLOW + '\nRUGDOC API RESULT : HIGH_FEE \n'
'/!\ /!\ A high trading fee (Between 20% and 50%) was detected when selling or buying this token. Our system was however able to sell the token again.'),
"MEDIUM_FEE": (style.YELLOW + '\nRUGDOC API RESULT : MEDIUM_FEE \n'
'/!\ A trading fee of over 10% but less then 20% was detected when selling or buying this token. Our system was however able to sell the token again.'),
"APPROVE_FAILED": (style.RED + '\nRUGDOC API RESULT : APPROVE_FAILED \n'
'/!\ /!\ /!\ Failed to approve the token.\n This is very likely a honeypot.'),
"SWAP_FAILED": (style.RED + '\nRUGDOC API RESULT : SWAP_FAILED \n'
'/!\ /!\ /!\ Failed to sell the token. \n This is very likely a honeypot.')
}
# Function to check rugdoc API
def honeypot_check(address):
url = (honeypot_url + address + rugdocchain)
# sending get request and saving the response as response object
return requests.get(url)
def save_settings(pwd):
global settings_changed
if len(pwd) > 0:
encrypted_settings = settings.copy()
encrypted_settings['LIMITWALLETPRIVATEKEY'] = 'aes:' + cryptocode.encrypt(settings['LIMITWALLETPRIVATEKEY'], pwd)
encrypted_settings['PRIVATEKEY'] = 'aes:' + cryptocode.encrypt(settings['PRIVATEKEY'], pwd)
# MASSAGE OUTPUT - LimitSwap currently loads settings.json as a [0] element, so we need to massage our
# settings.json output so that it's reasable. This should probably be fixed by us importing
# the entire json file, instead of just the [0] element.
if settings_changed == True:
print (timestamp(), "Writing settings to file.")
if settings['ENCRYPTPRIVATEKEYS'] == "true":
output_settings = encrypted_settings
else:
output_settings = settings
with open('settings.json', 'w') as f:
f.write("[\n")
f.write(json.dumps(output_settings, indent=4))
f.write("\n]\n")
def load_wallet_settings(pwd):
global settings
global settings_changed
# Check for limit wallet information
if " " in settings['LIMITWALLETADDRESS'] or settings['LIMITWALLETADDRESS'] == "":
settings_changed = True
settings['LIMITWALLETADDRESS'] = input("Please provide the wallet address where you have your LIMIT: ")
# Check for limit wallet private key
if " " in settings['LIMITWALLETPRIVATEKEY'] or settings['LIMITWALLETPRIVATEKEY'] == "":
settings_changed = True
settings['LIMITWALLETPRIVATEKEY'] = input(
"Please provide the private key for the wallet where you have your LIMIT: ")
# If the limit wallet private key is already set and encrypted, decrypt it
elif settings['LIMITWALLETPRIVATEKEY'].startswith('aes:'):
print (timestamp(), "Decrypting limit wallet private key.")
settings['LIMITWALLETPRIVATEKEY'] = settings['LIMITWALLETPRIVATEKEY'].replace('aes:', "", 1)
settings['LIMITWALLETPRIVATEKEY'] = cryptocode.decrypt(settings['LIMITWALLETPRIVATEKEY'], pwd)
if settings['LIMITWALLETPRIVATEKEY'] == False:
print(style.RED + "ERROR: Your private key decryption password is incorrect")
print(style.RESET + "Please re-launch the bot and try again")
sleep(10)
sys.exit()
# Check for trading wallet information
if " " in settings['WALLETADDRESS'] or settings['WALLETADDRESS'] == "":
settings_changed = True
settings['WALLETADDRESS'] = input("Please provide the wallet address for your trading wallet: ")
# Check for trading wallet private key
if " " in settings['PRIVATEKEY'] or settings['PRIVATEKEY'] == "":
settings_changed = True
settings['PRIVATEKEY'] = input("Please provide the private key for the wallet you want to trade with: ")
# If the trading wallet private key is already set and encrypted, decrypt it
elif settings['PRIVATEKEY'].startswith('aes:'):
print (timestamp(), "Decrypting limit wallet private key.")
settings['PRIVATEKEY'] = settings['PRIVATEKEY'].replace('aes:', "", 1)
settings['PRIVATEKEY'] = cryptocode.decrypt(settings['PRIVATEKEY'], pwd)
def decimals(address):
try:
balanceContract = client.eth.contract(address=Web3.toChecksumAddress(address), abi=standardAbi)
decimals = balanceContract.functions.decimals().call()
DECIMALS = 10 ** decimals
except ABIFunctionNotFound:
DECIMALS = 10 ** 18
except ValueError as ve:
logging.exception(ve)
print("Please check your SELLPRICE values.")
return DECIMALS
def check_logs():
print(timestamp(), "Quickly Checking Log Size")
with open('./logs/errors.log') as f:
line_count = 0
for line in f:
line_count += 1
if line_count > 100:
with open('./logs/errors.log', "r") as f:
lines = f.readlines()
with open('./logs/errors.log', "w") as f:
f.writelines(lines[20:])
f.close()
def decode_key():
private_key = settings['LIMITWALLETPRIVATEKEY']
acct = client.eth.account.privateKeyToAccount(private_key)
addr = acct.address
return addr
def check_release():
try:
url = 'https://api.github.com/repos/CryptoGnome/LimitSwap/releases/latest'
r = requests.get(url).json()['tag_name']
print("Checking Latest Release Version on Github, Please Make Sure You are Staying Updated = ", r)
logging.info("Checking Latest Release Version on Github, Please Make Sure You are Staying Updated = " + r)
except Exception:
r = "github api down, please ignore"
return r
def auth():
my_provider2 = 'https://reverent-raman:[email protected]'
client2 = Web3(Web3.HTTPProvider(my_provider2))
print(timestamp(), "Connected to Ethereum BlockChain =", client2.isConnected())
# Insert LIMITSWAP Token Contract Here To Calculate Staked Verification
address = Web3.toChecksumAddress("0x1712aad2c773ee04bdc9114b32163c058321cd85")
abi = standardAbi
balanceContract = client2.eth.contract(address=address, abi=abi)
decimals = balanceContract.functions.decimals().call()
DECIMALS = 10 ** decimals
# Exception for incorrect Key Input
try:
decode = decode_key()
except Exception:
print("There is a problem with your private key : please check if it's correct. Don't enter seed phrase !")
logging.info(
"There is a problem with your private key : please check if it's correct. Don't enter seed phrase !")
wallet_address = Web3.toChecksumAddress(decode)
balance = balanceContract.functions.balanceOf(wallet_address).call()
true_balance = balance / DECIMALS
print(timestamp(), "Current Tokens Staked =", true_balance)
logging.info("Current Tokens Staked = " + str(true_balance))
return true_balance
def approve(address, amount):
print(timestamp(), "Approving", address)
eth_balance = Web3.fromWei(client.eth.getBalance(settings['WALLETADDRESS']), 'ether')
if eth_balance > 0.05:
print("Estimating Gas Cost Using Web3")
if settings['EXCHANGE'].lower() == 'uniswap':
print("Estimating Gas Cost Using Web3")
gas = (((client.eth.gasPrice) / 1000000000)) + ((client.eth.gasPrice) / 1000000000) * (int(20) / 100)
print("Current Gas Price =", gas)
elif settings['EXCHANGE'].lower() == 'pancakeswap':
gas = (((client.eth.gasPrice) / 1000000000)) + ((client.eth.gasPrice) / 1000000000) * (int(20) / 100)
print("Current Gas Price = ", gas)
elif settings['EXCHANGE'].lower() == 'spiritswap':
gas = (((client.eth.gasPrice) / 1000000000)) + ((client.eth.gasPrice) / 1000000000) * (int(20) / 100)
print("Current Gas Price = ", gas)
elif settings['EXCHANGE'].lower() == 'spookyswap':
gas = (((client.eth.gasPrice) / 1000000000)) + ((client.eth.gasPrice) / 1000000000) * (int(20) / 100)
print("Current Gas Price = ", gas)
elif settings['EXCHANGE'].lower() == 'pangolin':
gas = (((client.eth.gasPrice) / 1000000000)) + ((client.eth.gasPrice) / 1000000000) * (int(20) / 100)
print("Current Gas Price = ", gas)
elif settings['EXCHANGE'].lower() == 'quickswap':
gas = (((client.eth.gasPrice) / 1000000000)) + ((client.eth.gasPrice) / 1000000000) * (int(20) / 100)
print("Current Gas Price = ", gas)
elif settings['EXCHANGE'].lower() == 'kuswap' or 'koffeeswap':
gas = (((client.eth.gasPrice) / 1000000000)) + ((client.eth.gasPrice) / 1000000000) * (int(20) / 100)
print("Current Gas Price = ", gas)
else:
print("EXCHANGE NAME IN SETTINGS IS SPELLED INCORRECTLY OR NOT SUPPORTED YET CHECK WIKI!")
logging.info("EXCHANGE NAME IN SETTINGS IS SPELLED INCORRECTLY OR NOT SUPPORTED YET CHECK WIKI!")
exit()
contract = client.eth.contract(address=Web3.toChecksumAddress(address), abi=standardAbi)
transaction = contract.functions.approve(routerAddress, amount
).buildTransaction({
'gasPrice': Web3.toWei(gas, 'gwei'),
'gas': 300000,
'from': Web3.toChecksumAddress(settings['WALLETADDRESS']),
'nonce': client.eth.getTransactionCount(settings['WALLETADDRESS'])
})
signed_txn = client.eth.account.signTransaction(transaction, private_key=settings['PRIVATEKEY'])
try:
return client.eth.sendRawTransaction(signed_txn.rawTransaction)
finally:
print(timestamp(), "Transaction Hash = ", Web3.toHex(client.keccak(signed_txn.rawTransaction)))
# LOG TX TO JSON
with open('./transactions.json', 'r') as fp:
data = json.load(fp)
tx_hash = client.toHex(client.keccak(signed_txn.rawTransaction))
tx_input = {"hash": tx_hash}
data.append(tx_input)
with open('./transactions.json', 'w') as fp:
json.dump(data, fp, indent=2)
fp.close()
return tx_hash
else:
print(timestamp(),
"You have less than 0.01 ETH/BNB/FTM/MATIC or network gas token in your wallet, bot needs at least 0.05 to cover fees : please add some more in your wallet.")
logging.info(
"You have less than 0.01 ETH/BNB/FTM/MATIC or network gas token in your wallet, bot needs at least 0.05 to cover fees : please add some more in your wallet.")
sleep(10)
sys.exit()
def check_approval(address, balance):
print(timestamp(), "Checking Approval Status", address)
contract = client.eth.contract(address=Web3.toChecksumAddress(address), abi=standardAbi)
allowance = contract.functions.allowance(Web3.toChecksumAddress(settings['WALLETADDRESS']), routerAddress).call()
if allowance < balance:
if settings["EXCHANGE"].lower() == 'quickswap':
print("Revert to Zero To change approval")
tx = approve(address, 0)
wait_for_tx(tx, address, False)
tx = approve(address, balance)
wait_for_tx(tx, address, False)
else:
tx = approve(address, balance)
wait_for_tx(tx, address, False)
return
else:
pass
def check_bnb_balance():
balance = client.eth.getBalance(settings['WALLETADDRESS'])
print(timestamp(), "Current Wallet Balance is :", Web3.fromWei(balance, 'ether'), base_symbol)
return balance
def check_balance(address, symbol):
address = Web3.toChecksumAddress(address)
DECIMALS = decimals(address)
balanceContract = client.eth.contract(address=address, abi=standardAbi)
balance = balanceContract.functions.balanceOf(settings['WALLETADDRESS']).call()
print(timestamp(), "Current Wallet Balance is: " + str(balance / DECIMALS) + " " + symbol)
return balance
def fetch_pair(inToken, outToken):
print(timestamp(), "Fetching Pair Address")
pair = factoryContract.functions.getPair(inToken, outToken).call()
print(timestamp(), "Pair Address = ", pair)
return pair
def sync(inToken, outToken):
pair = factoryContract.functions.getPair(inToken, outToken).call()
syncContract = client.eth.contract(address=Web3.toChecksumAddress(pair), abi=lpAbi)
sync = syncContract.functions.sync().call()
def check_pool(inToken, outToken, symbol):
# This function is made to calculate Liquidity of a token
pair_address = factoryContract.functions.getPair(inToken, outToken).call()
DECIMALS = decimals(outToken)
pair_contract = client.eth.contract(address=pair_address, abi=lpAbi)
reserves = pair_contract.functions.getReserves().call()
pooled = reserves[1] / DECIMALS
# print("Debug LIQUIDITYAMOUNT line 627 :", pooled, "in token:", outToken)
return pooled
def check_price(inToken, outToken, symbol, base, custom, routing, buypriceinbase):
# CHECK GET RATE OF THE TOKEn
DECIMALS = decimals(inToken)
stamp = timestamp()
if custom.lower() == 'false':
base = base_symbol
else:
pass
if routing == 'true':
if outToken != weth:
price_check = routerContract.functions.getAmountsOut(1 * DECIMALS, [inToken, weth, outToken]).call()[-1]
DECIMALS = decimals(outToken)
tokenPrice = price_check / DECIMALS
print(stamp, symbol, " Price ", tokenPrice, base, "//// your buyprice =", buypriceinbase, base)
else:
price_check = routerContract.functions.getAmountsOut(1 * DECIMALS, [inToken, weth]).call()[-1]
DECIMALS = decimals(outToken)
tokenPrice = price_check / DECIMALS
price_output = "{:.18f}".format(tokenPrice)
print(stamp, symbol, "Price =", price_output, base, "//// your buyprice =", buypriceinbase, base)
else:
if outToken != weth:
price_check = routerContract.functions.getAmountsOut(1 * DECIMALS, [inToken, outToken]).call()[-1]
DECIMALS = decimals(outToken)
tokenPrice = price_check / DECIMALS
print(stamp, symbol, " Price ", tokenPrice, base, "//// your buyprice =", buypriceinbase, base)
else:
price_check = routerContract.functions.getAmountsOut(1 * DECIMALS, [inToken, weth]).call()[-1]
DECIMALS = decimals(outToken)
tokenPrice = price_check / DECIMALS
price_output = "{:.18f}".format(tokenPrice)
print(stamp, symbol, "Price =", price_output, base, "//// your buyprice =", buypriceinbase, base)
return tokenPrice
def wait_for_tx(tx_hash, address, check):
print(timestamp(), "............Waiting 1 minute for TX to Confirm............")
timeout = time() + 60
while True:
print(timestamp(), "............Waiting 1 minute for TX to Confirm............")
sleep(1)
try:
txn_receipt = client.eth.getTransactionReceipt(tx_hash)
return txn_receipt['status']
except Exception as e:
txn_receipt = None
if txn_receipt is not None and txn_receipt['blockHash'] is not None:
return txn_receipt['status']
elif time() > timeout:
print(style.RED + "\n")
print(timestamp(), "Transaction was not confirmed after 1 minute : something wrong happened.\n"
"Please check if :\n"
"- your node is running correctly\n"
"- you have enough Gaslimit (check 'Gas Used by Transaction') if you have a failed Tx")
print(style.RESET + "\n")
failedtransactionsamount += 1
logging.info("Transaction was not confirmed after 1 minute, breaking Check Cycle....")
sleep(5)
break
# loop to check for balance after purchase
if check == True:
timeout = time() + 30
print(style.RESET + "\n")
while True:
print(timestamp(), ".........Waiting 30s to check tokens balance in your wallet after purchase............")
sleep(1)
balance = check_balance(address, address)
if balance > 0:
break
elif time() > timeout:
print(timestamp(),
"NO BUY FOUND, WE WILL CHECK A FEW TIMES TO SEE IF THERE IS BLOCKCHAIN DELAY, IF NOT WE WILL ASSUME THE TX HAS FAILED")
logging.info(
"NO BUY FOUND, WE WILL CHECK A FEW TIMES TO SEE IF THERE IS BLOCKCHAIN DELAY, IF NOT WE WILL ASSUME THE TX HAS FAILED")
break
def preapprove(tokens):
for token in tokens:
check_approval(token['ADDRESS'], 115792089237316195423570985008687907853269984665640564039457584007913129639934)
if token['USECUSTOMBASEPAIR'].lower() == 'false':
check_approval(weth, 115792089237316195423570985008687907853269984665640564039457584007913129639934)
else:
check_approval(token['BASEADDRESS'],
115792089237316195423570985008687907853269984665640564039457584007913129639934)
def buy(amount, inToken, outToken, gas, slippage, gaslimit, boost, fees, custom, symbol, base, routing, waitseconds, failedtransactionsnumber):
seconds = int(waitseconds)
if int(failedtransactionsamount) == int(failedtransactionsnumber):
print(style.RED + "\n ---------------------------------------------------------------\n"
" Bot has reached maximum FAILED TRANSACTIONS number: it stops\n"
" ---------------------------------------------------------------\n\n")
logging.info("Bot has reached maximum FAILED TRANSACTIONS number: it stops")
sleep(10)
sys.exit()
else:
if waitseconds != '0':
print("Bot will wait", waitseconds, " seconds before buy, as you entered in BUYAFTER_XXX_SECONDS parameter")
sleep(seconds)
print(timestamp(), "Placing New Buy Order for " + symbol)
if int(gaslimit) < 250000:
print("Your GASLIMIT parameter is too low : LimitSwap has forced it to 300000 otherwise your transaction would fail for sure. We advise you to raise it to 1000000.")
gaslimit = 300000
if custom.lower() == 'false':
balance = Web3.fromWei(check_bnb_balance(), 'ether')
base = base_symbol
else:
address = Web3.toChecksumAddress(inToken)
DECIMALS = decimals(address)
balance_check = check_balance(inToken, base)
balance = balance_check / DECIMALS
if balance > Decimal(amount):
if gas.lower() == 'boost':
gas_check = client.eth.gasPrice
gas_price = gas_check / 1000000000
gas = (gas_price * ((int(boost)) / 100)) + gas_price
else:
gas = int(gas)
gaslimit = int(gaslimit)
slippage = int(slippage)
DECIMALS = decimals(inToken)
amount = int(float(amount) * DECIMALS)
if custom.lower() == 'false':
amount_out = routerContract.functions.getAmountsOut(amount, [weth, outToken]).call()[-1]
if settings['UNLIMITEDSLIPPAGE'].lower() == 'true':
min_tokens = 100
else:
min_tokens = int(amount_out * (1 - (slippage / 100)))
deadline = int(time() + + 60)
# THIS SECTION IS FOR MODIFIED CONTRACTS AND EACH EXCHANGE IS SPECIFIED
if modified == True:
if settings["EXCHANGE"].lower() == 'koffeeswap':
transaction = routerContract.functions.swapExactKCSForTokens(
min_tokens,
[weth, outToken],
Web3.toChecksumAddress(settings['WALLETADDRESS']),
deadline
).buildTransaction({
'gasPrice': Web3.toWei(gas, 'gwei'),
'gas': gaslimit,
'value': amount,
'from': Web3.toChecksumAddress(settings['WALLETADDRESS']),
'nonce': client.eth.getTransactionCount(settings['WALLETADDRESS'])
})
elif settings["EXCHANGE"].lower() == 'pangolin' or settings["EXCHANGE"].lower() == 'traderjoe':
transaction = routerContract.functions.swapExactAVAXForTokens(
min_tokens,
[weth, outToken],
Web3.toChecksumAddress(settings['WALLETADDRESS']),
deadline
).buildTransaction({
'gasPrice': Web3.toWei(gas, 'gwei'),
'gas': gaslimit,
'value': amount,
'from': Web3.toChecksumAddress(settings['WALLETADDRESS']),
'nonce': client.eth.getTransactionCount(settings['WALLETADDRESS'])
})
else:
# THIS SECTION IS FOR MODIFIED CONTRACTS AND EACH EXCHANGE IS SPECIFIED
if modified == True:
if settings["EXCHANGE"].lower() == 'koffeeswap':
transaction = routerContract.functions.swapExactKCSForTokens(
min_tokens,
[weth, outToken],
Web3.toChecksumAddress(settings['WALLETADDRESS']),
deadline
).buildTransaction({
'gasPrice': Web3.toWei(gas, 'gwei'),
'gas': gaslimit,
'value': amount,
'from': Web3.toChecksumAddress(settings['WALLETADDRESS']),
'nonce': client.eth.getTransactionCount(settings['WALLETADDRESS'])
})
elif settings["EXCHANGE"].lower() == 'pangolin' or settings["EXCHANGE"].lower() == 'traderjoe':
transaction = routerContract.functions.swapExactAVAXForTokens(
min_tokens,
[weth, outToken],
Web3.toChecksumAddress(settings['WALLETADDRESS']),
deadline
).buildTransaction({
'gasPrice': Web3.toWei(gas, 'gwei'),
'gas': gaslimit,
'value': amount,
'from': Web3.toChecksumAddress(settings['WALLETADDRESS']),
'nonce': client.eth.getTransactionCount(settings['WALLETADDRESS'])
})
else:
transaction = routerContract.functions.swapExactETHForTokens(
min_tokens,
[weth, outToken],
Web3.toChecksumAddress(settings['WALLETADDRESS']),
deadline
).buildTransaction({
'gasPrice': Web3.toWei(gas, 'gwei'),
'gas': gaslimit,
'value': amount,
'from': Web3.toChecksumAddress(settings['WALLETADDRESS']),
'nonce': client.eth.getTransactionCount(settings['WALLETADDRESS'])
})
else:
if inToken == weth:
amount_out = routerContract.functions.getAmountsOut(amount, [weth, outToken]).call()[-1]
if settings['UNLIMITEDSLIPPAGE'].lower() == 'true':
min_tokens = 100
else:
min_tokens = int(amount_out * (1 - (slippage / 100)))
deadline = int(time() + + 60)
transaction = routerContract.functions.swapExactTokensForTokens(
amount,
min_tokens,
[weth, outToken],
Web3.toChecksumAddress(settings['WALLETADDRESS']),
deadline
).buildTransaction({
'gasPrice': Web3.toWei(gas, 'gwei'),
'gas': gaslimit,
'from': Web3.toChecksumAddress(settings['WALLETADDRESS']),
'nonce': client.eth.getTransactionCount(settings['WALLETADDRESS'])
})
else:
if routing.lower() == 'true':
amount_out = routerContract.functions.getAmountsOut(amount, [inToken, weth, outToken]).call()[-1]
if settings['UNLIMITEDSLIPPAGE'].lower() == 'true':
min_tokens = 100
else:
min_tokens = int(amount_out * (1 - (slippage / 100)))
deadline = int(time() + + 60)
transaction = routerContract.functions.swapExactTokensForTokens(