test-ic-wallet-middleware-icrc
Version:
Ic middleware wallet ICRC protocol
86 lines (85 loc) • 2.54 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubAccountId = void 0;
const principal_1 = require("@dfinity/principal");
const common_1 = require("@ic-wallet-middleware/common");
const errors_1 = require("../../errors");
class SubAccountId {
_subAccount;
constructor(subAccount) {
this._subAccount = subAccount;
}
toUint8Array() {
return (0, common_1.hexToUint8Array)(this._subAccount);
}
toString() {
return this._subAccount;
}
toNumber() {
return parseInt(this._subAccount, 16);
}
;
toPrincipal() {
return principal_1.Principal.fromHex(this._subAccount.substring(2));
}
;
equals(subAccountId) {
return this._subAccount === subAccountId._subAccount;
}
notEquals(subAccountId) {
return !this.equals(subAccountId);
}
static parseFromUint8Array(uint8Array) {
const str = Buffer.from(uint8Array.buffer).toString('hex').replace(/^0+/, "").trim();
if (!str) {
return new SubAccountId("0x0");
}
else {
return new SubAccountId(`0x${str}`);
}
}
static parseFromNumber(number) {
if (number >= 0 && Number.isInteger(number)) {
const subAccountStr = `0x${number.toString(16)}`;
return new SubAccountId(subAccountStr);
}
throw new errors_1.SubAccountIdError("Invalid subAccount value");
}
static Default() {
return SubAccountId.parseFromString("0x0");
}
static tryParseFromNumber(number) {
try {
return SubAccountId.parseFromNumber(number);
}
catch {
return undefined;
}
}
static parseFromString(hexString) {
if (/^0x[a-fA-F0-9]+$/.test(hexString)) {
let hex = hexString.substring(2);
if (hex.indexOf("0") === 0) {
hex = hex.replace(/^0+/, "");
if (hex == "") {
hex = "0";
}
hexString = `0x${hex}`;
}
return new SubAccountId(hexString);
}
throw new errors_1.SubAccountIdError("Invalid subAccount format, expected 0xHEX");
}
static tryParseFromString(hexString) {
if (!hexString) {
return undefined;
}
try {
return SubAccountId.parseFromString(hexString);
}
catch {
return undefined;
}
}
}
exports.SubAccountId = SubAccountId;