feat: add getBlockTime method

This commit is contained in:
Justin Starry 2020-05-19 11:27:36 +08:00 committed by Michael Vines
parent e10a5c90ab
commit 4b613a4574
4 changed files with 50 additions and 0 deletions

1
web3.js/module.d.ts vendored
View File

@ -198,6 +198,7 @@ declare module '@solana/web3.js' {
commitment?: Commitment,
): Promise<RpcResponseAndContext<number>>;
getBalance(publicKey: PublicKey, commitment?: Commitment): Promise<number>;
getBlockTime(slot: number): Promise<number | null>;
getClusterNodes(): Promise<Array<ContactInfo>>;
getConfirmedBlock(slot: number): Promise<ConfirmedBlock>;
getConfirmedTransaction(

View File

@ -211,6 +211,7 @@ declare module '@solana/web3.js' {
commitment: ?Commitment,
): Promise<RpcResponseAndContext<number>>;
getBalance(publicKey: PublicKey, commitment: ?Commitment): Promise<number>;
getBlockTime(slot: number): Promise<number | null>;
getClusterNodes(): Promise<Array<ContactInfo>>;
getConfirmedBlock(slot: number): Promise<ConfirmedBlock>;
getConfirmedTransaction(

View File

@ -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<number | null> {
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
*/

View File

@ -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);