-
Notifications
You must be signed in to change notification settings - Fork 150
/
LimitSwap.py
executable file
·2300 lines (1949 loc) · 110 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
# -*- coding: utf-8 -*-
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
import argparse
import signal
# DEVELOPER CONSIDERATIONS
#
# USER INTERACTION - Do not depend on user interaction. If you develop a setting that is going to require
# user interaction while the bot is running, warn the user before hand. Accept a value before the check
# for liquidity, and provide a command line flag. Basically, provide ways for the bot to continue it's
# entire process from buying all the way to selling multiple positions and multiple pairs with zero user
# interaction.
#
# HANDLING NEW ENTRIES IN settings.json - When adding a new configuration item in settings.json be sure to
# review comment "COMMAND LINE ARGUMENTS" and the functions load_settings_file and save_settings.
# Do not assume a user has changed their settings.json file to work with the new version, your additions
# should be backwards compatible and have safe default values if possible
#
# HANDLING NEW ENTRIES IN tokens.json - When adding a new configuration item in tokens.json be sure to
# review comment "COMMAND LINE ARGUMENTS" and the functions load_tokens_file and save_tokens_file
# Do not assume a user has changed their tokens.json file to work with the new version, your additions
# should be backwards compatible and have safe default values if possible
# initialization of number of failed transactions
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'
# Function to cleanly exit on SIGINT
def signal_handler(sig, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def timestamp():
timestamp = time()
dt_object = datetime.fromtimestamp(timestamp)
return dt_object
#
# COMMAND LINE ARGUMENTS
#
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--password", type=str,
help="Password to decrypt private keys (WARNING: your password could be saved in your command prompt history)")
parser.add_argument("-s", "--settings", type=str, help="Specify the file to user for settings (default: settings.json)",
default="./settings.json")
parser.add_argument("-t", "--tokens", type=str,
help="Specify the file to use for tokens to trade (default: tokens.json)", default="./tokens.json")
parser.add_argument("-v", "--verbose", action='store_true', help="Print detailed messages to stdout")
command_line_args = parser.parse_args()
def printt(*print_args):
# Function: printt
# ----------------------------
# provides normal print() functionality but also prints our timestamp
#
# returns: nothing
print(timestamp(), ' '.join(map(str, print_args)))
def printt_v(*print_args):
# Function: printt
# ----------------------------
# provides normal print() functionality but also prints our timestamp and pays attention to user set verbosity.
#
# returns: nothing
if command_line_args.verbose == True:
print(timestamp(), ' '.join(map(str, print_args)))
def printt_err(*print_args):
# Function: printt_err
# --------------------
# provides normal print() functionality but also prints our timestamp and the text highlighted to display an error
#
# returns: nothing
print(timestamp(), " ", style.RED, ' '.join(map(str, print_args)), style.RESET, sep="")
def printt_ok(*print_args):
# Function: printt_ok
# --------------------
# provides normal print() functionality but also prints our timestamp and the text highlighted to display an OK text
#
# returns: nothing
print(timestamp(), " ", style.GREEN, ' '.join(map(str, print_args)), style.RESET, sep="")
def printt_info(*print_args):
# Function: printt_info
# --------------------
# provides normal print() functionality but also prints our timestamp and the text highlighted to display an INFO text in yellow
#
# returns: nothing
print(timestamp(), " ", style.YELLOW, ' '.join(map(str, print_args)), style.RESET, sep="")
def load_settings_file(settings_path, load_message=True):
# Function: load_settings_file
# ----------------------------
# loads the settings file defined by command_line_args.settings, sets sane defaults if variables aren't found in settings file
# exits with an error message if necessary variables are not found in the settings files
#
# settings_path = the path of the file to load settings from
#
# returns: a dictionary with the settings from the file loaded
if load_message == True:
print(timestamp(), "Loading settings from", command_line_args.settings)
f = open(command_line_args.settings, )
settings = json.load(f)[0]
f.close()
for default_false in ['UNLIMITEDSLIPPAGE', 'USECUSTOMNODE']:
if default_false not in settings:
printt_v(default_false, "not found in settings configuration file, settings a default value of false.")
settings[default_false] = "false"
else:
settings[default_false] = settings[default_false].lower()
for default_true in ['PREAPPROVE']:
if default_true not in settings:
printt_v(default_true, "not found in settings configuration file, settings a default value of true.")
settings[default_true] = "true"
else:
settings[default_true] = settings[default_true].lower()
# Keys that must be set
for required_key in ['EXCHANGE']:
if required_key not in settings:
printt_err(required_key, "not found in settings configuration file.")
exit(-1)
else:
settings[required_key] = settings[required_key].lower()
return settings
def load_tokens_file(tokens_path, load_message=True):
# Function: load_tokens_File
# ----------------------------
# loads the token definition file defined by command_line_args.settings, sets sane defaults if variables aren't found in settings file
# exits with an error message if necessary variables are not found in the settings files
#
# tokens_path: the path of the file to load tokens from
#
# returns: a dictionary with the settings from the file loaded
if load_message == True:
print(timestamp(), "Loading tokens from", command_line_args.tokens)
s = open(command_line_args.tokens, )
tokens = json.load(s)
s.close()
# Make sure all values are lowercase
for token in tokens:
for default_false in ['ENABLED', 'LIQUIDITYCHECK', 'LIQUIDITYINNATIVETOKEN', 'USECUSTOMBASEPAIR', 'HASFEES']:
if default_false not in token:
printt_v(default_false, "not found in configuration file in configuration for to token",
token['SYMBOL'], "setting a default value of false")
token[default_false] = "false"
else:
token[default_false] = token[default_false].lower()
# Keys that must be set
for required_key in ['ADDRESS', 'BUYAMOUNTINBASE', 'BUYPRICEINBASE', 'SELLPRICEINBASE', 'GASPRIORITY_FOR_ETH_ONLY', 'STOPLOSSPRICEINBASE']:
if required_key not in token:
printt_err(required_key, "not found in configuration file in configuration for token",
token['SYMBOL'], ". \n Be careful, sometimes new parameters are added : please check default tokens.json file")
logging.info("A parameter is missing in your tokens.json : " + str(required_key))
sleep(20)
exit(-1)
token_defaults = {
'SLIPPAGE': 49,
'MAXTOKENS': 0,
'MOONBAG': 0,
'SELLAMOUNTINTOKENS': 'all',
'GAS': 8,
'BOOSTPERCENT': 50,
'GASLIMIT': 1000000,
'STOPLOSSPRICEINBASE': 0,
'GASPRIORITY_FOR_ETH_ONLY': 1.5
}
for default_key in token_defaults:
if default_key not in token:
printt_v(default_key, "not found in configuration file in configuration for to token", token['SYMBOL'],
"setting a value of", token_defaults['default_key'])
token[default_key] = token_defaults[default_key]
elif default_key == 'SELLAMOUNTINTOKENS':
token_defaults[default_key] = token_defaults[default_key].lower()
return tokens
"""""""""""""""""""""""""""
//PRELOAD
"""""""""""""""""""""""""""
print(timestamp(), "Preloading Data")
settings = load_settings_file(command_line_args.settings)
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
"""""""""""""""""""""""""""
os.makedirs('./logs', exist_ok=True)
if not os.path.exists('./logs/errors.log'):
open('./logs/errors.log', 'w').close()
if not os.path.exists('./logs/exceptions.log'):
open('./logs/exceptions.log', 'w').close()
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() == 'pancakeswaptesnet':
if settings['USECUSTOMNODE'].lower() == 'true':
my_provider = settings['CUSTOMNODE']
print(timestamp(), 'Using custom node.')
else:
my_provider = "https://data-seed-prebsc-1-s2.binance.org:8545"
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("0xD99D1c33F9fC3444f8101754aBC46c52416550D1")
factoryAddress = Web3.toChecksumAddress("0x6725F303b657a9451d8BA641348b6761A6CC7a17")
routerContract = client.eth.contract(address=routerAddress, abi=routerAbi)
factoryContract = client.eth.contract(address=factoryAddress, abi=factoryAbi)
weth = Web3.toChecksumAddress("0xae13d989dac2f0debff460ac112a837c89baa7cd")
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() == 'biswap':
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("0x3a6d8cA21D1CF76F653A67577FA0D27453350dD8")
factoryAddress = Web3.toChecksumAddress("0x858E3312ed3A876947EA49d572A7C42DE08af7EE")
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://mainnet.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"
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():
# Function: get_password
# ----------------------------
# Handles the decision making logic concerning private key encryption and asking the user for their password.
#
# returns: the user's password
settings_changed = False
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":
if command_line_args.password:
pwd = command_line_args.password
else:
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()
if settings_changed == True:
save_settings(settings, pwd)
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.'),
"chain not found": (style.RED + '\nRUGDOC API RESULT : chain not found \n'
'/!\ Sorry, rugdoc API does not work on this chain... (it does not work on ETH, mainly) \n')
}
# 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(settings, pwd):
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)
# TODO: 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.
print(timestamp(), "Writing settings to file.")
if settings['ENCRYPTPRIVATEKEYS'] == "true":
output_settings = encrypted_settings
else:
output_settings = settings
with open(command_line_args.settings, 'w') as f:
f.write("[\n")
f.write(json.dumps(output_settings, indent=4))
f.write("\n]\n")
def parse_wallet_settings(settings, pwd):
# Function: load_wallet_settings
# ----------------------------
# Handles the process of deciding whether or not the user's private key needs to be decrypted
# Accepts user input for new private keys and wallet addresses
#
# returns: none (exits on incorrect password)
settings_changed = False
# 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:'):
printt("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)
if settings_changed == True:
save_settings(settings, 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':
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.05 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.05 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, allowancetocomparewith):
print(timestamp(), "Checking Approval Status", address)
contract = client.eth.contract(address=Web3.toChecksumAddress(address), abi=standardAbi)
actualallowance = contract.functions.allowance(Web3.toChecksumAddress(settings['WALLETADDRESS']), routerAddress).call()
if actualallowance < allowancetocomparewith:
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, 115792089237316195423570985008687907853269984665640564039457584007913129639935)
wait_for_tx(tx, address, False)
else:
printt_info("\n ---------------------------------------------------------------------------\n"
" You need to APPROVE this token before selling it : LimitSwap will do it now\n"
" ---------------------------------------------------------------------------\n")
tx = approve(address, 115792089237316195423570985008687907853269984665640564039457584007913129639935)
wait_for_tx(tx, address, False)
printt_ok("\n ---------------------------------------------------------\n"
" Token is now approved : LimitSwap can sell this token\n"
" ---------------------------------------------------------\n")
logging.info("Token is now approved : LimitSwap can sell this token")
return
else:
printt_ok("Token is already approved --> LimitSwap can sell this token ")
pass
def check_bnb_balance():