gauravlochab commited on
Commit
15f0ff4
·
1 Parent(s): b287ed8

refactor: Improve error handling and retries for token price API request

Browse files
Files changed (1) hide show
  1. app_value_locked.py +30 -16
app_value_locked.py CHANGED
@@ -238,23 +238,37 @@ def get_token_decimals(web3, token_address):
238
  ])
239
  return token_contract.functions.decimals().call()
240
 
241
- def get_token_price_usd(chain, token_address):
 
242
  chain_dict = {"optimism": "optimistic-ethereum", "base": "base", "ethereum": "ethereum"}
243
- chain_name = chain_dict.get(chain, chain)
244
- time.sleep(4)
245
- url = f"https://api.coingecko.com/api/v3/simple/token_price/{chain_name}?contract_addresses={token_address}&vs_currencies=usd"
246
-
247
- headers = {
248
- "accept": "application/json",
249
- "x-cg-api-key": "CG-mf5xZnGELpSXeSqmHDLY2nNU"
250
- }
251
-
252
- response = requests.get(url, headers=headers)
253
- data = response.json()
254
-
255
- # Extract USD price
256
- key = token_address.lower()
257
- return data.get(key, {}).get('usd', None)
 
 
 
 
 
 
 
 
 
 
 
 
 
258
 
259
  def load_existing_transactions(file_path):
260
  """Load existing transactions from a CSV file."""
 
238
  ])
239
  return token_contract.functions.decimals().call()
240
 
241
+ def get_token_price_usd(chain, token_address, retries=3, delay=5):
242
+ """Fetch the USD price for a given ERC-20 token using CoinGecko API with retries and error handling."""
243
  chain_dict = {"optimism": "optimistic-ethereum", "base": "base", "ethereum": "ethereum"}
244
+ chain_name = chain_dict.get(chain, chain)
245
+
246
+ for attempt in range(retries):
247
+ try:
248
+ time.sleep(4) # Initial delay to avoid hitting rate limits
249
+ url = f"https://api.coingecko.com/api/v3/simple/token_price/{chain_name}?contract_addresses={token_address}&vs_currencies=usd"
250
+
251
+ headers = {
252
+ "accept": "application/json",
253
+ "x-cg-api-key": "CG-mf5xZnGELpSXeSqmHDLY2nNU"
254
+ }
255
+
256
+ response = requests.get(url, headers=headers)
257
+ response.raise_for_status() # Raise an HTTPError for bad responses
258
+
259
+ data = response.json()
260
+
261
+ # Extract USD price
262
+ key = token_address.lower()
263
+ return data.get(key, {}).get('usd', None)
264
+
265
+ except requests.exceptions.RequestException as e:
266
+ logging.error(f"Error fetching token price for {token_address} on attempt {attempt + 1}/{retries}: {e}")
267
+ if attempt < retries - 1:
268
+ time.sleep(delay) # Wait before retry
269
+ else:
270
+ logging.error(f"Failed to fetch token price after {retries} attempts")
271
+ return None # Return None if all retry attempts fail
272
 
273
  def load_existing_transactions(file_path):
274
  """Load existing transactions from a CSV file."""