diff --git a/lib/common/defaults.js b/lib/common/defaults.js index cc8a4ba..52e6d5a 100644 --- a/lib/common/defaults.js +++ b/lib/common/defaults.js @@ -37,4 +37,7 @@ Defaults.FEE_LEVELS = [{ defaultValue: 10000 }]; +// Minimum nb of addresses a wallet must have to start using 2-step balance optimization +Defaults.TWO_STEP_BALANCE_THRESHOLD = 100; + module.exports = Defaults; diff --git a/lib/server.js b/lib/server.js index 7ea7518..fea698f 100644 --- a/lib/server.js +++ b/lib/server.js @@ -1060,26 +1060,33 @@ WalletService.prototype._getActiveAddresses = function(cb) { WalletService.prototype.getBalance2Steps = function(opts, cb) { var self = this; - self._getActiveAddresses(function(err, activeAddresses) { + self.storage.countAddresses(self.walletId, function(err, nbAddresses) { if (err) return cb(err); - if (_.isEmpty(activeAddresses)) { + if (nbAddresses < Defaults.TWO_STEP_BALANCE_THRESHOLD) { return self.getBalance(opts, cb); - } else { - self._getBalanceFromAddresses(activeAddresses, function(err, partialBalance) { - if (err) return cb(err); - cb(null, partialBalance); - setTimeout(function() { - self.getBalance(opts, function(err, fullBalance) { - if (err) return; - if (!_.isEqual(partialBalance, fullBalance)) { - log.debug('Cache miss: balance in active addresses differs from final balance'); - self._notify('BalanceUpdated', fullBalance); - } - }); - }, 1); - return; - }); } + + self._getActiveAddresses(function(err, activeAddresses) { + if (err) return cb(err); + if (_.isEmpty(activeAddresses)) { + return self.getBalance(opts, cb); + } else { + self._getBalanceFromAddresses(activeAddresses, function(err, partialBalance) { + if (err) return cb(err); + cb(null, partialBalance); + setTimeout(function() { + self.getBalance(opts, function(err, fullBalance) { + if (err) return; + if (!_.isEqual(partialBalance, fullBalance)) { + log.debug('Cache miss: balance in active addresses differs from final balance'); + self._notify('BalanceUpdated', fullBalance); + } + }); + }, 1); + return; + }); + } + }); }); }; diff --git a/lib/storage.js b/lib/storage.js index b454bac..0dfc76e 100644 --- a/lib/storage.js +++ b/lib/storage.js @@ -389,6 +389,12 @@ Storage.prototype.fetchAddresses = function(walletId, cb) { }); }; +Storage.prototype.countAddresses = function(walletId, cb) { + this.db.collection(collections.ADDRESSES).find({ + walletId: walletId, + }).count(cb); +}; + Storage.prototype.storeAddress = function(address, cb) { var self = this;