diff --git a/public/dashwallet.js b/public/dashwallet.js new file mode 100644 index 0000000..b7fe895 --- /dev/null +++ b/public/dashwallet.js @@ -0,0 +1,79 @@ +var DashWallet = ('object' === typeof module && exports) || {}; +(function (window, DashWallet) { + 'use strict'; + + let DashTx = window.DashTx; + + /** + * @template {Pick} T + * @param {Array} utxos + * @param {Number} output - including fee estimate + * @return {Array} + */ + DashWallet.selectOptimalUtxos = function (utxos, satsOut) { + let balance = DashTx.sum(utxos); + let fees = DashTx.appraise({ + //@ts-ignore + inputs: [{}], + outputs: [{}], + }); + + let fullSats = satsOut + fees.min; + + if (balance < fullSats) { + return []; + } + + // from largest to smallest + utxos.sort(function (a, b) { + return b.satoshis - a.satoshis; + }); + + /** @type Array */ + let included = []; + let total = 0; + + // try to get just one + utxos.every(function (utxo) { + if (utxo.satoshis > fullSats) { + included[0] = utxo; + total = utxo.satoshis; + return true; + } + return false; + }); + if (total) { + return included; + } + + // try to use as few coins as possible + utxos.some(function (utxo, i) { + included.push(utxo); + total += utxo.satoshis; + if (total >= fullSats) { + return true; + } + + // it quickly becomes astronomically unlikely to hit the one + // exact possibility that least to paying the absolute minimum, + // but remains about 75% likely to hit any of the mid value + // possibilities + if (i < 2) { + // 1 input 25% chance of minimum (needs ~2 tries) + // 2 inputs 6.25% chance of minimum (needs ~8 tries) + fullSats = fullSats + DashTx.MIN_INPUT_SIZE; + return false; + } + // but by 3 inputs... 1.56% chance of minimum (needs ~32 tries) + // by 10 inputs... 0.00953674316% chance (needs ~524288 tries) + fullSats = fullSats + DashTx.MIN_INPUT_SIZE + 1; + }); + return included; + }; + + //@ts-ignore + window.DashWallet = DashWallet; +})(globalThis.window || {}, DashWallet); +if ('object' === typeof module) { + module.exports = DashWallet; +} diff --git a/public/index.html b/public/index.html index b4f84be..9c46934 100644 --- a/public/index.html +++ b/public/index.html @@ -11,6 +11,7 @@ +