solanasolana-web3jsanchor-solanasolana-program-library

Estimate gas cost for transaction to custom Solana Program written with Anchor


How can I get a gasFee estimate for a transaction of my custom contract?

For a normal transaction execution from the SPL library I can do so like this:

import { Transaction } from '@solana/web3.js';

const transaction = new Transaction({
  recentBlockhash: recentBlockhash.blockhash,
  feePayer: wallet.publicKey
}).add(
  // someFunctionCall
);
const estimatedGas = await transaction.getEstimatedFee(connection);

But I do not use new Transaction() to call my custom Program's methods. It's done like:

const tx = await program.methods
        .myCustomMethod(...)
        .accounts(...)
        .rpc();

How can I estimate the gas for the tx w/o actually calling it?


Solution

  • I found out you can replace .rpc() with .transaction() which will return an object of type Transaction (from @solana/web3.js).

    Then you can exercise the same logic for gas estimation on that object as in the first example.

    And, of course, you will need to sendAndConfirm the transaction as an extra step, because otherwise the .rpc() call was taking care of that.