From 8d25f238496444ccc26ceb7ea5fa1b732219076b Mon Sep 17 00:00:00 2001 From: Ivan Socolsky Date: Fri, 19 Feb 2016 11:11:43 -0300 Subject: [PATCH] get send max info --- lib/model/txproposal.js | 8 ++++-- lib/server.js | 62 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/lib/model/txproposal.js b/lib/model/txproposal.js index 6f5d782..dfa98cd 100644 --- a/lib/model/txproposal.js +++ b/lib/model/txproposal.js @@ -252,10 +252,14 @@ TxProposal.prototype.getEstimatedSize = function() { return parseInt((size * (1 + safetyMargin)).toFixed(0)); }; -TxProposal.prototype.estimateFee = function() { +TxProposal.prototype.getEstimatedFee = function() { $.checkState(_.isNumber(this.feePerKb)); var fee = this.feePerKb * this.getEstimatedSize() / 1000; - this.fee = parseInt(fee.toFixed(0)); + return parseInt(fee.toFixed(0)); +}; + +TxProposal.prototype.estimateFee = function() { + this.fee = this.getEstimatedFee(); }; /** diff --git a/lib/server.js b/lib/server.js index 1eefa57..f828faa 100644 --- a/lib/server.js +++ b/lib/server.js @@ -1148,6 +1148,68 @@ WalletService.prototype.getBalance = function(opts, cb) { }); }; +/** + * Return info needed to send all funds in the wallet + * @param {Object} opts + * @param {string} opts.feePerKb - The fee per KB used to compute the TX. + * @param {string} opts.excludeUnconfirmedUtxos - Exclude unconfirmed UTXOs from calculation. + * @returns {Object} sendMaxInfo + */ +WalletService.prototype.getSendMaxInfo = function(opts, cb) { + var self = this; + + + opts = opts || {}; + + if (!Utils.checkRequired(opts, ['feePerKb', 'excludeUnconfirmedUtxos'])) + return cb(new ClientError('Required argument missing')); + + self.getWallet({}, function(err, wallet) { + if (err) return cb(err); + + self._getUtxosForCurrentWallet(null, function(err, utxos) { + if (err) return cb(err); + + var info = { + size: 0, + amount: 0, + fee: 0, + nbInputs: 0, + }; + + var inputs = _.reject(utxos, 'locked'); + if (opts.excludeUnconfirmedUtxos) { + inputs = _.filter(inptus, 'confirmations'); + } + inputs = _.sortBy(inputs, 'satoshis'); + + if (_.isEmpty(inputs)) return cb(null, info); + + var txp = Model.TxProposal.create({ + walletId: self.walletId, + network: wallet.network, + walletM: wallet.m, + walletN: wallet.n, + feePerKb: opts.feePerKb, + }); + + var lastFee = txp.getEstimatedFee(); + _.eachRight(inputs, function(input) { + txp.inputs.push(input); + var fee = txp.getEstimatedFee(); + if (fee - lastFee > input.satoshis) return false; + lastFee = fee; + }); + + info.size = txp.getEstimatedSize(); + info.fee = txp.getEstimatedFee(); + info.amount = _.sum(txp.inputs, 'satoshis') - info.fee; + info.nbInputs = txp.inputs.length; + + return cb(null, info); + }); + }); +}; WalletService.prototype._sampleFeeLevels = function(network, points, cb) { var self = this;