UNPKG

@taquito/michelson-encoder

Version:

Michelson encoding and decoding utilities for Taquito.

94 lines (93 loc) 2.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IntToken = exports.IntValidationError = void 0; const token_1 = require("../token"); const bignumber_js_1 = require("bignumber.js"); /** * @category Error * Error that indicates a failure happening when parsing encoding/executing Int */ class IntValidationError extends token_1.TokenValidationError { constructor(value, token, message) { super(value, token, message); this.value = value; this.token = token; this.name = 'IntValidationError'; } } exports.IntValidationError = IntValidationError; class IntToken extends token_1.ComparableToken { constructor(val, idx, fac) { super(val, idx, fac); this.val = val; this.idx = idx; this.fac = fac; } Execute(val) { return new bignumber_js_1.default(val[Object.keys(val)[0]]); } generateSchema() { return { __michelsonType: IntToken.prim, schema: IntToken.prim, }; } /** * @throws {@link IntValidationError} */ validate(val) { let bigNumber; try { bigNumber = new bignumber_js_1.default(val); } catch { throw new IntValidationError(val, this, `Value is not a number: ${JSON.stringify(val)}`); } if (bigNumber.isNaN()) { throw new IntValidationError(val, this, `Value is not a number: ${JSON.stringify(val)}`); } } /** * @throws {@link IntValidationError} */ Encode(args) { const val = args.pop(); this.validate(val); return { int: new bignumber_js_1.default(val).toFixed() }; } /** * @throws {@link IntValidationError} */ EncodeObject(val, semantic) { this.validate(val); if (semantic && semantic[IntToken.prim]) { return semantic[IntToken.prim](val); } return { int: new bignumber_js_1.default(val).toFixed() }; } ToBigMapKey(val) { return { key: { int: String(val) }, type: { prim: IntToken.prim }, }; } ToKey({ int }) { return int; } compare(int1, int2) { const o1 = Number(int1); const o2 = Number(int2); if (o1 === o2) { return 0; } return o1 < o2 ? -1 : 1; } findAndReturnTokens(tokenToFind, tokens) { if (IntToken.prim === tokenToFind) { tokens.push(this); } return tokens; } } exports.IntToken = IntToken; IntToken.prim = 'int';