Search code examples
node.jscallbackweb3jssolanasolana-web3js

@solana/web3.js subscribe to incoming tokens


I want to recieve callback when I receive tokens on some account in nodeJS. This code work properly, but only for SOL. How to do the same for USDT in solana or for any token?

const web3 = require("@solana/web3.js");
(async () => {
  const publicKey = new web3.PublicKey(wallet);
  const solanaConnection = new web3.Connection(httpsNode, {
    wsEndpoint: wssNode,
  });
  solanaConnection.onLogs(
    publicKey,
    (logs, context) => console.log("Updated account info: ", logs),
    "confirmed"
  );
})();

Solution

  • You can do essentially the same thing, but instead of using publicKey, you should use the USDT associated token account address for that wallet, e.g.

    const web3 = require("@solana/web3.js");
    const splToken = require("@solana/spl-token");
    (async () => {
      const walletPublicKey = new web3.PublicKey(wallet);
      const usdtMint = new web3.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");
      const publicKey = splToken.getAssociatedTokenAddressSync(usdtMint, walletPublicKey);
      const solanaConnection = new web3.Connection(httpsNode, {
        wsEndpoint: wssNode,
      });
      solanaConnection.onLogs(
        publicKey,
        (logs, context) => console.log("Updated account info: ", logs),
        "confirmed"
      );
    })();