quickfix decimals issue (todo fix properly)

This commit is contained in:
Dobromir Popov 2024-10-07 17:27:56 +03:00
parent b7974fbc93
commit e2b67c88a8
2 changed files with 35 additions and 13 deletions

1
.gitignore vendored
View File

@ -18,3 +18,4 @@ agent-mAId/dist/main.exe
agent-mAId/output.wav
.node-persist/storage/*
logs/*
crypto/sol/.env

View File

@ -289,12 +289,14 @@ async def get_wallet_balances(wallet_address):
mint = info['mint']
#amount = float(info['tokenAmount']['amount']) / (10 ** info['tokenAmount']['decimals'])
amount = float(info['tokenAmount']['amount'])/10**info['tokenAmount']['decimals']
decimals = info['tokenAmount']['decimals']
if amount > 0:
token_name = await get_token_name(mint) or 'Unknown'
balances[mint] = {
'name': token_name,
'address': mint,
'amount': amount
'amount': amount,
'decimals': decimals
}
logging.debug(f"Balance for {token_name} ({mint}): {amount}")
else:
@ -430,14 +432,17 @@ async def get_swap_transaction_details(tx_signature_str):
return None
async def get_transaction_details_with_retry(transaction_id, retry_delay = 9, max_retries = 7):
async def get_transaction_details_with_retry(transaction_id, retry_delay = 11, max_retries = 11):
# wait for the transaction to be confirmed
# await async_client.wait_for_confirmation(Signature.from_string(transaction_id))
# qwery every 5 seconds for the transaction details untill not None or 30 seconds
for _ in range(max_retries):
try:
tx_details = await get_transaction_details_rpc(transaction_id)
if tx_details is not None:
break
except Exception as e:
logging.error(f"Error fetching transaction details: {e}")
logging.info(f"({_} of {max_retries}) Waiting for transaction details for {transaction_id}")
await asyncio.sleep(retry_delay)
return tx_details
@ -505,6 +510,7 @@ async def get_transaction_details_rpc(tx_signature, readfromDump=False):
amount = float(info['amount']) if 'amount' in info else float(info['tokenAmount']['amount'])
decimals = info['tokenAmount']['decimals'] if 'tokenAmount' in info else 0
adjusted_amount = amount / (10 ** decimals)
# adjusted_amount = float(info["amount"]) / (10 ** (info["tokenAmount"]["decimals"] if 'tokenAmount' in info else 0))
transfers.append({
'mint': info.get('mint'),
'amount': adjusted_amount,
@ -622,7 +628,7 @@ async def process_log(log_result):
logs = log_result['value']['logs']
try:
# Detect swap operations in logs
swap_operations = ['Program log: Instruction: Swap', 'Program log: Instruction: Swap2']
swap_operations = ['Program log: Instruction: Swap', 'Program log: Instruction: Swap2', 'Program log: Instruction: SwapExactAmountIn']
if any(op in logs for op in swap_operations):
# Save the log to a file
@ -688,6 +694,9 @@ async def process_log(log_result):
# onlt needed if no details got
if before_source_balance > 0 and source_token_change > 0:
tr_details["percentage_swapped"] = (source_token_change / before_source_balance) * 100
#dirty fix for percentage > 100 (decimals 9 but expecting 6)
if tr_details["percentage_swapped"] > 100:
tr_details["percentage_swapped"] = tr_details["percentage_swapped"] / 1000
message_text = (
@ -730,7 +739,7 @@ async def get_transaction_details_info(tx_signature_str: str, logs: List[str]) -
tr_info['amount_in_usd'] = tr_info['amount_in'] * token_prices.get(tr_info['token_in'], 0)
tr_info['amount_out_usd'] = tr_info['amount_out'] * token_prices.get(tr_info['token_out'], 0)
# Calculate the percentage of the source balance that was swapped
# Calculate the percentage of the source balance that was swapped; ToDo: fix decimals for percentage
tr_info['percentage_swapped'] = (tr_info['amount_in'] / tr_info['before_source_balance']) * 100 if tr_info['before_source_balance'] > 0 else 50
return tr_info
@ -759,20 +768,24 @@ async def follow_move(move):
# Calculate the amount to swap based on the same percentage as the followed move
amount_to_swap = your_balance * (move['percentage_swapped'] / 100)
# # always get 99% of the amount to swap
# amount_to_swap = amount_to_swap * 0.99
if your_balance >= amount_to_swap:
try:
private_key = Keypair.from_bytes(base58.b58decode(os.getenv("PK")))
async_client = AsyncClient(SOLANA_WS_URL)
jupiter = Jupiter(async_client, private_key)
# Convert to lamports
# if decimals is 6, then amount = amount * 1e6; if 9, then amount = amount * 1e9
amount = int(amount_to_swap * 10**your_balance_info['decimals'])
transaction_data = await jupiter.swap(
input_mint=move['token_in'],
output_mint=move['token_out'],
amount=int(amount_to_swap * 1e6), # Convert to lamports
slippage_bps=50, # Increased to 0.5%
amount=amount,
slippage_bps=100, # Increased to 1%
)
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])
@ -782,6 +795,14 @@ async def follow_move(move):
transaction_id = json.loads(result.to_json())['result']
print(f"Follow Transaction Sent: https://solscan.io/tx/{transaction_id}")
notification = (
f"<b>Move Initiated:</b>\n (decimals: {your_balance_info['decimals']})\n"
f"Swapping {move['percentage_swapped']:.2f}% ({amount_to_swap}) {token_name} ({move['token_in']}) "
f"for {move['token_out']}"
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)
tx_details = await get_transaction_details_with_retry(transaction_id)