3

Using JS, how would I go about getting transaction information on transactions that affect the balance of a specific account?

I've been able to listen for account changes with the following code, but it only provides the updated account information. Specifically, I want to know the amount of the transfer, what token was transferred, and what account it was transferred from.

import { clusterApiUrl, Connection, PublicKey } from '@solana/web3.js';

const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');

const subscriptionID = connection.onAccountChange(
  new PublicKey('xxxxxxxxxxx'),
  (updatedAccountInfo, context) => {
    console.log(updatedAccountInfo, context)
  },
  "confirmed"
)

1 Answer 1

3

It's a bit goofy, but if you want the full transaction info on every update, you'll need to query the signatures for that address, and then fetch the transaction, so roughly that would be:

const subscriptionID = connection.onAccountChange(
  new PublicKey('xxxxxxxxxxx'),
  (updatedAccountInfo, context) => {
    const signatures = await connection.getSignaturesForAddress('xxxxxxx');
    const transaction = await connection.getTransaction(signatures[0].signature);
  },
  "confirmed"
)
1
  • Thanks, gonna mark this as the answer but damn, I was hoping there was a better solution :/. I guess the only thing I would add is passing in the slot from the context for additional precision on getting the right tx?
    – gxc
    Commented Jan 20, 2023 at 23:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.