Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

web3.js: add Connection.getFeeForMessage #22128

Merged
merged 4 commits into from
Jan 11, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions web3.js/src/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2998,6 +2998,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 | null>> {
fanatid marked this conversation as resolved.
Show resolved Hide resolved
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.value === null) {
fanatid marked this conversation as resolved.
Show resolved Hide resolved
throw new Error('invalid blockhash');
}
return res.result;
fanatid marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Fetch a recent blockhash from the cluster
* @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>}
Expand Down
32 changes: 32 additions & 0 deletions web3.js/test/connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down