'use strict';Object.defineProperty(exports, "__esModule", { value: true });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 _extends = Object.assign || function (target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i];for (var key in source) {if (Object.prototype.hasOwnProperty.call(source, key)) {target[key] = source[key];}}}return target;}; // 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/>.
exports.












getSender = getSender;exports.



loadSender = loadSender;exports.














setSender = setSender;exports.




trackRequest = trackRequest;exports.






















getTxOptions = getTxOptions;exports.
















































estimateGas = estimateGas;exports.








postTransaction = postTransaction;exports.








deployEstimateGas = deployEstimateGas;exports.
























deploy = deploy;exports.































parseTransactionReceipt = parseTransactionReceipt;exports.








































patchApi = patchApi;exports.






patchContract = patchContract;exports.











checkIfTxFailed = checkIfTxFailed;exports.











waitForConfirmations = waitForConfirmations;var _bignumber = require('bignumber.js');var _bignumber2 = _interopRequireDefault(_bignumber);var _wallets = require('./wallets');var _wallets2 = _interopRequireDefault(_wallets);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };} /**
                                                                                                                                                                                                                                                                                                                              * The sender is by default (when the UI loads) the
                                                                                                                                                                                                                                                                                                                              * default dapp address. It can then be modified when
                                                                                                                                                                                                                                                                                                                              * sending transactions....
                                                                                                                                                                                                                                                                                                                              */var currentSender = '';var hasCurrentSenderChanged = false;function getSender() {return currentSender;}function loadSender(api) {// If the current sender has been changed
  // then don't bother checking changes of the
  // default sender
  if (hasCurrentSenderChanged) {return Promise.resolve(currentSender);}return api.parity.getNewDappsDefaultAddress().then(function (defaultAccount) {currentSender = defaultAccount;return defaultAccount;});}function setSender(sender) {currentSender = sender;hasCurrentSenderChanged = true;}function trackRequest(api, options, statusCallback) {var requestId = options.requestId,transactionHash = options.transactionHash;var txHashPromise = transactionHash ? Promise.resolve(transactionHash) : api.pollMethod('parity_checkRequest', requestId);return txHashPromise.then(function (transactionHash) {statusCallback(null, { transactionHash: transactionHash });return api.pollMethod('eth_getTransactionReceipt', transactionHash, isValidReceipt);}).then(function (transactionReceipt) {statusCallback(null, { transactionReceipt: transactionReceipt });}).catch(function (error) {statusCallback(error);});}var isValidReceipt = function isValidReceipt(receipt) {return receipt && receipt.blockNumber && receipt.blockNumber.gt(0);};function getTxOptions(api, func, _options) {var values = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];var options = _extends({}, _options);var address = options.from;if (func && func.contract) {options.to = options.to || func.contract.address;}var promise = !address ? Promise.resolve(false) : _wallets2.default.isWallet(api, address);return promise.then(function (isWallet) {if (!isWallet) {return { func: func, options: options, values: values };}if (func && func.contract) {options.data = func.contract.getCallData(func, options, values);}if (!options.to) {return { func: func, options: options, values: values };}return _wallets2.default.getCallArgs(api, options, values).then(function (callArgs) {if (!callArgs) {return { func: func, options: options, values: values };}return callArgs;});}).then(function (_ref) {var func = _ref.func,options = _ref.options,values = _ref.values;if (func) {options.data = func.contract.getCallData(func, options, values);}if (!options.value) {options.value = new _bignumber2.default(0);}return options;});}function estimateGas(_func, _options) {var _values = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];var api = _func.contract.api;return getTxOptions(api, _func, _options, _values).then(function (options) {return api.eth.estimateGas(options);});}function postTransaction(_func, _options) {var _values = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];var api = _func.contract.api;return getTxOptions(api, _func, _options, _values).then(function (options) {return api.parity.postTransaction(options);});}function deployEstimateGas(contract, _options, values) {var options = _extends({}, _options);var api = contract.api;var address = options.from;return _wallets2.default.isWallet(api, address).then(function (isWallet) {if (!isWallet) {return contract.deployEstimateGas(options, values);}return _wallets2.default.getDeployArgs(contract, options, values).then(function (callArgs) {var func = callArgs.func,options = callArgs.options,values = callArgs.values;return func.estimateGas(options, values);}).then(function (gasEst) {return [gasEst, gasEst.mul(1.05)];});});}function deploy(contract, options, values) {var skipGasEstimate = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;var api = contract.api;var address = options.from;var gasEstPromise = skipGasEstimate ? Promise.resolve(null) : deployEstimateGas(contract, options, values).then(function (_ref2) {var _ref3 = _slicedToArray(_ref2, 2),gasEst = _ref3[0],gas = _ref3[1];return gas;});return gasEstPromise.then(function (gas) {if (gas) {options.gas = gas.toFixed(0);}return _wallets2.default.isWallet(api, address);}).then(function (isWallet) {if (!isWallet) {var encodedOptions = contract._encodeOptions(contract.constructors[0], options, values);return api.parity.postTransaction(encodedOptions);}return _wallets2.default.getDeployArgs(contract, options, values).then(function (callArgs) {var func = callArgs.func,options = callArgs.options,values = callArgs.values;return func._postTransaction(options, values);});});}function parseTransactionReceipt(api, options, receipt) {if (receipt.gasUsed.eq(options.gas)) {var error = new Error('Contract not deployed, gasUsed == ' + options.gas.toFixed(0));return Promise.reject(error);} // If regular contract creation, only validate the contract
  if (receipt.contractAddress) {return validateContract(api, receipt.contractAddress);} // Otherwise, needs to check for a contract deployment
  // from a multisig wallet
  var walletResult = _wallets2.default.parseTransactionLogs(api, options, receipt.logs || []);if (!walletResult) {var _error = new Error('Something went wrong in the contract deployment...');return Promise.reject(_error);}if (walletResult.pending) {return Promise.resolve(null);}return validateContract(api, walletResult.contractAddress);}function validateContract(api, contractAddress) {return api.eth.getCode(contractAddress).then(function (code) {if (code === '0x') {throw new Error('Contract not deployed, getCode returned 0x');}return contractAddress;});}function patchApi(api) {api.patch = _extends({}, api.patch, { contract: patchContract });}function patchContract(contract) {contract._functions.forEach(function (func) {if (!func.constant) {func._postTransaction = func.postTransaction;func._estimateGas = func.estimateGas;func.postTransaction = postTransaction.bind(contract, func);func.estimateGas = estimateGas.bind(contract, func);}});}function checkIfTxFailed(api, tx, gasSent) {return api.pollMethod('eth_getTransactionReceipt', tx).then(function (receipt) {// TODO: Right now, there's no way to tell wether the EVM code crashed.
    // Because you usually send a bit more gas than estimated (to make sure
    // it gets mined quickly), we transaction probably failed if all the gas
    // has been used up.
    return receipt.gasUsed.eq(gasSent);});}function waitForConfirmations(api, tx, confirmations) {return new Promise(function (resolve, reject) {api.pollMethod('eth_getTransactionReceipt', tx, isValidReceipt).then(function (receipt) {var subscription = void 0;api.subscribe('eth_blockNumber', function (err, block) {if (err) {reject(err);} else if (block.minus(confirmations - 1).gte(receipt.blockNumber)) {if (subscription) {api.unsubscribe(subscription);}
          resolve();
        }
      }).
      then(function (_subscription) {
        subscription = _subscription;
      }).
      catch(reject);
    });
  });
}