diff --git a/js/coin.js b/js/coin.js index 1ba2682..c979a4a 100644 --- a/js/coin.js +++ b/js/coin.js @@ -746,9 +746,41 @@ r.parse(); return r; } + + coinjs.cpmareUnspents = function( unspent1, unspent2){ + return ( unspent1.amount - unspent2.amount); + } + + coinjs.partition = function(arr, start, end, compare){ + const pivot = arr[end]; + let pIndex = start; + for (let i = start; i < end; i++) { + if (compare(arr[i] , pivot) < 0 ) { + // Swap + [arr[i], arr[pIndex]] = [arr[pIndex], arr[i]]; + pIndex++; + } + } + + [arr[pIndex], arr[end]] = [arr[end], arr[pIndex]] + return pIndex; +}; + +coinjs.qSort = function(arr, start, end, compare) { + // terminating condition + if (start >= end) { + return; + } + let index = partition(arr, start, end, compare); + + // Recursively apply the same logic to the left and right subarrays + qSort(arr, start, index - 1, compare); + qSort(arr, index + 1, end, compare); +} - /* start of transaction functions */ + /* start of transaction functions */ + /* create a new transaction object */ coinjs.transaction = function() { @@ -841,7 +873,7 @@ } /* add unspent to transaction */ - r.addUnspent = function(address, callback, script, sequence){ + r.addUnspent = function(address, amount, callback, script, sequence){ var self = this; this.listUnspent(address, function(data){ @@ -852,9 +884,9 @@ var x = {}; var unspent = JSON.parse(data); - console.log("Unspent is"+unspent); - - for(i=0;i<=unspent.length-1;i++){ + console.log("Unspent is:"+unspent); + //qSort(unspent, 0, unspent.length, compareUnspents); + for(i=0;i<=unspent.length-1 && value < amount;i++){ var txhash = unspent[i].txid, n = unspent[i].vout, scr = unspent[i].scriptPubKey, @@ -874,10 +906,10 @@ } /* add unspent and sign */ - r.addUnspentAndSign = function(wif, callback){ + r.addUnspentAndSign = function(wif, amount, callback){ var self = this; var address = coinjs.wif2address(wif); - self.addUnspent(address['address'], function(data){ + self.addUnspent(address['address'], amount, function(data){ self.sign(wif); return callback(data); }); diff --git a/js/coinbin.js b/js/coinbin.js index 99d3f06..286f765 100644 --- a/js/coinbin.js +++ b/js/coinbin.js @@ -118,7 +118,7 @@ console.log("Finished wallet spend"); var sequence = false; - tx.addUnspent($("#walletAddress").html(), function(data){ + tx.addUnspent($("#walletAddress").html(), total, function(data){ console.log("Going into tx.addUnspent"+data.value); var dvalue = (data.value).toFixed(8) * 1;