async function handleTransaction(transaction) {
  if (!transaction || !transaction.meta || !transaction.meta.logMessages) {
    return;
  }
  
  const currentTimestamp = Date.now();
  const transactionTimestamp = transaction.blockTime ? transaction.blockTime * 1000 : currentTimestamp;
  const transactionAge = currentTimestamp - transactionTimestamp;
  
  // Ignore transactions older than 5 minutes
  if (transactionAge > 2 * 1000) {
    return;
  }
  
  const instructions = transaction.transaction.message.instructions;
  let tokenMint, userWallet, purchaseAmount;

  const isBuyTransaction = (logMessages) => {
    return logMessages.some(log => log.toLowerCase().includes('instruction: buy'));
  };

  if (!isBuyTransaction(transaction.meta.logMessages)) {
    return;
  }

  // Calculate the purchase amount in SOL
  const preBalances = transaction.meta.preBalances;
  const postBalances = transaction.meta.postBalances;
  if (preBalances && postBalances && preBalances.length > 0 && postBalances.length > 0) {
    purchaseAmount = (preBalances[0] - postBalances[0]) / 1e9; // Convert lamports to SOL
  } else {
    return;
  }

  // Check if the purchase amount is between 0.9 and 1.05 SOL
  if (purchaseAmount < 0.9 || purchaseAmount > 1.05) {
    return;
  }

  try {
    if (transaction.transaction && transaction.transaction.message) {
      const accountKeys = transaction.transaction.message.accountKeys;
      if (Array.isArray(accountKeys) && accountKeys.length > 0) {
        const firstAccount = accountKeys[0];
        if (typeof firstAccount === 'string') {
          userWallet = firstAccount;
        } else if (firstAccount && typeof firstAccount.toBase58 === 'function') {
          userWallet = firstAccount.toBase58();
        } else if (firstAccount && firstAccount.pubkey && typeof firstAccount.pubkey.toBase58 === 'function') {
          userWallet = firstAccount.pubkey.toBase58();
        } else {
          throw new Error('Unexpected account key format');
        }
        logger.debug(`Extracted user wallet: ${userWallet}`);
      } else {
        throw new Error('No account keys found in transaction');
      }
    } else {
      throw new Error('Invalid transaction structure');
    }
  } catch (error) {
    userWallet = 'Unknown';
  }

  for (const ix of instructions) {
    logger.debug(`Processing instruction: ${JSON.stringify(ix)}`);
    if (ix.programId.toString() === PUMP_PROGRAM_ID.toString()) {
      logger.debug(`Found PUMP program instruction`);

      if (!tokenMint && transaction.meta.preTokenBalances && transaction.meta.preTokenBalances.length > 0) {
        const preTokenBalance = transaction.meta.preTokenBalances.find(balance => balance.mint);
        if (preTokenBalance) {
          tokenMint = preTokenBalance.mint;
        }
      }

      if (tokenMint) {
    const transactionTimestamp = Date.now(); // Mevcut zaman damgası
    const lastTransactionTime = tokenLastTransactionTimes.get(tokenMint) || 0;

    // Hata ayıklama: lastTransactionTime'ın geçerli bir değer olduğunu kontrol et
    if (lastTransactionTime > transactionTimestamp) {
        logger.error(`Hata: ${tokenMint} için kaydedilen son işlem zamanı (${new Date(lastTransactionTime).toISOString()}) şu anki zamandan (${new Date(transactionTimestamp).toISOString()}) daha ileri.`);
        // Hatalı veriyi düzelt, örneğin son 24 saat içinde bir zaman olarak ayarla
        lastTransactionTime = transactionTimestamp - (24 * 60 * 60 * 1000);
    }

    const timeSinceLastTransaction = transactionTimestamp - lastTransactionTime;
    const minutesSinceLastTransaction = timeSinceLastTransaction / (60 * 1000);
    const hoursSinceLastTransaction = minutesSinceLastTransaction / 60;
    const daysSinceLastTransaction = hoursSinceLastTransaction / 24;

    if (lastTransactionTime === 0 || minutesSinceLastTransaction >= 5) {
        logger.info(`${tokenMint} tokeni için işlem işleniyor.`);
        logger.info(`Son işlemden bu yana geçen süre: ${minutesSinceLastTransaction.toFixed(2)} dakika`);
        logger.info(`(${hoursSinceLastTransaction.toFixed(2)} saat veya ${daysSinceLastTransaction.toFixed(2)} gün)`);
        logger.info(`Son işlem zamanı: ${new Date(lastTransactionTime).toISOString()}`);
        logger.info(`Şu anki zaman: ${new Date(transactionTimestamp).toISOString()}`);

        tokenLastTransactionTimes.set(tokenMint, transactionTimestamp);
		
		  
          try {
            const { marketCap, tokenAgeInfo, holderCount } = await getTokenInfo(tokenMint);
            const { formattedAge, ageInMilliseconds } = tokenAgeInfo;
            const ageInMinutes = ageInMilliseconds / (1000 * 60);
            logger.info(`${purchaseAmount} SOL`);

            if (holderCount > 100) {
              logger.info(`Skipping token ${tokenMint} as holder count (${holderCount}) is greater than 100`);
              return;
            }

            // Check for multiple buys in the same second
            const transactionSecond = Math.floor(transactionTimestamp / 1000);
            const tokenKey = `${tokenMint}_${transactionSecond}`;
            const buyCount = buyTransactionsMap.get(tokenKey) || 0;

            if (buyCount >= MAX_BUY_PER_SECOND) {
              logger.info(`Skipping token ${tokenMint} as too many buys (${buyCount}) occurred in the same second.`);
              return;
            }

            // Record this buy
            buyTransactionsMap.set(tokenKey, buyCount + 1);

            if (ageInMinutes > 12 && marketCap > 25 && marketCap < 28) {
              logger.info(`Token holder count ${tokenMint} ${holderCount}`);

              const message = `User executed a BUY on pump.fun \nToken: ${tokenMint}\nMarket Cap: ${marketCap} SOL\nToken Age: ${formattedAge}\nHolder Count: ${holderCount}\nPurchase Amount: ${purchaseAmount.toFixed(2)} SOL\nUser Wallet: ${userWallet}\nTransaction Age: ${(transactionAge / 1000).toFixed(2)} seconds\nTime since last transaction: ${(timeSinceLastTransaction / 1000 / 60).toFixed(2)} minutes\nTransaction: https://photon-sol.tinyastro.io/en/lp/${tokenMint}`;

              const now = Date.now();
              const lastSent = messageTimestamps.get(tokenMint) || 0;
              if (now - lastSent >= MESSAGE_THROTTLE_MS) {
                messageTimestamps.set(tokenMint, now);
                await sendTelegramMessage(message);
                logger.info(`Sent message for token: ${tokenMint}`);
              } else {
                logger.debug(`Message throttled for token: ${tokenMint}`);
              }
            }
          } catch (error) {
            logger.error(`Error processing transaction for token ${tokenMint}: ${error.message}`);
          }
        } else {
          logger.debug(`Skipping transaction for token ${tokenMint}. Time since last transaction: ${timeSinceLastTransaction / 1000 / 60} minutes (less than ${MIN_TIME_DIFFERENCE / 1000 / 60} minutes)`);
        }
      }
    }
  }
  return { tokenMint, userWallet, purchaseAmount };
}  boşlukları  düzelt