"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _util = require("@polkadot/util");

// Copyright 2017-2019 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
class RpcCoder {
  constructor() {
    this.id = 0;
  }

  decodeResponse(response) {
    (0, _util.assert)(response, 'Empty response object received');
    (0, _util.assert)(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object');
    const isSubscription = !(0, _util.isUndefined)(response.params) && !(0, _util.isUndefined)(response.method);
    (0, _util.assert)((0, _util.isNumber)(response.id) || isSubscription && (0, _util.isNumber)(response.params.subscription), 'Invalid id field in decoded object');
    this.checkError(response.error);
    (0, _util.assert)(!(0, _util.isUndefined)(response.result) || isSubscription, 'No result found in JsonRpc response');

    if (isSubscription) {
      this.checkError(response.params.error);
      return response.params.result;
    }

    return response.result;
  }

  encodeJson(method, params) {
    return JSON.stringify(this.encodeObject(method, params));
  }

  encodeObject(method, params) {
    return {
      id: ++this.id,
      jsonrpc: '2.0',
      method,
      params
    };
  }

  getId() {
    return this.id;
  }

  checkError(error) {
    if (error) {
      const {
        code,
        data,
        message
      } = error;

      const _data = (0, _util.isUndefined)(data) ? '' : ": ".concat((0, _util.isString)(data) ? data : JSON.stringify(data)).substr(0, 22);

      throw new Error("".concat(code, ": ").concat(message).concat(_data));
    }
  }

}

exports.default = RpcCoder;