feat: add support for getFirstAvailableBlock method

This commit is contained in:
Justin Starry
2020-05-23 17:33:04 +08:00
committed by Michael Vines
parent 1b8fe71230
commit 925c225885
4 changed files with 39 additions and 3 deletions

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

@ -219,6 +219,7 @@ declare module '@solana/web3.js' {
getBalance(publicKey: PublicKey, commitment?: Commitment): Promise<number>;
getBlockTime(slot: number): Promise<number | null>;
getMinimumLedgerSlot(): Promise<number>;
getFirstAvailableBlock(): Promise<number>;
getSupply(commitment?: Commitment): Promise<RpcResponseAndContext<Supply>>;
getLargestAccounts(
config?: GetLargestAccountsConfig,

View File

@ -232,6 +232,7 @@ declare module '@solana/web3.js' {
getBalance(publicKey: PublicKey, commitment: ?Commitment): Promise<number>;
getBlockTime(slot: number): Promise<number | null>;
getMinimumLedgerSlot(): Promise<number>;
getFirstAvailableBlock(): Promise<number>;
getSupply(commitment: ?Commitment): Promise<RpcResponseAndContext<Supply>>;
getLargestAccounts(
config: ?GetLargestAccountsConfig,

View File

@ -417,9 +417,9 @@ const GetBlockTimeRpcResult = struct({
});
/**
* Expected JSON RPC response for the "minimumLedgerSlot" message
* Expected JSON RPC response for the "minimumLedgerSlot" and "getFirstAvailableBlock" messages
*/
const MinimumLedgerSlotRpcResult = struct({
const SlotRpcResult = struct({
jsonrpc: struct.literal('2.0'),
id: 'string',
error: 'any?',
@ -1081,7 +1081,7 @@ export class Connection {
*/
async getMinimumLedgerSlot(): Promise<number> {
const unsafeRes = await this._rpcRequest('minimumLedgerSlot', []);
const res = MinimumLedgerSlotRpcResult(unsafeRes);
const res = SlotRpcResult(unsafeRes);
if (res.error) {
throw new Error(
'failed to get minimum ledger slot: ' + res.error.message,
@ -1091,6 +1091,21 @@ export class Connection {
return res.result;
}
/**
* Fetch the slot of the lowest confirmed block that has not been purged from the ledger
*/
async getFirstAvailableBlock(): Promise<number> {
const unsafeRes = await this._rpcRequest('getFirstAvailableBlock', []);
const res = SlotRpcResult(unsafeRes);
if (res.error) {
throw new Error(
'failed to get first available block: ' + res.error.message,
);
}
assert(typeof res.result !== 'undefined');
return res.result;
}
/**
* Fetch information about the current supply
*/

View File

@ -1109,6 +1109,25 @@ test('get minimum ledger slot', async () => {
expect(minimumLedgerSlot).toBeGreaterThanOrEqual(0);
});
test('get first available block', async () => {
const connection = new Connection(url);
mockRpc.push([
url,
{
method: 'getFirstAvailableBlock',
params: [],
},
{
error: null,
result: 0,
},
]);
const firstAvailableBlock = await connection.getFirstAvailableBlock();
expect(firstAvailableBlock).toBeGreaterThanOrEqual(0);
});
test('get supply', async () => {
const connection = new Connection(url);