This commit is contained in:
Dobromir Popov 2024-10-25 23:43:47 +03:00
parent 25384ec5a8
commit e56f007082
5 changed files with 32 additions and 26 deletions

View File

@ -34,15 +34,10 @@ load_dotenv('.env.secret')
# Configuration # Configuration
from config import (FOLLOWED_WALLET, YOUR_WALLET, SOLANA_WS_URL, SOLANA_HTTP_URL, FOLLOW_AMOUNT, SOLANA_ENDPOINTS, logging, error_logger, logger) from config import (FOLLOWED_WALLET, YOUR_WALLET, SOLANA_WS_URL, SOLANA_HTTP_URL, FOLLOW_AMOUNT, SOLANA_ENDPOINTS, logging, error_logger, logger)
TOKENS_INFO = {}
try:
with open('./logs/token_info.json', 'r') as f:
TOKENS_INFO = json.load(f)
except Exception as e:
logging.error(f"Error loading token info: {str(e)}")
# # # # # # # # # # TELEGRAM # # # # # # # # # # # # # # # # # # # # TELEGRAM # # # # # # # # # #
# if not telegram_utils.bot: # if not telegram_utils.bot:
@ -180,8 +175,8 @@ async def process_log(log_result):
# await get_token_prices(all_token_addresses) # await get_token_prices(all_token_addresses)
try: try:
token_in = TOKENS_INFO[tr_details["token_in"]] token_in = SAPI.dex.TOKENS_INFO[tr_details["token_in"]]
token_out = TOKENS_INFO[tr_details["token_out"]] token_out = SAPI.dex.TOKENS_INFO[tr_details["token_out"]]
tr_details["symbol_in"] = token_in.get('symbol') tr_details["symbol_in"] = token_in.get('symbol')
tr_details["symbol_out"] = token_out.get('symbol') tr_details["symbol_out"] = token_out.get('symbol')
@ -231,9 +226,9 @@ async def follow_move(move):
your_balance = your_balance_info['amount'] your_balance = your_balance_info['amount']
token_info = TOKENS_INFO.get(move['token_in']) token_info = SAPI.dex.TOKENS_INFO.get(move['token_in'])
token_name_in = token_info.get('symbol') or await SAPI.get_token_metadata(move['token_in']) token_name_in = token_info.get('symbol') or await SAPI.get_token_metadata(move['token_in'])
token_name_out = TOKENS_INFO[move['token_out']].get('symbol') or await solanaAPI.get_token_metadata_symbol(move['token_out']) token_name_out = SAPI.dex.TOKENS_INFO[move['token_out']].get('symbol') or await solanaAPI.get_token_metadata_symbol(move['token_out'])
if not your_balance: if not your_balance:
msg = f"<b>Move not followed:</b>\nNo balance found for token {move['symbol_in']}. Cannot follow move." msg = f"<b>Move not followed:</b>\nNo balance found for token {move['symbol_in']}. Cannot follow move."

View File

@ -4,6 +4,8 @@ import os
import logging import logging
from dotenv import load_dotenv from dotenv import load_dotenv
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
import json
# Load environment variables # Load environment variables
load_dotenv() load_dotenv()
@ -33,6 +35,9 @@ TOKEN_ADDRESSES = {
"TARD": "4nfn86ssbv7wiqcsw7bpvn46k24jhe334fudtyxhp1og", "TARD": "4nfn86ssbv7wiqcsw7bpvn46k24jhe334fudtyxhp1og",
} }
# Logging configuration # Logging configuration
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

View File

