1818#
1919# ------------------------------------------------------------------------------
2020
21+ """Choose staking program."""
22+
2123import argparse
24+ import json
2225import os
23- import requests
2426import sys
2527import textwrap
26- import json
27- from dotenv import dotenv_values , set_key , unset_key
2828from pathlib import Path
29- from typing import Any , Dict , List , Tuple
29+ from typing import Any , Dict , List
30+
31+ import requests
32+ from dotenv import dotenv_values , set_key , unset_key
3033from web3 import Web3
3134
35+
3236SCRIPT_PATH = Path (__file__ ).resolve ().parent
3337STORE_PATH = Path (SCRIPT_PATH , ".." , ".trader_runner" )
3438DOTENV_PATH = Path (STORE_PATH , ".env" )
3539RPC_PATH = Path (STORE_PATH , "rpc.txt" )
36- STAKING_TOKEN_INSTANCE_ABI_PATH = Path (SCRIPT_PATH , ".." , "trader" , "packages" , "valory" , "contracts" , "staking_token" , "build" , "StakingToken.json" )
40+ STAKING_TOKEN_INSTANCE_ABI_PATH = Path (
41+ SCRIPT_PATH ,
42+ ".." ,
43+ "trader" ,
44+ "packages" ,
45+ "valory" ,
46+ "contracts" ,
47+ "staking_token" ,
48+ "build" ,
49+ "StakingToken.json" ,
50+ )
3751STAKING_TOKEN_IMPLEMENTATION_ABI_PATH = STAKING_TOKEN_INSTANCE_ABI_PATH
38- ACTIVITY_CHECKER_ABI_PATH = Path (SCRIPT_PATH , ".." , "trader" , "packages" , "valory" , "contracts" , "mech_activity" , "build" , "MechActivity.json" )
52+ ACTIVITY_CHECKER_ABI_PATH = Path (
53+ SCRIPT_PATH ,
54+ ".." ,
55+ "trader" ,
56+ "packages" ,
57+ "valory" ,
58+ "contracts" ,
59+ "mech_activity" ,
60+ "build" ,
61+ "MechActivity.json" ,
62+ )
3963
4064IPFS_ADDRESS = "https://gateway.autonolas.tech/ipfs/f01701220{hash}"
4165NEVERMINED_MECH_CONTRACT_ADDRESS = "0x327E26bDF1CfEa50BFAe35643B23D5268E41F7F9"
@@ -87,18 +111,20 @@ def _prompt_select_staking_program() -> str:
87111 env_file_vars = dotenv_values (DOTENV_PATH )
88112
89113 program_id = None
90- if ' STAKING_PROGRAM' in env_file_vars :
114+ if " STAKING_PROGRAM" in env_file_vars :
91115 print ("The staking program is already selected." )
92116
93- program_id = env_file_vars .get (' STAKING_PROGRAM' )
117+ program_id = env_file_vars .get (" STAKING_PROGRAM" )
94118 if program_id not in STAKING_PROGRAMS :
95119 print (f"WARNING: Selected staking program { program_id } is unknown." )
96120 print ("" )
97121 program_id = None
98122
99123 if not program_id :
100124 if os .environ .get ("ATTENDED" ) == "false" :
101- print ("No staking program set in environment variable STAKING_PROGRAM. Defaulting to 'no_staking'." )
125+ print (
126+ "No staking program set in environment variable STAKING_PROGRAM. Defaulting to 'no_staking'."
127+ )
102128 return NO_STAKING_PROGRAM_ID
103129
104130 print ("Please, select your staking program preference" )
@@ -108,7 +134,9 @@ def _prompt_select_staking_program() -> str:
108134 metadata = _get_staking_contract_metadata (program_id = key )
109135 name = metadata ["name" ]
110136 description = metadata ["description" ]
111- wrapped_description = textwrap .fill (description , width = 80 , initial_indent = ' ' , subsequent_indent = ' ' )
137+ wrapped_description = textwrap .fill (
138+ description , width = 80 , initial_indent = " " , subsequent_indent = " "
139+ )
112140 print (f"{ index + 1 } ) { name } \n { wrapped_description } \n " )
113141
114142 while True :
@@ -127,8 +155,12 @@ def _prompt_select_staking_program() -> str:
127155
128156
129157def _get_abi (contract_address : str ) -> List :
130- contract_abi_url = "https://gnosis.blockscout.com/api/v2/smart-contracts/{contract_address}"
131- response = requests .get (contract_abi_url .format (contract_address = contract_address )).json ()
158+ contract_abi_url = (
159+ "https://gnosis.blockscout.com/api/v2/smart-contracts/{contract_address}"
160+ )
161+ response = requests .get (
162+ contract_abi_url .format (contract_address = contract_address )
163+ ).json ()
132164
133165 if "result" in response :
134166 result = response ["result" ]
@@ -145,7 +177,9 @@ def _get_abi(contract_address: str) -> List:
145177
146178def _load_abi_from_file (path : Path ) -> Dict [str , Any ]:
147179 if not os .path .exists (path ):
148- print ("Error: Contract airtfacts not found. Please execute 'run_service.sh' before executing this script." )
180+ print (
181+ "Error: Contract airtfacts not found. Please execute 'run_service.sh' before executing this script."
182+ )
149183 sys .exit (1 )
150184
151185 with open (path , "r" , encoding = "utf-8" ) as f :
@@ -161,7 +195,7 @@ def _get_staking_token_contract(program_id: str, use_blockscout: bool = False) -
161195 if program_id in contracts_cache :
162196 return contracts_cache [program_id ]
163197
164- with open (RPC_PATH , 'r' , encoding = "utf-8" ) as file :
198+ with open (RPC_PATH , "r" , encoding = "utf-8" ) as file :
165199 rpc = file .read ().strip ()
166200
167201 w3 = Web3 (Web3 .HTTPProvider (rpc ))
@@ -172,7 +206,7 @@ def _get_staking_token_contract(program_id: str, use_blockscout: bool = False) -
172206 abi = _load_abi_from_file (STAKING_TOKEN_INSTANCE_ABI_PATH )
173207 contract = w3 .eth .contract (address = staking_token_instance_address , abi = abi )
174208
175- if ' getImplementation' in [func .fn_name for func in contract .all_functions ()]:
209+ if " getImplementation" in [func .fn_name for func in contract .all_functions ()]:
176210 # It is a proxy contract
177211 implementation_address = contract .functions .getImplementation ().call ()
178212 if use_blockscout :
@@ -185,49 +219,63 @@ def _get_staking_token_contract(program_id: str, use_blockscout: bool = False) -
185219 return contract
186220
187221
188- def _get_staking_contract_metadata (program_id : str , use_blockscout : bool = False ) -> Dict [str , str ]:
222+ def _get_staking_contract_metadata (
223+ program_id : str , use_blockscout : bool = False
224+ ) -> Dict [str , str ]:
189225 try :
190226 if program_id == NO_STAKING_PROGRAM_ID :
191227 return NO_STAKING_PROGRAM_METADATA
192228
193- staking_token_contract = _get_staking_token_contract (program_id = program_id , use_blockscout = use_blockscout )
229+ staking_token_contract = _get_staking_token_contract (
230+ program_id = program_id , use_blockscout = use_blockscout
231+ )
194232 metadata_hash = staking_token_contract .functions .metadataHash ().call ()
195233 ipfs_address = IPFS_ADDRESS .format (hash = metadata_hash .hex ())
196234 response = requests .get (ipfs_address )
197235
198236 if response .status_code == 200 :
199237 return response .json ()
200238
201- raise Exception (f"Failed to fetch data from { ipfs_address } : { response .status_code } " )
202- except Exception :
239+ raise Exception ( # pylint: disable=broad-except
240+ f"Failed to fetch data from { ipfs_address } : { response .status_code } "
241+ )
242+ except Exception : # pylint: disable=broad-except
203243 return {
204244 "name" : program_id ,
205245 "description" : program_id ,
206246 }
207247
208248
209- def _get_staking_env_variables (program_id : str , use_blockscout : bool = False ) -> Dict [str , str ]:
249+ def _get_staking_env_variables ( # pylint: disable=too-many-locals
250+ program_id : str , use_blockscout : bool = False
251+ ) -> Dict [str , str ]:
210252 if program_id == NO_STAKING_PROGRAM_ID :
211253 return NO_STAKING_PROGRAM_ENV_VARIABLES
212254
213255 staking_token_instance_address = STAKING_PROGRAMS .get (program_id )
214- staking_token_contract = _get_staking_token_contract (program_id = program_id , use_blockscout = use_blockscout )
256+ staking_token_contract = _get_staking_token_contract (
257+ program_id = program_id , use_blockscout = use_blockscout
258+ )
215259 agent_id = staking_token_contract .functions .agentIds (0 ).call ()
216260 service_registry = staking_token_contract .functions .serviceRegistry ().call ()
217261 staking_token = staking_token_contract .functions .stakingToken ().call ()
218- service_registry_token_utility = staking_token_contract .functions .serviceRegistryTokenUtility ().call ()
262+ service_registry_token_utility = (
263+ staking_token_contract .functions .serviceRegistryTokenUtility ().call ()
264+ )
219265 min_staking_deposit = staking_token_contract .functions .minStakingDeposit ().call ()
220266 min_staking_bond = min_staking_deposit
221267
222- if 'activityChecker' in [func .fn_name for func in staking_token_contract .all_functions ()]:
268+ if "activityChecker" in [
269+ func .fn_name for func in staking_token_contract .all_functions ()
270+ ]:
223271 activity_checker = staking_token_contract .functions .activityChecker ().call ()
224272
225273 if use_blockscout :
226274 abi = _get_abi (activity_checker )
227275 else :
228276 abi = _load_abi_from_file (ACTIVITY_CHECKER_ABI_PATH )
229277
230- with open (RPC_PATH , 'r' , encoding = "utf-8" ) as file :
278+ with open (RPC_PATH , "r" , encoding = "utf-8" ) as file :
231279 rpc = file .read ().strip ()
232280
233281 w3 = Web3 (Web3 .HTTPProvider (rpc ))
@@ -255,7 +303,12 @@ def _get_staking_env_variables(program_id: str, use_blockscout: bool = False) ->
255303def _set_dotenv_file_variables (env_vars : Dict [str , str ]) -> None :
256304 for key , value in env_vars .items ():
257305 if value :
258- set_key (dotenv_path = DOTENV_PATH , key_to_set = key , value_to_set = value , quote_mode = "never" )
306+ set_key (
307+ dotenv_path = DOTENV_PATH ,
308+ key_to_set = key ,
309+ value_to_set = value ,
310+ quote_mode = "never" ,
311+ )
259312 else :
260313 unset_key (dotenv_path = DOTENV_PATH , key_to_unset = key )
261314
@@ -264,32 +317,50 @@ def _get_nevermined_env_variables() -> Dict[str, str]:
264317 env_file_vars = dotenv_values (DOTENV_PATH )
265318 use_nevermined = False
266319
267- if 'USE_NEVERMINED' not in env_file_vars :
268- set_key (dotenv_path = DOTENV_PATH , key_to_set = "USE_NEVERMINED" , value_to_set = "false" , quote_mode = "never" )
269- elif env_file_vars .get ('USE_NEVERMINED' ).strip () not in ("True" , "true" ):
270- set_key (dotenv_path = DOTENV_PATH , key_to_set = "USE_NEVERMINED" , value_to_set = "false" , quote_mode = "never" )
320+ if "USE_NEVERMINED" not in env_file_vars :
321+ set_key (
322+ dotenv_path = DOTENV_PATH ,
323+ key_to_set = "USE_NEVERMINED" ,
324+ value_to_set = "false" ,
325+ quote_mode = "never" ,
326+ )
327+ elif env_file_vars .get ("USE_NEVERMINED" ).strip () not in ("True" , "true" ):
328+ set_key (
329+ dotenv_path = DOTENV_PATH ,
330+ key_to_set = "USE_NEVERMINED" ,
331+ value_to_set = "false" ,
332+ quote_mode = "never" ,
333+ )
271334 else :
272335 use_nevermined = True
273336
274337 if use_nevermined :
275- print (" - A Nevermined subscription will be used to pay for the mech requests." )
338+ print (
339+ " - A Nevermined subscription will be used to pay for the mech requests."
340+ )
276341 return {
277342 "MECH_CONTRACT_ADDRESS" : NEVERMINED_MECH_CONTRACT_ADDRESS ,
278343 "AGENT_REGISTRY_ADDRESS" : NEVERMINED_AGENT_REGISTRY_ADDRESS ,
279- "MECH_REQUEST_PRICE" : NEVERMINED_MECH_REQUEST_PRICE
344+ "MECH_REQUEST_PRICE" : NEVERMINED_MECH_REQUEST_PRICE ,
280345 }
281346 else :
282347 print (" - No Nevermined subscription set." )
283- return {
284- "AGENT_REGISTRY_ADDRESS" : "" ,
285- "MECH_REQUEST_PRICE" : ""
286- }
348+ return {"AGENT_REGISTRY_ADDRESS" : "" , "MECH_REQUEST_PRICE" : "" }
287349
288350
289351def main () -> None :
352+ """Main method"""
290353 parser = argparse .ArgumentParser (description = "Set up staking configuration." )
291- parser .add_argument ("--reset" , action = "store_true" , help = "Reset USE_STAKING and STAKING_PROGRAM in .env file" )
292- parser .add_argument ("--use_blockscout" , action = "store_true" , help = "Use Blockscout to retrieve contract data." )
354+ parser .add_argument (
355+ "--reset" ,
356+ action = "store_true" ,
357+ help = "Reset USE_STAKING and STAKING_PROGRAM in .env file" ,
358+ )
359+ parser .add_argument (
360+ "--use_blockscout" ,
361+ action = "store_true" ,
362+ help = "Use Blockscout to retrieve contract data." ,
363+ )
293364 args = parser .parse_args ()
294365
295366 if args .reset :
@@ -300,23 +371,35 @@ def main() -> None:
300371 print ("=====================================" )
301372 print ("" )
302373 print (f"Your current staking program preference is set to '{ staking_program } '." )
303- print ("You can reset your preference. However, your trader might not be able to switch between staking contracts until it has been staked for a minimum staking period in the current program." )
374+ print (
375+ "You can reset your preference. However, your trader might not be able to switch between staking contracts until it has been staked for a minimum staking period in the current program."
376+ )
304377 print ("" )
305378 if os .environ .get ("ATTENDED" ) == "true" :
306- response = input ("Do you want to reset your staking program preference? (yes/no): " ).strip ().lower ()
307- if response not in ['yes' , 'y' ]:
379+ response = (
380+ input (
381+ "Do you want to reset your staking program preference? (yes/no): "
382+ )
383+ .strip ()
384+ .lower ()
385+ )
386+ if response not in ["yes" , "y" ]:
308387 return
309388
310389 print ("" )
311390 unset_key (dotenv_path = DOTENV_PATH , key_to_unset = "USE_STAKING" )
312391 unset_key (dotenv_path = DOTENV_PATH , key_to_unset = "STAKING_PROGRAM" )
313- print (f"Environment variables USE_STAKING and STAKING_PROGRAM have been reset in '{ DOTENV_PATH } '." )
392+ print (
393+ f"Environment variables USE_STAKING and STAKING_PROGRAM have been reset in '{ DOTENV_PATH } '."
394+ )
314395 print ("" )
315396
316397 program_id = _prompt_select_staking_program ()
317398
318399 print (" - Populating staking program variables in the .env file" )
319- staking_env_variables = _get_staking_env_variables (program_id , use_blockscout = args .use_blockscout )
400+ staking_env_variables = _get_staking_env_variables (
401+ program_id , use_blockscout = args .use_blockscout
402+ )
320403 _set_dotenv_file_variables (staking_env_variables )
321404
322405 print (" - Populating Nevermined variables in the .env file" )
@@ -326,5 +409,6 @@ def main() -> None:
326409 print ("" )
327410 print ("Finished populating the .env file." )
328411
412+
329413if __name__ == "__main__" :
330414 main ()
0 commit comments