diff --git a/web3.js/src/connection.ts b/web3.js/src/connection.ts index ee21927198..9c19dc056e 100644 --- a/web3.js/src/connection.ts +++ b/web3.js/src/connection.ts @@ -2407,6 +2407,28 @@ export class Connection { } } + /** + * Fetch all the account info for multiple accounts specified by an array of public keys + */ + async getMultipleAccountsInfo( + publicKeys: PublicKey[], + commitment?: Commitment, + ): Promise[] | null> { + const keys = publicKeys.map(key => key.toBase58()); + const args = this._buildArgs([keys], commitment, 'base64'); + const unsafeRes = await this._rpcRequest('getMultipleAccounts', args); + const res = create( + unsafeRes, + jsonRpcResultAndContext(nullable(array(AccountInfoResult))), + ); + if ('error' in res) { + throw new Error( + 'failed to get info for accounts ' + keys + ': ' + res.error.message, + ); + } + return res.result.value; + } + /** * Returns epoch activation information for a stake account that has been delegated */ diff --git a/web3.js/test/connection.test.ts b/web3.js/test/connection.test.ts index fb0097f017..344c89bb5c 100644 --- a/web3.js/test/connection.test.ts +++ b/web3.js/test/connection.test.ts @@ -155,6 +155,76 @@ describe('Connection', () => { .be.null; }); + it('get multiple accounts info', async () => { + const account1 = Keypair.generate(); + const account2 = Keypair.generate(); + + { + await helpers.airdrop({ + connection, + address: account1.publicKey, + amount: LAMPORTS_PER_SOL, + }); + + await helpers.airdrop({ + connection, + address: account2.publicKey, + amount: LAMPORTS_PER_SOL, + }); + } + + const value = [ + { + owner: '11111111111111111111111111111111', + lamports: LAMPORTS_PER_SOL, + data: ['', 'base64'], + executable: false, + rentEpoch: 0, + }, + { + owner: '11111111111111111111111111111111', + lamports: LAMPORTS_PER_SOL, + data: ['', 'base64'], + executable: false, + rentEpoch: 0, + }, + ]; + + await mockRpcResponse({ + method: 'getMultipleAccounts', + params: [ + [account1.publicKey.toBase58(), account2.publicKey.toBase58()], + {encoding: 'base64'}, + ], + value: value, + withContext: true, + }); + + const res = await connection.getMultipleAccountsInfo( + [account1.publicKey, account2.publicKey], + 'confirmed', + ); + + const expectedValue = [ + { + owner: new PublicKey('11111111111111111111111111111111'), + lamports: LAMPORTS_PER_SOL, + data: Buffer.from([]), + executable: false, + rentEpoch: 0, + }, + { + owner: new PublicKey('11111111111111111111111111111111'), + lamports: LAMPORTS_PER_SOL, + data: Buffer.from([]), + executable: false, + rentEpoch: 0, + }, + ]; + + expect(res).to.eql(expectedValue); + }); + it('get program accounts', async () => { const account0 = Keypair.generate(); const account1 = Keypair.generate();