0

please help me to get both incoming and outcoming transactions

static async getTransactions(wallet) {
            try {
                const provider = await ProviderFactory.getProvider(wallet.chain)
                const pubKey = new PublicKey(wallet.walletAddress)
            const desiredLimit = 10;
            let transactions = [];
            let beforeSignature = null;

        while (transactions.length < desiredLimit) {
            const transactionSignatures = await provider.connection.getSignaturesForAddress(
                pubKey,
                { limit: desiredLimit - transactions.length, before: beforeSignature }
            );

            if (transactionSignatures.length === 0) break;

            const transactionPromises = transactionSignatures.map(signatureInfo =>
                provider.connection.getTransaction(signatureInfo.signature)
            );
            const transactionsData = await Promise.all(transactionPromises);

            for (let i = 0; i < transactionsData.length; i++) {
                const transaction = transactionsData[i];

                if (transaction && transaction.meta &&
                    transaction.meta.postTokenBalances &&
                    transaction.meta.preTokenBalances) {

                    const signatureInfo = transactionSignatures[i];
                    const txHash = signatureInfo.signature;

                    // Track token movements for the relevant mint
                    const tokenTransfers = transaction.meta.postTokenBalances
                        .filter(balance => balance.mint === wallet.contract)
                        .map(postBalance => {
                            const preBalance = transaction.meta.preTokenBalances.find(balance =>
                                balance.mint === wallet.contract && balance.owner === postBalance.owner
                            );
                            const change = postBalance.uiTokenAmount.uiAmount - (preBalance ? preBalance.uiTokenAmount.uiAmount : 0);
                            return { owner: postBalance.owner, change };
                        });

                    // Identify sender and receiver based on balance changes
                    let from, to;
                    if (tokenTransfers.some(transfer => transfer.owner === wallet.walletAddress && transfer.change > 0)) {
                        // Receive transaction
                        to = wallet.walletAddress;
                        from = tokenTransfers.find(transfer => transfer.change < 0)?.owner;
                    } else if (tokenTransfers.some(transfer => transfer.owner === wallet.walletAddress && transfer.change < 0)) {
                        // Send transaction
                        from = wallet.walletAddress;
                        to = tokenTransfers.find(transfer => transfer.change > 0)?.owner;
                    }

                    if (!to || !from) continue;

                    const status = transaction.meta.err ? '0' : '-1';
                    const createdAt = moment(transaction.blockTime * 1000).fromNow();
                    const value = Math.abs(tokenTransfers.find(transfer => transfer.owner === to)?.change || 0);
                    const gasFee = transaction.meta.fee;
                    const isSender = wallet.walletAddress === from;
                    const explore = configProperties.solana.explore + `tx/${txHash}`;
                    const type = isSender ? 'outgoing' : 'incoming';

                    transactions.push({
                        txHash, to, from, status, createdAt, gasFee, value, isSender, explore, type
                    });
                }
            }

            beforeSignature = transactionSignatures[transactionSignatures.length - 1]?.signature;
        }

        return {
            success: true,
            data: transactions
        };
    } catch (error) {
        Logs.info('WalletFactory: getTransactions', error);
        throw new Error(error.message)
    }
}

1 Answer 1

0

An SPL Token transfer takes the source token account, destination token account, and source account owner. Note that it does not include the destination account owner. In your case, you're fetching transactions that reference the account owner, which means that it will only catch outgoing transfers.

If you want to get incoming transfers, you'll need to fetch transactions that reference the token account as well.

For example, if the wallet is JCGeBSz785g7wtAK6f3Y8Vg6EoTx5HGqR8kZMNVe3YQm, and the mint is APsCzbUffowbJJcBC5ZKMS5h4Fiqazc8KeMmH1XgFEzk, then the associated token account is 3RhYHj23RQQxZhoh6A7xa7TGFGFDrhmSQz1tV6hZs49p, so you'd also want to get transactions for 3RhYHj23RQQxZhoh6A7xa7TGFGFDrhmSQz1tV6hZs49p.

2
  • how to subscribe to the token accounts?
    – sulthan
    Commented Aug 27 at 12:34
  • I've edited my answer -- I hope it's clear!
    – Jon C
    Commented Aug 27 at 20:15

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.