-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathweb3_handler.py
More file actions
1983 lines (1674 loc) · 83.5 KB
/
web3_handler.py
File metadata and controls
1983 lines (1674 loc) · 83.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
# web3.py
# For the more advanced and self-sustainable version of the Web3 Handler with dynamic NLP execution, check: https://github.com/arpahls/hermes3
import os
import re
import json
from decimal import Decimal
from dotenv import load_dotenv
from web3 import Web3
from colorama import Fore, Style
from kun import known_user_names
import time
import requests
# Load environment variables from .env
load_dotenv()
# Retrieve the agent's private key and RPC URLs from the environment
AGENT_PRIVATE_KEY = os.getenv("AGENT_PRIVATE_KEY")
BASE_RPC_URL = os.getenv("BASE_RPC_URL")
ETHEREUM_RPC_URL = os.getenv("ETHEREUM_RPC_URL")
POLYGON_RPC_URL = os.getenv("POLYGON_RPC_URL")
# Error handling if environment variables are missing
if not AGENT_PRIVATE_KEY or not BASE_RPC_URL or not ETHEREUM_RPC_URL or not POLYGON_RPC_URL:
print(Fore.RED + "Error: Missing environment variables. Check your .env file.")
exit()
# Initialize Web3 Connections for multiple chains
CHAIN_INFO = {
'Base': {
'chain_id': 8453,
'rpc_url': BASE_RPC_URL,
'symbol': 'ETH',
'decimals': 18,
'explorer_url': 'https://basescan.org',
},
'Ethereum': {
'chain_id': 1,
'rpc_url': ETHEREUM_RPC_URL,
'symbol': 'ETH',
'decimals': 18,
'explorer_url': 'https://etherscan.io',
},
'Polygon': {
'chain_id': 137,
'rpc_url': POLYGON_RPC_URL,
'symbol': 'MATIC',
'decimals': 18,
'explorer_url': 'https://polygonscan.com',
},
}
# Token dictionary with human-readable names
TOKENS = {
'Degen': {
'Base': '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
'Ethereum': '0xABCDEF1234567890ABCDEF1234567890ABCDEF12',
'Polygon': '0x1234567890ABCDEF1234567890ABCDEF12345678'
},
'USDC': {
'Base': '0x7F5c764cBc14f9669B88837ca1490cCa17c31607',
'Ethereum': '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606EB48',
'Polygon': '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
},
}
# Web3 connection object and gas strategy
web3_connection = None
gas_strategy = 'medium'
# Token ABI for ERC20 tokens (simplified)
TOKEN_ABI = [
{
"constant": True,
"inputs": [],
"name": "decimals",
"outputs": [{"name": "", "type": "uint8"}],
"payable": False,
"stateMutability": "view",
"type": "function"
},
{
"constant": True,
"inputs": [],
"name": "symbol",
"outputs": [{"name": "", "type": "string"}],
"payable": False,
"stateMutability": "view",
"type": "function"
},
{
"constant": False,
"inputs": [
{"name": "_to", "type": "address"},
{"name": "_value", "type": "uint256"}
],
"name": "transfer",
"outputs": [],
"payable": False,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": False,
"inputs": [
{"name": "_spender", "type": "address"},
{"name": "_value", "type": "uint256"}
],
"name": "approve",
"outputs": [{"name": "", "type": "bool"}],
"payable": False,
"stateMutability": "nonpayable",
"type": "function"
}
]
# Add this near the top of the file with other constants
ROUTER_ABI = [
# Quotes
{
"inputs": [
{"internalType": "uint256", "name": "amountOut", "type": "uint256"},
{"internalType": "address[]", "name": "path", "type": "address[]"}
],
"name": "getAmountsIn",
"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{"internalType": "uint256", "name": "amountIn", "type": "uint256"},
{"internalType": "address[]", "name": "path", "type": "address[]"}
],
"name": "getAmountsOut",
"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],
"stateMutability": "view",
"type": "function"
},
# Swapping
{
"inputs": [
{"internalType": "uint256", "name": "amountIn", "type": "uint256"},
{"internalType": "uint256", "name": "amountOutMin", "type": "uint256"},
{"internalType": "address[]", "name": "path", "type": "address[]"},
{"internalType": "address", "name": "to", "type": "address"},
{"internalType": "uint256", "name": "deadline", "type": "uint256"}
],
"name": "swapExactTokensForTokens",
"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{"internalType": "uint256", "name": "amountOutMin", "type": "uint256"},
{"internalType": "address[]", "name": "path", "type": "address[]"},
{"internalType": "address", "name": "to", "type": "address"},
{"internalType": "uint256", "name": "deadline", "type": "uint256"}
],
"name": "swapExactETHForTokens",
"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{"internalType": "uint256", "name": "amountIn", "type": "uint256"},
{"internalType": "uint256", "name": "amountOutMin", "type": "uint256"},
{"internalType": "address[]", "name": "path", "type": "address[]"},
{"internalType": "address", "name": "to", "type": "address"},
{"internalType": "uint256", "name": "deadline", "type": "uint256"}
],
"name": "swapExactTokensForETH",
"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],
"stateMutability": "nonpayable",
"type": "function"
},
# Factory
{
"inputs": [],
"name": "factory",
"outputs": [{"internalType": "address", "name": "", "type": "address"}],
"stateMutability": "view",
"type": "function"
},
# WETH
{
"inputs": [],
"name": "WETH",
"outputs": [{"internalType": "address", "name": "", "type": "address"}],
"stateMutability": "view",
"type": "function"
}
]
class Web3Handler:
def __init__(self, known_user_names):
"""Initialize Web3Handler with user data"""
self.known_user_names = known_user_names
self.web3_connection = None
self.current_chain = None
# Use the code's dictionaries as primary source
self.CHAIN_INFO = CHAIN_INFO.copy()
self.TOKENS = TOKENS.copy()
# Get the directory for temporary JSON storage
self.config_dir = os.path.dirname(os.path.abspath(__file__))
self.gas_strategy = 'medium'
self.AGENT_WALLET = {
'private_key': AGENT_PRIVATE_KEY,
'public_key': Web3.to_checksum_address('0x89A7f83Db9C1919B89370182002ffE5dfFc03e21')
}
# Initialize connection to default chain
self.connect_to_chain('Base')
def save_chain_config(self):
"""Save chain configuration to JSON file"""
with open('chain_config.json', 'w') as f:
json.dump(self.CHAIN_INFO, f, indent=4)
def save_token_config(self):
"""Save token configuration to JSON file"""
with open('token_config.json', 'w') as f:
json.dump(self.TOKENS, f, indent=4)
def add_chain(self):
"""Add a new chain configuration"""
try:
print(Fore.YELLOW + "\nAdding new chain configuration:")
# Get chain details
chain_name = input("Chain name: ").strip()
if chain_name in self.CHAIN_INFO:
print(Fore.RED + "Chain already exists!")
return
try:
chain_id = int(input("Chain ID: ").strip())
rpc_url = input("RPC URL: ").strip()
symbol = input("Native token symbol: ").strip()
explorer_url = input("Block explorer URL: ").strip()
# Test connection
web3 = Web3(Web3.HTTPProvider(rpc_url))
if not web3.is_connected():
raise ValueError("Unable to connect to RPC URL")
# Update runtime dictionary
self.CHAIN_INFO[chain_name] = {
'chain_id': chain_id,
'rpc_url': rpc_url,
'symbol': symbol,
'decimals': 18,
'explorer_url': explorer_url
}
# Save to temporary JSON for persistence until code is updated
self.save_chain_config()
# Update the Python file
self._update_python_file_chain(chain_name)
print(Fore.GREEN + f"\nChain {chain_name} added successfully!")
except Exception as e:
raise ValueError(f"Failed to add chain: {str(e)}")
except Exception as e:
raise ValueError(f"Failed to add chain: {str(e)}")
def add_token(self):
"""Interactive token addition"""
print(Fore.YELLOW + "\nAdding new token configuration:")
# Get token details
token_name = input("Token name: ").strip()
chain_name = input("Chain name: ").strip()
if chain_name not in self.CHAIN_INFO:
print(Fore.RED + f"Chain {chain_name} not supported!")
return
try:
contract_address = input("Contract address: ").strip()
contract_address = Web3.to_checksum_address(contract_address)
# Verify contract
web3 = Web3(Web3.HTTPProvider(self.CHAIN_INFO[chain_name]['rpc_url']))
contract = web3.eth.contract(address=contract_address, abi=TOKEN_ABI)
# Try to get token symbol
symbol = contract.functions.symbol().call()
# Add token
if token_name not in self.TOKENS:
self.TOKENS[token_name] = {}
self.TOKENS[token_name][chain_name] = contract_address
self.TOKENS[token_name]['symbol'] = symbol
print(Fore.GREEN + f"\nToken {token_name} ({symbol}) added successfully on {chain_name}!")
except Exception as e:
print(Fore.RED + f"Error adding token: {str(e)}")
def connect_to_chain(self, chain_name):
"""Establish a connection to the specified blockchain."""
if chain_name not in self.CHAIN_INFO:
print(Fore.RED + f"Error: Chain '{chain_name}' not supported.")
return False
chain = self.CHAIN_INFO[chain_name]
try:
provider = Web3.HTTPProvider(chain['rpc_url'])
self.web3_connection = Web3(provider)
if self.web3_connection.is_connected():
self.current_chain = chain_name
return True
else:
print(Fore.RED + f"Failed to connect to {chain_name}")
return False
except Exception as e:
print(Fore.RED + f"Error connecting to {chain_name}: {str(e)}")
return False
def get_gas_price(self):
"""Return gas price based on the current strategy (low, medium, high)."""
if self.gas_strategy == 'low':
return self.web3_connection.eth.gas_price * 0.8
elif self.gas_strategy == 'high':
return self.web3_connection.eth.gas_price * 1.5
else: # medium is default
return self.web3_connection.eth.gas_price
def set_gas_strategy(self, level):
"""Set the gas strategy for transactions."""
if level in ['low', 'medium', 'high']:
self.gas_strategy = level
print(Fore.GREEN + f"Gas strategy set to {self.gas_strategy}.")
else:
print(Fore.RED + "Error: Invalid gas level. Choose 'low', 'medium', or 'high'.")
def get_recipient_address(self, recipient_name):
"""Fetch recipient's public Ethereum address by matching full_name or call_name."""
for user in self.known_user_names.values():
if user['full_name'].lower() == recipient_name.lower() or user['call_name'].lower() == recipient_name.lower():
return user['public0x']
return None
def confirm_transaction(self):
"""Ask the user for confirmation before committing the transaction."""
print(Fore.LIGHTRED_EX + "Please confirm the transaction by typing or saying 'confirm' or cancel by typing 'cancel'.")
user_input = input().strip().lower()
if user_input == 'confirm':
return True
elif user_input == 'cancel':
print(Fore.RED + "Transaction cancelled.")
return False
else:
print(Fore.RED + "Invalid input. Transaction cancelled.")
return False
def get_transaction_url(self, chain_name, tx_hash):
"""Returns the appropriate URL for viewing the transaction based on the chain."""
if chain_name in self.CHAIN_INFO and 'explorer_url' in self.CHAIN_INFO[chain_name]:
base_url = self.CHAIN_INFO[chain_name]['explorer_url'].rstrip('/')
return f"{base_url}/tx/{tx_hash}"
return f"Unknown chain: {chain_name}"
def send_tokens(self, chain, token_name, amount, recipient_name):
# First, ensure connection to the right chain
if not self.connect_to_chain(chain):
print(Fore.RED + f"Error: Failed to connect to {chain}.")
return
recipient_address = self.get_recipient_address(recipient_name)
if not recipient_address:
print(Fore.RED + f"Error: Recipient '{recipient_name}' not found or has no known public address.")
return
# Set default token as native token if not specified
if token_name == '':
token_name = self.CHAIN_INFO[chain]['symbol']
chain_data = self.CHAIN_INFO[chain]
print(Fore.LIGHTYELLOW_EX + f"Preparing to send {amount} {token_name} to {recipient_name} ({recipient_address}) on {chain} network.")
if not self.confirm_transaction():
return
if token_name == chain_data['symbol']: # Native token
amount_in_wei = self.web3_connection.to_wei(amount, 'ether')
transaction = {
'from': self.AGENT_WALLET['public_key'],
'to': recipient_address,
'value': amount_in_wei,
'gas': 21000,
'gasPrice': self.get_gas_price(),
'chainId': chain_data['chain_id'],
}
signed_txn = self.web3_connection.eth.account.sign_transaction(
transaction,
private_key=self.AGENT_WALLET['private_key']
)
tx_hash = self.web3_connection.eth.send_raw_transaction(signed_txn.raw_transaction)
# Get transaction URL and print success message
tx_url = self.get_transaction_url(chain, self.web3_connection.to_hex(tx_hash))
print(Fore.LIGHTGREEN_EX + f"Transaction sent! View it on explorer: {tx_url}")
else: # ERC-20 token
token_address = self.TOKENS.get(token_name, {}).get(chain)
if not token_address:
print(Fore.RED + f"Error: Token '{token_name}' is not supported on {chain}.")
return
token_contract = self.web3_connection.eth.contract(
address=Web3.to_checksum_address(token_address),
abi=TOKEN_ABI
)
amount_in_wei = self.web3_connection.to_wei(amount, 'ether')
transaction = token_contract.functions.transfer(
recipient_address,
amount_in_wei
).build_transaction({
'from': self.AGENT_WALLET['public_key'],
'gas': 100000,
'gasPrice': self.get_gas_price(),
'nonce': self.web3_connection.eth.get_transaction_count(self.AGENT_WALLET['public_key']),
'chainId': chain_data['chain_id'],
})
signed_txn = self.web3_connection.eth.account.sign_transaction(
transaction,
private_key=self.AGENT_WALLET['private_key']
)
tx_hash = self.web3_connection.eth.send_raw_transaction(signed_txn.raw_transaction)
# Get transaction URL and print success message
tx_url = self.get_transaction_url(chain, self.web3_connection.to_hex(tx_hash))
print(Fore.LIGHTGREEN_EX + f"Transaction sent! View it on explorer: {tx_url}")
def handle_send_command(self, command, agent_voice_active=False, voice_mode_active=False, speak_response=None):
"""Handle the /send command logic."""
try:
match = re.match(r'(?:/send|/0x\s+send)\s+(\w+)\s+([\w|\'\']+)\s+(\d+(\.\d+)?)\s+to\s+(\w+)', command)
if not match:
raise ValueError("Invalid command format. Use: /send <chain> <token|''> <amount> to <recipient>.")
chain = match.group(1).capitalize()
token_name = match.group(2).capitalize()
amount = float(match.group(3))
recipient_name = match.group(5)
if chain not in self.CHAIN_INFO:
chain_matches = [c for c in self.CHAIN_INFO.keys() if c.lower() == chain.lower()]
if chain_matches:
chain = chain_matches[0]
else:
raise ValueError(f"Chain '{chain}' is not supported.")
# Check if token exists (case-insensitive)
if token_name and token_name not in self.TOKENS: # Fix: Use global TOKENS
token_matches = [t for t in self.TOKENS.keys() if t.lower() == token_name.lower()]
if token_matches:
token_name = token_matches[0]
else:
raise ValueError(f"Token '{token_name}' is not supported.")
self.send_tokens(chain, token_name, amount, recipient_name)
except ValueError as ve:
error_message = f"Error: {ve}"
print(Fore.RED + error_message)
if agent_voice_active or voice_mode_active and speak_response:
speak_response(error_message)
def handle_gas_command(self, command):
"""Handle the /send gas command."""
try:
args = command.split()
if len(args) < 2:
raise ValueError("Invalid format. Use: /send gas <low|medium|high>.")
gas_level = args[2]
self.set_gas_strategy(gas_level)
except ValueError as ve:
print(Fore.RED + f"Error: {ve}")
def handle_receive_command(self, current_user=None):
"""Display wallet addresses and supported tokens/chains"""
print(Fore.LIGHTMAGENTA_EX + "\nWallet Information & Supported Assets")
print("=" * 50)
# Display wallet addresses
if current_user and current_user in self.known_user_names:
user_wallet = self.known_user_names[current_user]['public0x']
print(Fore.LIGHTYELLOW_EX + f"\n{current_user}'s Wallet:")
print(f"Address: {user_wallet}")
print(Fore.LIGHTYELLOW_EX + "\nOPSIE's Wallet:")
print(f"Address: {self.AGENT_WALLET['public_key']}")
# Display supported chains
print(Fore.LIGHTYELLOW_EX + "\nSupported Chains:")
for chain_name, chain_data in self.CHAIN_INFO.items(): # Fix: Use global CHAIN_INFO
print(f"\n{chain_name}:")
print(f" Native Token: {chain_data['symbol']}")
print(f" Explorer: {chain_data['explorer_url']}")
# Display supported tokens per chain
print(Fore.LIGHTYELLOW_EX + "\nSupported Tokens:")
for chain_name in self.CHAIN_INFO.keys(): # Fix: Use global CHAIN_INFO
print(f"\n{chain_name} Tokens:")
chain_tokens = [token for token, data in self.TOKENS.items() # Fix: Use global TOKENS
if chain_name in data]
for token in chain_tokens:
contract = self.TOKENS[token].get(chain_name) # Fix: Use global TOKENS
print(f" {token}: {contract}")
print("\n" + "=" * 50)
def parse_transaction_intent(self, command):
"""Parse user's natural language input into transaction parameters"""
if not command:
return None
# Normalize input
command = command.lower().strip()
# Initialize parameters
params = {
'action': None, # buy, sell
'amount': None, # numeric amount, 'all', 'half', '50%', etc.
'token': None, # token to buy/sell
'chain': None, # chain to operate on
'using_token': None, # token to pay with (for buy) or receive (for sell)
'amount_is_target': False # True if amount refers to using_token instead of main token
}
# Extract chain (look for "on <chain>")
chain_match = re.search(r'on\s+(\w+)', command)
if chain_match and chain_match.group(1):
chain_name = chain_match.group(1).capitalize()
if chain_name in self.CHAIN_INFO: # Fix: Use global CHAIN_INFO
params['chain'] = chain_name
# Determine action
if 'sell' in command:
params['action'] = 'sell'
elif 'buy' in command:
params['action'] = 'buy'
# Extract amount and token
amount_patterns = [
r'(all)(?:\s+my)?\s+(\w+)',
r'(half)(?:\s+of)?\s+(?:my)?\s+(\w+)',
r'(\d+(?:\.\d+)?%?)(?:\s+of)?\s+(?:my)?\s+(\w+)',
r'(\d+(?:\.\d+)?)\s+(\w+)'
]
for pattern in amount_patterns:
match = re.search(pattern, command)
if match:
amount_str, token_name = match.groups()
# Process amount
if amount_str == 'all':
params['amount'] = 'all'
elif amount_str == 'half':
params['amount'] = '50%'
elif '%' in amount_str:
params['amount'] = amount_str
else:
try:
params['amount'] = float(amount_str)
except ValueError:
continue
# Find matching token
for trusted_token in self.TOKENS: # Fix: Use global TOKENS
if trusted_token.lower() == token_name.lower():
params['token'] = trusted_token
break
# Check if it's a native token
for chain_name, chain_data in self.CHAIN_INFO.items(): # Fix: Use global CHAIN_INFO
if chain_data.get('symbol', '').lower() == token_name.lower():
params['token'] = chain_data['symbol']
break
if params['token']:
break
# Handle target token amount (e.g., "sell degen for 0.1 eth")
for pattern in [r'for\s+(\d+(?:\.\d+)?)\s+(\w+)', r'using\s+(\d+(?:\.\d+)?)\s+(\w+)']:
match = re.search(pattern, command)
if match:
amount_str, token_name = match.groups()
try:
params['amount'] = float(amount_str)
params['amount_is_target'] = True
# Check if it's a native token
for chain_name, chain_data in self.CHAIN_INFO.items(): # Fix: Use global CHAIN_INFO
if chain_data.get('symbol', '').lower() == token_name.lower():
params['using_token'] = chain_data['symbol']
break
# If not native, check trusted tokens
if not params['using_token']:
for trusted_token in self.TOKENS: # Fix: Use global TOKENS
if trusted_token.lower() == token_name.lower():
params['using_token'] = trusted_token
break
except ValueError:
continue
# If no target amount found, look for target token
if not params['using_token']:
for pattern in [r'for\s+(\w+)', r'using\s+(\w+)']:
match = re.search(pattern, command)
if match and match.group(1):
token_name = match.group(1)
# Check native tokens
for chain_name, chain_data in self.CHAIN_INFO.items(): # Fix: Use global CHAIN_INFO
if chain_data.get('symbol', '').lower() == token_name.lower():
params['using_token'] = chain_data['symbol']
break
# Check trusted tokens
if not params['using_token']:
for trusted_token in self.TOKENS: # Fix: Use global TOKENS
if trusted_token.lower() == token_name.lower():
params['using_token'] = trusted_token
break
return params
def validate_and_complete_transaction(self, params):
"""Validate transaction parameters and prompt for missing information"""
if not params:
raise ValueError("Could not understand transaction intent. Please try again.")
# Validate/prompt for chain
if not params['chain']:
print(Fore.YELLOW + "\nAvailable chains:")
for chain in self.CHAIN_INFO.keys():
print(f"- {chain}")
chain_input = input("Which chain would you like to use? ").strip()
if chain_input.capitalize() in self.CHAIN_INFO:
params['chain'] = chain_input.capitalize()
else:
raise ValueError(f"Unsupported chain: {chain_input}")
# Validate/prompt for token
if not params['token']:
print(Fore.YELLOW + f"\nAvailable tokens on {params['chain']}:")
available_tokens = [token for token, data in self.TOKENS.items()
if params['chain'] in data]
for token in available_tokens:
print(f"- {token}")
token_input = input("Which token would you like to trade? ").strip().upper()
if token_input in [t.upper() for t in available_tokens]:
params['token'] = next(t for t in available_tokens if t.upper() == token_input)
else:
raise ValueError(f"Unsupported token: {token_input}")
# For buy/sell operations, validate/prompt for using_token
if params['action'] in ['buy', 'sell'] and not params['using_token']:
print(Fore.YELLOW + f"\nAvailable tokens to trade with:")
# Get available tokens excluding the one being traded
available_tokens = [token for token, data in self.TOKENS.items()
if params['chain'] in data and token != params['token']]
# Add native token
native_token = self.CHAIN_INFO[params['chain']]['symbol']
available_tokens.append(native_token)
for token in available_tokens:
print(f"- {token}")
token_input = input(f"Which token would you like to {'pay with' if params['action'] == 'buy' else 'receive'}? ").strip().upper()
if token_input in [t.upper() for t in available_tokens]:
params['using_token'] = next(t for t in available_tokens if t.upper() == token_input)
else:
raise ValueError(f"Unsupported token: {token_input}")
# Validate/prompt for amount
if not params['amount'] and params['amount'] != 0:
amount_input = input("How much would you like to trade? (or 'all' for entire balance) ").strip()
if amount_input.lower() == 'all':
params['amount'] = 'all'
else:
try:
params['amount'] = float(amount_input)
except ValueError:
raise ValueError("Invalid amount specified")
return params
def format_transaction_preview(self, params, price_data):
"""Format transaction details for user confirmation"""
preview = []
if params['action'] in ['buy', 'sell']:
# Token amounts
if params['action'] == 'buy':
preview.extend([
"Price Quotes:",
"Best Price from DEX:",
f" You give: {price_data['amount_in_formatted']} {params['using_token']}",
f" You get: {price_data['amount_out_formatted']} {params['token']}"
])
else: # sell remains unchanged
preview.extend([
"Price Quotes:",
"Best Price from DEX:",
f" You give: {params['amount']} {params['token']}",
f" You get: {price_data['amount_out_formatted']} {params['using_token']}"
])
# Exchange rate
if params['action'] == 'buy':
preview.extend([
"",
"Exchange Rate:",
f" 1 {params['using_token']} = {1/price_data['exchange_rate']:.6f} {params['token']}"
])
else: # sell remains unchanged
preview.extend([
"",
"Exchange Rate:",
f" 1 {params['token']} = {price_data['exchange_rate']:.6f} {params['using_token']}"
])
# Rest of the preview formatting remains the same
preview.extend([
"",
"USD Values:",
f" Input: ${price_data['usd_values']['input']:.2f}",
f" Output: ${price_data['usd_values']['output']:.2f}",
f" Price Impact: {((price_data['usd_values']['output'] - price_data['usd_values']['input']) / price_data['usd_values']['input'] * 100):.2f}%",
"",
"Available Routes:"
])
for route in price_data['all_quotes']['dexes']:
preview.append(f" - {route['name']} via {route['router']}")
return "\n".join(preview)
def get_best_price(self, params):
"""Get best price across multiple DEXes with USD values"""
try:
# Ensure we have a connection
if not self.web3_connection or not self.web3_connection.is_connected():
if not self.connect_to_chain(params['chain']):
raise ValueError(f"Failed to connect to {params['chain']}")
router = self.get_dex_router(params['chain'])
token_address = Web3.to_checksum_address(self.TOKENS[params['token']][params['chain']])
using_token_address = (self.get_weth_address(params['chain'])
if params['using_token'] == self.CHAIN_INFO[params['chain']]['symbol']
else Web3.to_checksum_address(self.TOKENS[params['using_token']][params['chain']]))
if params['action'] == 'buy':
# Get token decimals
token_contract = self.web3_connection.eth.contract(
address=token_address,
abi=TOKEN_ABI
)
token_decimals = token_contract.functions.decimals().call()
# Calculate the target amount of tokens we want to buy
amount_out = int(float(params['amount']) * (10 ** token_decimals))
# Get amounts from router using getAmountsIn()
amounts = router.functions.getAmountsIn(
amount_out, # Amount of tokens we want to receive
[using_token_address, token_address] # Path: ETH -> Token
).call()
amount_in = amounts[0] # This is how much ETH we need to pay
# Format amounts for display
amount_in_formatted = Web3.from_wei(amount_in, 'ether')
amount_out_formatted = float(params['amount'])
# Get USD values
eth_price = self.get_token_usd_price('ETH', params['chain'])
input_usd = float(amount_in_formatted) * eth_price
output_usd = input_usd # Simplified for now
return {
'source': 'DEX',
'amount_in': amount_in,
'amount_in_formatted': amount_in_formatted,
'amount_out': amount_out,
'amount_out_formatted': amount_out_formatted,
# For display purposes, we want to show how many tokens per ETH
'exchange_rate': float(amount_in_formatted) / float(amount_out_formatted),
'decimals': {
'from': 18, # ETH decimals
'to': token_decimals
},
'usd_values': {
'input': input_usd,
'output': output_usd
},
'quote': {
'router': router.address,
'path': [using_token_address, token_address]
},
'all_quotes': {
'dexes': [{
'name': 'BaseSwap',
'router': router.address
}]
}
}
else: # sell
# Get token decimals
token_contract = self.web3_connection.eth.contract(
address=token_address,
abi=TOKEN_ABI
)
token_decimals = token_contract.functions.decimals().call()
# Calculate amount in wei
amount_in = int(float(params['amount']) * (10 ** token_decimals))
# Get amounts from router
amounts = router.functions.getAmountsOut(
amount_in,
[token_address, using_token_address]
).call()
amount_out = amounts[1]
# Format amounts for display
amount_in_formatted = float(params['amount'])
amount_out_formatted = Web3.from_wei(amount_out, 'ether')
# Calculate exchange rate
exchange_rate = float(amount_out_formatted) / float(amount_in_formatted)
# Get USD values
eth_price = self.get_token_usd_price('ETH', params['chain'])
output_usd = float(amount_out_formatted) * eth_price
input_usd = output_usd # Simplified for now
return {
'source': 'DEX',
'amount_in': amount_in,
'amount_in_formatted': amount_in_formatted,
'amount_out': amount_out,
'amount_out_formatted': amount_out_formatted,
'exchange_rate': exchange_rate,
'decimals': {
'from': token_decimals,
'to': 18 # ETH decimals
},
'usd_values': {
'input': input_usd,
'output': output_usd
},
'quote': {
'router': router.address,
'path': [token_address, using_token_address]
},
'all_quotes': {
'dexes': [{
'name': 'UniswapV2',
'router': router.address
}]
}
}
except Exception as e:
raise ValueError(f"Failed to get price: {str(e)}")
def execute_buy(self, params):
"""Execute a buy transaction with additional validation"""
try:
if not self.connect_to_chain(params['chain']):
raise ValueError(f"Failed to connect to {params['chain']}")
# Get price quote first
price_quote = self.get_best_price(params)
token_address = Web3.to_checksum_address(self.TOKENS[params['token']][params['chain']])
using_token_address = (self.get_weth_address(params['chain'])
if params['using_token'] == self.CHAIN_INFO[params['chain']]['symbol']
else Web3.to_checksum_address(self.TOKENS[params['using_token']][params['chain']]))
router = self.get_dex_router(params['chain'])
# Calculate slippage and deadline
slippage = 0.005 # 0.5% slippage tolerance
amount_out_min = int(price_quote['amount_out'] * (1 - slippage))
deadline = int(time.time()) + 300 # 5 minutes
if params['using_token'] == self.CHAIN_INFO[params['chain']]['symbol']:
# Check ETH balance
balance = self.web3_connection.eth.get_balance(self.AGENT_WALLET['public_key'])
if balance < price_quote['amount_in']:
raise ValueError(f"Insufficient ETH balance. Need {Web3.from_wei(price_quote['amount_in'], 'ether')} ETH")
# Execute ETH swap
swap_tx = router.functions.swapExactETHForTokens(
amount_out_min, # minimum amount of tokens to receive
[using_token_address, token_address], # path
self.AGENT_WALLET['public_key'], # recipient
deadline
).build_transaction({
'from': self.AGENT_WALLET['public_key'],
'value': price_quote['amount_in'], # amount of ETH to send
'gas': 250000,
'gasPrice': self.get_gas_price(),
'nonce': self.web3_connection.eth.get_transaction_count(self.AGENT_WALLET['public_key']),
'chainId': self.web3_connection.eth.chain_id
})
else:
# Handle ERC20 token
token_contract = self.web3_connection.eth.contract(
address=using_token_address,
abi=TOKEN_ABI
)
# Check token balance
balance = token_contract.functions.balanceOf(self.AGENT_WALLET['public_key']).call()
if balance < price_quote['amount_in']:
raise ValueError(f"Insufficient {params['using_token']} balance")
# Approve tokens if needed
allowance = token_contract.functions.allowance(
self.AGENT_WALLET['public_key'],
router.address
).call()
if allowance < price_quote['amount_in']:
approve_tx = token_contract.functions.approve(
router.address,
price_quote['amount_in']
).build_transaction({
'from': self.AGENT_WALLET['public_key'],
'gas': 100000,
'gasPrice': self.get_gas_price(),
'nonce': self.web3_connection.eth.get_transaction_count(self.AGENT_WALLET['public_key']),
'chainId': self.web3_connection.eth.chain_id
})
signed_tx = self.web3_connection.eth.account.sign_transaction(
approve_tx,
private_key=self.AGENT_WALLET['private_key']
)
tx_hash = self.web3_connection.eth.send_raw_transaction(signed_tx.raw_transaction)
self.web3_connection.eth.wait_for_transaction_receipt(tx_hash)
# Execute token swap
swap_tx = router.functions.swapExactTokensForTokens(
price_quote['amount_in'], # amount of tokens to send
amount_out_min, # minimum amount of tokens to receive
[using_token_address, token_address], # path
self.AGENT_WALLET['public_key'], # recipient
deadline
).build_transaction({
'from': self.AGENT_WALLET['public_key'],
'gas': 250000,
'gasPrice': self.get_gas_price(),
'nonce': self.web3_connection.eth.get_transaction_count(self.AGENT_WALLET['public_key']),
'chainId': self.web3_connection.eth.chain_id
})
# Sign and send transaction
signed_tx = self.web3_connection.eth.account.sign_transaction(
swap_tx,
private_key=self.AGENT_WALLET['private_key']
)
tx_hash = self.web3_connection.eth.send_raw_transaction(signed_tx.raw_transaction)
receipt = self.web3_connection.eth.wait_for_transaction_receipt(tx_hash)
if receipt['status'] == 1:
success_message = (
f"\nBought {price_quote['amount_out_formatted']} {params['token']} "
f"using {price_quote['amount_in_formatted']} {params['using_token']} "
f"at rate 1 {params['using_token']} = {1/price_quote['exchange_rate']:.8f} {params['token']} "
f"via UniswapV2 pool"
)
print(Fore.GREEN + success_message)