blockchainsoliditysmartcontractstron

Interact with TRC20 tokens in solidity Tron Smart Contract


What is the proper method to check for example the USDT balance of a given smart contract within that contract in Solidity?

For the TRX balance you can just do

uint256 balance = address(this).balance;

But how do you call the USDT balance for that SC?

Thanks


Solution

  • All right so I finally managed to figure this out. In order to interact with a token contract you need two things:

    The first is your chosen token contract address so that should be easy, search for it by name on your desired newtork and you will find it's main contract address. For USDT on Tron for example it's: TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t (here).

    For the second you just need a piece of code at the top of your contract something like this. Starts with the keyword interface and then the name of the "contract standard" (whatever that means - most of the concepts used in these blockchain networks seem very loosely defined and there seems to be a great lack of proper documentation) and within you then reference the desired functions you whish to call for said smart contract as in the example below.

    interface IERC20 {
       function transfer(address _to, uint256 _value) external returns (bool);
       function balanceOf(address account) external view returns (uint);
    }
    

    Last step is to initialize the interface with your contract, like creating a new object in OOP.

    IERC20 usdt = IERC20(address("token smart contract address in hex format"));
    

    Finally to interact with the token smart contract you just need to pass it the proper parameters as in the functions provieded. For example to check the token balance for your wallet address you would do:

    uint256 usdtBalance = usdt.balanceOf('your wallet address in hex format');
    

    Implementing the code above will basically give you two contracts that the tronIDE or remix IDE could deploy but you only need to deploy your own, not the IERC20 interface one and everything will work just fine.

    Hope this helps someone.