bitcore-wallet-service/bit-wallet/cli-utils.js

94 lines
2.1 KiB
JavaScript
Raw Normal View History

2015-02-15 08:14:36 -08:00
var _ = require('lodash');
var Client = require('../lib/client');
2015-02-15 13:26:05 -08:00
var Utils = function() {};
2015-02-15 08:14:36 -08:00
2015-02-15 13:26:05 -08:00
var die = Utils.die = function(err) {
2015-02-15 08:14:36 -08:00
if (err) {
console.error(err);
process.exit(1);
}
};
2015-02-15 13:26:05 -08:00
Utils.parseMN = function(MN) {
2015-02-19 16:37:13 -08:00
if (!MN)
2015-02-15 08:14:36 -08:00
die('No m-n parameter');
var mn = MN.split('-');
2015-02-19 16:37:13 -08:00
var m = parseInt(mn[0]);
2015-02-15 08:14:36 -08:00
var n = parseInt(mn[1]);
2015-02-19 16:37:13 -08:00
if (!m || !n) {
2015-02-17 22:12:22 -08:00
die('Bad m-n parameter:' + MN);
2015-02-15 08:14:36 -08:00
}
return [m, n];
};
2015-02-15 13:26:05 -08:00
Utils.shortID = function(id) {
2015-02-15 08:14:36 -08:00
return id.substr(id.length - 4);
};
2015-02-17 16:06:11 -08:00
Utils.confirmationId = function(copayer) {
return parseInt(copayer.xPubKeySignature.substr(-4), 16).toString().substr(-4);
}
2015-02-15 13:26:05 -08:00
Utils.getClient = function(args) {
2015-02-15 08:14:36 -08:00
var storage = new Client.FileStorage({
filename: args.config || process.env['BIT_FILE'],
2015-02-15 08:14:36 -08:00
});
return new Client({
storage: storage,
2015-02-17 15:31:03 -08:00
baseUrl: args.host || process.env['BIT_HOST'],
2015-02-15 08:14:36 -08:00
verbose: args.verbose
});
}
2015-02-15 13:26:05 -08:00
Utils.findOneTxProposal = function(txps, id) {
2015-02-15 08:14:36 -08:00
var matches = _.filter(txps, function(tx) {
2015-02-15 13:26:05 -08:00
return _.endsWith(Utils.shortID(tx.id), id);
2015-02-15 08:14:36 -08:00
});
if (!matches.length)
2015-02-15 13:26:05 -08:00
Utils.die('Could not find TX Proposal:' + id);
2015-02-15 08:14:36 -08:00
if (matches.length > 1)
2015-02-15 13:26:05 -08:00
Utils.die('More than one TX Proposals match:' + id + ' : ' + _.map(matches, function(tx) {
2015-02-15 08:14:36 -08:00
return tx.id;
}).join(' '));;
return matches[0];
};
2015-02-19 16:37:13 -08:00
Utils.UNITS = {
'btc': 100000000,
'bit': 100,
'sat': 1,
};
Utils.parseAmount = function(text) {
if (!_.isString(text))
text = text.toString();
var regex = '^(\\d*(\\.\\d{0,8})?)\\s*(' + _.keys(Utils.UNITS).join('|') + ')?$';
var match = new RegExp(regex, 'i').exec(text.trim());
if (!match || match.length === 0) throw new Error('Invalid amount');
var amount = parseFloat(match[1]);
if (!_.isNumber(amount) || _.isNaN(amount)) throw new Error('Invalid amount');
var unit = (match[3] || 'sat').toLowerCase();
var rate = Utils.UNITS[unit];
if (!rate) throw new Error('Invalid unit')
var amountSat = parseFloat((amount * rate).toPrecision(12));
if (amountSat != Math.round(amountSat)) throw new Error('Invalid amount');
return amountSat;
};
2015-02-15 08:14:36 -08:00
2015-02-15 13:26:05 -08:00
module.exports = Utils;