@confluxfans/cip-23
Version:
Tiny library with utility functions that can help with signing and verifying CIP-23 based messages
69 lines (59 loc) • 1.88 kB
JavaScript
import { array, intersection, number, object, optional, pattern, record, refinement, string, type, union } from 'superstruct';
export const TYPE_REGEX = /^\w+/;
export const ARRAY_REGEX = /^(.*)\[([0-9]*?)]$/;
export const BYTES_REGEX = /^bytes([0-9]{1,2})$/;
export const NUMBER_REGEX = /^u?int([0-9]{0,3})$/;
export const STATIC_TYPES = ['address', 'bool', 'bytes', 'string'];
const TYPE = refinement(string(), 'Type', (type, context) => {
return isValidType(context.branch[0].types, type);
});
export const CIP_23_TYPE = object({
name: string(),
type: TYPE
});
export const CIP_23_DOMAIN_TYPE = object({
name: optional(string()),
version: optional(string()),
chainId: optional(union([string(), number()])),
verifyingContract: optional(pattern(string(), /^0x[0-9a-z]{40}$/i)),
salt: optional(union([array(number()), pattern(string(), /^0x[0-9a-z]{64}$/i)]))
});
export const CIP_23_TYPED_DATA_TYPE = object({
types: intersection([type({
CIP23Domain: array(CIP_23_TYPE)
}), record(string(), array(CIP_23_TYPE))]),
primaryType: string(),
domain: CIP_23_DOMAIN_TYPE,
message: object()
});
export const isValidType = (types, type) => {
if (STATIC_TYPES.includes(type)) {
return true;
}
if (types[type]) {
return true;
}
if (type.match(ARRAY_REGEX)) {
const match = type.match(TYPE_REGEX);
if (match) {
const innerType = match[0];
return isValidType(types, innerType);
}
}
const bytesMatch = type.match(BYTES_REGEX);
if (bytesMatch) {
const length = Number(bytesMatch[1]);
if (length >= 1 && length <= 32) {
return true;
}
}
const numberMatch = type.match(NUMBER_REGEX);
if (numberMatch) {
const length = Number(numberMatch[1]);
if (length >= 8 && length <= 256 && length % 8 === 0) {
return true;
}
}
return false;
};
//# sourceMappingURL=types.js.map