From 4ae90c294453829ad663a5c9fd9d0a3f4d94aa20 Mon Sep 17 00:00:00 2001 From: Tyera Eulberg Date: Thu, 26 Sep 2019 14:13:57 -0600 Subject: [PATCH] fix: add api for getMinimumBalanceForRentExemption --- web3.js/src/connection.js | 22 ++++++++++++++++++++++ web3.js/test/connection.test.js | 19 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/web3.js/src/connection.js b/web3.js/src/connection.js index 77e70dd225..02b4d12e41 100644 --- a/web3.js/src/connection.js +++ b/web3.js/src/connection.js @@ -294,6 +294,11 @@ const GetTransactionCountRpcResult = jsonRpcResult('number'); */ const GetTotalSupplyRpcResult = jsonRpcResult('number'); +/** + * Expected JSON RPC response for the "getMinimumBalanceForRentExemption" message + */ +const GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult('number'); + /** * Expected JSON RPC response for the "getRecentBlockhash" message */ @@ -683,6 +688,23 @@ export class Connection { return GetInflationResult(res.result); } + /** + * Fetch the minimum balance needed to exempt an account of `dataLength` + * size from rent + */ + async getMinimumBalanceForRentExemption(dataLength: number): Promise { + const unsafeRes = await this._rpcRequest( + 'getMinimumBalanceForRentExemption', + [dataLength], + ); + const res = GetMinimumBalanceForRentExemptionRpcResult(unsafeRes); + if (res.error) { + throw new Error(res.error.message); + } + assert(typeof res.result !== 'undefined'); + return Number(res.result); + } + /** * Fetch a recent blockhash from the cluster */ diff --git a/web3.js/test/connection.test.js b/web3.js/test/connection.test.js index ec3898be21..2ec2320b2e 100644 --- a/web3.js/test/connection.test.js +++ b/web3.js/test/connection.test.js @@ -330,6 +330,25 @@ test('get total supply', async () => { expect(count).toBeGreaterThanOrEqual(0); }); +test('get minimum balance for rent exemption', async () => { + const connection = new Connection(url); + + mockRpc.push([ + url, + { + method: 'getMinimumBalanceForRentExemption', + params: [512], + }, + { + error: null, + result: 1000000, + }, + ]); + + const count = await connection.getMinimumBalanceForRentExemption(512); + expect(count).toBeGreaterThanOrEqual(0); +}); + test('get recent blockhash', async () => { const connection = new Connection(url);