-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1471 lines (1229 loc) · 61.5 KB
/
Copy pathmain.py
File metadata and controls
1471 lines (1229 loc) · 61.5 KB
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 aiohttp import (
ClientResponseError,
ClientSession,
ClientTimeout,
BasicAuth,
FormData
)
from aiohttp_socks import ProxyConnector
from fake_useragent import FakeUserAgent
from base58 import b58decode, b58encode
from nacl.signing import SigningKey
from colorama import Fore, Style, Back, init
from PIL import Image
import asyncio, random, base64, uuid, json, re, io, os, sys, time
import requests
from solana.keypair import Keypair
from solana.publickey import PublicKey
from solana.transaction import Transaction
from spl.token.constants import TOKEN_PROGRAM_ID, WRAPPED_SOL_MINT
from solana.system_program import create_account, CreateAccountParams
from spl.token.instructions import (
initialize_account,
InitializeAccountParams,
transfer_checked,
TransferCheckedParams,
close_account,
CloseAccountParams
)
# Initialize colorama
init(autoreset=True)
requests.packages.urllib3.disable_warnings()
class Valiant:
proxies = [] # Shared class variable for proxies
def __init__(self, account=None) -> None:
self.RPC_URL = "https://testnet.fogo.io/"
self.VALIANT_API = "https://api.valiant.trade/dex"
self.EXPLORER_URL = "https://fogoscan.com/tx/"
self.OWNER_ADDRESS = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
self.FOGO_TOKEN = {
"name": "SPL FOGO",
"ticker": "FOGO",
"address": "So11111111111111111111111111111111111111112",
"decimals": 9,
}
self.FUSD_TOKEN = {
"ticker": "FOGO USD",
"ticker": "FUSD",
"address": "fUSDNGgHkZfwckbr5RLLvRbvqvRcTLdH9hcHJiq4jry",
"decimals": 6,
}
self.USDT_TOKEN = {
"name": "USD TOKEN",
"ticker": "USDT",
"address": "7fc38fbxd1q7gC5WqfauwdVME7ms64VGypyoHaTnLUAt",
"decimals": 6,
}
self.USDC_TOKEN = {
"name": "USD COIN",
"ticker": "USDC",
"address": "ELNbJ1RtERV2fjtuZjbTscDekWhVzkQ1LjmiPsxp5uND",
"decimals": 6,
}
self.HEADERS = {}
self.proxy_index = 0
self.account_proxies = {}
self.current_proxy = None
self.wallet_name = None
self.signing_key = None
self.address = None
self.private_key = None
self.trade_count = 1
self.fogo_trade_amount = 0.001
self.fusd_trade_amount = 0.001
self.usdt_trade_amount = 0.001
self.usdc_trade_amount = 0.001
self.position_count = 1
self.fogo_position_amount = 0.002
self.fusd_position_amount = 0.002
self.usdt_position_amount = 0.002
self.deploy_count = 5
self.min_delay = 1
self.max_delay = 3
self.wrap_amount = 0.003
self.unwrap_amount = 0.002
self.wrap_count = 1
self.unwrap_count = 1
self.config_file = 'config.json'
self.load_config()
if account:
self.signing_key, self.address, self.private_key = self.generate_wallet(account)
if self.signing_key and self.address:
self.wallet_name = self.address[:6] + '...' + self.address[-6:]
self.HEADERS[self.address] = {
"Accept": "*/*",
"Accept-Language": "id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7",
"Origin": "https://valiant.trade",
"Referer": "https://valiant.trade/",
"User-Agent": FakeUserAgent().random
}
def clear_terminal(self):
os.system('cls' if os.name == 'nt' else 'clear')
def display_banner(self):
banner = f"""
{Fore.YELLOW + Style.BRIGHT} Fogo auto bot - Copy right by: https://t.me/airdrophuntersieutoc {Style.RESET_ALL}
{Fore.YELLOW + Style.BRIGHT} Store - https://amautomarket.com/ {Style.RESET_ALL}
"""
print(banner)
def display_menu(self):
"""Display main menu"""
print(f"\n{Fore.CYAN + Style.BRIGHT}{'=' * 60}{Style.RESET_ALL}")
print(f"{Fore.YELLOW + Style.BRIGHT}MAIN MENU{Style.RESET_ALL}")
print(f"{Fore.CYAN + Style.BRIGHT}{'=' * 60}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT}1.{Style.RESET_ALL} {Fore.WHITE + Style.BRIGHT}Wrap FOGO to SPL {Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT}2.{Style.RESET_ALL} {Fore.WHITE + Style.BRIGHT}Unwrap SPL FOGO {Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT}3.{Style.RESET_ALL} {Fore.WHITE + Style.BRIGHT}Start Trade{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT}4.{Style.RESET_ALL} {Fore.WHITE + Style.BRIGHT}Set Position{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT}5.{Style.RESET_ALL} {Fore.WHITE + Style.BRIGHT}Set Deployment{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT}6.{Style.RESET_ALL} {Fore.WHITE + Style.BRIGHT}Set Transaction Count{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT}7.{Style.RESET_ALL} {Fore.WHITE + Style.BRIGHT}Auto All{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT}8.{Style.RESET_ALL} {Fore.WHITE + Style.BRIGHT}Exit{Style.RESET_ALL}")
print(f"{Fore.CYAN + Style.BRIGHT}{'=' * 60}{Style.RESET_ALL}")
def log(self, message, type="INFO"):
"""Enhanced logging with wallet name"""
wallet_display = f"{self.wallet_name}" if self.wallet_name else "System"
if type == "SUCCESS":
prefix = f"{Fore.GREEN + Style.BRIGHT}[SUCCESS]"
msg_color = Fore.GREEN + Style.BRIGHT
elif type == "ERROR":
prefix = f"{Fore.RED + Style.BRIGHT}[ERROR]"
msg_color = Fore.RED + Style.BRIGHT
elif type == "WARNING":
prefix = f"{Fore.YELLOW + Style.BRIGHT}[WARNING]"
msg_color = Fore.YELLOW + Style.BRIGHT
elif type == "PROCESS":
prefix = f"{Fore.CYAN + Style.BRIGHT}[PROCESS]"
msg_color = Fore.CYAN + Style.BRIGHT
elif type == "TX":
prefix = f"{Fore.MAGENTA + Style.BRIGHT}[TX]"
msg_color = Fore.MAGENTA + Style.BRIGHT
elif type == "BLOCK":
prefix = f"{Fore.YELLOW + Style.BRIGHT}[BLOCK]"
msg_color = Fore.BLUE + Style.BRIGHT
else:
prefix = f"{Fore.WHITE + Style.BRIGHT}[INFO]"
msg_color = Fore.WHITE + Style.BRIGHT
print(f"{Fore.BLUE + Style.BRIGHT}[{wallet_display}]{Style.RESET_ALL} {prefix}{Style.RESET_ALL} {msg_color}{message}{Style.RESET_ALL}")
def load_config(self):
"""Load configuration from config.json"""
try:
if os.path.exists(self.config_file):
with open(self.config_file, 'r') as f:
config = json.load(f)
self.wrap_count = config.get('wrap_count', 1)
self.unwrap_count = config.get('unwrap_count', 1)
self.trade_count = config.get('trade_count', 1)
self.position_count = config.get('position_count', 1)
self.deploy_count = config.get('deploy_count', 5)
self.min_delay = config.get('min_delay', 1)
self.max_delay = config.get('max_delay', 3)
else:
self.save_config()
except Exception as e:
self.save_config()
def save_config(self):
"""Save configuration to config.json"""
try:
config = {
'wrap_count': self.wrap_count,
'unwrap_count': self.unwrap_count,
'trade_count': self.trade_count,
'position_count': self.position_count,
'deploy_count': self.deploy_count,
'min_delay': self.min_delay,
'max_delay': self.max_delay
}
with open(self.config_file, 'w') as f:
json.dump(config, f, indent=4)
except Exception as e:
self.log(f"Error saving config: {str(e)}", "ERROR")
def set_transaction_counts(self):
"""Set transaction counts interactively"""
try:
print(f"\n{Fore.CYAN + Style.BRIGHT}{'=' * 60}{Style.RESET_ALL}")
print(f"{Fore.YELLOW + Style.BRIGHT}SET TRANSACTION COUNTS{Style.RESET_ALL}")
print(f"{Fore.CYAN + Style.BRIGHT}{'=' * 60}{Style.RESET_ALL}")
print(f"\n{Fore.WHITE + Style.BRIGHT}Current Settings:{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Wrap Count: {self.wrap_count}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Unwrap Count: {self.unwrap_count}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Trade Count: {self.trade_count}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Position Count: {self.position_count}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Deploy Count: {self.deploy_count}{Style.RESET_ALL}")
# Get wrap count
while True:
wrap_input = input(f"\n{Fore.GREEN + Style.BRIGHT}Enter wrap count (1-100) [{self.wrap_count}]: {Style.RESET_ALL}").strip()
if not wrap_input:
break
try:
count = int(wrap_input)
if 1 <= count <= 100:
self.wrap_count = count
break
else:
self.log("Please enter a number between 1 and 100", "WARNING")
except ValueError:
self.log("Invalid input. Please enter a number", "ERROR")
# Get unwrap count
while True:
unwrap_input = input(f"{Fore.GREEN + Style.BRIGHT}Enter unwrap count (1-100) [{self.unwrap_count}]: {Style.RESET_ALL}").strip()
if not unwrap_input:
break
try:
count = int(unwrap_input)
if 1 <= count <= 100:
self.unwrap_count = count
break
else:
self.log("Please enter a number between 1 and 100", "WARNING")
except ValueError:
self.log("Invalid input. Please enter a number", "ERROR")
# Get trade count
while True:
trade_input = input(f"{Fore.GREEN + Style.BRIGHT}Enter trade count (1-100) [{self.trade_count}]: {Style.RESET_ALL}").strip()
if not trade_input:
break
try:
count = int(trade_input)
if 1 <= count <= 100:
self.trade_count = count
break
else:
self.log("Please enter a number between 1 and 100", "WARNING")
except ValueError:
self.log("Invalid input. Please enter a number", "ERROR")
# Get position count
while True:
pos_input = input(f"{Fore.GREEN + Style.BRIGHT}Enter position count (1-100) [{self.position_count}]: {Style.RESET_ALL}").strip()
if not pos_input:
break
try:
count = int(pos_input)
if 1 <= count <= 100:
self.position_count = count
break
else:
self.log("Please enter a number between 1 and 100", "WARNING")
except ValueError:
self.log("Invalid input. Please enter a number", "ERROR")
# Get deploy count
while True:
dep_input = input(f"{Fore.GREEN + Style.BRIGHT}Enter deploy count (1-100) [{self.deploy_count}]: {Style.RESET_ALL}").strip()
if not dep_input:
break
try:
count = int(dep_input)
if 1 <= count <= 100:
self.deploy_count = count
break
else:
self.log("Please enter a number between 1 and 100", "WARNING")
except ValueError:
self.log("Invalid input. Please enter a number", "ERROR")
# Save configuration
self.save_config()
print(f"\n{Fore.WHITE + Style.BRIGHT}New Settings:{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Wrap Count: {self.wrap_count}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Unwrap Count: {self.unwrap_count}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Trade Count: {self.trade_count}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Position Count: {self.position_count}{Style.RESET_ALL}")
print(f"{Fore.GREEN + Style.BRIGHT} Deploy Count: {self.deploy_count}{Style.RESET_ALL}")
print(f"{Fore.CYAN + Style.BRIGHT}{'=' * 60}{Style.RESET_ALL}")
self.log("Configuration saved successfully!", "SUCCESS")
except Exception as e:
self.log(f"Error setting transaction counts: {str(e)}", "ERROR")
def rpc_request(self, method, params=None):
if params is None:
params = []
payload = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
res = requests.post(self.RPC_URL, json=payload, verify=False)
res.raise_for_status()
return res.json()
def get_min_rent_exempt_for_token_account(self):
size = 165
resp = self.rpc_request("getMinimumBalanceForRentExemption", [size])
return int(resp["result"])
def get_latest_blockhash(self):
r = self.rpc_request("getLatestBlockhash", [{"commitment": "finalized"}])
return r["result"]["value"]["blockhash"]
def get_fogo_balance(self, pubkey: str) -> int:
resp = self.rpc_request("getBalance", [pubkey, {"commitment": "finalized"}])
return int(resp["result"]["value"])
def get_spl_fogo_balance(self, owner: str) -> int:
resp = self.rpc_request(
"getTokenAccountsByOwner",
[owner, {"mint": str(WRAPPED_SOL_MINT)}, {"encoding": "jsonParsed"}],
)
accounts = resp.get("result", {}).get("value", [])
total = 0
for ta in accounts:
amt = int(ta["account"]["data"]["parsed"]["info"]["tokenAmount"]["amount"])
total += amt
return total
def send_raw_transaction(self, tx_bytes_b64):
return self.rpc_request(
"sendTransaction",
[
tx_bytes_b64,
{"skipPreflight": False, "preflightCommitment": "finalized", "encoding": "base64"},
],
)
async def wrap_fogo(self, private_key: str, amount_fogo: float):
self.log("Starting FOGO Wrap Process", "PROCESS")
secret_bytes = b58decode(private_key)
wallet = Keypair.from_secret_key(secret_bytes)
owner = wallet.public_key
self.log(f"Wallet Address: {str(owner)}", "INFO")
fogo_balance = self.get_fogo_balance(str(owner))
self.log(f"Current FOGO Balance: {fogo_balance/1e9:.9f} FOGO", "INFO")
amount = int(amount_fogo * 10**9)
self.log(f"Amount to Wrap: {amount_fogo:.9f} FOGO", "INFO")
if fogo_balance < amount:
self.log("Insufficient FOGO Balance for Wrapping!", "ERROR")
return None
resp = self.rpc_request(
"getTokenAccountsByOwner",
[str(owner), {"mint": str(WRAPPED_SOL_MINT)}, {"encoding": "jsonParsed"}],
)
token_accounts = resp.get("result", {}).get("value", [])
spl_fogo_account = None
for ta in token_accounts:
ata_pubkey = PublicKey(ta["pubkey"])
spl_fogo_account = ata_pubkey
break
if not spl_fogo_account:
self.log("No Existing SPL FOGO Account Found!", "ERROR")
return None
self.log(f"SPL FOGO Account: {str(spl_fogo_account)}", "INFO")
spl_fogo_balance = self.get_spl_fogo_balance(str(owner))
self.log(f"Current SPL FOGO Balance: {spl_fogo_balance/1e9:.9f} SPL FOGO", "INFO")
self.log("Creating Wrap Transaction...", "PROCESS")
temp_account_kp = Keypair()
temp_account_pub = temp_account_kp.public_key
rent_lamports = self.get_min_rent_exempt_for_token_account()
create_account_ix = create_account(
CreateAccountParams(
from_pubkey=owner,
new_account_pubkey=temp_account_pub,
lamports=rent_lamports + amount,
space=165,
program_id=TOKEN_PROGRAM_ID,
)
)
init_ix = initialize_account(
InitializeAccountParams(
account=temp_account_pub,
mint=WRAPPED_SOL_MINT,
owner=owner,
program_id=TOKEN_PROGRAM_ID,
)
)
transfer_ix = transfer_checked(
TransferCheckedParams(
program_id=TOKEN_PROGRAM_ID,
source=temp_account_pub,
mint=WRAPPED_SOL_MINT,
dest=spl_fogo_account,
owner=owner,
amount=amount,
decimals=9,
)
)
close_ix = close_account(
CloseAccountParams(
program_id=TOKEN_PROGRAM_ID,
account=temp_account_pub,
dest=owner,
owner=owner,
)
)
tx = Transaction()
tx.add(create_account_ix, init_ix, transfer_ix, close_ix)
blockhash = self.get_latest_blockhash()
tx.recent_blockhash = blockhash
tx.fee_payer = owner
tx.sign(wallet, temp_account_kp)
tx_bytes = tx.serialize()
tx_b64 = base64.b64encode(tx_bytes).decode("utf-8")
self.log("Sending Transaction...", "PROCESS")
resp = self.send_raw_transaction(tx_b64)
if "result" in resp:
self.log("FOGO Successfully Wrapped to SPL FOGO!", "SUCCESS")
signature = resp["result"]
self.log(f"Tx Hash: {signature}", "TX")
self.log(f"Explorer: {self.EXPLORER_URL}{signature}", "INFO")
return str(spl_fogo_account)
else:
self.log("Transaction failed!", "ERROR")
if "error" in resp:
self.log(f"Error: {resp['error']}", "ERROR")
return None
async def unwrap_fogo(self, private_key: str, amount_spl_fogo: float):
self.log("Starting SPL FOGO Unwrap Process", "PROCESS")
secret_bytes = b58decode(private_key)
wallet = Keypair.from_secret_key(secret_bytes)
owner = wallet.public_key
self.log(f"Wallet Address: {str(owner)}", "INFO")
fogo_balance = self.get_fogo_balance(str(owner))
self.log(f"Current FOGO Balance: {fogo_balance/1e9:.9f} FOGO", "INFO")
spl_fogo_balance = self.get_spl_fogo_balance(str(owner))
self.log(f"Current SPL FOGO Balance: {spl_fogo_balance/1e9:.9f} SPL FOGO", "INFO")
amount = int(amount_spl_fogo * 10**9)
self.log(f"Amount to Unwrap: {amount_spl_fogo:.9f} SPL FOGO", "INFO")
if spl_fogo_balance < amount:
self.log("Insufficient SPL FOGO Balance for Unwrapping!", "ERROR")
return
self.log("Preparing Transaction...", "PROCESS")
blockhash = self.get_latest_blockhash()
resp = self.rpc_request(
"getTokenAccountsByOwner",
[str(owner), {"mint": str(WRAPPED_SOL_MINT)}, {"encoding": "jsonParsed"}],
)
token_accounts = resp.get("result", {}).get("value", [])
source_ata = None
for ta in token_accounts:
ta_amount = int(ta["account"]["data"]["parsed"]["info"]["tokenAmount"]["amount"])
if ta_amount > 0:
source_ata = PublicKey(ta["pubkey"])
break
if source_ata is None:
self.log("No SPL FOGO Token Account Found With Balance!", "ERROR")
return
self.log(f"Source SPL FOGO Account: {str(source_ata)}", "INFO")
temp_account_kp = Keypair()
temp_account_pub = temp_account_kp.public_key
rent_lamports = self.get_min_rent_exempt_for_token_account()
self.log("Building Transaction...", "PROCESS")
create_account_ix = create_account(
CreateAccountParams(
from_pubkey=owner,
new_account_pubkey=temp_account_pub,
lamports=rent_lamports,
space=165,
program_id=TOKEN_PROGRAM_ID,
)
)
init_ix = initialize_account(
InitializeAccountParams(
account=temp_account_pub,
mint=WRAPPED_SOL_MINT,
owner=owner,
program_id=TOKEN_PROGRAM_ID,
)
)
transfer_ix = transfer_checked(
TransferCheckedParams(
program_id=TOKEN_PROGRAM_ID,
source=source_ata,
mint=WRAPPED_SOL_MINT,
dest=temp_account_pub,
owner=owner,
amount=amount,
decimals=9,
)
)
close_ix = close_account(
CloseAccountParams(
program_id=TOKEN_PROGRAM_ID,
account=temp_account_pub,
dest=owner,
owner=owner,
)
)
tx = Transaction()
tx.add(create_account_ix, init_ix, transfer_ix, close_ix)
tx.recent_blockhash = blockhash
tx.fee_payer = owner
tx.sign(wallet, temp_account_kp)
tx_bytes = tx.serialize()
tx_b64 = base64.b64encode(tx_bytes).decode("utf-8")
self.log("Sending Transaction...", "PROCESS")
resp = self.send_raw_transaction(tx_b64)
if "result" in resp:
self.log("SPL FOGO Successfully Unwrapped to FOGO!", "SUCCESS")
signature = resp["result"]
self.log(f"Tx Hash: {signature}", "TX")
self.log(f"Explorer: {self.EXPLORER_URL}{signature}", "INFO")
else:
self.log("Transaction failed!", "ERROR")
if "error" in resp:
self.log(f"Error: {resp['error']}", "ERROR")
def format_seconds(self, seconds):
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{int(hours):02}:{int(minutes):02}:{int(seconds):02}"
def check_proxy_schemes(self, proxies):
schemes = ["http://", "https://", "socks4://", "socks5://"]
if any(proxies.startswith(scheme) for scheme in schemes):
return proxies
return f"http://{proxies}"
def get_next_proxy_for_account(self, account):
if account not in self.account_proxies:
if not Valiant.proxies:
return None
proxy = self.check_proxy_schemes(Valiant.proxies[self.proxy_index])
self.account_proxies[account] = proxy
self.proxy_index = (self.proxy_index + 1) % len(Valiant.proxies)
self.current_proxy = self.account_proxies[account]
return self.account_proxies[account]
def build_proxy_config(self, proxy=None):
if not proxy:
return None, None, None
if proxy.startswith("socks"):
connector = ProxyConnector.from_url(proxy)
return connector, None, None
elif proxy.startswith("http"):
match = re.match(r"http://(.*?):(.*?)@(.*)", proxy)
if match:
username, password, host_port = match.groups()
clean_url = f"http://{host_port}"
auth = BasicAuth(username, password)
return None, clean_url, auth
else:
return None, proxy, None
raise Exception("Unsupported Proxy Type.")
def generate_wallet(self, account_data: str):
try:
# Parse privatekey:wallet_name format
account = account_data
secret_key = b58decode(account)
signing_key = SigningKey(secret_key[:32])
verify_key = signing_key.verify_key
public_key = b58encode(verify_key.encode()).decode()
self.wallet_name = public_key
return signing_key, public_key, account
except Exception as e:
self.log(f"Error generating wallet: {e}", "ERROR")
return None, None, None
def sign_transaction(self, signing_key: SigningKey, serialized_tx: str, sig_index: int):
try:
tx = bytearray(base64.b64decode(serialized_tx))
num_signatures = tx[0]
msg_offset = 1 + 64 * num_signatures
message = bytes(tx[msg_offset:])
sig = signing_key.sign(message).signature
start = 1 + 64 * sig_index
end = start + 64
tx[start:end] = sig
signed_tx = base64.b64encode(bytes(tx)).decode()
return signed_tx
except Exception as e:
return None
def mask_account(self, account):
try:
mask_account = account[:6] + '*' * 6 + account[-6:]
return mask_account
except Exception as e:
return None
def build_twohop_url(self, address: str, quote: dict, slippage_bps=100):
token_in = int(quote["tokenIn"])
token_est_out = int(quote["tokenEstOut"])
min_amount_out = token_est_out * (10_000 - slippage_bps) // 10_000
params = {
"userAddress": address,
"isExactIn": "true",
"inputAmount": token_in,
"outputAmount": min_amount_out,
"sessionAddress": address,
"feePayer": address,
}
query_parts = [f"{k}={v}" for k, v in params.items()]
for r in quote["quote"]["route"]:
query_parts.append(f"route={r}")
for p in quote["quote"]["pools"]:
query_parts.append(f"pools={p}")
return f"{self.VALIANT_API}/txs/twoHopSwap?{'&'.join(query_parts)}"
def generate_random_trade_pair(self):
pairs = [
("FOGO", "FUSD", self.FOGO_TOKEN, self.FUSD_TOKEN, self.fogo_trade_amount),
("FOGO", "USDT", self.FOGO_TOKEN, self.USDT_TOKEN, self.fogo_trade_amount),
("FOGO", "USDC", self.FOGO_TOKEN, self.USDC_TOKEN, self.fogo_trade_amount),
("FUSD", "FOGO", self.FUSD_TOKEN, self.FOGO_TOKEN, self.fusd_trade_amount),
("FUSD", "USDT", self.FUSD_TOKEN, self.USDT_TOKEN, self.fusd_trade_amount),
("FUSD", "USDC", self.FUSD_TOKEN, self.USDC_TOKEN, self.fusd_trade_amount),
("USDT", "FOGO", self.USDT_TOKEN, self.FOGO_TOKEN, self.usdt_trade_amount),
("USDT", "FUSD", self.USDT_TOKEN, self.FUSD_TOKEN, self.usdt_trade_amount),
("USDT", "USDC", self.USDT_TOKEN, self.USDC_TOKEN, self.usdt_trade_amount),
("USDC", "FOGO", self.USDC_TOKEN, self.FOGO_TOKEN, self.usdc_trade_amount),
("USDC", "FUSD", self.USDC_TOKEN, self.FUSD_TOKEN, self.usdc_trade_amount),
("USDC", "USDT", self.USDC_TOKEN, self.USDT_TOKEN, self.usdc_trade_amount),
]
ticker_a, ticker_b, token_a, token_b, amount_in = random.choice(pairs)
return ticker_a, ticker_b, token_a, token_b, amount_in
def generate_random_position_pair(self):
pairs = [
("FOGO", "FUSD", self.FOGO_TOKEN, self.FUSD_TOKEN, 64, self.fogo_position_amount),
("FOGO", "USDT", self.FOGO_TOKEN, self.USDT_TOKEN, 64, self.fogo_position_amount),
("FOGO", "USDC", self.FOGO_TOKEN, self.USDC_TOKEN, 64, self.fogo_position_amount),
("FUSD", "USDT", self.FUSD_TOKEN, self.USDT_TOKEN, 1, self.fusd_position_amount),
("FUSD", "USDC", self.FUSD_TOKEN, self.USDC_TOKEN, 1, self.fusd_position_amount),
("USDT", "USDC", self.USDT_TOKEN, self.USDC_TOKEN, 1, self.usdt_position_amount),
]
ticker_a, ticker_b, token_a, token_b, tick, amount_in = random.choice(pairs)
return ticker_a, ticker_b, token_a, token_b, tick, amount_in
def generate_new_token(self):
signing_key = SigningKey.generate()
verify_key = signing_key.verify_key
mint_address = b58encode(verify_key.encode()).decode()
return {
"signing_key": signing_key,
"pub_key": mint_address
}
def generate_raw_token(self):
default_name, default_symbol = random.choice([
("Token", "TKN"), ("MyToken", "MTK"), ("NewToken", "NTK"),
("CryptoCoin", "CRC"), ("SmartToken", "SMT"), ("MetaCoin", "MTC"),
("ChainToken", "CTK"), ("BlockCoin", "BKC"), ("FutureToken", "FUT"),
("GalaxyCoin", "GLX"), ("QuantumToken", "QTK"), ("StarCoin", "STR"),
("HyperToken", "HPT"), ("NovaCoin", "NVC"), ("PulseToken", "PLT"),
("OrbitCoin", "ORC"), ("UnityToken", "UNT"), ("PrimeCoin", "PMC"),
("AeroToken", "AET"), ("LunaCoin", "LNC"),
])
numbers = str(random.randint(0, 999999))
token_name = default_name + numbers
token_symbol = default_symbol + numbers
supply_amounts = [100000000, 1000000000, 10000000000]
raw_supply = random.choice(supply_amounts)
initial_supply = str(raw_supply * (10 ** 9))
return token_name, token_symbol, raw_supply, initial_supply
async def print_timer(self):
delay = random.randint(self.min_delay, self.max_delay)
for remaining in range(delay, 0, -1):
print(
f"{Fore.CYAN + Style.BRIGHT}[{self.wallet_name}]{Style.RESET_ALL} "
f"{Fore.YELLOW + Style.BRIGHT}[WAIT]{Style.RESET_ALL} "
f"{Fore.WHITE + Style.BRIGHT}Waiting {remaining} seconds for next transaction...{Style.RESET_ALL}",
end="\r",
flush=True
)
await asyncio.sleep(1)
print(" " * 100, end="\r") # Clear the line
async def check_connection(self, proxy_url=None):
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=30)) as session:
async with session.get(url="https://api.ipify.org?format=json", proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
return True
except (Exception, ClientResponseError) as e:
self.log(f"Connection error: {str(e)}", "ERROR")
return None
async def get_native_balance(self, address: str, use_proxy: bool, retries=5):
data = json.dumps({
"jsonrpc": "2.0",
"method": "getBalance",
"params": [ address ],
"id": str(uuid.uuid4())
})
headers = {
**self.HEADERS[address],
"Content-Length": str(len(data)),
"Content-Type": "application/json"
}
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.post(url=self.RPC_URL, headers=headers, data=data, proxy=proxy, proxy_auth=proxy_auth, ssl=False) as response:
response.raise_for_status()
return await response.json()
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Fetch Native Balance Failed: {str(e)}", "ERROR")
return None
async def get_token_balances(self, address: str, use_proxy: bool, retries=5):
data = json.dumps({
"method": "getTokenAccountsByOwner",
"jsonrpc": "2.0",
"params": [
address,
{ "programId": self.OWNER_ADDRESS },
{ "encoding": "jsonParsed", "commitment": "confirmed" }
],
"id": str(uuid.uuid4())
})
headers = {
**self.HEADERS[address],
"Content-Length": str(len(data)),
"Content-Type": "application/json"
}
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.post(url=self.RPC_URL, headers=headers, data=data, proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
return await response.json()
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Fetch Tokens Balance Failed: {str(e)}", "ERROR")
return None
async def get_quote(self, address: str, from_token: str, to_token: str, amount_in: int, use_proxy: bool, retries=5):
url = f"{self.VALIANT_API}/twoHopQuote?inputMint={from_token}&outputMint={to_token}&isExactIn=true&inputAmount={amount_in}"
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.get(url=url, headers=self.HEADERS[address], proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
return await response.json()
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Fetch Quote Amount Failed: {str(e)}", "ERROR")
return None
async def get_trade_txs(self, address: str, url: str, use_proxy: bool, retries=5):
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.get(url=url, headers=self.HEADERS[address], proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
return await response.json()
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Build Trade Txs Failed: {str(e)}", "ERROR")
return None
async def get_new_position(self, address: str, from_token:str, to_token: str, tick: int, amount_in: int, use_proxy: bool, retries=5):
url = f"{self.VALIANT_API}/txs/newPosition?userAddress={address}&mintA={from_token}&mintB={to_token}&amountA={amount_in}&slippageToleranceBps=0&tickSpacing={tick}&feePayer={address}&sessionAddress={address}"
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.get(url=url, headers=self.HEADERS[address], proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
return await response.json()
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Build Position Txs Failed: {str(e)}", "ERROR")
return None
async def download_random_image(self, address: str, use_proxy: bool, retries=3):
url = "https://thispersondoesnotexist.com"
headers = {
"User-Agent": FakeUserAgent().random
}
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.get(url=url, headers=headers, proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
img_bytes = await response.read()
img = Image.open(io.BytesIO(img_bytes))
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
quality = 85
while True:
buffer = io.BytesIO()
img.save(buffer, format="JPEG", quality=quality, optimize=True)
size_kb = buffer.tell() / 1024
if size_kb < 200 or quality <= 20:
break
quality -= 5
# Create images directory if it doesn't exist
if not os.path.exists("images"):
os.makedirs("images")
with open("images/my_token.jpeg", "wb") as f:
f.write(buffer.getvalue())
return True
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Download Token Images Failed: {str(e)}", "ERROR")
return None
async def get_presigned_url(self, address: str, use_proxy: bool, retries=5):
url = f"{self.VALIANT_API}/getPresignedUrl"
headers = {
**self.HEADERS[address],
"Content-Length": "0"
}
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.post(url=url, headers=headers, proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
return await response.json()
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Fetch Presigned URL Failed: {str(e)}", "ERROR")
return None
async def pinata_upload(self, address: str, url: str, use_proxy: bool, retries=5):
data = FormData()
data.add_field(
name="file",
value=open("images/my_token.jpeg", "rb"),
filename="my_token.jpeg",
content_type="image/jpeg"
)
data.add_field(
name="network",
value="public"
)
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.post(url=url, headers=self.HEADERS[address], data=data, proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
return await response.json()
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Upload Image Failed: {str(e)}", "ERROR")
return None
async def post_new_token(self, address: str, token_name: str, token_symbol: str, c_id: str, initial_supply: str, mint_address: str, use_proxy: bool, retries=5):
url = f"{self.VALIANT_API}/txs/newToken"
data = json.dumps({
"newTokenTransactionDetails": {
"name": token_name,
"symbol": token_symbol,
"description": "",
"image": f"https://ipfs.io/ipfs/{c_id}",
"decimals": 9,
"initialSupply": initial_supply,
"userAddress": address,
"website": "https://valiant.com",
"mint": mint_address
}
})
headers = {
**self.HEADERS[address],
"Content-Length": str(len(data)),
"Content-Type": "application/json"
}
for attempt in range(retries):
proxy_url = self.get_next_proxy_for_account(address) if use_proxy else None
connector, proxy, proxy_auth = self.build_proxy_config(proxy_url)
try:
async with ClientSession(connector=connector, timeout=ClientTimeout(total=120)) as session:
async with session.post(url=url, headers=headers, data=data, proxy=proxy, proxy_auth=proxy_auth) as response:
response.raise_for_status()
return await response.json()
except (Exception, ClientResponseError) as e:
if attempt < retries - 1:
await asyncio.sleep(5)
continue
self.log(f"Build New Token Txs Failed: {str(e)}", "ERROR")
return None
async def send_transaction(self, address: str, signed_tx: str, use_proxy: bool, retries=5):
data = json.dumps({
"jsonrpc": "2.0",