diff --git a/web3.js/src/connection.ts b/web3.js/src/connection.ts index 45b9fb83a..0f9b78864 100644 --- a/web3.js/src/connection.ts +++ b/web3.js/src/connection.ts @@ -3023,6 +3023,27 @@ export class Connection { }; } + /** + * Fetch the fee for a message from the cluster, return with context + */ + async getFeeForMessage( + message: Message, + commitment?: Commitment, + ): Promise> { + const wireMessage = message.serialize().toString('base64'); + const args = this._buildArgs([wireMessage], commitment); + const unsafeRes = await this._rpcRequest('getFeeForMessage', args); + + const res = create(unsafeRes, jsonRpcResultAndContext(nullable(number()))); + if ('error' in res) { + throw new Error('failed to get slot: ' + res.error.message); + } + if (res.result === null) { + throw new Error('invalid blockhash'); + } + return res.result as unknown as RpcResponseAndContext; + } + /** * Fetch a recent blockhash from the cluster * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>} diff --git a/web3.js/test/connection.test.ts b/web3.js/test/connection.test.ts index 958eb298d..e34ccc0f9 100644 --- a/web3.js/test/connection.test.ts +++ b/web3.js/test/connection.test.ts @@ -2278,6 +2278,38 @@ describe('Connection', () => { expect(feeCalculator.lamportsPerSignature).to.eq(5000); }); + it('get fee for message', async () => { + const accountFrom = Keypair.generate(); + const accountTo = Keypair.generate(); + + const {blockhash} = await helpers.recentBlockhash({connection}); + + const transaction = new Transaction({ + feePayer: accountFrom.publicKey, + recentBlockhash: blockhash, + }).add( + SystemProgram.transfer({ + fromPubkey: accountFrom.publicKey, + toPubkey: accountTo.publicKey, + lamports: 10, + }), + ); + const message = transaction.compileMessage(); + + await mockRpcResponse({ + method: 'getFeeForMessage', + params: [ + message.serialize().toString('base64'), + {commitment: 'confirmed'}, + ], + value: 5000, + withContext: true, + }); + + const fee = (await connection.getFeeForMessage(message, 'confirmed')).value; + expect(fee).to.eq(5000); + }); + it('get block time', async () => { await mockRpcResponse({ method: 'getBlockTime',