lotus-sdk
Version:
Central repository for several classes of tools for integrating with, and building for, the Lotusia ecosystem
56 lines (55 loc) • 1.41 kB
JavaScript
import bs58 from 'bs58';
const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.split('');
export class Base58 {
buf;
constructor(obj) {
if (Buffer.isBuffer(obj)) {
const buf = obj;
this.fromBuffer(buf);
}
else if (typeof obj === 'string') {
const str = obj;
this.fromString(str);
}
else if (obj) {
this.set(obj);
}
}
static validCharacters(chars) {
if (Buffer.isBuffer(chars)) {
chars = chars.toString();
}
return Array.from(chars).every(char => ALPHABET.includes(char));
}
set(obj) {
this.buf = obj.buf || this.buf || undefined;
return this;
}
static encode(buf) {
if (!Buffer.isBuffer(buf)) {
throw new Error('Input should be a buffer');
}
return bs58.encode(buf);
}
static decode(str) {
if (typeof str !== 'string') {
throw new Error('Input should be a string');
}
return Buffer.from(bs58.decode(str));
}
fromBuffer(buf) {
this.buf = buf;
return this;
}
fromString(str) {
const buf = Base58.decode(str);
this.buf = buf;
return this;
}
toBuffer() {
return this.buf;
}
toString() {
return Base58.encode(this.buf);
}
}