<commit_before>'use strict';

angular.module('copayApp.directives')
  .directive('validAddress', ['$rootScope',
    function($rootScope) {

      var bitcore = require('bitcore');
      var Address = bitcore.Address;
      var bignum = bitcore.Bignum;

      return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
          var validator = function(value) {
            var uri = copay.HDPath.parseBitcoinURI(value);

            // Is this a payment protocol URI (BIP-72)?
            if (uri && uri.merchant) {
              scope.wallet.fetchPaymentTx(uri.merchant, function(err, merchantData) {
                var balance = $rootScope.availableBalance;
                var available = +(balance * config.unitToSatoshi).toFixed(0);

                if ((err && err.message === 'No unspent outputs.')
                    || available < +merchantData.total) {
                  // TODO: Actually display a notification window here
                  // instead of simply saying the URI is invalid.
                  ctrl.$setValidity('validAddress', false);
                  return;
                }

                if (err) {
                  if (scope._resetPayPro) scope._resetPayPro();
                  ctrl.$setValidity('validAddress', false);
                  return;
                }

                var expires = new Date(merchantData.pr.pd.expires * 1000);
                var memo = merchantData.pr.pd.memo;
                var payment_url = merchantData.pr.pd.payment_url;
                var total = merchantData.total;

                if (typeof total === 'string') {
                  total = bignum(total, 10).toBuffer({
                    endian: 'little',
                    size: 1
                  });
                }

                total = bignum
                  .fromBuffer(total, {
                    endian: 'little',
                    size: 1
                  })
                  .toString(10);

                // XXX There needs to be a better way to do this:
                total = +total / config.unitToSatoshi;

                // XXX Pretty much all of this code accesses the raw DOM. It's
                // very bad, there's probably a better, more angular-y way to
                // do things here.

                var address = angular.element(
                  document.querySelector('input#address'));

                var amount = angular.element(
                  document.querySelector('input#amount'));
                amount.val(total);
                if (+merchantData.total !== 0) {
                  amount.attr('disabled', true);
                }

                var sendto = angular.element(document
                  .querySelector('div.send-note > p[ng-class]:first-of-type'));
                sendto.html(sendto.html() + '<br><b>Server:</b> ' + memo);

                var tamount = angular.element(document
                  .querySelector('div.send-note > p[ng-class]:nth-of-type(2)'));
                var ca = merchantData.pr.ca
                  || '<span style="color:red;">Untrusted</span>';
                tamount.attr('class',
                  tamount.attr('class').replace(' hidden', ''))
                tamount.html(total + ' (CA: ' + ca
                  + '. Expires: '
                  + expires.toISOString()
                  + ')');

                var submit = angular.element(
                  document.querySelector('button[type=submit]'));
                submit.attr('disabled', false);

                var sendall = angular.element(
                  document.querySelector('[title="Send all funds"]'));
                sendall.attr('class', sendall.attr('class') + ' hidden');

                // Reset all the changes from the payment protocol weirdness.
                // XXX Bad hook. Find a better more angular-y way of doing this.
                // This will also closure scope every variable above forever.
                if (!scope._resetPayPro) {
                  scope._resetPayPro = function() {
                    var val = address.val();
                    var uri = copay.HDPath.parseBitcoinURI(val || '');
                    if (!uri || !uri.merchant) {
                      if (amount.attr('disabled')) {
                        amount.val('');
                        amount.attr('disabled', false);
                      }
                      sendto.html(sendto.html().replace(/<br><b>Server:.*$/, ''));
                      if (!/hidden/.test(tamount.attr('class'))) {
                        tamount.attr(tamount.attr('class') + ' hidden');
                      }
                      if (~tamount.html().indexOf('(CA: ')) {
                        tamount.html('');
                      }
                      if (!submit.attr('disabled')) {
                        submit.attr('disabled', true);
                      }
                      if (/ hidden$/.test(sendall.attr('class'))) {
                        sendall.attr('class',
                          sendall.attr('class').replace(' hidden', ''));
                      }
                    }
                    // TODO: Check paymentRequest expiration,
                    // delete if beyond expiration date.
                  };
                  scope.$watch('address',scope._resetPayPro);
                }

                ctrl.$setValidity('validAddress', true);

                // XXX With PayPro, since amount is already filled in among
                // other field oddities, the form is always invalid. Make it
                // valid.
                scope.sendForm.$valid = true;
                scope.sendForm.$invalid = false;
                scope.sendForm.$pristine = true;

                scope.sendForm.address.$valid = true;
                scope.sendForm.address.$invalid = false;
                scope.sendForm.address.$pristine = true;

                scope.sendForm.amount.$valid = true;
                scope.sendForm.amount.$invalid = false;
                scope.sendForm.amount.$pristine = true;
              });

              ctrl.$setValidity('validAddress', true);

              return 'Merchant: '+ uri.merchant;
            }

            var a = new Address(value);
            ctrl.$setValidity('validAddress', a.isValid() && a.network().name === config.networkName);
            return value;
          };

          ctrl.$parsers.unshift(validator);
          ctrl.$formatters.unshift(validator);
        }
      };
    }
  ])
  .directive('enoughAmount', ['$rootScope',
    function($rootScope) {
      var bitcore = require('bitcore');
      var feeSat = Number(bitcore.TransactionBuilder.FEE_PER_1000B_SAT);
      return {
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
          var val = function(value) {
            var availableBalanceNum = Number(($rootScope.availableBalance * config.unitToSatoshi).toFixed(0));
            var vNum = Number((value * config.unitToSatoshi).toFixed(0)) + feeSat;
            if (typeof vNum == "number" && vNum > 0) {
              if (availableBalanceNum < vNum) {
                ctrl.$setValidity('enoughAmount', false);
                scope.notEnoughAmount = true;
              } else {
                ctrl.$setValidity('enoughAmount', true);
                scope.notEnoughAmount = null;
              }
            } else {
              scope.notEnoughAmount = null;
            }<commit_msg>paypro: minor refactor - clean up whitespace in directives.<commit_after>'use strict';

angular.module('copayApp.directives')
  .directive('validAddress', ['$rootScope',
    function($rootScope) {

      var bitcore = require('bitcore');
      var Address = bitcore.Address;
      var bignum = bitcore.Bignum;

      return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
          var validator = function(value) {
            var uri;

            if (/^https?:\/\//.test(value)) {
              uri = { merchant: value };
            } else {
              uri = copay.HDPath.parseBitcoinURI(value);
            }

            // Regular Address
            if (!uri || !uri.merchant) {
              var a = new Address(value);
              ctrl.$setValidity('validAddress', a.isValid() && a.network().name === config.networkName);
              return value;
            }

            // Payment Protocol URI (BIP-72)
            scope.wallet.fetchPaymentTx(uri.merchant, function(err, merchantData) {
              var balance = $rootScope.availableBalance;
              var available = +(balance * config.unitToSatoshi).toFixed(0);

              if ((err && err.message === 'No unspent outputs.')
                  || available < +merchantData.total) {
                // TODO: Actually display a notification window here
                // instead of simply saying the URI is invalid.
                ctrl.$setValidity('validAddress', false);
                return;
              }

              if (err) {
                if (scope._resetPayPro) scope._resetPayPro();
                ctrl.$setValidity('validAddress', false);
                return;
              }

              var expires = new Date(merchantData.pr.pd.expires * 1000);
              var memo = merchantData.pr.pd.memo;
              var payment_url = merchantData.pr.pd.payment_url;
              var total = merchantData.total;

              if (typeof total === 'string') {
                total = bignum(total, 10).toBuffer({
                  endian: 'little',
                  size: 1
                });
              }

              total = bignum
                .fromBuffer(total, {
                  endian: 'little',
                  size: 1
                })
                .toString(10);

              // XXX There needs to be a better way to do this:
              total = +total / config.unitToSatoshi;

              // XXX Pretty much all of this code accesses the raw DOM. It's
              // very bad, there's probably a better, more angular-y way to
              // do things here.

              var address = angular.element(
                document.querySelector('input#address'));

              var amount = angular.element(
                document.querySelector('input#amount'));
              amount.val(total);
              if (+merchantData.total !== 0) {
                amount.attr('disabled', true);
              }

              var sendto = angular.element(document
                .querySelector('div.send-note > p[ng-class]:first-of-type'));
              sendto.html(sendto.html() + '<br><b>Server:</b> ' + memo);

              var tamount = angular.element(document
                .querySelector('div.send-note > p[ng-class]:nth-of-type(2)'));
              var ca = merchantData.pr.ca
                || '<span style="color:red;">Untrusted</span>';
              tamount.attr('class',
                tamount.attr('class').replace(' hidden', ''))
              tamount.html(total + ' (CA: ' + ca
                + '. Expires: '
                + expires.toISOString()
                + ')');

              var submit = angular.element(
                document.querySelector('button[type=submit]'));
              submit.attr('disabled', false);

              var sendall = angular.element(
                document.querySelector('[title="Send all funds"]'));
              sendall.attr('class', sendall.attr('class') + ' hidden');

              // Reset all the changes from the payment protocol weirdness.
              // XXX Bad hook. Find a better more angular-y way of doing this.
              // This will also closure scope every variable above forever.
              if (!scope._resetPayPro) {
                scope._resetPayPro = function() {
                  var val = address.val();
                  var uri = copay.HDPath.parseBitcoinURI(val || '');
                  if (!uri || !uri.merchant) {
                    if (amount.attr('disabled')) {
                      amount.val('');
                      amount.attr('disabled', false);
                    }
                    sendto.html(sendto.html().replace(/<br><b>Server:.*$/, ''));
                    if (!/hidden/.test(tamount.attr('class'))) {
                      tamount.attr(tamount.attr('class') + ' hidden');
                    }
                    if (~tamount.html().indexOf('(CA: ')) {
                      tamount.html('');
                    }
                    if (!submit.attr('disabled')) {
                      submit.attr('disabled', true);
                    }
                    if (/ hidden$/.test(sendall.attr('class'))) {
                      sendall.attr('class',
                        sendall.attr('class').replace(' hidden', ''));
                    }
                  }
                  // TODO: Check paymentRequest expiration,
                  // delete if beyond expiration date.
                };
                scope.$watch('address',scope._resetPayPro);
              }

              ctrl.$setValidity('validAddress', true);

              // XXX With PayPro, since amount is already filled in among
              // other field oddities, the form is always invalid. Make it
              // valid.
              scope.sendForm.$valid = true;
              scope.sendForm.$invalid = false;
              scope.sendForm.$pristine = true;

              scope.sendForm.address.$valid = true;
              scope.sendForm.address.$invalid = false;
              scope.sendForm.address.$pristine = true;

              scope.sendForm.amount.$valid = true;
              scope.sendForm.amount.$invalid = false;
              scope.sendForm.amount.$pristine = true;
            });

            ctrl.$setValidity('validAddress', true);

            return 'Merchant: '+ uri.merchant;
          };

          ctrl.$parsers.unshift(validator);
          ctrl.$formatters.unshift(validator);
        }
      };
    }
  ])
  .directive('enoughAmount', ['$rootScope',
    function($rootScope) {
      var bitcore = require('bitcore');
      var feeSat = Number(bitcore.TransactionBuilder.FEE_PER_1000B_SAT);
      return {
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
          var val = function(value) {
            var availableBalanceNum = Number(($rootScope.availableBalance * config.unitToSatoshi).toFixed(0));
            var vNum = Number((value * config.unitToSatoshi).toFixed(0)) + feeSat;
            if (typeof vNum == "number" && vNum > 0) {
              if (availableBalanceNum < vNum) {
                ctrl.$setValidity('enoughAmount', false);
                scope.notEnoughAmount = true;
              } else {
                ctrl.$setValidity('enoughAmount', true);
                scope.notEnoughAmount = null;
              }
            } else {
              scope.notEnoughAmount = null;
            }
{'fraction_non_alphanumeric': 0.12220286747956585, 'fraction_numerical': 0.0029478761892000535, 'mean_word_length': 1.38032211768458, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1151556', 'n_tokens_mistral': 3891, 'n_tokens_neox': 3622, 'n_words': 799}