feat: add Connection.getFeeForMessage (#22128)

* web3.js: add Connection.getFeeForMessage

* throw if value is null

* fix null value

* fix types
This commit is contained in:
Kirill Fomichev 2022-01-11 12:49:28 +03:00 committed by GitHub
parent d064c40617
commit 3c44d405c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 0 deletions

View File

@ -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<RpcResponseAndContext<number>> {
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<number>;
}
/**
* Fetch a recent blockhash from the cluster
* @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>}

View File

@ -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',