diff --git a/web3.js/src/transaction.ts b/web3.js/src/transaction.ts index 87ee92508..b3e4ec9ca 100644 --- a/web3.js/src/transaction.ts +++ b/web3.js/src/transaction.ts @@ -2,6 +2,7 @@ import nacl from 'tweetnacl'; import bs58 from 'bs58'; import {Buffer} from 'buffer'; +import {Connection} from './connection'; import {Message} from './message'; import {PublicKey} from './publickey'; import * as shortvec from './util/shortvec-encoding'; @@ -405,6 +406,13 @@ export class Transaction { return this._compile().serialize(); } + /** + * Get the estimated fee associated with a transaction + */ + async getEstimatedFee(connection: Connection): Promise { + return (await connection.getFeeForMessage(this.compileMessage())).value; + } + /** * Specify the public keys which will be used to sign the Transaction. * The first signer will be used as the transaction fee payer account. diff --git a/web3.js/test/transaction.test.ts b/web3.js/test/transaction.test.ts index 93ff213fa..de9450c40 100644 --- a/web3.js/test/transaction.test.ts +++ b/web3.js/test/transaction.test.ts @@ -3,6 +3,7 @@ import {Buffer} from 'buffer'; import nacl from 'tweetnacl'; import {expect} from 'chai'; +import {Connection} from '../src/connection'; import {Keypair} from '../src/keypair'; import {PublicKey} from '../src/publickey'; import {Transaction, TransactionInstruction} from '../src/transaction'; @@ -11,6 +12,7 @@ import {SystemProgram} from '../src/system-program'; import {Message} from '../src/message'; import invariant from '../src/util/assert'; import {toBuffer} from '../src/util/to-buffer'; +import {helpers} from './mocks/rpc-http'; describe('Transaction', () => { describe('compileMessage', () => { @@ -112,6 +114,28 @@ describe('Transaction', () => { }); }); + it('getEstimatedFee', async () => { + const connection = new Connection('https://api.testnet.solana.com'); + const accountFrom = Keypair.generate(); + const accountTo = Keypair.generate(); + + const {blockhash} = await helpers.latestBlockhash({connection}); + + const transaction = new Transaction({ + feePayer: accountFrom.publicKey, + recentBlockhash: blockhash, + }).add( + SystemProgram.transfer({ + fromPubkey: accountFrom.publicKey, + toPubkey: accountTo.publicKey, + lamports: 10, + }), + ); + + const fee = await transaction.getEstimatedFee(connection); + expect(fee).to.eq(5000); + }); + it('partialSign', () => { const account1 = Keypair.generate(); const account2 = Keypair.generate();