try even if we report no ballance

This commit is contained in:
Dobromir Popov 2024-10-09 14:11:47 +03:00
parent 3471f6aa6d
commit 12769cd3cc

View File

@ -58,8 +58,6 @@ error_logger.setLevel(logging.ERROR)
error_logger.addHandler(error_file_handler)
app = Flask(__name__)
ENV_FILE = '.env'
@ -911,7 +909,7 @@ async def process_log(log_result):
logging.error(f"Error fetching token prices: {e}")
message_text = (
f"<b>Swap detected:</b>\n"
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"
@ -990,91 +988,97 @@ async def follow_move(move):
# amount_to_swap = amount_to_swap * 0.99
if your_balance >= amount_to_swap:
try:
# Convert to lamports
# if decimals is 6, then amount = amount * 1e6; if 9, then amount = amount * 1e9
amount = int(amount_to_swap * 10**token_info.get('decimals') )
try:
notification = (
f"<b>Initiating move:</b>\n (decimals: {token_info.get('decimals')})\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)
except Exception as e:
logging.error(f"Error sending notification: {e}")
for retry in range(2):
private_key = Keypair.from_bytes(base58.b58decode(pk))
async_client = AsyncClient(SOLANA_WS_URL)
jupiter = Jupiter(async_client, private_key)
transaction_data = await jupiter.swap(
input_mint=move['token_in'],
output_mint=move['token_out'],
amount=amount,
slippage_bps=100, # Increased to 1%
)
error_logger.info(f"Initiating move. Transaction data:\n {transaction_data}")
raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))
signature = private_key.sign_message(message.to_bytes_versioned(raw_transaction.message))
signed_txn = VersionedTransaction.populate(raw_transaction.message, [signature])
opts = TxOpts(skip_preflight=False, preflight_commitment=Processed)
# send the transaction
result = await async_client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)
transaction_id = json.loads(result.to_json())['result']
print(f"Follow Transaction Sent: https://solscan.io/tx/{transaction_id}")
send_telegram_message(f"Follow Transaction Sent: {transaction_id}")
tx_details = await get_transaction_details_with_retry(transaction_id)
if tx_details is not None:
break
else:
logging.warning(f"Failed to get transaction details for {transaction_id}. Probably transaction failed. Retrying again...")
await asyncio.sleep(5)
await get_wallet_balances(YOUR_WALLET, doGetTokenName=False)
try:
if tx_details is None:
logging.info(f"Failed to get transaction details for {transaction_id}")
notification = (
f"<b>Move Followed:</b>\n"
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>"
)
else:
notification = (
f"<b>Move Followed:</b>\n"
f"Swapped {amount_to_swap:.6f} {token_name_in} ({move['symbol_in']}) "
f"(same {move['percentage_swapped']:.2f}% as followed wallet)\n"
f"for {tx_details['amount_out']:.2f} {token_name_out}"
# f"Amount In USD: {tr_details['amount_in_USD']}\n"
f"\n\n<b>Transaction:</b> <a href='https://solscan.io/tx/{transaction_id}'>{transaction_id}</a>"
)
logging.info(notification)
await send_telegram_message(notification)
except Exception as e:
logging.error(f"Error sending notification: {e}")
except Exception as e:
error_message = f"<b>Swap Follow Error:</b>\n{str(e)}"
logging.error(error_message)
# log the errors to /logs/errors.log
error_logger.error(error_message)
error_logger.exception(e)
# await send_telegram_message(error_message)
else:
msg = (
f"<b>Move Not Followed:</b>\n"
f"Insufficient balance to swap {amount_to_swap:.6f} {token_name_in} ({move['token_in']})"
f"<b>Warning:</b>\n"
f"We have {your_balance:.6f} {token_name_in}. Insufficient balance to swap {amount_to_swap:.6f} ({move['token_in']}). This will probably fail. But we will try anyway."
)
logging.warning(msg)
await send_telegram_message(msg)
try:
# Convert to lamports
# if decimals is 6, then amount = amount * 1e6; if 9, then amount = amount * 1e9
amount = int(amount_to_swap * 10**token_info.get('decimals') )
try:
notification = (
f"<b>Initiating move:</b>\n (decimals: {token_info.get('decimals')})\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)
except Exception as e:
logging.error(f"Error sending notification: {e}")
for retry in range(2):
private_key = Keypair.from_bytes(base58.b58decode(pk))
async_client = AsyncClient(SOLANA_WS_URL)
jupiter = Jupiter(async_client, private_key)
transaction_data = await jupiter.swap(
input_mint=move['token_in'],
output_mint=move['token_out'],
amount=amount,
slippage_bps=100, # Increased to 1%
)
error_logger.info(f"Initiating move. Transaction data:\n {transaction_data}")
raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))
signature = private_key.sign_message(message.to_bytes_versioned(raw_transaction.message))
signed_txn = VersionedTransaction.populate(raw_transaction.message, [signature])
opts = TxOpts(skip_preflight=False, preflight_commitment=Processed)
# send the transaction
result = await async_client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)
transaction_id = json.loads(result.to_json())['result']
print(f"Follow Transaction Sent: https://solscan.io/tx/{transaction_id}")
send_telegram_message(f"Follow Transaction Sent: {transaction_id}")
tx_details = await get_transaction_details_with_retry(transaction_id)
if tx_details is not None:
break
else:
logging.warning(f"Failed to get transaction details for {transaction_id}. Probably transaction failed. Retrying again...")
await asyncio.sleep(5)
await get_wallet_balances(YOUR_WALLET, doGetTokenName=False)
try:
if tx_details is None:
logging.info(f"Failed to get transaction details for {transaction_id}")
notification = (
f"<b>Move Followed:</b>\n"
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>"
)
else:
notification = (
f"<b>Move Followed:</b>\n"
f"Swapped {amount_to_swap:.6f} {token_name_in} ({move['symbol_in']}) "
f"(same {move['percentage_swapped']:.2f}% as followed wallet)\n"
f"for {tx_details['amount_out']:.2f} {token_name_out}"
# f"Amount In USD: {tr_details['amount_in_USD']}\n"
f"\n\n<b>Transaction:</b> <a href='https://solscan.io/tx/{transaction_id}'>{transaction_id}</a>"
)
logging.info(notification)
await send_telegram_message(notification)
except Exception as e:
logging.error(f"Error sending notification: {e}")
except Exception as e:
error_message = f"<b>Swap Follow Error:</b>\n{str(e)}"
logging.error(error_message)
# log the errors to /logs/errors.log
error_logger.error(error_message)
error_logger.exception(e)
# await send_telegram_message(error_message)
# else:
# msg = (
# f"<b>Move Not Followed:</b>\n"
# f"Insufficient balance to swap {amount_to_swap:.6f} {token_name_in} ({move['token_in']})"
# )
# logging.warning(msg)
# await send_telegram_message(msg)
# Helper functions (implement these according to your needs)
@ -1181,7 +1185,6 @@ if not pk:
async def main():
# Initialize logging
await send_telegram_message("Solana Agent Started. Connecting to mainnet...")
asyncio.create_task( list_initial_wallet_states())
await subscribe_to_wallet()