This commit is contained in:
Dobromir Popov 2024-10-12 19:38:02 +03:00
commit a2add44772

View File

@ -43,8 +43,17 @@ import random
app = Flask(__name__)
# config = load_config()
load_dotenv()
load_dotenv('.env.secret') # ToDo - make it work
load_dotenv('.env.secret')
# Configuration
DEVELOPER_CHAT_ID = os.getenv("DEVELOPER_CHAT_ID")
FOLLOWED_WALLET = os.getenv("FOLLOWED_WALLET")
YOUR_WALLET = os.getenv("YOUR_WALLET")
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')
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
@ -102,30 +111,8 @@ async def retry_last_log():
# Configuration
DEVELOPER_CHAT_ID = os.getenv("DEVELOPER_CHAT_ID")
FOLLOWED_WALLET = os.getenv("FOLLOWED_WALLET")
YOUR_WALLET = os.getenv("YOUR_WALLET")
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')
# Use the production Solana RPC endpoint
solana_client = AsyncClient(SOLANA_HTTP_URL)
dexscreener_client = DexscreenerClient()
# Initialize Telegram Bot
# Create a custom connection pool
conn_pool = aiohttp.TCPConnector(limit=100) # Increase the connection limit
timeout = aiohttp.ClientTimeout(total=30) # Set a longer timeout
# Create the bot with the custom connection pool
bot = Bot(TELEGRAM_BOT_TOKEN, request=aiohttp.ClientSession(connector=conn_pool, timeout=timeout).request)
bot = None
# Token addresses (initialize with some known tokens)
TOKEN_ADDRESSES = {
"SOL": "So11111111111111111111111111111111111111112",
@ -346,6 +333,8 @@ async def get_sol_price_from_dexscreener() -> float:
# # # # # # # # # # SOLANA BLOCKCHAIN # # # # # # # # # #
solana_client = AsyncClient(SOLANA_HTTP_URL)
async def get_token_balance_rpc(wallet_address, token_address):
url = SOLANA_HTTP_URL
headers = {"Content-Type": "application/json"}
@ -1155,12 +1144,12 @@ async def follow_move(move):
try:
notification = (
f"<b>Initiating move:</b>\n (decimals: {token_info.get('decimals')})\n"
f"<b>Initiating move:</b>\n"
f"Swapping {move['percentage_swapped']:.2f}% ({amount_to_swap:.2f}) {token_name_in} for {token_name_out}"
)
logging.info(notification)
error_logger.info(notification)
await send_telegram_message(notification)
# logging.info(notification)
# error_logger.info(notification)
# await send_telegram_message(notification)
except Exception as e:
logging.error(f"Error sending notification: {e}")
@ -1187,6 +1176,9 @@ async def follow_move(move):
transaction_id = json.loads(result.to_json())['result']
print(f"Follow Transaction Sent: https://solscan.io/tx/{transaction_id}")
# append to notification
notification += f"\n\n<b>Transaction:</b> <a href='https://solscan.io/tx/{transaction_id}'>{transaction_id}</a>"
await send_telegram_message(f"Follow Transaction Sent: {transaction_id}")
tx_details = await get_transaction_details_with_retry(transaction_id)
@ -1265,7 +1257,7 @@ SUBSCRIBE_INTERVAL = 1*60 # Resubscribe every 10 minutes
_first_subscription = True
_process_task = None
async def wallet_watch_loop():
global first_subscription, process_task
global _first_subscription, _process_task
reconnect_delay = 5
max_reconnect_delay = 60
@ -1431,9 +1423,40 @@ async def check_PK():
async def main():
global bot, PROCESSING_LOG
# Initialize Telegram Bot
# Create a custom connection pool
conn_pool = aiohttp.TCPConnector(limit=100) # Increase the connection limit
timeout = aiohttp.ClientTimeout(total=30) # Set a longer timeout
bot = Bot(TELEGRAM_BOT_TOKEN) # , request=aiohttp.ClientSession(connector=conn_pool, timeout=timeout).request)
await send_telegram_message("Solana Agent Started. Connecting to mainnet...")
await check_PK()
await wallet_watch_loop()
# new: restart wallet_watch_loop every hour
while True:
wallet_watch_task = asyncio.create_task(wallet_watch_loop())
try:
# Wait for an hour or until the task completes, whichever comes first
await asyncio.wait_for(wallet_watch_task, timeout=3600)
except asyncio.TimeoutError:
# If an hour has passed, cancel the task if not PROCESSING
if PROCESSING_LOG:
logging.info("wallet_watch_loop is processing logs. Will not restart.")
await send_telegram_message("wallet_watch_loop is processing logs. Will not restart.")
else:
wallet_watch_task.cancel()
try:
await wallet_watch_task
except asyncio.CancelledError:
logging.info("wallet_watch_loop was cancelled after running for an hour")
except Exception as e:
logging.error(f"Error in wallet_watch_loop: {str(e)}")
await send_telegram_message(f"Error in wallet_watch_loop: {str(e)}")
logging.info("Restarting wallet_watch_loop")
await send_telegram_message("Restarting wallet_watch_loop")
async def run_flask():
loop = asyncio.get_running_loop()