javascriptpythonblockchaincryptocurrencytron

Tron fee estimation bofore confirming transaction


I am trying to create an application which is actually a Tron(TRX) wallet, how can I make it calculate the fee for every transaction before being confirmed from the user? I understand the fact that tron uses some BP(Bandwidth Points) every time for making a transaction if possible and it would be amazing if anyone could help with related calculations as well.

By the way, I am using python to create such application but I don't mind using javascript if needed, so help of any kind will be appreciated.

I have tried using tronpy and tronapi as google bard recommended but they can't calculate the transaction fees as long as I know. There might be some ways around using tronweb, but since i am not a professional in javascript and crypto, I couldn't use it much. Maye some code snippets from experts will help me more with the understanding.

Please feel free to mention some APIs and SDKs that you think will help in any ways.


Solution

  • I finally have the trick.

    The fee estimation used to return 0.2 TRX at first because I forgot to sign the transaction with private key. It returns 0.267 TRX now by including the private key and signature.

    It does not need energy to transfer Tron(TRX) on it's own unless you start dealing with smart contracts.

    the following code should work just perfectly for my needs, hope it can help anyone else having similar issues.

    import requests
    from tronpy import Tron
    import trontxsize
    from tronpy.keys import PrivateKey
    
    
    def get_bandwidth_price():
        url = "https://api.trongrid.io/wallet/getchainparameters"
        response = requests.get(url)
        data = response.json()
        bandwidth_price = data['chainParameter'][3]['value'] / 1000_000
        return bandwidth_price
    
    
    def create_transaction(sender_address, recipient_address, amount):
        priv_key = PrivateKey(bytes.fromhex("Your_Private_Key"))
        tron = Tron()
        txn = (
            tron.trx.transfer(sender_address, recipient_address, amount)
            .build()
            .inspect()
            .sign(priv_key)
        )
        return txn
    
    
    def calculate_transaction_fee(transaction):
        bandwidth_price = get_bandwidth_price()
        txsize = trontxsize.get_tx_size({"raw_data": transaction._raw_data, "signature": transaction._signature})
        bandwidth_points = txsize * bandwidth_price
        total_fee = bandwidth_points
        return total_fee
    
    
    if __name__ == "__main__":
        sender_address = 'Wallet_Address'
        recipient_address = "recipient_address"
        amount = 1000000 # Replace with your amount
    
        transaction = create_transaction(sender_address, recipient_address, amount)
        fee = calculate_transaction_fee(transaction)
        print(f'Transaction Fee: {fee} TRX')