Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] TypeError: Cannot read properties of undefined (reading 'length') #605

Open
dev4pear opened this issue Dec 13, 2024 · 2 comments
Open
Labels
bug Something isn't working

Comments

@dev4pear
Copy link

🐛 Bug Description

When using aptos.getAccountEventsByCreationNumber, unexpected error occurred.

Error fetching events: TypeError: Cannot read properties of undefined (reading 'length')
    at fc (C:\Users\Russell\Desktop\LiquidSwapBuyBot\node_modules\@aptos-labs\ts-sdk\dist\common\index.js:8:1412)
    at mc (C:\Users\Russell\Desktop\LiquidSwapBuyBot\node_modules\@aptos-labs\ts-sdk\dist\common\index.js:8:1340)
    at new exports.AptosApiError (C:\Users\Russell\Desktop\LiquidSwapBuyBot\node_modules\@aptos-labs\ts-sdk\dist\common\index.js:8:300)
    at Jr (C:\Users\Russell\Desktop\LiquidSwapBuyBot\node_modules\@aptos-labs\ts-sdk\dist\common\index.js:8:2803)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async h (C:\Users\Russell\Desktop\LiquidSwapBuyBot\node_modules\@aptos-labs\ts-sdk\dist\common\index.js:479:383)
    at async xr (C:\Users\Russell\Desktop\LiquidSwapBuyBot\node_modules\@aptos-labs\ts-sdk\dist\common\index.js:481:25050)
    at async Timeout.fetchAndProcessEvents [as _onTimeout] (C:\Users\Russell\Desktop\LiquidSwapBuyBot\index.js:19:20)

How to reproduce

https://github.com/dev4pear/LiquidSwapBuyBot

System information

System details:

  • Typescript SDK Version: @aptos-labs/ts-sdk^1.33.1
  • Platform: Node v18.20.5
@dev4pear dev4pear added the bug Something isn't working label Dec 13, 2024
@gregnazario gregnazario moved this from 🎉 New to 🦆 Todo in Developer Experience Jan 7, 2025
@abhinabphy
Copy link

abhinabphy commented Jan 24, 2025

Actually you are passing wrong inputs ,to filer events and see their creation numbers associated with it try out the below code and then pass a correct creation number

 `
   import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
  const config = new AptosConfig({ network: Network.MAINNET });
  const aptos = new Aptos(config);
 
async function runExample() {
    const whereCondition = {
            account_address: { _eq:"0x61d2c22a6cb7831bee0f48363b0eec92369357aece0d1142062f7d5d85c7bef8" },
            //creation_number: { _eq: "9604" } //IT WILL NOT WORK AS IT THERE IS NO EVENT WITH CREATION NUMBER 9604
         // replace with a real CREATION NUMBER
          };
    const events = await aptos.getEvents({
       options: {where: whereCondition},
    });

    console.log(events);
}
runExample().catch(console.error);

`
pick any one of the creation numbers of the logged events on console after running this code,it wil work !!

@abhinabphy
Copy link

abhinabphy commented Jan 24, 2025

here is the corrected code syntax with some minor corrections ! works fine for fetching events .Don't forget to put target account address and bot token id!

import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
import { Telegraf } from "telegraf";

const bot = new Telegraf("YOUR_TELEGRAM_BOT_TOKEN");
const config = new AptosConfig({ network: Network.MAINNET });
const aptosClient = new Aptos(config);

const accountAddress =
  "Your account address"; // Replace with the account address you want to monitor
const creationNumber = 360;//keep it in integer format

// Keep track of the last processed sequence number
let lastProcessedSequenceNumber = null;
let isFirstRun = true; // Flag to check if this is the first run
let chatId = null; // Store chat ID after /start is received

async function fetchAndProcessEvents() {
  try {
    const events = await aptosClient.getAccountEventsByCreationNumber({
      accountAddress:accountAddress,//pass here by this desired format
      creationNumber: creationNumber,//pass here by this desired format
    });
    console.log(events);

    let hasNewEvents = false;

    // Loop through each event to check if it is new and relevant
    for (const event of events) {
      const isNewEvent =
        lastProcessedSequenceNumber === null ||
        event.sequence_number > lastProcessedSequenceNumber;
      const isRelevantEvent = event.data.y_in !== "0";

      // Process the event only if it is new and meets the criteria
      if (isNewEvent && isRelevantEvent) {
        lastProcessedSequenceNumber = event.sequence_number;
        hasNewEvents = true;

        // Skip displaying events during the first run, just update the sequence number
        if (isFirstRun) {
          continue;
        }

        // Send the new event message if chatId is set
        if (chatId) {
          sendMessages(event, chatId);
        }

        // Display the new event in the console
        console.log("New event:", event);
      }
    }

    // Handle the first run: mark as complete and show initial state
    if (isFirstRun) {
      isFirstRun = false;

      if (hasNewEvents) {
        console.log("Initial setup done. Now waiting for new events...");
        console.log("Last sequence number:", lastProcessedSequenceNumber);
      } else {
        console.log("No events found during the initial setup.");
      }
    } else if (!hasNewEvents) {
      // If there are no new events after the initial run
      console.log("No new events.");
    }
  } catch (error) {
    console.error("Error fetching events:", error);
  }
}

function sendMessages(event, chatId) {
  const aptosAmount = (+event.data.y_in / 100000000).toFixed(2);
  const tokenAmount = (+event.data.x_out / 1000000).toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
  const transactioVersion = event.transaction_version;

  bot.telegram.sendMessage(
    chatId,
    `
Someone buys $NRUH!!!

Spent: ${aptosAmount} APT
Got: ${tokenAmount} NRUH

<a href="https://explorer.aptoslabs.com/txn/${transactioVersion}/balanceChange?network=mainnet" style="color: BLUE; text-decoration: none;">Transaction</a>
`,
    { parse_mode: "HTML", disable_web_page_preview: true }
  );
}

// Telegram bot command to start monitoring
bot.start((ctx) => {
  chatId = ctx.chat.id; // Save the chat ID to send messages to this chat
  ctx.reply("Bot started! You will receive updates on new events.");

  // Start polling for events
  fetchAndProcessEvents().then(() => {
    setInterval(fetchAndProcessEvents, 5000); // Poll every 5 seconds
  });
});

// Start the bot
bot.launch();

console.log("Bot is running. Type /start in Telegram to receive updates.");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
Status: 🦆 Todo
Development

No branches or pull requests

2 participants