biuauthui
Version:
Ui modal for biuAuth
65 lines (59 loc) • 2.2 kB
text/typescript
import { Address } from "../payTypes/types";
import { ChainId } from "./chain";
export const getAddress = (address: Address, chainId?: number): string => {
return address[chainId as number] ? address[chainId as number] : address[ChainId.ETHEREUM];
};
export function normalizeHexAddress(address: string | Buffer): string {
if (!address) {
return "";
}
const addressString = typeof address === "object" && !("toLowerCase" in address) ? address.toString("hex") : address;
if (typeof addressString === "string") {
const noPrefix = addressString.replace(/^0x/, "");
const even = noPrefix.length % 2 === 0 ? noPrefix : `0${noPrefix}`;
return `0x${Buffer.from(even, "hex").toString("hex")}`;
}
return "";
}
export function sameEVMAddress(address1: string | Buffer | undefined | null, address2: string | Buffer | undefined | null): boolean {
if (typeof address1 === "undefined" || typeof address2 === "undefined" || address1 === null || address2 === null) {
return false;
}
return normalizeHexAddress(address1) === normalizeHexAddress(address2);
}
export const randomSecret = () => {
// the first 4 bytes of the namehash of enslabs.biu
const platformSource = "9923eb94";
// v3
const version = "00000003";
const bytes = Buffer.allocUnsafe(24);
return `0x${platformSource}${version}${window.crypto.getRandomValues(bytes).toString("hex")}`;
};
// 科学计数法转数值 - 处理 1e-7 这类精度问题
export function getFullNum(num: number) {
// 处理非数字
if (isNaN(num)) {
return num;
}
// 处理不需要转换的数字
const str = String(num);
if (!/e/i.test(str)) {
return num;
}
return Number(num)
.toFixed(18)
.replace(/\.?0+$/, "");
}
export function toFixed(number: number, pp: number) {
let num: number | string = isNaN(number) || !number ? 0 : number;
const p = isNaN(pp) || !pp ? 0 : pp;
num = getFullNum(num);
var n = (num + "").split("."); // eslint-disable-line
var x = n.length > 1 ? n[1] : ""; // eslint-disable-line
if (x.length > p) {
x = x.substr(0, p);
} else {
x += Array(p - x.length + 1).join("0");
}
return n[0] + (x == "" ? "" : "." + x); // eslint-disable-line
}