@ -36,7 +36,7 @@ import requests
from datetime import datetime from datetime import datetime
from solana.rpc.types import TokenAccountOpts, TxOpts from solana.rpc.types import TokenAccountOpts, TxOpts
from typing import List, Dict, Any, Tuple from typing import List, Dict, Any, Tuple
import traceback
# # # solders/solana libs (solana_client) # # # # # # solders/solana libs (solana_client) # # #
from spl.token._layouts import MINT_LAYOUT from spl.token._layouts import MINT_LAYOUT
@ -53,9 +53,7 @@ logger = logging.getLogger(__name__)
PING_INTERVAL = 30 PING_INTERVAL = 30
SUBSCRIBE_INTERVAL = 10*60 # Resubscribe every 1 minute SUBSCRIBE_INTERVAL = 10*60 # Resubscribe every 1 minute
from config import ( from config import ( FOLLOWED_WALLET, SOLANA_HTTP_URL, DISPLAY_CURRENCY, SOLANA_ENDPOINTS, YOUR_WALLET)
FOLLOWED_WALLET, SOLANA_HTTP_URL, DISPLAY_CURRENCY, SOLANA_ENDPOINTS, YOUR_WALLET
)
from modules.utils import telegram_utils, async_safe_call from modules.utils import telegram_utils, async_safe_call
@ -81,7 +79,7 @@ class SolanaWS:
while True: while True:
try: try:
current_url = random.choice(SOLANA_ENDPOINTS) current_url = random.choice(SOLANA_ENDPOINTS)
self.websocket = await websockets.connect(current_url, ping_interval=30, ping_timeout=20) self.websocket = await websockets.connect(current_url, ping_interval=30, ping_timeout=10)
logger.info(f"Connected to Solana websocket: {current_url}") logger.info(f"Connected to Solana websocket: {current_url}")
return return
except Exception as e: except Exception as e:
@ -126,6 +124,7 @@ class SolanaWS:
# define onmessage as inline callback to get subscription_id which waits for last_msg_responded # define onmessage as inline callback to get subscription_id which waits for last_msg_responded
# self.on_message = lambda message: self.subscription_id = message.get('result') # self.on_message = lambda message: self.subscription_id = message.get('result')
await self.ws_jsonrpc("logsSubscribe", params, False) await self.ws_jsonrpc("logsSubscribe", params, False)
await asyncio.sleep(.4)
await self.receive_messages(True) await self.receive_messages(True)
result = await self.process_messages(True) result = await self.process_messages(True)
@ -149,6 +148,7 @@ class SolanaWS:
async def receive_messages(self, one = False): async def receive_messages(self, one = False):
while True: while True:
try: try:
response = await self.websocket.recv() response = await self.websocket.recv()
response_data = json.loads(response) response_data = json.loads(response)
self.last_msg_responded = True self.last_msg_responded = True
@ -260,6 +260,7 @@ class SolanaAPI:
except Exception as e: except Exception as e:
logger.error(f"An unexpected error occurred: {e}") logger.error(f"An unexpected error occurred: {e}")
logger.error("".join(traceback.format_exception(None, e, e.__traceback__)))
finally: finally:
try: try:
await solana_ws.unsubscribe() await solana_ws.unsubscribe()
@ -613,6 +614,11 @@ class SolanaDEX:
self.TOKEN_ADDRESSES = {} self.TOKEN_ADDRESSES = {}
self.FOLLOWED_WALLET_VALUE = 0 self.FOLLOWED_WALLET_VALUE = 0
self.YOUR_WALLET_VALUE = 0 self.YOUR_WALLET_VALUE = 0
try:
with open('../logs/token_info.json', 'r') as f:
self.TOKENS_INFO = json.load(f)
except Exception as e:
logging.error(f"Error loading token info: {str(e)}")
async def get_token_prices(self, token_addresses: List[str]) -> Dict[str, float]: async def get_token_prices(self, token_addresses: List[str]) -> Dict[str, float]:
prices = {addr: 1.0 for addr in token_addresses if addr == "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"} prices = {addr: 1.0 for addr in token_addresses if addr == "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}
@ -800,19 +806,14 @@ class SolanaDEX:
if isinstance(info, dict) and 'mint' in info and 'tokenAmount' in info: if isinstance(info, dict) and 'mint' in info and 'tokenAmount' in info:
mint = info['mint'] mint = info['mint']
decimals = int(info['tokenAmount']['decimals']) decimals = int(info['tokenAmount']['decimals'])
amount = info['tokenAmount']['amount'] amount = int(info['tokenAmount']['amount'])
try: amount = float(amount /10**decimals)
amount = float(amount) if amount > 1:
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: if mint in self.TOKENS_INFO:
token_name = self.TOKENS_INFO[mint].get('symbol') token_name = self.TOKENS_INFO[mint].get('symbol')
elif doGetTokenName: elif doGetTokenName:
token_name = await self.get_token_metadata_symbol(mint) or 'N/A' token_name = await self.get_token_metadata_symbol(mint) or 'N/A'
self.TOKENS_INFO[mint] = {'symbol': token_name}
await asyncio.sleep(2) await asyncio.sleep(2)
self.TOKENS_INFO[mint]['holdedAmount'] = round(amount,decimals) self.TOKENS_INFO[mint]['holdedAmount'] = round(amount,decimals)
@ -823,7 +824,10 @@ class SolanaDEX:
'amount': amount, 'amount': amount,
'decimals': decimals 'decimals': decimals
} }
logging.debug(f"Account balance for {token_name} ({mint}): {amount}") try:
logging.debug(f"Account balance for {token_name} ({mint}): {amount}")
except Exception as e:
logging.error(f"Error logging account balance: {str(e)}")
else: else:
logging.warning(f"Unexpected data format for account: {account}") logging.warning(f"Unexpected data format for account: {account}")
except Exception as e: except Exception as e:

@ -0,0 +1 @@
Subproject commit aed6399bdc7acb8b7d9baabb3f9f2f00bba3ebc2

1
trading Submodule

@ -0,0 +1 @@
Subproject commit 78e4a087f0f71c8b8b1b743fa8bd79ef5d6ae5af