I am using smart contract functions in my DAPP. I want to display the transaction cost before the user presses on the button. Is there a way to get the total transaction fee before the function is called? I know that Phantom Wallet is able to accomplish that
You could keep the price/value of a asset as a constant and calculate that in a function and return that value before performing a transaction or If you set the value on the web side you can get that value and update it in a variable via cron job to update it and then calculate via function and return before the transaction.– Syed Murtaza Ali ShahOct 24, 2022 at 7:51
I think what you are looking for is the
getFeeForMessage function offered by Solana web3js (or
getFees if you're using an older version). As the name implies, this function computes the fee the network will charge for a particular message.
Note: This is not 100% fool-proof, a program may charge some extra fee for itself. E.g. a DEX may charge a percent fee of the total amount traded which you'd likely want to include for your user as well. For this, there's obviously no silver bullet and you need to handle it on a case-by-case basis, but for basic network fees the above should be perfect.
If my transaction involves a transfer of an amount of Sol, is it possible for me to display the sol that are to be transferred because getFeeForMessage only displays network fee– frawdOct 25, 2022 at 5:08
Absolutely, that's part of what I was referring to in my
Note:section. In that case just get the network fee like described and either add the sol to be transferred on top or display the two amounts separately, whichever fits better for your specific usecase. The way to fetch how much sol is being transferred is different on a case-by-case basis, more info on tx parsing can be found here Oct 25, 2022 at 5:22