diff --git a/web3.js/src/connection.js b/web3.js/src/connection.js index 9d5029d55e..4a8ac2b1a8 100644 --- a/web3.js/src/connection.js +++ b/web3.js/src/connection.js @@ -71,7 +71,7 @@ type VoteAccountStatus = { * (see https://docs.solana.com/book/v/master/implemented-proposals/ed_overview) * * @typedef {Object} Inflation - * @property {number} foundation + * @property {number} foundation * @property {number} foundation_term * @property {number} initial * @property {number} storage @@ -87,10 +87,27 @@ const GetInflationResult = struct({ terminal: 'number', }); +/** + * EpochInfo parameters + * (see https://docs.solana.com/book/v/master/terminology#epoch) + * + * @typedef {Object} EpochInfo + * @property {number} epoch + * @property {number} slotIndex + * @property {number} slotsInEpoch + * @property {number} absoluteSlot + */ +const GetEpochInfoResult = struct({ + epoch: 'number', + slotIndex: 'number', + slotsInEpoch: 'number', + absoluteSlot: 'number', +}); + /** * EpochSchedule parameters * (see https://docs.solana.com/book/v/master/terminology#epoch) - * + * * @typedef {Object} EpochSchedule * @property {number} slots_per_epoch * @property {number} leader_schedule_slot_offset @@ -148,6 +165,16 @@ const GetInflationRpcResult = struct({ result: GetInflationResult, }); +/** + * Expected JSON RPC response for the "getEpochInfo" message + */ +const GetEpochInfoRpcResult = struct({ + jsonrpc: struct.literal('2.0'), + id: 'string', + error: 'any?', + result: GetEpochInfoResult, +}); + /** * Expected JSON RPC response for the "getEpochSchedule" message */ @@ -718,6 +745,19 @@ export class Connection { return GetInflationResult(res.result); } + /** + * Fetch the Epoch Info parameters + */ + async getEpochInfo(): Promise { + const unsafeRes = await this._rpcRequest('getEpochInfo', []); + const res = GetEpochInfoRpcResult(unsafeRes); + if (res.error) { + throw new Error(res.error.message); + } + assert(typeof res.result !== 'undefined'); + return GetEpochInfoResult(res.result); + } + /** * Fetch the Epoch Schedule parameters */ diff --git a/web3.js/test/connection.test.js b/web3.js/test/connection.test.js index ae34f7124f..47e4630321 100644 --- a/web3.js/test/connection.test.js +++ b/web3.js/test/connection.test.js @@ -170,6 +170,34 @@ test('get inflation', async () => { } }); +test('get epoch info', async () => { + const connection = new Connection(url); + + mockRpc.push([ + url, + { + method: 'getEpochInfo', + params: [], + }, + { + error: null, + result: { + epoch: 1, + slotIndex: 1, + slotsInEpoch: 8192, + absoluteSlot: 1, + }, + }, + ]); + + const epochInfo = await connection.getEpochInfo(); + + for (const key of ['epoch', 'slotIndex', 'slotsInEpoch', 'absoluteSlot']) { + expect(epochInfo).toHaveProperty(key); + expect(epochInfo[key]).toBeGreaterThan(0); + } +}); + test('get epoch schedule', async () => { const connection = new Connection(url);