How to transfer TRC20 token using tronpy?

2.2k views Asked by At

I want to send USDT TRC20 tokens using tronpy, while i succeded to transfer TRX, same approach failed for the TRC20 tokens, here's my code:

import codecs
from tronpy.keys import PrivateKey
from hexbytes import HexBytes

def transfer(self, private_key: str, to_address: str, amount: int, contract_address: str, abi: str = None) -> HexBytes:
    pk = PrivateKey(bytes.fromhex(private_key))

    # Prepare contract
    contract = self._tron.get_contract(contract_address)
    contract.abi = abi

    # Base tx
    tx = (
        contract.functions.transfer(
            to_address,
            amount)
        .with_owner(pk.public_key.to_base58check_address())
        #.fee_limit(5_000_000)
        .build()
        .sign(pk)
    )

    broadcasted_tx = tx.broadcast().wait()

    return HexBytes(codecs.decode(broadcasted_tx['id'], 'hex_codec'))

Where:

abi = [{
     "outputs":[
        {
           "type":"bool"
        }
     ],
     "inputs":[
        {
           "name":"_to",
           "type":"address"
        },
        {
           "name":"_value",
           "type":"uint256"
        }
     ],
     "name":"transfer",
     "stateMutability":"Nonpayable",
     "type":"Function"
  }]

and:

contract_address = 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf' # USDT token on Nile testnet

And the transaction is broadcasted then get failed: https://nile.tronscan.org/#/transaction/70ac4ff25674d94dd7860e815560fbe425bfd275cf1afaa11d4897efa83d706a

What's wrong with my transaction building ? Anyway to get it done using tronpy and not tronapi ?

1

There are 1 answers

3
zfou On

After some debugging, it seems my account were not popped up with the right tokens: i've received USDT from nile's faucet and they are marked "suspicious": https://nile.tronscan.org/#/token20/TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj

After popping my wallet from another faucet (tron's discord bot), my transfer using the same code shared in my question is now working successfuly: https://nile.tronscan.org/#/transaction/2da04e8bfd24522ee99f3c2090ee6c03db4632ac5a497cc63f21d9d880854e4c