UNPKG

@taquito/michelson-encoder

Version:

converts michelson data and types into convenient JS/TS objects

91 lines (90 loc) 3.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ViewSchema = void 0; const createToken_1 = require("../tokens/createToken"); const errors_1 = require("./errors"); class ViewSchema { /** * * @description Create an instance of ViewSchema for each view in a script * * @param val contract script obtained from the RPC * @returns array of ViewSchema or empty array if there is no view in the contract * @throws {@link InvalidScriptError} */ static fromRPCResponse(val) { const allViewSchema = []; const views = val && val.script && Array.isArray(val.script.code) && val.script.code.filter((x) => x.prim === 'view'); if (views) { views.forEach((view) => { allViewSchema.push(new ViewSchema(view.args)); }); } return allViewSchema; } /** * @throws {@link InvalidScriptError} */ constructor(viewArgs) { if (!viewArgs) { throw new errors_1.InvalidScriptError(viewArgs, 'the args are not defined'); } if (viewArgs.length !== 4) { throw new errors_1.InvalidScriptError(viewArgs, `there should be exactly 4 arguments`); } if (!('string' in viewArgs[0]) || !viewArgs[0]['string']) { throw new errors_1.InvalidScriptError(viewArgs, `The first argument should be a string, representing the view name. It should be in the form: { string: 'viewName' }`); } this.viewName = viewArgs[0]['string']; this.viewArgsType = viewArgs[1]; this.viewReturnType = viewArgs[2]; this.instructions = viewArgs[3]; this.rootArgsType = (0, createToken_1.createToken)(this.viewArgsType, 0); this.rootReturnType = (0, createToken_1.createToken)(this.viewReturnType, 0); } /** * * @description Transform the view parameter into Michelson * * @param args parameter of the view in js format * @returns parameter of the view in Michelson * @throws {@link ParameterEncodingError} */ encodeViewArgs(args) { try { return this.rootArgsType.EncodeObject(args); } catch (ex) { throw new errors_1.ParameterEncodingError(this.viewName, undefined, args, ex); } } /** * * @description Transform the view result from Michelson to readable data * * @param val result of the view in JSON Michelson * @param semantics optional semantics to override the default decoding behavior * @returns result of the view in a readable format */ decodeViewResult(val, semantics) { return this.rootReturnType.Execute(val, semantics); } /** * * @description Return the signature of the view parameter */ extractArgsSchema() { return this.rootArgsType.ExtractSchema(); } /** * * @description Return the format of the view result */ extractResultSchema() { return this.rootReturnType.ExtractSchema(); } } exports.ViewSchema = ViewSchema;