diff --git a/web3.js/src/connection.ts b/web3.js/src/connection.ts index 610980a929..1b2b6277a2 100644 --- a/web3.js/src/connection.ts +++ b/web3.js/src/connection.ts @@ -3107,6 +3107,26 @@ export class Connection { }; } + /** + * Fetch confirmed blocks between two slots + */ + async getBlocks( + startSlot: number, + endSlot?: number, + commitment?: Finality, + ): Promise> { + const args = this._buildArgsAtLeastConfirmed( + endSlot !== undefined ? [startSlot, endSlot] : [startSlot], + commitment, + ); + const unsafeRes = await this._rpcRequest('getBlocks', args); + const res = create(unsafeRes, jsonRpcResult(array(number()))); + if ('error' in res) { + throw new Error('failed to get blocks: ' + res.error.message); + } + return res.result; + } + /** * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards */ diff --git a/web3.js/test/connection.test.ts b/web3.js/test/connection.test.ts index 10135be180..035ff626b7 100644 --- a/web3.js/test/connection.test.ts +++ b/web3.js/test/connection.test.ts @@ -2078,6 +2078,54 @@ describe('Connection', () => { ); }); + it('get blocks between two slots', async () => { + await mockRpcResponse({ + method: 'getBlocks', + params: [0, 10], + value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + }); + + await mockRpcResponse({ + method: 'getSlot', + params: [], + value: 10, + }); + + const latestSlot = await connection.getSlot(); + const blocks = await connection.getBlocks(0, latestSlot); + expect(blocks).to.have.length(latestSlot); + expect(blocks).to.contain(1); + expect(blocks).to.contain(latestSlot); + }); + + it('get blocks from starting slot', async () => { + await mockRpcResponse({ + method: 'getBlocks', + params: [0], + value: [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, + ], + }); + + await mockRpcResponse({ + method: 'getSlot', + params: [], + value: 20, + }); + + while ((await connection.getSlot()) <= 0) { + continue; + } + + const blocks = await connection.getBlocks(0); + const latestSlot = await connection.getSlot(); + expect(blocks).to.have.lengthOf.greaterThanOrEqual(latestSlot); + expect(blocks).to.contain(1); + expect(blocks).to.contain(latestSlot); + }); + it('get confirmed block signatures', async () => { await mockRpcResponse({ method: 'getSlot',