@taquito/michelson-encoder
Version:
Michelson encoding and decoding utilities for Taquito.
91 lines (90 loc) • 2.63 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BytesToken = exports.BytesValidationError = void 0;
const token_1 = require("../token");
const utils_1 = require("@taquito/utils");
/**
* @category Error
* Error that indicates a failure happening when parsing encoding/executing Bytes
*/
class BytesValidationError extends token_1.TokenValidationError {
constructor(value, token, message) {
super(value, token, message);
this.value = value;
this.token = token;
this.name = 'BytesValidationError';
}
}
exports.BytesValidationError = BytesValidationError;
class BytesToken extends token_1.ComparableToken {
constructor(val, idx, fac) {
super(val, idx, fac);
this.val = val;
this.idx = idx;
this.fac = fac;
}
ToBigMapKey(val) {
return {
key: { bytes: val },
type: { prim: BytesToken.prim },
};
}
/**
* @throws {@link BytesValidationError}
*/
validate(val) {
if (typeof val === 'string' && /^[0-9a-fA-F]*$/.test(val) && val.length % 2 === 0) {
return;
}
throw new BytesValidationError(val, this, `Invalid bytes: ${val}`);
}
convertUint8ArrayToHexString(val) {
return val.constructor === Uint8Array ? (0, utils_1.buf2hex)(val) : val;
}
/**
* @throws {@link BytesValidationError}
*/
Encode(args) {
let val = args.pop();
val = (0, utils_1.stripHexPrefix)(this.convertUint8ArrayToHexString(val));
this.validate(val);
return { bytes: String(val).toString() };
}
/**
* @throws {@link BytesValidationError}
*/
EncodeObject(val, semantic) {
val = this.convertUint8ArrayToHexString(val);
if (typeof val === 'string') {
val = (0, utils_1.stripHexPrefix)(val);
}
this.validate(val);
if (semantic && semantic[BytesToken.prim]) {
return semantic[BytesToken.prim](val);
}
return { bytes: String(val).toString() };
}
Execute(val) {
return val.bytes;
}
generateSchema() {
return {
__michelsonType: BytesToken.prim,
schema: BytesToken.prim,
};
}
ToKey({ bytes, string }) {
if (string) {
return string;
}
return bytes;
}
findAndReturnTokens(tokenToFind, tokens) {
if (BytesToken.prim === tokenToFind) {
tokens.push(this);
}
return tokens;
}
}
exports.BytesToken = BytesToken;
BytesToken.prim = 'bytes';