'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
/**
 * @param {MinterApiInstance} apiInstance
 * @param {import('axios').AxiosRequestConfig} [factoryAxiosOptions]
 * @return {PostSignedTxInstance}
 */
function PostSignedTx(apiInstance, factoryAxiosOptions) {
  /**
   * @typedef {Function} PostSignedTxInstance
   * @param {string|Buffer} signedTx
   * @param {import('axios').AxiosRequestConfig} [axiosOptions]
   * @return {Promise<PostTxResponse>}
   */
  return function postSignedTx(signedTx, axiosOptions) {
    if (Buffer.isBuffer(signedTx)) {
      signedTx = "0x".concat(signedTx.toString('hex'));
    }
    return apiInstance.post('send_transaction', {
      tx: signedTx
    }, _objectSpread(_objectSpread({}, factoryAxiosOptions), axiosOptions)).then(function (response) {
      var _resData$transaction;
      var resData = response.data;
      if (((_resData$transaction = resData.transaction) === null || _resData$transaction === void 0 ? void 0 : _resData$transaction.code) > 0) {
        throw new Error("Transaction included in the block with error code ".concat(resData.transaction.code, ": ").concat(resData.transaction.log));
      }

      // @TODO check error code
      return resData.transaction || {
        hash: resData.hash
      };
    });
  };
}

/**
 * @typedef {NodeTransaction|{hash: string}} PostTxResponse
 */

/**
 * @typedef NodeTransaction
 * @property {string} hash
 * @property {string} raw_tx
 * @property {string} height
 * @property {string} from
 * @property {string} nonce
 * @property {string} gas
 * @property {number} gas_price
 * @property {string} gas_coin
 * @property {number} type
 * @property {TxData} data
 * @property {string} payload
 * @property {object} tags
 */

module.exports = PostSignedTx;
