Wallet/src/js/controllers/amount.js

489 lines
14 KiB
JavaScript
Raw Normal View History

2016-07-07 16:55:04 -03:00
'use strict';
2017-03-27 16:59:01 -03:00
angular.module('copayApp.controllers').controller('amountController', function($scope, $filter, $timeout, $ionicScrollDelegate, $ionicHistory, gettextCatalog, platformInfo, lodash, configService, rateService, $stateParams, $window, $state, $log, txFormatService, ongoingProcess, popupService, bwcError, payproService, profileService, bitcore, amazonService, nodeWebkitService) {
2017-12-12 17:15:39 +09:00
2017-08-31 17:56:28 -03:00
var _id;
var unitToSatoshi;
var satToUnit;
var unitDecimals;
var satToBtc;
var SMALL_FONT_SIZE_LIMIT = 10;
var LENGTH_EXPRESSION_LIMIT = 19;
var isNW = platformInfo.isNW;
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
var unitIndex = 0;
var altUnitIndex = 0;
var availableUnits = [];
var fiatCode;
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
var fixedUnit;
2017-08-29 10:52:26 -03:00
$scope.amountModel = { amount: 0 };
2017-08-31 17:56:28 -03:00
$scope.isChromeApp = platformInfo.isChromeApp;
$scope.isAndroid = platformInfo.isAndroid;
$scope.isIos = platformInfo.isIOS;
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
$scope.$on('$ionicView.leave', function() {
angular.element($window).off('keydown');
});
2017-08-29 12:45:10 -03:00
2017-08-31 17:56:28 -03:00
$scope.$on("$ionicView.beforeEnter", function(event, data) {
2017-12-12 17:15:39 +09:00
if (data.stateParams.shapeshiftOrderId && data.stateParams.shapeshiftOrderId.length > 0) {
2017-12-12 17:15:39 +09:00
$scope.minShapeshiftAmount = parseFloat(data.stateParams.minShapeshiftAmount);
$scope.maxShapeshiftAmount = parseFloat(data.stateParams.maxShapeshiftAmount);
2017-12-14 17:56:47 +09:00
$scope.shapeshiftOrderId = data.stateParams.shapeshiftOrderId;
$scope.fromWalletId = data.stateParams.fromWalletId;
2017-12-12 17:15:39 +09:00
}
if (data.stateParams.noPrefix) {
$scope.showWarningMessage = data.stateParams.noPrefix != 0;
}
2017-08-31 17:56:28 -03:00
var config = configService.getSync().wallet.settings;
2017-08-31 17:13:54 -03:00
2017-08-31 17:56:28 -03:00
function setAvailableUnits() {
var defaults = configService.getDefaults();
var configCache = configService.getSync();
2017-08-31 17:56:28 -03:00
availableUnits = [];
2017-08-31 17:13:54 -03:00
2017-08-31 17:56:28 -03:00
var hasBCHWallets = profileService.getWallets({
coin: 'bch'
}).length;
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
if (hasBCHWallets) {
availableUnits.push({
name: 'Bitcoin Cash',
id: 'bch',
shortName: (configCache.bitcoinCashAlias || defaults.bitcoinCashAlias).toUpperCase(),
2017-08-31 17:56:28 -03:00
});
};
2017-11-15 18:24:48 +09:00
var hasBTCWallets = profileService.getWallets({
coin: 'btc'
}).length;
if (hasBTCWallets) {
availableUnits.push({
name: 'Bitcoin',
id: 'btc',
shortName: (configCache.bitcoinAlias || defaults.bitcoinAlias).toUpperCase(),
});
}
2017-08-31 17:56:28 -03:00
unitIndex = 0;
if (data.stateParams.coin) {
var coins = data.stateParams.coin.split(',');
var newAvailableUnits = [];
lodash.each(coins, function(c) {
var coin = lodash.find(availableUnits, {
id: c
});
if (!coin) {
$log.warn('Could not find desired coin:' + data.stateParams.coin)
} else {
newAvailableUnits.push(coin);
}
2017-08-31 17:13:54 -03:00
});
2017-08-31 17:56:28 -03:00
if (newAvailableUnits.length > 0) {
availableUnits = newAvailableUnits;
2017-08-31 17:13:54 -03:00
}
2017-08-31 17:56:28 -03:00
}
// currency have preference
var fiatName;
if (data.stateParams.currency) {
fiatCode = data.stateParams.currency;
altUnitIndex = unitIndex
unitIndex = availableUnits.length;
} else {
fiatCode = config.alternativeIsoCode || 'USD';
fiatName = config.alternanativeName || fiatCode;
altUnitIndex = availableUnits.length;
}
availableUnits.push({
name: fiatName || fiatCode,
// TODO
id: fiatCode,
shortName: fiatCode,
isFiat: true,
});
if (data.stateParams.fixedUnit) {
fixedUnit = true;
}
unitIndex = lodash.findIndex(availableUnits, {
isFiat: true
});
altUnitIndex = 0;
2017-08-31 17:13:54 -03:00
};
2017-08-31 17:56:28 -03:00
// Go to...
_id = data.stateParams.id; // Optional (BitPay Card ID or Wallet ID)
$scope.nextStep = data.stateParams.nextStep;
setAvailableUnits();
updateUnitUI();
$scope.hasMaxAmount = true;
if ($ionicHistory.backView().stateName == 'tabs.receive') {
$scope.hasMaxAmount = false;
}
2017-08-31 17:56:28 -03:00
$scope.showMenu = $ionicHistory.backView() && ($ionicHistory.backView().stateName == 'tabs.send' || $ionicHistory.backView().stateName == 'tabs.bitpayCard');
$scope.recipientType = data.stateParams.recipientType || null;
$scope.toAddress = data.stateParams.toAddress;
$scope.displayAddress = data.stateParams.displayAddress;
2017-08-31 17:56:28 -03:00
$scope.toName = data.stateParams.toName;
$scope.toEmail = data.stateParams.toEmail;
$scope.toColor = data.stateParams.toColor;
if (!$scope.nextStep && !data.stateParams.toAddress) {
$log.error('Bad params at amount')
throw ('bad params');
}
var reNr = /^[1234567890\.]$/;
var reOp = /^[\*\+\-\/]$/;
if (!$scope.isAndroid && !$scope.isIos) {
var disableKeys = angular.element($window).on('keydown', function(e) {
if (!e.key) return;
if (e.which === 8) { // you can add others here inside brackets.
e.preventDefault();
$scope.removeDigit();
}
2017-08-31 17:56:28 -03:00
if (e.key.match(reNr)) {
$scope.pushDigit(e.key);
} else if (e.key.match(reOp)) {
$scope.pushOperator(e.key);
} else if (e.keyCode === 86) {
if (e.ctrlKey || e.metaKey) processClipboard();
} else if (e.keyCode === 13) $scope.finish();
2017-08-31 17:56:28 -03:00
$timeout(function() {
$scope.$apply();
});
2017-08-31 17:56:28 -03:00
});
}
2017-08-31 17:56:28 -03:00
$scope.specificAmount = $scope.specificAlternativeAmount = '';
$scope.isCordova = platformInfo.isCordova;
unitToSatoshi = config.unitToSatoshi;
satToUnit = 1 / unitToSatoshi;
satToBtc = 1 / 100000000;
unitDecimals = config.unitDecimals;
$scope.resetAmount();
// in SAT ALWAYS
if ($stateParams.toAmount) {
$scope.amountModel.amount = (($stateParams.toAmount) * satToUnit).toFixed(unitDecimals);
2017-08-31 17:56:28 -03:00
}
$scope.processAmount();
2017-08-31 17:56:28 -03:00
$timeout(function() {
$ionicScrollDelegate.resize();
}, 10);
});
2017-12-14 17:56:47 +09:00
$scope.goBack = function() {
if ($scope.shapeshiftOrderId) {
$state.go('tabs.send').then(function() {
$ionicHistory.clearHistory();
$state.go('tabs.home').then(function() {
$state.transitionTo('tabs.shapeshift');
});
});
} else {
$ionicHistory.goBack();
}
}
2017-08-31 17:56:28 -03:00
function paste(value) {
$scope.amountModel.amount = value;
$scope.processAmount();
2017-08-31 17:56:28 -03:00
$timeout(function() {
$scope.$apply();
});
};
2016-11-03 17:53:32 -03:00
2017-08-31 17:56:28 -03:00
function processClipboard() {
if (!isNW) return;
var value = nodeWebkitService.readFromClipboard();
if (value && evaluate(value) > 0) paste(evaluate(value));
};
2016-11-03 17:53:32 -03:00
2017-08-31 17:56:28 -03:00
$scope.sendMax = function() {
$scope.useSendMax = true;
$scope.finish();
};
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
$scope.toggleAlternative = function() {
if ($scope.amountModel.amount && isExpression($scope.amountModel.amount)) {
var amount = evaluate(format($scope.amountModel.amount));
2017-08-31 17:56:28 -03:00
$scope.globalResult = '= ' + processResult(amount);
}
};
2016-07-07 16:55:04 -03:00
2017-08-31 17:56:28 -03:00
function updateUnitUI() {
$scope.unit = availableUnits[unitIndex].shortName;
$scope.alternativeUnit = availableUnits[altUnitIndex].shortName;
2017-08-29 10:52:26 -03:00
$scope.processAmount();
2017-08-31 17:56:28 -03:00
$log.debug('Update unit coin @amount unit:' + $scope.unit + " alternativeUnit:" + $scope.alternativeUnit);
};
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
$scope.changeUnit = function() {
if ($scope.alternativeAmount == 0) {
$scope.alternativeAmount = null;
}
2017-08-31 17:56:28 -03:00
if (fixedUnit) return;
2017-08-29 10:52:26 -03:00
if (!(availableUnits[unitIndex].isFiat && availableUnits.length > 2 && altUnitIndex == 0)) {
unitIndex++;
if (unitIndex >= availableUnits.length) unitIndex = 0;
}
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
if (availableUnits[unitIndex].isFiat) {
altUnitIndex = altUnitIndex == 0 && availableUnits.length > 2 ? 1 : 0;
2017-08-31 17:56:28 -03:00
} else {
altUnitIndex = lodash.findIndex(availableUnits, {
isFiat: true
});
}
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
updateUnitUI();
};
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
$scope.changeAlternativeUnit = function() {
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
// Do nothing is fiat is not main unit
if (!availableUnits[unitIndex].isFiat) return;
2017-08-29 10:52:26 -03:00
2017-08-31 17:56:28 -03:00
var nextCoin = lodash.findIndex(availableUnits, function(x) {
if (x.isFiat) return false;
if (x.id == availableUnits[altUnitIndex].id) return false;
return true;
});
2017-08-31 17:56:28 -03:00
if (nextCoin >= 0) {
altUnitIndex = nextCoin;
updateUnitUI();
}
};
function checkFontSize() {
if ($scope.amountModel.amount && $scope.amountModel.amount.length >= SMALL_FONT_SIZE_LIMIT) $scope.smallFont = true;
2017-08-31 17:56:28 -03:00
else $scope.smallFont = false;
};
$scope.pushDigit = function(digit) {
if ($scope.amountModel.amount && $scope.amountModel.amount.length >= LENGTH_EXPRESSION_LIMIT) return;
if (!$scope.isAndroid && !$scope.isIos && $scope.amountModel.amount.indexOf('.') > -1 && digit == '.') return;
if (availableUnits[unitIndex].isFiat && $scope.amountModel.amount.indexOf('.') > -1 && $scope.amountModel.amount[$scope.amountModel.amount.indexOf('.') + 2]) return;
2017-08-31 17:56:28 -03:00
$scope.amountModel.amount = ($scope.amountModel.amount + digit).replace('..', '.');
2017-08-31 17:56:28 -03:00
checkFontSize();
$scope.processAmount();
2017-08-31 17:56:28 -03:00
};
$scope.pushOperator = function(operator) {
if (!$scope.amountModel.amount || $scope.amountModel.amount.length == 0) return;
$scope.amountModel.amount = _pushOperator($scope.amountModel.amount);
2017-08-31 17:56:28 -03:00
function _pushOperator(val) {
if (!isOperator(lodash.last(val))) {
return val + operator;
} else {
return val.slice(0, -1) + operator;
}
2016-07-07 16:55:04 -03:00
};
2017-08-31 17:56:28 -03:00
};
function isOperator(val) {
var regex = /[\/\-\+\x\*]/;
return regex.test(val);
};
function isExpression(val) {
var regex = /^\.?\d+(\.?\d+)?([\/\-\+\*x]\d?\.?\d+)+$/;
return regex.test(val);
};
$scope.removeDigit = function() {
$scope.amountModel.amount = ($scope.amountModel.amount).toString().slice(0, -1);
$scope.processAmount();
2017-08-31 17:56:28 -03:00
checkFontSize();
};
$scope.resetAmount = function() {
$scope.amountModel.amount = $scope.alternativeAmount = $scope.globalResult = '';
2017-08-31 17:56:28 -03:00
$scope.allowSend = false;
checkFontSize();
};
$scope.processAmount = function() {
var formatedValue = format($scope.amountModel.amount);
2017-08-31 17:56:28 -03:00
var result = evaluate(formatedValue);
2017-12-12 17:15:39 +09:00
2017-08-31 17:56:28 -03:00
if (lodash.isNumber(result)) {
$scope.globalResult = isExpression($scope.amountModel.amount) ? '= ' + processResult(result) : '';
2017-08-31 17:56:28 -03:00
if (availableUnits[unitIndex].isFiat) {
2017-08-31 18:16:50 -03:00
var a = fromFiat(result);
if (a) {
$scope.alternativeAmount = txFormatService.formatAmount(a * unitToSatoshi, true);
2018-02-19 20:12:37 +05:30
$scope.allowSend = lodash.isNumber(a) && a > 0
&& (!$scope.shapeshiftOrderId
|| (a >= $scope.minShapeshiftAmount && a <= $scope.maxShapeshiftAmount));
2017-08-31 18:16:50 -03:00
} else {
if (result) {
$scope.alternativeAmount = 'N/A';
} else {
$scope.alternativeAmount = null;
}
2017-08-31 18:16:50 -03:00
$scope.allowSend = false;
}
2017-08-31 17:56:28 -03:00
} else {
$scope.alternativeAmount = $filter('formatFiatAmount')(toFiat(result));
2018-02-19 20:12:37 +05:30
$scope.allowSend = lodash.isNumber(result) && result > 0
&& (!$scope.shapeshiftOrderId
|| (result >= $scope.minShapeshiftAmount && result <= $scope.maxShapeshiftAmount));
2017-08-31 17:56:28 -03:00
}
}
};
function processResult(val) {
if (availableUnits[unitIndex].isFiat) return $filter('formatFiatAmount')(val);
else return txFormatService.formatAmount(val.toFixed(unitDecimals) * unitToSatoshi, true);
};
function fromFiat(val) {
return parseFloat((rateService.fromFiat(val, fiatCode, availableUnits[altUnitIndex].id) * satToUnit).toFixed(unitDecimals));
};
function toFiat(val) {
2017-08-31 18:16:50 -03:00
if (!rateService.getRate(fiatCode)) return;
2017-08-31 17:56:28 -03:00
return parseFloat((rateService.toFiat(val * unitToSatoshi, fiatCode, availableUnits[unitIndex].id)).toFixed(2));
};
function evaluate(val) {
var result;
try {
result = $scope.$eval(val);
} catch (e) {
return 0;
}
if (!lodash.isFinite(result)) return 0;
return result;
};
function format(val) {
if (!val) return;
var result = val.toString();
if (isOperator(lodash.last(val))) result = result.slice(0, -1);
return result.replace('x', '*');
};
$scope.finish = function() {
function finish() {
var unit = availableUnits[unitIndex];
var _amount = evaluate(format($scope.amountModel.amount));
var coin = unit.id;
2017-08-31 17:56:28 -03:00
if (unit.isFiat) {
coin = availableUnits[altUnitIndex].id;
2017-08-31 17:56:28 -03:00
}
if ($scope.nextStep) {
$state.transitionTo($scope.nextStep, {
id: _id,
amount: $scope.useSendMax ? null : _amount,
currency: unit.id.toUpperCase(),
coin: coin,
useSendMax: $scope.useSendMax
});
} else {
var amount = _amount;
if (unit.isFiat) {
amount = (fromFiat(amount) * unitToSatoshi).toFixed(0);
} else {
amount = (amount * unitToSatoshi).toFixed(0);
}
var confirmData = {
recipientType: $scope.recipientType,
toAmount: amount,
toAddress: $scope.toAddress,
displayAddress: $scope.displayAddress || $scope.toAddress,
toName: $scope.toName,
toEmail: $scope.toEmail,
toColor: $scope.toColor,
coin: coin,
useSendMax: $scope.useSendMax,
};
if ($scope.shapeshiftOrderId) {
var shapeshiftOrderUrl = 'https://www.shapeshift.io/#/status/';
shapeshiftOrderUrl += $scope.shapeshiftOrderId;
confirmData.description = shapeshiftOrderUrl;
confirmData.fromWalletId = $scope.fromWalletId;
if (confirmData.useSendMax) {
var wallet = lodash.find(profileService.getWallets({ coin: coin }),
function(w) {
return w.id == $scope.fromWalletId;
});
var balance = parseFloat(wallet.cachedBalance.substring(0, wallet.cachedBalance.length-4));
if (balance < $scope.minShapeshiftAmount * 1.04) {
confirmData.useSendMax = false;
confirmData.toAmount = $scope.minShapeshiftAmount * unitToSatoshi;
} else if (balance > $scope.maxShapeshiftAmount) {
confirmData.useSendMax = false;
confirmData.toAmount = $scope.maxShapeshiftAmount * unitToSatoshi * 0.99;
}
}
}
$state.transitionTo('tabs.send.confirm', confirmData);
}
$scope.useSendMax = null;
}
if ($scope.showWarningMessage) {
var u = $scope.unit == 'BCH' || $scope.unit == 'BTC' ? $scope.unit : $scope.alternativeUnit;
var message = 'Are you sure you want to send ' + u.toUpperCase() + '?';
2018-02-04 10:37:53 -04:00
popupService.showConfirm(message, '', 'Yes', 'No', function(res) {
if (!res) {
$scope.useSendMax = null;
return;
};
finish();
});
} else {
finish();
2017-08-31 17:56:28 -03:00
}
2017-08-31 17:56:28 -03:00
};
2016-07-09 15:36:49 -03:00
});