diff --git a/web3.js/module.d.ts b/web3.js/module.d.ts index 7620b89a37..40e5d2ac0e 100644 --- a/web3.js/module.d.ts +++ b/web3.js/module.d.ts @@ -198,6 +198,7 @@ declare module '@solana/web3.js' { commitment?: Commitment, ): Promise>; getBalance(publicKey: PublicKey, commitment?: Commitment): Promise; + getBlockTime(slot: number): Promise; getClusterNodes(): Promise>; getConfirmedBlock(slot: number): Promise; getConfirmedTransaction( diff --git a/web3.js/module.flow.js b/web3.js/module.flow.js index b3967d9a8b..80b8405399 100644 --- a/web3.js/module.flow.js +++ b/web3.js/module.flow.js @@ -211,6 +211,7 @@ declare module '@solana/web3.js' { commitment: ?Commitment, ): Promise>; getBalance(publicKey: PublicKey, commitment: ?Commitment): Promise; + getBlockTime(slot: number): Promise; getClusterNodes(): Promise>; getConfirmedBlock(slot: number): Promise; getConfirmedTransaction( diff --git a/web3.js/src/connection.js b/web3.js/src/connection.js index a2cd8453a4..bfedc9efff 100644 --- a/web3.js/src/connection.js +++ b/web3.js/src/connection.js @@ -356,6 +356,16 @@ const GetEpochScheduleRpcResult = struct({ */ const GetBalanceAndContextRpcResult = jsonRpcResultAndContext('number?'); +/** + * Expected JSON RPC response for the "getBlockTime" message + */ +const GetBlockTimeRpcResult = struct({ + jsonrpc: struct.literal('2.0'), + id: 'string', + error: 'any?', + result: struct.union(['null', 'number']), +}); + /** * Expected JSON RPC response for the "getVersion" message */ @@ -942,6 +952,21 @@ export class Connection { }); } + /** + * Fetch the estimated production time of a block + */ + async getBlockTime(slot: number): Promise { + const unsafeRes = await this._rpcRequest('getBlockTime', [slot]); + const res = GetBlockTimeRpcResult(unsafeRes); + if (res.error) { + throw new Error( + 'failed to get block time for slot ' + slot + ': ' + res.error.message, + ); + } + assert(typeof res.result !== 'undefined'); + return res.result; + } + /** * Fetch all the account info for the specified public key, return with context */ diff --git a/web3.js/test/connection.test.js b/web3.js/test/connection.test.js index 605d845177..021eb798b1 100644 --- a/web3.js/test/connection.test.js +++ b/web3.js/test/connection.test.js @@ -1039,6 +1039,29 @@ test('get recent blockhash', async () => { expect(feeCalculator.lamportsPerSignature).toBeGreaterThanOrEqual(0); }); +test('get block time', async () => { + const connection = new Connection(url); + + mockRpc.push([ + url, + { + method: 'getBlockTime', + params: [1], + }, + { + error: null, + result: 10000, + }, + ]); + + const blockTime = await connection.getBlockTime(1); + if (blockTime === null) { + expect(blockTime).not.toBeNull(); + } else { + expect(blockTime).toBeGreaterThan(0); + } +}); + test('getVersion', async () => { const connection = new Connection(url);