tronprotocol / tronweb

Javascript API Library for interacting with the TRON Network
MIT License
431 stars 272 forks source link

How to get contract address via address? #532

Closed DengSihan closed 3 months ago

DengSihan commented 3 months ago

I want to achieve an effect that when someone sends any TRC20 USDTs to a specific address, I can detect it and check the amount of USDT via TronWeb v6.0.0-beta.3


In the Nile testnet, I sent some USDTs to my account and I've confirmed in the blockchain explorer.

I can only know my USDT amount by checking my contract address through the blockchain browser rather than automatically obtaining it through the code.

In my express app

export const show = async (req, res) => {

    const { address } = req.params;

    const tronWeb = new TronWeb({
        fullHost: process.env.TRON_FULL_HOST,
        headers: {
            'TRON-PRO-API-KEY': process.env.TRON_PRO_API_KEY,
        },
        privateKey: ''
    });

    tronWeb.setAddress(address);

    try {
        // 👇 how can I get the contract address instead of finding it in the blockchain explorer
        const contractAddress = 'TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj';

        const contract = await tronWeb.contract().at(contractAddress);

        const balance = await contract.balanceOf(address).call();
        const formattedBalance = + parseFloat(tronWeb.fromSun(balance.toNumber()))

        res.status(200).json({
            address: address,
            balance: formattedBalance
        });

    } catch (error) {
        res.status(500).json({
            error: 'Failed to check the balance',
            message: error.message
        });
    }
};

I would greatly appreciate any help!