"use strict";
// Copyright 2017-2020 @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.
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("@polkadot/util");
/** @internal */
class RpcCoder {
    constructor() {
        this.id = 0;
    }
    decodeResponse(response) {
        util_1.assert(response, 'Empty response object received');
        util_1.assert(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object');
        const isSubscription = !util_1.isUndefined(response.params) && !util_1.isUndefined(response.method);
        util_1.assert(util_1.isNumber(response.id) || (isSubscription && util_1.isNumber(response.params.subscription)), 'Invalid id field in decoded object');
        this.checkError(response.error);
        util_1.assert(!util_1.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;
            // We need some sort of cut-off here since these can be very large and
            // very nested, pick a number and trim the result display to it
            const _data = util_1.isUndefined(data)
                ? ''
                : `: ${util_1.isString(data) ? data : JSON.stringify(data)}`.substr(0, 35);
            throw new Error(`${code}: ${message}${_data}`);
        }
    }
}
exports.default = RpcCoder;
