try to fix invalid digit in follow_move();

better logging
This commit is contained in:
Dobromir Popov
2024-10-21 10:35:04 +03:00
parent 37bc6bb086
commit fdd3a66644
5 changed files with 1381 additions and 568 deletions

View File

@ -54,6 +54,7 @@ TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
SOLANA_WS_URL = os.getenv("SOLANA_WS_URL")
SOLANA_HTTP_URL = os.getenv("SOLANA_HTTP_URL")
DISPLAY_CURRENCY = os.getenv('DISPLAY_CURRENCY', 'USD')
FOLLOW_AMOUNT = os.getenv('FOLLOW_AMOUNT', 'percentage')
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
@ -70,9 +71,48 @@ error_logger = logging.getLogger('error_logger')
error_logger.setLevel(logging.ERROR)
error_logger.addHandler(error_file_handler)
# Set up success logger for accounting CSV
class CSVFormatter(logging.Formatter):
def __init__(self):
super().__init__()
self.output = None
def format(self, record):
if self.output is None:
self.output = csv.writer(record.stream)
self.output.writerow(['Timestamp', 'Token In', 'Token Out', 'Amount In', 'Amount Out', 'USD Value In', 'USD Value Out', 'Transaction Hash', 'Wallet Address'])
self.output.writerow([
self.formatTime(record, self.datefmt),
record.token_in,
record.token_out,
record.amount_in,
record.amount_out,
record.usd_value_in,
record.usd_value_out,
record.tx_hash,
record.wallet_address
])
return ''
def log_successful_swap(token_in, token_out, amount_in, amount_out, usd_value_in, usd_value_out, tx_hash, wallet_address):
success_logger_accounting_csv.info('', extra={
'token_in': token_in,
'token_out': token_out,
'amount_in': amount_in,
'amount_out': amount_out,
'usd_value_in': usd_value_in,
'usd_value_out': usd_value_out,
'tx_hash': tx_hash,
'wallet_address': wallet_address
})
success_log_file = os.path.join(log_dir, 'successful_swaps.csv')
success_file_handler = RotatingFileHandler(success_log_file, maxBytes=10*1024*1024, backupCount=5)
success_file_handler.setFormatter(CSVFormatter())
success_logger_accounting_csv = logging.getLogger('success_logger_accounting_csv')
success_logger_accounting_csv.setLevel(logging.INFO)
success_logger_accounting_csv.addHandler(success_file_handler)
# Function to find the latest log file
@ -954,8 +994,9 @@ async def process_log(log_result):
try:
# Detect swap operations in logs
PROCESSING_LOG = True
swap_operations = ['Program log: Instruction: Swap', 'Program log: Instruction: Swap2', 'Program log: Instruction: SwapExactAmountIn']
swap_operations = ['Program log: Instruction: Swap', 'Program log: Instruction: Swap2', 'Program log: Instruction: SwapExactAmountIn', 'Program log: Instruction: SwapV2']
if any(op in logs for op in swap_operations):
# Save the log to a file
await save_log(log_result)
@ -1034,10 +1075,8 @@ async def process_log(log_result):
message_text = (
f"<b>Swap detected: </b>\n"
f"Token In: {tr_details['symbol_in']} ({tr_details['token_in']})\n"
f"Token Out: {tr_details['symbol_out']} ({tr_details['token_out']})\n"
f"Amount In USD: {tr_details['amount_in_USD']:.2f}\n"
f"Percentage Swapped: {tr_details['percentage_swapped']:.2f}%"
f"{tr_details['amount_in_USD']:.2f} worth of {tr_details['symbol_in']} ({tr_details['percentage_swapped']:.2f}% ) swapped for " # ({tr_details['token_in']}) ({tr_details['token_out']})
f"{tr_details['symbol_out']} \n"
)
await send_telegram_message(message_text)
await follow_move(tr_details)
@ -1046,8 +1085,6 @@ async def process_log(log_result):
except Exception as e:
logging.error(f"Error aquiring log details and following: {e}")
await send_telegram_message(f"Not followed! Error following move.")
except Exception as e:
logging.error(f"Error processing log: {e}")
@ -1096,6 +1133,7 @@ def _get_pre_balance(transaction_details: Dict[str, Any], token: str) -> float:
async def follow_move(move):
tx_details = None
your_balances = await get_wallet_balances(YOUR_WALLET, doGetTokenName=False)
your_balance_info = next((balance for balance in your_balances.values() if balance['address'] == move['token_in']), None)
if your_balance_info is not None:
@ -1119,18 +1157,26 @@ async def follow_move(move):
await send_telegram_message(msg)
return
# move["percentage_swapped"] = (move["amount_out"] / move["amount_in"]) * 100
# Calculate the amount to swap based on the same percentage as the followed move
amount_to_swap = your_balance * (move['percentage_swapped'] / 100)
if FOLLOW_AMOUNT == 'percentage':
# Calculate the amount to swap based on the same percentage as the followed move
amount_to_swap = your_balance * (move['percentage_swapped'] / 100)
elif FOLLOW_AMOUNT == 'exact':
amount_to_swap = move['amount_in']
else:
try:
fixed_amount = float(FOLLOW_AMOUNT)
amount_to_swap = min(fixed_amount, your_balance)
except ValueError:
msg = f"<b>Move not followed:</b>\nInvalid FOLLOW_AMOUNT '{FOLLOW_AMOUNT}'. Must be 'percentage' or a number."
logging.warning(msg)
await send_telegram_message(msg)
return
amount_to_swap = min(amount_to_swap, your_balance) # should not happen
amount_to_swap = min(amount_to_swap, your_balance) # Ensure we're not trying to swap more than we have
amount = int(amount)
logging.debug(f"Calculated amount in lamports: {amount}")
if token_name_in == 'USDC': # max 300
amount_to_swap = min(amount_to_swap, 300)
# # always get 99% of the amount to swap
# amount_to_swap = amount_to_swap * 0.95
decimals = token_info.get('decimals')
# Convert to lamports
# if decimals is 6, then amount = amount * 1e6; if 9, then amount = amount * 1e9
@ -1192,7 +1238,7 @@ async def follow_move(move):
logging.warning(f"Failed to get transaction details for {transaction_id}. Probably transaction failed. Retrying again...")
await asyncio.sleep(3)
except Exception as e:
error_message = f"<b>Move Failed:</b>\n{str(e)}"
error_message = f"<b>Move Failed:</b>\n{str(e)}</b>\n{transaction_data}</b>\n{move}"
logging.error(error_message)
# log the errors to /logs/errors.log
error_logger.error(error_message)
@ -1210,6 +1256,7 @@ async def follow_move(move):
f"Swapped {amount_to_swap:.6f} {token_name_in} ({move['token_in']}) "
f"(same {move['percentage_swapped']:.2f}% as followed wallet)\n"
f"\n\n<b>Transaction:</b> <a href='https://solscan.io/tx/{transaction_id}'>{transaction_id}</a>"
# log_successful_swap ()
)
else:
@ -1329,7 +1376,7 @@ async def wallet_watch_loop():
logger.error(f"An unexpected error occurred: {e}")
await unsubscribe(websocket, subscription_id)
await send_telegram_message("reconnecting...")
# await send_telegram_message("reconnecting...")
logger.info(f"Attempting to reconnect in {reconnect_delay} seconds...")
websocket.close()
except Exception as e:
@ -1364,7 +1411,7 @@ async def subscribe(websocket):
return None
except websockets.exceptions.ConnectionClosedError as e:
logger.error(f"Connection closed unexpectedly: {e}")
await send_telegram_message("Connection to Solana network was closed. Not listening for transactions right now. Attempting to reconnect...")
# await send_telegram_message("Connection to Solana network was closed. Not listening for transactions right now. Attempting to reconnect...")
await websocket.close()
return None
except Exception as e: