@taquito/michelson-encoder
Version:
converts michelson data and types into convenient JS/TS objects
115 lines (114 loc) • 3.45 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyToken = exports.KeyValidationError = void 0;
const token_1 = require("./token");
const utils_1 = require("@taquito/utils");
const publicKeyPrefixLength = 4;
/**
* @category Error
* @description Error that indicates a failure happening when parsing encoding/executing a Key
*/
class KeyValidationError extends token_1.TokenValidationError {
constructor(value, token, message) {
super(value, token, message);
this.value = value;
this.token = token;
this.name = 'KeyValidationError';
}
}
exports.KeyValidationError = KeyValidationError;
class KeyToken extends token_1.ComparableToken {
constructor(val, idx, fac) {
super(val, idx, fac);
this.val = val;
this.idx = idx;
this.fac = fac;
}
Execute(val) {
if (val.string) {
return val.string;
}
return (0, utils_1.encodeKey)(val.bytes);
}
/**
* @throws {@link KeyValidationError}
*/
validate(value) {
if ((0, utils_1.validatePublicKey)(value) !== utils_1.ValidationResult.VALID) {
throw new KeyValidationError(value, this, 'Key is not valid');
}
}
/**
* @throws {@link KeyValidationError}
*/
Encode(args) {
const val = args.pop();
this.validate(val);
return { string: val };
}
/**
* @throws {@link KeyValidationError}
*/
EncodeObject(val, semantic) {
this.validate(val);
if (semantic && semantic[KeyToken.prim]) {
return semantic[KeyToken.prim](val);
}
return { string: val };
}
/**
* @deprecated ExtractSchema has been deprecated in favor of generateSchema
*
*/
ExtractSchema() {
return KeyToken.prim;
}
generateSchema() {
return {
__michelsonType: KeyToken.prim,
schema: KeyToken.prim,
};
}
ToKey(val) {
return this.Execute(val);
}
ToBigMapKey(val) {
return {
key: { string: val },
type: { prim: KeyToken.prim },
};
}
compare(key1, key2) {
const keyPrefix1 = this.getPrefix(key1);
const keyPrefix2 = this.getPrefix(key2);
if (keyPrefix1 === utils_1.Prefix.EDPK && keyPrefix2 !== utils_1.Prefix.EDPK) {
return -1;
}
else if (keyPrefix1 === utils_1.Prefix.SPPK && keyPrefix2 !== utils_1.Prefix.SPPK) {
return keyPrefix2 === utils_1.Prefix.EDPK ? 1 : -1;
}
else if (keyPrefix1 === utils_1.Prefix.P2PK) {
if (keyPrefix2 !== utils_1.Prefix.P2PK) {
return 1;
}
const keyBytes1 = this.getP256PublicKeyComparableBytes(key1);
const keyBytes2 = this.getP256PublicKeyComparableBytes(key2);
return Buffer.compare(keyBytes1, keyBytes2);
}
return super.compare(key1, key2);
}
getPrefix(val) {
return val.substring(0, publicKeyPrefixLength);
}
getP256PublicKeyComparableBytes(p2pk) {
return (0, utils_1.b58cdecode)(p2pk, utils_1.prefix[utils_1.Prefix.P2PK]).slice(1);
}
findAndReturnTokens(tokenToFind, tokens) {
if (KeyToken.prim === tokenToFind) {
tokens.push(this);
}
return tokens;
}
}
exports.KeyToken = KeyToken;
KeyToken.prim = 'key';