This commit is contained in:
Dobromir Popov
2024-10-24 14:06:07 +03:00
parent 1a31455d98
commit 25384ec5a8
3 changed files with 58 additions and 41 deletions

View File

@ -35,6 +35,7 @@ from typing import Dict, List, Optional
import requests
from datetime import datetime
from solana.rpc.types import TokenAccountOpts, TxOpts
from typing import List, Dict, Any, Tuple
# # # solders/solana libs (solana_client) # # #
@ -166,8 +167,11 @@ class SolanaWS:
async def process_messages(self, one = False):
while True:
message = await self.message_queue.get()
message = json.loads(message)
if type(message) == int:
subscription_id = message
logger.info(f"Subscription id: {subscription_id}")
if self.on_message:
#message = json.loads(message)
await self.on_message(message)
logger.info(f"Received message: {message}")
if one:
@ -257,10 +261,15 @@ class SolanaAPI:
except Exception as e:
logger.error(f"An unexpected error occurred: {e}")
finally:
await solana_ws.unsubscribe()
if solana_ws.websocket:
await solana_ws.close()
await async_safe_call(self.on_bot_message,"Reconnecting...")
try:
await solana_ws.unsubscribe()
if solana_ws.websocket:
await solana_ws.close()
await async_safe_call(self.on_bot_message,"Reconnecting...")
receive_task.cancel()
process_task.cancel()
except Exception as e:
logger.error(f"An error occurred while unsubscribing: {e}")
await asyncio.sleep(5)
async def get_last_transactions(self, account_address, check_interval=300, limit=1000):
@ -464,8 +473,35 @@ class SolanaAPI:
except requests.exceptions.RequestException as e:
print("Error fetching transaction details:", e)
# "Program log: Instruction: Swap2",
# "Program log: order_id: 13985890735038016",
# "Program log: AbrMJWfDVRZ2EWCQ1xSCpoVeVgZNpq1U2AoYG98oRXfn", source
# "Program log: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", target
# "Program log: before_source_balance: 58730110139, before_destination_balance: 202377778, amount_in: 58730110139, expect_amount_out: 270109505, min_return: 267408410",
# "Program log: after_source_balance: 0, after_destination_balance: 472509072",
# "Program log: source_token_change: 58730110139, destination_token_change: 270131294",
async def get_transaction_details_info(tx_signature_str: str, logs: List[str]) -> Dict[str, Any]:
global TOKENS_INFO
tr_info = await self.get_transaction_details_with_retry(tx_signature_str)
try:
tr_info['percentage_swapped'] = (tr_info['amount_in'] / tr_info['before_source_balance']) * 100 if tr_info['before_source_balance'] > 0 else 50
except Exception as e:
logging.error(f"Error calculating percentage swapped: {e}")
return tr_info
# def _get_pre_balance(transaction_details: Dict[str, Any], token: str) -> float:
# pre_balances = transaction_details.get('meta', {}).get('preTokenBalances', [])
# for balance in pre_balances:
# if balance['mint'] == token:
# return float(balance['uiTokenAmount']['amount'])
# return 0.0
async def get_transaction_details_with_retry(transaction_id, retry_delay = 5, max_retries = 16):
# wait for the transaction to be confirmed
# await async_client.wait_for_confirmation(Signature.from_string(transaction_id))
@ -763,9 +799,16 @@ class SolanaDEX:
info = parsed_data['info']
if isinstance(info, dict) and 'mint' in info and 'tokenAmount' in info:
mint = info['mint']
decimals = info['tokenAmount']['decimals']
amount = float(info['tokenAmount']['amount'])/10**decimals
if amount > 0:
decimals = int(info['tokenAmount']['decimals'])
amount = info['tokenAmount']['amount']
try:
amount = float(amount)
except ValueError:
print(f"Error: amount '{amount}' cannot be converted to a float")
# You might want to add some error handling here
if amount > 0.0:
amount = amount /10**decimals
if mint in self.TOKENS_INFO:
token_name = self.TOKENS_INFO[mint].get('symbol')
elif doGetTokenName: