'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.default = undefined;var _slicedToArray = function () {function sliceIterator(arr, i) {var _arr = [];var _n = true;var _d = false;var _e = undefined;try {for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {_arr.push(_s.value);if (i && _arr.length === i) break;}} catch (err) {_d = true;_e = err;} finally {try {if (!_n && _i["return"]) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}return function (arr, i) {if (Array.isArray(arr)) {return arr;} else if (Symbol.iterator in Object(arr)) {return sliceIterator(arr, i);} else {throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}(); // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.

// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity.  If not, see <http://www.gnu.org/licenses/>.

var _signerActions = require('./signerActions');var actions = _interopRequireWildcard(_signerActions);

var _input = require('@parity/api/lib/format/input');

var _hardwareStore = require('../../mobx/hardwareStore');var _hardwareStore2 = _interopRequireDefault(_hardwareStore);
var _signer = require('../../util/signer');
var _qrscan = require('../../util/qrscan');function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _interopRequireWildcard(obj) {if (obj && obj.__esModule) {return obj;} else {var newObj = {};if (obj != null) {for (var key in obj) {if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];}}newObj.default = obj;return newObj;}}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}var

SignerMiddleware = function () {
  function SignerMiddleware(api) {var _this = this;_classCallCheck(this, SignerMiddleware);this.







































































































































    onConfirmStart = function (store, action) {var _action$payload =
      action.payload,condition = _action$payload.condition,_action$payload$gas = _action$payload.gas,gas = _action$payload$gas === undefined ? 0 : _action$payload$gas,_action$payload$gasPr = _action$payload.gasPrice,gasPrice = _action$payload$gasPr === undefined ? 0 : _action$payload$gasPr,id = _action$payload.id,password = _action$payload.password,payload = _action$payload.payload,txSigned = _action$payload.txSigned,dataSigned = _action$payload.dataSigned,decrypted = _action$payload.decrypted,wallet = _action$payload.wallet;
      var handlePromise = _this._createConfirmPromiseHandler(store, id);
      var transaction = payload.sendTransaction || payload.signTransaction;

      if (transaction) {
        var hardwareAccount = _this._hwstore.wallets[transaction.from];

        if (wallet) {
          return _this.confirmWalletTransaction(store, id, transaction, wallet, password);
        } else if (txSigned) {
          return _this.confirmSignedTransaction(store, id, txSigned);
        } else if (hardwareAccount) {
          switch (hardwareAccount.via) {
            case 'ledger':
              return _this.confirmLedgerTransaction(store, id, transaction);

            case 'parity':
            default:
              break;}

        }
      }

      // TODO [ToDr] Support eth_sign for external wallet (wallet && dataSigned)
      if (dataSigned) {
        return _this.confirmSignedData(store, id, dataSigned);
      }
      // TODO [ToDr] Support parity_decrypt for external wallet (wallet && decrypted)
      if (decrypted) {
        return _this.confirmDecryptedMsg(store, id, decrypted);
      }

      return handlePromise(_this._api.signer.confirmRequest(id, { gas: gas, gasPrice: gasPrice, condition: condition }, password));
    };this.

    onRejectStart = function (store, action) {
      var id = action.payload;

      return _this._api.signer.
      rejectRequest(id).
      then(function () {
        store.dispatch(actions.successRejectRequest({ id: id }));
      }).
      catch(function (error) {
        console.error('rejectRequest', id, error);
        store.dispatch(actions.errorRejectRequest({ id: id, err: error.message }));
      });
    };this._api = api;this._hwstore = _hardwareStore2.default.get(api);}_createClass(SignerMiddleware, [{ key: 'toMiddleware', value: function toMiddleware() {var _this2 = this;return function (store) {return function (next) {return function (action) {var delegate = void 0;switch (action.type) {case 'signerStartConfirmRequest':delegate = _this2.onConfirmStart;break;case 'signerStartRejectRequest':delegate = _this2.onRejectStart;break;default:next(action);return;}if (!delegate) {return;}next(action);delegate(store, action);};};};} }, { key: '_createConfirmPromiseHandler', value: function _createConfirmPromiseHandler(store, id) {return function (promise) {return promise.then(function (txHash) {if (!txHash) {store.dispatch(actions.errorConfirmRequest({ id: id, err: 'Unable to confirm.' }));return;}store.dispatch(actions.successConfirmRequest({ id: id, txHash: txHash }));}).catch(function (error) {console.error('confirmRequest', id, error);store.dispatch(actions.errorConfirmRequest({ id: id, err: error.message }));});};} }, { key: 'createNoncePromise', value: function createNoncePromise(transaction) {return !transaction.nonce || transaction.nonce.isZero() ? this._api.parity.nextNonce(transaction.from) : Promise.resolve(transaction.nonce);} }, { key: 'confirmLedgerTransaction', value: function confirmLedgerTransaction(store, id, transaction) {var _this3 = this;return this.createNoncePromise(transaction).then(function (nonce) {transaction.nonce = nonce;return _this3._hwstore.signLedger(transaction);}).then(function (rawTx) {return _this3.confirmRawRequest(store, id, rawTx);});} }, { key: 'confirmRawRequest', value: function confirmRawRequest(store, id, rawData) {var handlePromise = this._createConfirmPromiseHandler(store, id);return handlePromise(this._api.signer.confirmRequestRaw(id, rawData));} }, { key: 'confirmSignedData', value: function confirmSignedData(store, id, dataSigned) {var signature = dataSigned.signature;return this.confirmRawRequest(store, id, signature);} }, { key: 'confirmDecryptedMsg', value: function confirmDecryptedMsg(store, id, decrypted) {var msg = decrypted.msg;return this.confirmRawRequest(store, id, msg);} }, { key: 'confirmSignedTransaction', value: function confirmSignedTransaction(store, id, txSigned) {var netVersion = store.getState().nodeStatus.netVersion;var signature = txSigned.signature,tx = txSigned.tx;var _createSignedTx = (0, _qrscan.createSignedTx)(netVersion, signature, tx),rlp = _createSignedTx.rlp;return this.confirmRawRequest(store, id, rlp);} }, { key: 'confirmWalletTransaction', value: function confirmWalletTransaction(store, id, transaction, wallet, password) {var _this4 = this;var worker = store.getState().worker.worker;var signerPromise = worker && worker._worker.state === 'activated' ? worker.postMessage({ action: 'getSignerSeed', data: { wallet: wallet, password: password } }).then(function (result) {var seed = Buffer.from(result.data);return new _signer.Signer(seed);}) : _signer.Signer.fromJson(wallet, password); // NOTE: Derving the key takes significant amount of time,
      // make sure to display some kind of "in-progress" state.
      return Promise.all([signerPromise, this.createNoncePromise(transaction)]).then(function (_ref) {var _ref2 = _slicedToArray(_ref, 2),signer = _ref2[0],nonce = _ref2[1];var txData = { to: (0, _input.inHex)(transaction.to), nonce: (0, _input.inHex)(transaction.nonce.isZero() ? nonce : transaction.nonce), gasPrice: (0, _input.inHex)(transaction.gasPrice), gasLimit: (0, _input.inHex)(transaction.gas), value: (0, _input.inHex)(transaction.value), data: (0, _input.inHex)(transaction.data) };return signer.signTransaction(txData);}).then(function (rawTx) {return _this4.confirmRawRequest(store, id, rawTx);}).catch(function (error) {console.error(error.message);store.dispatch(actions.errorConfirmRequest({ id: id, err: error.message }));});} }]);return SignerMiddleware;}();exports.default = SignerMiddleware;