@rarible/types
Version:
`@rarible/types` is a TypeScript library that provides type definitions and interfaces for the Rarible ecosystem. This package is designed to facilitate seamless integration with Rarible's APIs and services, ensuring type safety and improved developer exp
47 lines (46 loc) • 1.37 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidBinaryError = exports.randomBinary = exports.randomWord = exports.ZERO_WORD = exports.toWord = exports.toBinary = void 0;
/**
* Convert string to binary string
* @note that it also convert to lowercase
*
* 0xTest -> 0xtest
* Test -> 0xtest
*/
function toBinary(value, re = /[0-9a-f]*/g) {
let hex;
if (value.startsWith("0x")) {
hex = value.substring(2).toLowerCase();
}
else {
hex = value.toLowerCase();
}
if (re.test(hex)) {
return `0x${hex}`;
}
throw new InvalidBinaryError(value);
}
exports.toBinary = toBinary;
function toWord(value) {
return toBinary(value, /[0-9a-f]{64}/g);
}
exports.toWord = toWord;
exports.ZERO_WORD = toWord("0x0000000000000000000000000000000000000000000000000000000000000000");
function randomWord() {
return toWord(randomBinary(32));
}
exports.randomWord = randomWord;
function randomBinary(size) {
return `0x${Array.from(new Array(size * 2))
.map(() => Math.floor(Math.random() * 16).toString(16))
.join("")}`;
}
exports.randomBinary = randomBinary;
class InvalidBinaryError extends Error {
constructor(value) {
super(`Not a binary ${value}`);
this.name = "InvalidBinaryError";
}
}
exports.InvalidBinaryError = InvalidBinaryError;