update export settings

This commit is contained in:
CounterFire2023 2024-01-17 15:16:12 +08:00
parent a1f0342942
commit eef63cafbf
65 changed files with 64695 additions and 479 deletions

View File

@ -1,11 +1,35 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/common/ZError.ts
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/common/ZError.ts
var ZError_exports = {};
__export(ZError_exports, {
ZError: () => ZError
});
module.exports = __toCommonJS(ZError_exports);
var ZError = class {
constructor(statusCode, message) {
this.statusCode = statusCode;
this.message = message;
}
};
exports.ZError = ZError;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ZError
});
//# sourceMappingURL=ZError.cjs.map

View File

@ -1 +1 @@
{"version":3,"sources":["../../src/common/ZError.ts"],"names":[],"mappings":";AACO,IAAM,SAAN,MAA8B;AAAA,EAMnC,YAAY,YAAoB,SAAiB;AAC/C,SAAK,aAAa;AAClB,SAAK,UAAU;AAAA,EACjB;AACF","sourcesContent":["\nexport class ZError implements Error {\n code: string\n statusCode?: number\n message: string\n name: string\n\n constructor(statusCode: number, message: string) {\n this.statusCode = statusCode\n this.message = message\n }\n}\n"]}
{"version":3,"sources":["../../src/common/ZError.ts"],"sourcesContent":["\nexport class ZError implements Error {\n code: string\n statusCode?: number\n message: string\n name: string\n\n constructor(statusCode: number, message: string) {\n this.statusCode = statusCode\n this.message = message\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,IAAM,SAAN,MAA8B;AAAA,EAMnC,YAAY,YAAoB,SAAiB;AAC/C,SAAK,aAAa;AAClB,SAAK,UAAU;AAAA,EACjB;AACF;","names":[]}

184
dist/index.cjs vendored
View File

@ -1,159 +1,37 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/utils/bn.util.ts
var isHexStrict = (hex) => typeof hex === "string" && /^((-)?0x[0-9a-f]+|(0x))$/i.test(hex);
var isHex = (hex) => typeof hex === "number" || typeof hex === "bigint" || typeof hex === "string" && /^((-0x|0x|-)?[0-9a-f]+|(0x))$/i.test(hex);
var base = BigInt(10);
var expo10 = (expo) => base ** BigInt(expo);
var ethUnitMap = {
noether: BigInt("0"),
wei: BigInt(1),
kwei: expo10(3),
Kwei: expo10(3),
babbage: expo10(3),
femtoether: expo10(3),
mwei: expo10(6),
Mwei: expo10(6),
lovelace: expo10(6),
picoether: expo10(6),
gwei: expo10(9),
Gwei: expo10(9),
shannon: expo10(9),
nanoether: expo10(9),
nano: expo10(9),
szabo: expo10(12),
microether: expo10(12),
micro: expo10(12),
finney: expo10(15),
milliether: expo10(15),
milli: expo10(15),
ether: expo10(18),
kether: expo10(21),
grand: expo10(21),
mether: expo10(24),
gether: expo10(27),
tether: expo10(30)
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var hexToNumber = (value) => {
if (!isHexStrict(value)) {
throw new Error("Invalid hex string");
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
const [negative, hexValue] = value.startsWith("-") ? [true, value.slice(1)] : [false, value];
const num = BigInt(hexValue);
if (num > Number.MAX_SAFE_INTEGER) {
return negative ? -num : num;
}
if (num < Number.MIN_SAFE_INTEGER) {
return num;
}
return negative ? -1 * Number(num) : Number(num);
return to;
};
var toNumber = (value) => {
if (typeof value === "number") {
return value;
}
if (typeof value === "bigint") {
return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER ? Number(value) : value;
}
if (typeof value === "string" && isHexStrict(value)) {
return hexToNumber(value);
}
try {
return toNumber(BigInt(value));
} catch (e) {
throw new Error("ivalid number: " + value);
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
ZError: () => ZError
});
module.exports = __toCommonJS(src_exports);
// src/common/ZError.ts
var ZError = class {
constructor(statusCode, message) {
this.statusCode = statusCode;
this.message = message;
}
};
var toBigInt = (value) => {
if (typeof value === "number") {
return BigInt(value);
}
if (typeof value === "bigint") {
return value;
}
if (typeof value === "string" && isHex(value)) {
return BigInt(value);
}
if (typeof value === "string" && value.indexOf(",") >= 0) {
return BigInt(value.replace(/,/g, ""));
}
throw new Error("invalid number" + value);
};
var toBigWei = (number, unit = "ether") => {
return toBigInt(toWei(number, unit));
};
var toWei = (number, unit = "ether") => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new Error("error unit: " + unit);
}
typeof number === "string" && number.indexOf(",") >= 0 && (number = number.replace(/,/g, ""));
const [integer, fraction] = String(typeof number === "string" && !isHexStrict(number) ? number : toNumber(number)).split(".").concat("");
const value = BigInt(`${integer}${fraction}`);
const updatedValue = value * denomination;
const numberOfZerosInDenomination = denomination.toString().length - 1;
const decimals = Math.min(fraction.length, numberOfZerosInDenomination);
if (decimals === 0) {
return updatedValue.toString();
}
return updatedValue.toString().padStart(decimals, "0").slice(0, -decimals);
};
var fromWei = (number, unit = "ether") => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new Error("invalid unit: " + unit);
}
const value = String(toNumber(number));
const numberOfZerosInDenomination = denomination.toString().length - 1;
if (numberOfZerosInDenomination <= 0) {
return value.toString();
}
const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, "0");
const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination);
const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, "");
if (integer === "") {
return `0.${fraction}`;
}
if (fraction === "") {
return integer;
}
return `${integer}.${fraction}`;
};
// src/utils/date.util.ts
var ONE_DAY = 24 * 60 * 60 * 1e3;
var formatDate = (date) => {
const year = date.getFullYear();
const month = (date.getMonth() + 1 + "").padStart(2, "0");
const day = (date.getDate() + "").padStart(2, "0");
return `${year}${month}${day}`;
};
var yesterday = (date) => {
date = date || /* @__PURE__ */ new Date();
date.setDate(date.getDate() - 1);
return date;
};
var nextday = (date) => {
date = date || /* @__PURE__ */ new Date();
date.setDate(date.getDate() + 1);
return date;
};
function daysBetween(date1, date2) {
const diffInMs = Math.abs(date1.getTime() - date2.getTime());
const diffInDays = Math.round(diffInMs / ONE_DAY);
return diffInDays;
}
exports.ONE_DAY = ONE_DAY; exports.daysBetween = daysBetween; exports.ethUnitMap = ethUnitMap; exports.formatDate = formatDate; exports.fromWei = fromWei; exports.hexToNumber = hexToNumber; exports.isHex = isHex; exports.nextday = nextday; exports.toBigInt = toBigInt; exports.toBigWei = toBigWei; exports.toNumber = toNumber; exports.toWei = toWei; exports.yesterday = yesterday;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ZError
});
//# sourceMappingURL=index.cjs.map

2
dist/index.cjs.map vendored

File diff suppressed because one or more lines are too long

79
dist/index.d.cts vendored
View File

@ -1,78 +1 @@
declare type HexString = string;
declare type Numbers = number | bigint | string | HexString;
declare type ValidInputTypes = Uint8Array | bigint | string | number | boolean;
declare const isHex: (hex: ValidInputTypes) => boolean;
declare const ethUnitMap: {
noether: bigint;
wei: bigint;
kwei: bigint;
Kwei: bigint;
babbage: bigint;
femtoether: bigint;
mwei: bigint;
Mwei: bigint;
lovelace: bigint;
picoether: bigint;
gwei: bigint;
Gwei: bigint;
shannon: bigint;
nanoether: bigint;
nano: bigint;
szabo: bigint;
microether: bigint;
micro: bigint;
finney: bigint;
milliether: bigint;
milli: bigint;
ether: bigint;
kether: bigint;
grand: bigint;
mether: bigint;
gether: bigint;
tether: bigint;
};
type EtherUnits = keyof typeof ethUnitMap;
/**
* Converts value to it's number representation
*/
declare const hexToNumber: (value: string) => bigint | number;
declare const toNumber: (value: Numbers) => number | bigint;
/**
* Auto converts any given value into it's bigint representation
*
* @param value - The value to convert
* @returns - Returns the value in bigint representation
* @example
* ```ts
* console.log(web3.utils.toBigInt(1));
* > 1n
* ```
*/
declare const toBigInt: (value: unknown) => bigint;
declare const toBigWei: (number: Numbers, unit?: EtherUnits) => bigint;
declare const toWei: (number: Numbers, unit?: EtherUnits) => string;
/**
* Takes a number of wei and converts it to any other ether unit.
* @param number - The value in wei
* @param unit - The unit to convert to
* @returns - Returns the converted value in the given unit
*
* @example
* ```ts
* console.log(web3.utils.fromWei("1", "ether"));
* > 0.000000000000000001
*
* console.log(web3.utils.fromWei("1", "shannon"));
* > 0.000000001
* ```
*/
declare const fromWei: (number: Numbers, unit?: EtherUnits) => string;
declare const ONE_DAY: number;
declare const formatDate: (date: Date) => string;
declare const yesterday: (date?: Date) => Date;
declare const nextday: (date?: Date) => Date;
declare function daysBetween(date1: Date, date2: Date): number;
export { type EtherUnits, type HexString, type Numbers, ONE_DAY, type ValidInputTypes, daysBetween, ethUnitMap, formatDate, fromWei, hexToNumber, isHex, nextday, toBigInt, toBigWei, toNumber, toWei, yesterday };
export { ZError } from './common/ZError.cjs';

79
dist/index.d.ts vendored
View File

@ -1,78 +1 @@
declare type HexString = string;
declare type Numbers = number | bigint | string | HexString;
declare type ValidInputTypes = Uint8Array | bigint | string | number | boolean;
declare const isHex: (hex: ValidInputTypes) => boolean;
declare const ethUnitMap: {
noether: bigint;
wei: bigint;
kwei: bigint;
Kwei: bigint;
babbage: bigint;
femtoether: bigint;
mwei: bigint;
Mwei: bigint;
lovelace: bigint;
picoether: bigint;
gwei: bigint;
Gwei: bigint;
shannon: bigint;
nanoether: bigint;
nano: bigint;
szabo: bigint;
microether: bigint;
micro: bigint;
finney: bigint;
milliether: bigint;
milli: bigint;
ether: bigint;
kether: bigint;
grand: bigint;
mether: bigint;
gether: bigint;
tether: bigint;
};
type EtherUnits = keyof typeof ethUnitMap;
/**
* Converts value to it's number representation
*/
declare const hexToNumber: (value: string) => bigint | number;
declare const toNumber: (value: Numbers) => number | bigint;
/**
* Auto converts any given value into it's bigint representation
*
* @param value - The value to convert
* @returns - Returns the value in bigint representation
* @example
* ```ts
* console.log(web3.utils.toBigInt(1));
* > 1n
* ```
*/
declare const toBigInt: (value: unknown) => bigint;
declare const toBigWei: (number: Numbers, unit?: EtherUnits) => bigint;
declare const toWei: (number: Numbers, unit?: EtherUnits) => string;
/**
* Takes a number of wei and converts it to any other ether unit.
* @param number - The value in wei
* @param unit - The unit to convert to
* @returns - Returns the converted value in the given unit
*
* @example
* ```ts
* console.log(web3.utils.fromWei("1", "ether"));
* > 0.000000000000000001
*
* console.log(web3.utils.fromWei("1", "shannon"));
* > 0.000000001
* ```
*/
declare const fromWei: (number: Numbers, unit?: EtherUnits) => string;
declare const ONE_DAY: number;
declare const formatDate: (date: Date) => string;
declare const yesterday: (date?: Date) => Date;
declare const nextday: (date?: Date) => Date;
declare function daysBetween(date1: Date, date2: Date): number;
export { type EtherUnits, type HexString, type Numbers, ONE_DAY, type ValidInputTypes, daysBetween, ethUnitMap, formatDate, fromWei, hexToNumber, isHex, nextday, toBigInt, toBigWei, toNumber, toWei, yesterday };
export { ZError } from './common/ZError.js';

160
dist/index.js vendored
View File

@ -1,159 +1,11 @@
// src/utils/bn.util.ts
var isHexStrict = (hex) => typeof hex === "string" && /^((-)?0x[0-9a-f]+|(0x))$/i.test(hex);
var isHex = (hex) => typeof hex === "number" || typeof hex === "bigint" || typeof hex === "string" && /^((-0x|0x|-)?[0-9a-f]+|(0x))$/i.test(hex);
var base = BigInt(10);
var expo10 = (expo) => base ** BigInt(expo);
var ethUnitMap = {
noether: BigInt("0"),
wei: BigInt(1),
kwei: expo10(3),
Kwei: expo10(3),
babbage: expo10(3),
femtoether: expo10(3),
mwei: expo10(6),
Mwei: expo10(6),
lovelace: expo10(6),
picoether: expo10(6),
gwei: expo10(9),
Gwei: expo10(9),
shannon: expo10(9),
nanoether: expo10(9),
nano: expo10(9),
szabo: expo10(12),
microether: expo10(12),
micro: expo10(12),
finney: expo10(15),
milliether: expo10(15),
milli: expo10(15),
ether: expo10(18),
kether: expo10(21),
grand: expo10(21),
mether: expo10(24),
gether: expo10(27),
tether: expo10(30)
};
var hexToNumber = (value) => {
if (!isHexStrict(value)) {
throw new Error("Invalid hex string");
}
const [negative, hexValue] = value.startsWith("-") ? [true, value.slice(1)] : [false, value];
const num = BigInt(hexValue);
if (num > Number.MAX_SAFE_INTEGER) {
return negative ? -num : num;
}
if (num < Number.MIN_SAFE_INTEGER) {
return num;
}
return negative ? -1 * Number(num) : Number(num);
};
var toNumber = (value) => {
if (typeof value === "number") {
return value;
}
if (typeof value === "bigint") {
return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER ? Number(value) : value;
}
if (typeof value === "string" && isHexStrict(value)) {
return hexToNumber(value);
}
try {
return toNumber(BigInt(value));
} catch {
throw new Error("ivalid number: " + value);
// src/common/ZError.ts
var ZError = class {
constructor(statusCode, message) {
this.statusCode = statusCode;
this.message = message;
}
};
var toBigInt = (value) => {
if (typeof value === "number") {
return BigInt(value);
}
if (typeof value === "bigint") {
return value;
}
if (typeof value === "string" && isHex(value)) {
return BigInt(value);
}
if (typeof value === "string" && value.indexOf(",") >= 0) {
return BigInt(value.replace(/,/g, ""));
}
throw new Error("invalid number" + value);
};
var toBigWei = (number, unit = "ether") => {
return toBigInt(toWei(number, unit));
};
var toWei = (number, unit = "ether") => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new Error("error unit: " + unit);
}
typeof number === "string" && number.indexOf(",") >= 0 && (number = number.replace(/,/g, ""));
const [integer, fraction] = String(typeof number === "string" && !isHexStrict(number) ? number : toNumber(number)).split(".").concat("");
const value = BigInt(`${integer}${fraction}`);
const updatedValue = value * denomination;
const numberOfZerosInDenomination = denomination.toString().length - 1;
const decimals = Math.min(fraction.length, numberOfZerosInDenomination);
if (decimals === 0) {
return updatedValue.toString();
}
return updatedValue.toString().padStart(decimals, "0").slice(0, -decimals);
};
var fromWei = (number, unit = "ether") => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new Error("invalid unit: " + unit);
}
const value = String(toNumber(number));
const numberOfZerosInDenomination = denomination.toString().length - 1;
if (numberOfZerosInDenomination <= 0) {
return value.toString();
}
const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, "0");
const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination);
const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, "");
if (integer === "") {
return `0.${fraction}`;
}
if (fraction === "") {
return integer;
}
return `${integer}.${fraction}`;
};
// src/utils/date.util.ts
var ONE_DAY = 24 * 60 * 60 * 1e3;
var formatDate = (date) => {
const year = date.getFullYear();
const month = (date.getMonth() + 1 + "").padStart(2, "0");
const day = (date.getDate() + "").padStart(2, "0");
return `${year}${month}${day}`;
};
var yesterday = (date) => {
date = date || /* @__PURE__ */ new Date();
date.setDate(date.getDate() - 1);
return date;
};
var nextday = (date) => {
date = date || /* @__PURE__ */ new Date();
date.setDate(date.getDate() + 1);
return date;
};
function daysBetween(date1, date2) {
const diffInMs = Math.abs(date1.getTime() - date2.getTime());
const diffInDays = Math.round(diffInMs / ONE_DAY);
return diffInDays;
}
export {
ONE_DAY,
daysBetween,
ethUnitMap,
formatDate,
fromWei,
hexToNumber,
isHex,
nextday,
toBigInt,
toBigWei,
toNumber,
toWei,
yesterday
ZError
};
//# sourceMappingURL=index.js.map

2
dist/index.js.map vendored

File diff suppressed because one or more lines are too long

161
dist/utils/bn.util.cjs vendored Normal file
View File

@ -0,0 +1,161 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/bn.util.ts
var bn_util_exports = {};
__export(bn_util_exports, {
ethUnitMap: () => ethUnitMap,
fromWei: () => fromWei,
hexToNumber: () => hexToNumber,
isHex: () => isHex,
toBigInt: () => toBigInt,
toBigWei: () => toBigWei,
toNumber: () => toNumber,
toWei: () => toWei
});
module.exports = __toCommonJS(bn_util_exports);
var isHexStrict = (hex) => typeof hex === "string" && /^((-)?0x[0-9a-f]+|(0x))$/i.test(hex);
var isHex = (hex) => typeof hex === "number" || typeof hex === "bigint" || typeof hex === "string" && /^((-0x|0x|-)?[0-9a-f]+|(0x))$/i.test(hex);
var base = BigInt(10);
var expo10 = (expo) => base ** BigInt(expo);
var ethUnitMap = {
noether: BigInt("0"),
wei: BigInt(1),
kwei: expo10(3),
Kwei: expo10(3),
babbage: expo10(3),
femtoether: expo10(3),
mwei: expo10(6),
Mwei: expo10(6),
lovelace: expo10(6),
picoether: expo10(6),
gwei: expo10(9),
Gwei: expo10(9),
shannon: expo10(9),
nanoether: expo10(9),
nano: expo10(9),
szabo: expo10(12),
microether: expo10(12),
micro: expo10(12),
finney: expo10(15),
milliether: expo10(15),
milli: expo10(15),
ether: expo10(18),
kether: expo10(21),
grand: expo10(21),
mether: expo10(24),
gether: expo10(27),
tether: expo10(30)
};
var hexToNumber = (value) => {
if (!isHexStrict(value)) {
throw new Error("Invalid hex string");
}
const [negative, hexValue] = value.startsWith("-") ? [true, value.slice(1)] : [false, value];
const num = BigInt(hexValue);
if (num > Number.MAX_SAFE_INTEGER) {
return negative ? -num : num;
}
if (num < Number.MIN_SAFE_INTEGER) {
return num;
}
return negative ? -1 * Number(num) : Number(num);
};
var toNumber = (value) => {
if (typeof value === "number") {
return value;
}
if (typeof value === "bigint") {
return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER ? Number(value) : value;
}
if (typeof value === "string" && isHexStrict(value)) {
return hexToNumber(value);
}
try {
return toNumber(BigInt(value));
} catch {
throw new Error("ivalid number: " + value);
}
};
var toBigInt = (value) => {
if (typeof value === "number") {
return BigInt(value);
}
if (typeof value === "bigint") {
return value;
}
if (typeof value === "string" && isHex(value)) {
return BigInt(value);
}
if (typeof value === "string" && value.indexOf(",") >= 0) {
return BigInt(value.replace(/,/g, ""));
}
throw new Error("invalid number" + value);
};
var toBigWei = (number, unit = "ether") => {
return toBigInt(toWei(number, unit));
};
var toWei = (number, unit = "ether") => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new Error("error unit: " + unit);
}
typeof number === "string" && number.indexOf(",") >= 0 && (number = number.replace(/,/g, ""));
const [integer, fraction] = String(typeof number === "string" && !isHexStrict(number) ? number : toNumber(number)).split(".").concat("");
const value = BigInt(`${integer}${fraction}`);
const updatedValue = value * denomination;
const numberOfZerosInDenomination = denomination.toString().length - 1;
const decimals = Math.min(fraction.length, numberOfZerosInDenomination);
if (decimals === 0) {
return updatedValue.toString();
}
return updatedValue.toString().padStart(decimals, "0").slice(0, -decimals);
};
var fromWei = (number, unit = "ether") => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new Error("invalid unit: " + unit);
}
const value = String(toNumber(number));
const numberOfZerosInDenomination = denomination.toString().length - 1;
if (numberOfZerosInDenomination <= 0) {
return value.toString();
}
const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, "0");
const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination);
const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, "");
if (integer === "") {
return `0.${fraction}`;
}
if (fraction === "") {
return integer;
}
return `${integer}.${fraction}`;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ethUnitMap,
fromWei,
hexToNumber,
isHex,
toBigInt,
toBigWei,
toNumber,
toWei
});
//# sourceMappingURL=bn.util.cjs.map

1
dist/utils/bn.util.cjs.map vendored Normal file

File diff suppressed because one or more lines are too long

72
dist/utils/bn.util.d.cts vendored Normal file
View File

@ -0,0 +1,72 @@
declare type HexString = string;
declare type Numbers = number | bigint | string | HexString;
declare type ValidInputTypes = Uint8Array | bigint | string | number | boolean;
declare const isHex: (hex: ValidInputTypes) => boolean;
declare const ethUnitMap: {
noether: bigint;
wei: bigint;
kwei: bigint;
Kwei: bigint;
babbage: bigint;
femtoether: bigint;
mwei: bigint;
Mwei: bigint;
lovelace: bigint;
picoether: bigint;
gwei: bigint;
Gwei: bigint;
shannon: bigint;
nanoether: bigint;
nano: bigint;
szabo: bigint;
microether: bigint;
micro: bigint;
finney: bigint;
milliether: bigint;
milli: bigint;
ether: bigint;
kether: bigint;
grand: bigint;
mether: bigint;
gether: bigint;
tether: bigint;
};
type EtherUnits = keyof typeof ethUnitMap;
/**
* Converts value to it's number representation
*/
declare const hexToNumber: (value: string) => bigint | number;
declare const toNumber: (value: Numbers) => number | bigint;
/**
* Auto converts any given value into it's bigint representation
*
* @param value - The value to convert
* @returns - Returns the value in bigint representation
* @example
* ```ts
* console.log(web3.utils.toBigInt(1));
* > 1n
* ```
*/
declare const toBigInt: (value: unknown) => bigint;
declare const toBigWei: (number: Numbers, unit?: EtherUnits) => bigint;
declare const toWei: (number: Numbers, unit?: EtherUnits) => string;
/**
* Takes a number of wei and converts it to any other ether unit.
* @param number - The value in wei
* @param unit - The unit to convert to
* @returns - Returns the converted value in the given unit
*
* @example
* ```ts
* console.log(web3.utils.fromWei("1", "ether"));
* > 0.000000000000000001
*
* console.log(web3.utils.fromWei("1", "shannon"));
* > 0.000000001
* ```
*/
declare const fromWei: (number: Numbers, unit?: EtherUnits) => string;
export { type EtherUnits, type HexString, type Numbers, type ValidInputTypes, ethUnitMap, fromWei, hexToNumber, isHex, toBigInt, toBigWei, toNumber, toWei };

72
dist/utils/bn.util.d.ts vendored Normal file
View File

@ -0,0 +1,72 @@
declare type HexString = string;
declare type Numbers = number | bigint | string | HexString;
declare type ValidInputTypes = Uint8Array | bigint | string | number | boolean;
declare const isHex: (hex: ValidInputTypes) => boolean;
declare const ethUnitMap: {
noether: bigint;
wei: bigint;
kwei: bigint;
Kwei: bigint;
babbage: bigint;
femtoether: bigint;
mwei: bigint;
Mwei: bigint;
lovelace: bigint;
picoether: bigint;
gwei: bigint;
Gwei: bigint;
shannon: bigint;
nanoether: bigint;
nano: bigint;
szabo: bigint;
microether: bigint;
micro: bigint;
finney: bigint;
milliether: bigint;
milli: bigint;
ether: bigint;
kether: bigint;
grand: bigint;
mether: bigint;
gether: bigint;
tether: bigint;
};
type EtherUnits = keyof typeof ethUnitMap;
/**
* Converts value to it's number representation
*/
declare const hexToNumber: (value: string) => bigint | number;
declare const toNumber: (value: Numbers) => number | bigint;
/**
* Auto converts any given value into it's bigint representation
*
* @param value - The value to convert
* @returns - Returns the value in bigint representation
* @example
* ```ts
* console.log(web3.utils.toBigInt(1));
* > 1n
* ```
*/
declare const toBigInt: (value: unknown) => bigint;
declare const toBigWei: (number: Numbers, unit?: EtherUnits) => bigint;
declare const toWei: (number: Numbers, unit?: EtherUnits) => string;
/**
* Takes a number of wei and converts it to any other ether unit.
* @param number - The value in wei
* @param unit - The unit to convert to
* @returns - Returns the converted value in the given unit
*
* @example
* ```ts
* console.log(web3.utils.fromWei("1", "ether"));
* > 0.000000000000000001
*
* console.log(web3.utils.fromWei("1", "shannon"));
* > 0.000000001
* ```
*/
declare const fromWei: (number: Numbers, unit?: EtherUnits) => string;
export { type EtherUnits, type HexString, type Numbers, type ValidInputTypes, ethUnitMap, fromWei, hexToNumber, isHex, toBigInt, toBigWei, toNumber, toWei };

130
dist/utils/bn.util.js vendored Normal file
View File

@ -0,0 +1,130 @@
// src/utils/bn.util.ts
var isHexStrict = (hex) => typeof hex === "string" && /^((-)?0x[0-9a-f]+|(0x))$/i.test(hex);
var isHex = (hex) => typeof hex === "number" || typeof hex === "bigint" || typeof hex === "string" && /^((-0x|0x|-)?[0-9a-f]+|(0x))$/i.test(hex);
var base = BigInt(10);
var expo10 = (expo) => base ** BigInt(expo);
var ethUnitMap = {
noether: BigInt("0"),
wei: BigInt(1),
kwei: expo10(3),
Kwei: expo10(3),
babbage: expo10(3),
femtoether: expo10(3),
mwei: expo10(6),
Mwei: expo10(6),
lovelace: expo10(6),
picoether: expo10(6),
gwei: expo10(9),
Gwei: expo10(9),
shannon: expo10(9),
nanoether: expo10(9),
nano: expo10(9),
szabo: expo10(12),
microether: expo10(12),
micro: expo10(12),
finney: expo10(15),
milliether: expo10(15),
milli: expo10(15),
ether: expo10(18),
kether: expo10(21),
grand: expo10(21),
mether: expo10(24),
gether: expo10(27),
tether: expo10(30)
};
var hexToNumber = (value) => {
if (!isHexStrict(value)) {
throw new Error("Invalid hex string");
}
const [negative, hexValue] = value.startsWith("-") ? [true, value.slice(1)] : [false, value];
const num = BigInt(hexValue);
if (num > Number.MAX_SAFE_INTEGER) {
return negative ? -num : num;
}
if (num < Number.MIN_SAFE_INTEGER) {
return num;
}
return negative ? -1 * Number(num) : Number(num);
};
var toNumber = (value) => {
if (typeof value === "number") {
return value;
}
if (typeof value === "bigint") {
return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER ? Number(value) : value;
}
if (typeof value === "string" && isHexStrict(value)) {
return hexToNumber(value);
}
try {
return toNumber(BigInt(value));
} catch {
throw new Error("ivalid number: " + value);
}
};
var toBigInt = (value) => {
if (typeof value === "number") {
return BigInt(value);
}
if (typeof value === "bigint") {
return value;
}
if (typeof value === "string" && isHex(value)) {
return BigInt(value);
}
if (typeof value === "string" && value.indexOf(",") >= 0) {
return BigInt(value.replace(/,/g, ""));
}
throw new Error("invalid number" + value);
};
var toBigWei = (number, unit = "ether") => {
return toBigInt(toWei(number, unit));
};
var toWei = (number, unit = "ether") => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new Error("error unit: " + unit);
}
typeof number === "string" && number.indexOf(",") >= 0 && (number = number.replace(/,/g, ""));
const [integer, fraction] = String(typeof number === "string" && !isHexStrict(number) ? number : toNumber(number)).split(".").concat("");
const value = BigInt(`${integer}${fraction}`);
const updatedValue = value * denomination;
const numberOfZerosInDenomination = denomination.toString().length - 1;
const decimals = Math.min(fraction.length, numberOfZerosInDenomination);
if (decimals === 0) {
return updatedValue.toString();
}
return updatedValue.toString().padStart(decimals, "0").slice(0, -decimals);
};
var fromWei = (number, unit = "ether") => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new Error("invalid unit: " + unit);
}
const value = String(toNumber(number));
const numberOfZerosInDenomination = denomination.toString().length - 1;
if (numberOfZerosInDenomination <= 0) {
return value.toString();
}
const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, "0");
const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination);
const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, "");
if (integer === "") {
return `0.${fraction}`;
}
if (fraction === "") {
return integer;
}
return `${integer}.${fraction}`;
};
export {
ethUnitMap,
fromWei,
hexToNumber,
isHex,
toBigInt,
toBigWei,
toNumber,
toWei
};
//# sourceMappingURL=bn.util.js.map

1
dist/utils/bn.util.js.map vendored Normal file

File diff suppressed because one or more lines are too long

15468
dist/utils/chain.util.cjs vendored Normal file

File diff suppressed because it is too large Load Diff

1
dist/utils/chain.util.cjs.map vendored Normal file

File diff suppressed because one or more lines are too long

37
dist/utils/chain.util.d.cts vendored Normal file
View File

@ -0,0 +1,37 @@
declare function recoverTypedSignatureV4(signObj: any, signature: string): string;
declare function formatAddress(address: string): string;
declare function buildLoginSignMsg(nonce: string, tips: string): {
types: {
EIP712Domain: {
name: string;
type: string;
}[];
set: {
name: string;
type: string;
}[];
};
primaryType: string;
domain: {
name: string;
version: string;
};
message: {
tips: string;
nonce: string;
};
};
declare const sign: ({ user, token, amount, saltNonce, }: {
user: string;
token: string;
amount: number | string;
saltNonce?: string;
}) => Promise<{
token: string;
amount: string;
startTime: number;
saltNonce: string;
signature: string;
}>;
export { buildLoginSignMsg, formatAddress, recoverTypedSignatureV4, sign };

37
dist/utils/chain.util.d.ts vendored Normal file
View File

@ -0,0 +1,37 @@
declare function recoverTypedSignatureV4(signObj: any, signature: string): string;
declare function formatAddress(address: string): string;
declare function buildLoginSignMsg(nonce: string, tips: string): {
types: {
EIP712Domain: {
name: string;
type: string;
}[];
set: {
name: string;
type: string;
}[];
};
primaryType: string;
domain: {
name: string;
version: string;
};
message: {
tips: string;
nonce: string;
};
};
declare const sign: ({ user, token, amount, saltNonce, }: {
user: string;
token: string;
amount: number | string;
saltNonce?: string;
}) => Promise<{
token: string;
amount: string;
startTime: number;
saltNonce: string;
signature: string;
}>;
export { buildLoginSignMsg, formatAddress, recoverTypedSignatureV4, sign };

15461
dist/utils/chain.util.js vendored Normal file

File diff suppressed because it is too large Load Diff

1
dist/utils/chain.util.js.map vendored Normal file

File diff suppressed because one or more lines are too long

59
dist/utils/date.util.cjs vendored Normal file
View File

@ -0,0 +1,59 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/date.util.ts
var date_util_exports = {};
__export(date_util_exports, {
ONE_DAY: () => ONE_DAY,
daysBetween: () => daysBetween,
formatDate: () => formatDate,
nextday: () => nextday,
yesterday: () => yesterday
});
module.exports = __toCommonJS(date_util_exports);
var ONE_DAY = 24 * 60 * 60 * 1e3;
var formatDate = (date) => {
const year = date.getFullYear();
const month = (date.getMonth() + 1 + "").padStart(2, "0");
const day = (date.getDate() + "").padStart(2, "0");
return `${year}${month}${day}`;
};
var yesterday = (date) => {
date = date || /* @__PURE__ */ new Date();
date.setDate(date.getDate() - 1);
return date;
};
var nextday = (date) => {
date = date || /* @__PURE__ */ new Date();
date.setDate(date.getDate() + 1);
return date;
};
function daysBetween(date1, date2) {
const diffInMs = Math.abs(date1.getTime() - date2.getTime());
const diffInDays = Math.round(diffInMs / ONE_DAY);
return diffInDays;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ONE_DAY,
daysBetween,
formatDate,
nextday,
yesterday
});
//# sourceMappingURL=date.util.cjs.map

1
dist/utils/date.util.cjs.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/utils/date.util.ts"],"sourcesContent":["export const ONE_DAY = 24 * 60 * 60 * 1000\n\n// format the date to the format we want\nexport const formatDate = (date: Date): string => {\n const year = date.getFullYear()\n const month = (date.getMonth() + 1 + '').padStart(2, '0')\n const day = (date.getDate() + '').padStart(2, '0')\n return `${year}${month}${day}`\n}\n\n// get formated datestring of yesterday\nexport const yesterday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() - 1)\n return date\n}\n\nexport const nextday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() + 1)\n return date\n}\n\n// calc days between two Date\nexport function daysBetween(date1: Date, date2: Date) {\n // hours*minutes*seconds*milliseconds\n const diffInMs = Math.abs(date1.getTime() - date2.getTime())\n const diffInDays = Math.round(diffInMs / ONE_DAY)\n return diffInDays\n}"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,UAAU,KAAK,KAAK,KAAK;AAG/B,IAAM,aAAa,CAAC,SAAuB;AAChD,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,SAAS,KAAK,SAAS,IAAI,IAAI,IAAI,SAAS,GAAG,GAAG;AACxD,QAAM,OAAO,KAAK,QAAQ,IAAI,IAAI,SAAS,GAAG,GAAG;AACjD,SAAO,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG;AAC9B;AAGO,IAAM,YAAY,CAAC,SAAgB;AACxC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAEO,IAAM,UAAU,CAAC,SAAgB;AACtC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAGO,SAAS,YAAY,OAAa,OAAa;AAEpD,QAAM,WAAW,KAAK,IAAI,MAAM,QAAQ,IAAI,MAAM,QAAQ,CAAC;AAC3D,QAAM,aAAa,KAAK,MAAM,WAAW,OAAO;AAChD,SAAO;AACT;","names":[]}

7
dist/utils/date.util.d.cts vendored Normal file
View File

@ -0,0 +1,7 @@
declare const ONE_DAY: number;
declare const formatDate: (date: Date) => string;
declare const yesterday: (date?: Date) => Date;
declare const nextday: (date?: Date) => Date;
declare function daysBetween(date1: Date, date2: Date): number;
export { ONE_DAY, daysBetween, formatDate, nextday, yesterday };

7
dist/utils/date.util.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
declare const ONE_DAY: number;
declare const formatDate: (date: Date) => string;
declare const yesterday: (date?: Date) => Date;
declare const nextday: (date?: Date) => Date;
declare function daysBetween(date1: Date, date2: Date): number;
export { ONE_DAY, daysBetween, formatDate, nextday, yesterday };

31
dist/utils/date.util.js vendored Normal file
View File

@ -0,0 +1,31 @@
// src/utils/date.util.ts
var ONE_DAY = 24 * 60 * 60 * 1e3;
var formatDate = (date) => {
const year = date.getFullYear();
const month = (date.getMonth() + 1 + "").padStart(2, "0");
const day = (date.getDate() + "").padStart(2, "0");
return `${year}${month}${day}`;
};
var yesterday = (date) => {
date = date || /* @__PURE__ */ new Date();
date.setDate(date.getDate() - 1);
return date;
};
var nextday = (date) => {
date = date || /* @__PURE__ */ new Date();
date.setDate(date.getDate() + 1);
return date;
};
function daysBetween(date1, date2) {
const diffInMs = Math.abs(date1.getTime() - date2.getTime());
const diffInDays = Math.round(diffInMs / ONE_DAY);
return diffInDays;
}
export {
ONE_DAY,
daysBetween,
formatDate,
nextday,
yesterday
};
//# sourceMappingURL=date.util.js.map

1
dist/utils/date.util.js.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/utils/date.util.ts"],"sourcesContent":["export const ONE_DAY = 24 * 60 * 60 * 1000\n\n// format the date to the format we want\nexport const formatDate = (date: Date): string => {\n const year = date.getFullYear()\n const month = (date.getMonth() + 1 + '').padStart(2, '0')\n const day = (date.getDate() + '').padStart(2, '0')\n return `${year}${month}${day}`\n}\n\n// get formated datestring of yesterday\nexport const yesterday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() - 1)\n return date\n}\n\nexport const nextday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() + 1)\n return date\n}\n\n// calc days between two Date\nexport function daysBetween(date1: Date, date2: Date) {\n // hours*minutes*seconds*milliseconds\n const diffInMs = Math.abs(date1.getTime() - date2.getTime())\n const diffInDays = Math.round(diffInMs / ONE_DAY)\n return diffInDays\n}"],"mappings":";AAAO,IAAM,UAAU,KAAK,KAAK,KAAK;AAG/B,IAAM,aAAa,CAAC,SAAuB;AAChD,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,SAAS,KAAK,SAAS,IAAI,IAAI,IAAI,SAAS,GAAG,GAAG;AACxD,QAAM,OAAO,KAAK,QAAQ,IAAI,IAAI,SAAS,GAAG,GAAG;AACjD,SAAO,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG;AAC9B;AAGO,IAAM,YAAY,CAAC,SAAgB;AACxC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAEO,IAAM,UAAU,CAAC,SAAgB;AACtC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAGO,SAAS,YAAY,OAAa,OAAa;AAEpD,QAAM,WAAW,KAAK,IAAI,MAAM,QAAQ,IAAI,MAAM,QAAQ,CAAC;AAC3D,QAAM,aAAa,KAAK,MAAM,WAAW,OAAO;AAChD,SAAO;AACT;","names":[]}

136
dist/utils/net.util.cjs vendored Normal file
View File

@ -0,0 +1,136 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/net.util.ts
var net_util_exports = {};
__export(net_util_exports, {
checkParamsNeeded: () => checkParamsNeeded,
fetchWithErrorHandling: () => fetchWithErrorHandling,
generateHeader: () => generateHeader,
handleFetch: () => handleFetch,
successfulFetch: () => successfulFetch,
timeoutFetch: () => timeoutFetch
});
module.exports = __toCommonJS(net_util_exports);
// src/common/ZError.ts
var ZError = class {
constructor(statusCode, message) {
this.statusCode = statusCode;
this.message = message;
}
};
// src/utils/net.util.ts
var TIMEOUT_ERROR = new Error("timeout");
async function successfulFetch(request, options) {
const response = await fetch(request, options);
if (!response.ok) {
throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`);
}
return response;
}
async function handleFetch(request, options) {
const response = await successfulFetch(request, options);
const object = await response.json();
return object;
}
async function fetchWithErrorHandling({
url,
options,
timeout,
errorCodesToCatch
}) {
let result;
try {
if (timeout) {
result = Promise.race([
await handleFetch(url, options),
new Promise(
(_, reject) => setTimeout(() => {
reject(TIMEOUT_ERROR);
}, timeout)
)
]);
} else {
result = await handleFetch(url, options);
}
} catch (e) {
logOrRethrowError(e, errorCodesToCatch);
}
return result;
}
async function timeoutFetch(url, options, timeout = 500) {
return Promise.race([
successfulFetch(url, options),
new Promise(
(_, reject) => setTimeout(() => {
reject(TIMEOUT_ERROR);
}, timeout)
)
]);
}
function logOrRethrowError(error, codesToCatch = []) {
if (!error) {
return;
}
const includesErrorCodeToCatch = codesToCatch.some(
(code) => error.message.includes(`Fetch failed with status '${code}'`)
);
if (error instanceof Error && (includesErrorCodeToCatch || error.message.includes("Failed to fetch") || error === TIMEOUT_ERROR)) {
console.error(error);
} else {
throw error;
}
}
function generateHeader() {
let random = function(start, end) {
return Math.random() * (end - start) + start | 0;
};
let getIp = function() {
return `${random(1, 254)}.${random(1, 254)}.${random(1, 254)}.${random(1, 254)}`;
};
let time = Date.now();
let useragent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${70 + Math.random() * 10 | 0}.0.4324.${Math.random() * 100 | 0} Safari/537.36`;
const ip = getIp();
return {
"Refresh-Token": time -= 5e3,
"Cache-Control": "no-cache",
"User-Agent": useragent,
"X-Forwarded-For": ip,
"X-Real-IP": ip,
"Content-Type": "application/json"
};
}
var checkParamsNeeded = (...args) => {
args.forEach((arg) => {
if (!arg) {
throw new ZError(10, "params mismatch");
}
});
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
checkParamsNeeded,
fetchWithErrorHandling,
generateHeader,
handleFetch,
successfulFetch,
timeoutFetch
});
//# sourceMappingURL=net.util.cjs.map

1
dist/utils/net.util.cjs.map vendored Normal file

File diff suppressed because one or more lines are too long

52
dist/utils/net.util.d.cts vendored Normal file
View File

@ -0,0 +1,52 @@
/**
* Execute fetch and verify that the response was successful.
*
* @param request - Request information.
* @param options - Fetch options.
* @returns The fetch response.
*/
declare function successfulFetch(request: string, options?: RequestInit): Promise<Response>;
/**
* Execute fetch and return object response.
*
* @param request - The request information.
* @param options - The fetch options.
* @returns The fetch response JSON data.
*/
declare function handleFetch(request: string, options?: RequestInit): Promise<any>;
/**
* Execute fetch and return object response, log if known error thrown, otherwise rethrow error.
*
* @param request - the request options object
* @param request.url - The request url to query.
* @param request.options - The fetch options.
* @param request.timeout - Timeout to fail request
* @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context
* @returns The fetch response JSON data or undefined (if error occurs).
*/
declare function fetchWithErrorHandling({ url, options, timeout, errorCodesToCatch, }: {
url: string;
options?: RequestInit;
timeout?: number;
errorCodesToCatch?: number[];
}): Promise<any>;
/**
* Fetch that fails after timeout.
*
* @param url - Url to fetch.
* @param options - Options to send with the request.
* @param timeout - Timeout to fail request.
* @returns Promise resolving the request.
*/
declare function timeoutFetch(url: string, options?: RequestInit, timeout?: number): Promise<Response>;
declare function generateHeader(): {
'Refresh-Token': number;
'Cache-Control': string;
'User-Agent': string;
'X-Forwarded-For': string;
'X-Real-IP': string;
'Content-Type': string;
};
declare const checkParamsNeeded: (...args: any[]) => void;
export { checkParamsNeeded, fetchWithErrorHandling, generateHeader, handleFetch, successfulFetch, timeoutFetch };

52
dist/utils/net.util.d.ts vendored Normal file
View File

@ -0,0 +1,52 @@
/**
* Execute fetch and verify that the response was successful.
*
* @param request - Request information.
* @param options - Fetch options.
* @returns The fetch response.
*/
declare function successfulFetch(request: string, options?: RequestInit): Promise<Response>;
/**
* Execute fetch and return object response.
*
* @param request - The request information.
* @param options - The fetch options.
* @returns The fetch response JSON data.
*/
declare function handleFetch(request: string, options?: RequestInit): Promise<any>;
/**
* Execute fetch and return object response, log if known error thrown, otherwise rethrow error.
*
* @param request - the request options object
* @param request.url - The request url to query.
* @param request.options - The fetch options.
* @param request.timeout - Timeout to fail request
* @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context
* @returns The fetch response JSON data or undefined (if error occurs).
*/
declare function fetchWithErrorHandling({ url, options, timeout, errorCodesToCatch, }: {
url: string;
options?: RequestInit;
timeout?: number;
errorCodesToCatch?: number[];
}): Promise<any>;
/**
* Fetch that fails after timeout.
*
* @param url - Url to fetch.
* @param options - Options to send with the request.
* @param timeout - Timeout to fail request.
* @returns Promise resolving the request.
*/
declare function timeoutFetch(url: string, options?: RequestInit, timeout?: number): Promise<Response>;
declare function generateHeader(): {
'Refresh-Token': number;
'Cache-Control': string;
'User-Agent': string;
'X-Forwarded-For': string;
'X-Real-IP': string;
'Content-Type': string;
};
declare const checkParamsNeeded: (...args: any[]) => void;
export { checkParamsNeeded, fetchWithErrorHandling, generateHeader, handleFetch, successfulFetch, timeoutFetch };

105
dist/utils/net.util.js vendored Normal file
View File

@ -0,0 +1,105 @@
// src/common/ZError.ts
var ZError = class {
constructor(statusCode, message) {
this.statusCode = statusCode;
this.message = message;
}
};
// src/utils/net.util.ts
var TIMEOUT_ERROR = new Error("timeout");
async function successfulFetch(request, options) {
const response = await fetch(request, options);
if (!response.ok) {
throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`);
}
return response;
}
async function handleFetch(request, options) {
const response = await successfulFetch(request, options);
const object = await response.json();
return object;
}
async function fetchWithErrorHandling({
url,
options,
timeout,
errorCodesToCatch
}) {
let result;
try {
if (timeout) {
result = Promise.race([
await handleFetch(url, options),
new Promise(
(_, reject) => setTimeout(() => {
reject(TIMEOUT_ERROR);
}, timeout)
)
]);
} else {
result = await handleFetch(url, options);
}
} catch (e) {
logOrRethrowError(e, errorCodesToCatch);
}
return result;
}
async function timeoutFetch(url, options, timeout = 500) {
return Promise.race([
successfulFetch(url, options),
new Promise(
(_, reject) => setTimeout(() => {
reject(TIMEOUT_ERROR);
}, timeout)
)
]);
}
function logOrRethrowError(error, codesToCatch = []) {
if (!error) {
return;
}
const includesErrorCodeToCatch = codesToCatch.some(
(code) => error.message.includes(`Fetch failed with status '${code}'`)
);
if (error instanceof Error && (includesErrorCodeToCatch || error.message.includes("Failed to fetch") || error === TIMEOUT_ERROR)) {
console.error(error);
} else {
throw error;
}
}
function generateHeader() {
let random = function(start, end) {
return Math.random() * (end - start) + start | 0;
};
let getIp = function() {
return `${random(1, 254)}.${random(1, 254)}.${random(1, 254)}.${random(1, 254)}`;
};
let time = Date.now();
let useragent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${70 + Math.random() * 10 | 0}.0.4324.${Math.random() * 100 | 0} Safari/537.36`;
const ip = getIp();
return {
"Refresh-Token": time -= 5e3,
"Cache-Control": "no-cache",
"User-Agent": useragent,
"X-Forwarded-For": ip,
"X-Real-IP": ip,
"Content-Type": "application/json"
};
}
var checkParamsNeeded = (...args) => {
args.forEach((arg) => {
if (!arg) {
throw new ZError(10, "params mismatch");
}
});
};
export {
checkParamsNeeded,
fetchWithErrorHandling,
generateHeader,
handleFetch,
successfulFetch,
timeoutFetch
};
//# sourceMappingURL=net.util.js.map

1
dist/utils/net.util.js.map vendored Normal file

File diff suppressed because one or more lines are too long

221
dist/utils/number.util.cjs vendored Normal file
View File

@ -0,0 +1,221 @@
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/number.util.ts
var number_util_exports = {};
__export(number_util_exports, {
addHexPrefix: () => addHexPrefix,
calcTokenValueToSend: () => calcTokenValueToSend,
convert: () => convert,
fastSplit: () => fastSplit,
fromTokenMinimalUnit: () => fromTokenMinimalUnit,
isDecimal: () => isDecimal,
numberToBN: () => numberToBN,
renderFromTokenMinimalUnit: () => renderFromTokenMinimalUnit,
renderFromWei: () => renderFromWei,
safeNumberToBN: () => safeNumberToBN,
stripHexPrefix: () => stripHexPrefix,
toBN: () => toBN
});
module.exports = __toCommonJS(number_util_exports);
var import_web3 = __toESM(require("web3"), 1);
var import_ethereumjs_util = require("ethereumjs-util");
function renderFromTokenMinimalUnit(tokenValue, decimals, decimalsToShow = 5) {
const minimalUnit = fromTokenMinimalUnit(tokenValue || 0, decimals);
const minimalUnitNumber = parseFloat(minimalUnit);
let renderMinimalUnit;
if (minimalUnitNumber < 1e-5 && minimalUnitNumber > 0) {
renderMinimalUnit = "< 0.00001";
} else {
const base = Math.pow(10, decimalsToShow);
renderMinimalUnit = (Math.round(minimalUnitNumber * base) / base).toString();
}
return renderMinimalUnit;
}
function fromTokenMinimalUnit(minimalInput, decimals) {
minimalInput = addHexPrefix(Number(minimalInput).toString(16));
let minimal = safeNumberToBN(minimalInput);
const negative = minimal.lt(new import_ethereumjs_util.BN(0));
const base = import_web3.default.utils.toBN(Math.pow(10, decimals).toString());
if (negative) {
minimal = minimal.mul(new import_ethereumjs_util.BN(-1));
}
let fraction = minimal.mod(base).toString(10);
while (fraction.length < decimals) {
fraction = "0" + fraction;
}
fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
const whole = minimal.div(base).toString(10);
let value = "" + whole + (fraction === "0" ? "" : "." + fraction);
if (negative) {
value = "-" + value;
}
return value;
}
function renderFromWei(value, decimalsToShow = 5) {
let renderWei = "0";
if (value) {
const wei = import_web3.default.utils.fromWei(value);
const weiNumber = parseFloat(wei);
if (weiNumber < 1e-5 && weiNumber > 0) {
renderWei = "< 0.00001";
} else {
const base = Math.pow(10, decimalsToShow);
renderWei = (Math.round(weiNumber * base) / base).toString();
}
}
return renderWei;
}
function calcTokenValueToSend(value, decimals) {
return value ? (value * Math.pow(10, decimals)).toString(16) : 0;
}
function isDecimal(value) {
return Number.isFinite(parseFloat(value)) && !Number.isNaN(parseFloat(value)) && !isNaN(+value);
}
function toBN(value) {
return import_web3.default.utils.toBN(value);
}
var addHexPrefix = (str) => {
if (typeof str !== "string" || str.match(/^-?0x/u)) {
return str;
}
if (str.match(/^-?0X/u)) {
return str.replace("0X", "0x");
}
if (str.startsWith("-")) {
return str.replace("-", "-0x");
}
return `0x${str}`;
};
function safeNumberToBN(value) {
const safeValue = fastSplit(value.toString()) || "0";
return numberToBN(safeValue);
}
function fastSplit(value, divider = ".") {
value += "";
const [from, to] = [value.indexOf(divider), 0];
return value.substring(from, to) || value;
}
function stripHexPrefix(str) {
if (typeof str !== "string") {
return str;
}
return str.slice(0, 2) === "0x" ? str.slice(2) : str;
}
function numberToBN(arg) {
if (typeof arg === "string" || typeof arg === "number") {
var multiplier = import_web3.default.utils.toBN(1);
var formattedString = String(arg).toLowerCase().trim();
var isHexPrefixed = formattedString.substr(0, 2) === "0x" || formattedString.substr(0, 3) === "-0x";
var stringArg = stripHexPrefix(formattedString);
if (stringArg.substr(0, 1) === "-") {
stringArg = stripHexPrefix(stringArg.slice(1));
multiplier = import_web3.default.utils.toBN(-1);
}
stringArg = stringArg === "" ? "0" : stringArg;
if (!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/) || stringArg.match(/^[a-fA-F]+$/) || isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/)) {
return import_web3.default.utils.toBN(stringArg).mul(multiplier);
}
if ((stringArg.match(/^-?[0-9]+$/) || stringArg === "") && isHexPrefixed === false) {
return import_web3.default.utils.toBN(stringArg).mul(multiplier);
}
} else if (typeof arg === "object" && arg.toString && !arg.pop && !arg.push) {
if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) {
return import_web3.default.utils.toBN(arg.toString(10));
}
}
throw new Error(
"[number-to-bn] while converting number " + JSON.stringify(arg) + " to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported."
);
}
function checkRadixLegal(radix) {
return radix >= 2 && radix <= 62;
}
function transformCharToNum(letter, base) {
if (base <= 36) {
letter = letter.toLowerCase();
}
if (letter >= "0" && letter <= "9") {
return parseInt(letter);
}
if (letter >= "a" && letter <= "z") {
return letter.charCodeAt(0) - "a".charCodeAt(0) + 10;
}
if (letter >= "A" && letter <= "Z") {
return letter.charCodeAt(0) - "A".charCodeAt(0) + 36;
}
return 0;
}
function transformNumToChar(num, alphabet) {
alphabet = alphabet || "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return alphabet.charAt(num);
}
function convert({
numStr,
base,
to,
alphabet
}) {
if (base === to || !checkRadixLegal(base) || !checkRadixLegal(to)) {
return numStr;
}
let p = 0;
let number10 = 0;
while (p < numStr.length) {
number10 *= base;
number10 += transformCharToNum(numStr.charAt(p), base);
p++;
}
if (to === 10) {
return number10.toString();
}
let result = "";
let cur;
while (number10) {
cur = number10 % to;
result = transformNumToChar(cur, alphabet) + result;
number10 = Math.floor(number10 / to);
}
return result;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
addHexPrefix,
calcTokenValueToSend,
convert,
fastSplit,
fromTokenMinimalUnit,
isDecimal,
numberToBN,
renderFromTokenMinimalUnit,
renderFromWei,
safeNumberToBN,
stripHexPrefix,
toBN
});
//# sourceMappingURL=number.util.cjs.map

1
dist/utils/number.util.cjs.map vendored Normal file

File diff suppressed because one or more lines are too long

90
dist/utils/number.util.d.cts vendored Normal file
View File

@ -0,0 +1,90 @@
import { BN } from 'ethereumjs-util';
/**
* Converts some token minimal unit to render format string, showing 5 decimals
*
* @param {Number|String|BN} tokenValue - Token value to convert
* @param {Number} decimals - Token decimals to convert
* @param {Number} decimalsToShow - Decimals to 5
* @returns {String} - Number of token minimal unit, in render format
* If value is less than 5 precision decimals will show '< 0.00001'
*/
declare function renderFromTokenMinimalUnit(tokenValue: any, decimals: any, decimalsToShow?: number): any;
/**
* Converts token minimal unit to readable string value
*
* @param {number|string|Object} minimalInput - Token minimal unit to convert
* @param {string} decimals - Token decimals to convert
* @returns {string} - String containing the new number
*/
declare function fromTokenMinimalUnit(minimalInput: any, decimals: any): string;
/**
* Converts wei to render format string, showing 5 decimals
*
* @param {Number|String|BN} value - Wei to convert
* @param {Number} decimalsToShow - Decimals to 5
* @returns {String} - Number of token minimal unit, in render format
* If value is less than 5 precision decimals will show '< 0.00001'
*/
declare function renderFromWei(value: any, decimalsToShow?: number): string;
/**
* Converts token BN value to hex string number to be sent
*
* @param {Object} value - BN instance to convert
* @param {number} decimals - Decimals to be considered on the conversion
* @returns {string} - String of the hex token value
*/
declare function calcTokenValueToSend(value: any, decimals: any): string | 0;
/**
* Determines if a string is a valid decimal
*
* @param {string} value - String to check
* @returns {boolean} - True if the string is a valid decimal
*/
declare function isDecimal(value: any): boolean;
/**
* Creates a BN object from a string
*
* @param {string} value - Some numeric value represented as a string
* @returns {Object} - BN instance
*/
declare function toBN(value: any): BN;
/**
* Prefixes a hex string with '0x' or '-0x' and returns it. Idempotent.
*
* @param {string} str - The string to prefix.
* @returns {string} The prefixed string.
*/
declare const addHexPrefix: (str: string) => string;
/**
* Wraps 'numberToBN' method to avoid potential undefined and decimal values
*
* @param {number|string} value - number
* @returns {Object} - The converted value as BN instance
*/
declare function safeNumberToBN(value: number | string): BN;
/**
* Performs a fast string split and returns the first item of the string based on the divider provided
*
* @param {number|string} value - number/string to be splitted
* @param {string} divider - string value to use to split the string (default '.')
* @returns {string} - the selected splitted element
*/
declare function fastSplit(value: any, divider?: string): any;
declare function stripHexPrefix(str: string): string;
declare function numberToBN(arg: any): BN;
/**
* num从base进制转为to指定的进制
* @param {string} numStr
* @param {number} base num的进制
* @param {number} to
* @return {string}
*/
declare function convert({ numStr, base, to, alphabet, }: {
numStr: string;
base: number;
to: number;
alphabet?: string;
}): string;
export { addHexPrefix, calcTokenValueToSend, convert, fastSplit, fromTokenMinimalUnit, isDecimal, numberToBN, renderFromTokenMinimalUnit, renderFromWei, safeNumberToBN, stripHexPrefix, toBN };

90
dist/utils/number.util.d.ts vendored Normal file
View File

@ -0,0 +1,90 @@
import { BN } from 'ethereumjs-util';
/**
* Converts some token minimal unit to render format string, showing 5 decimals
*
* @param {Number|String|BN} tokenValue - Token value to convert
* @param {Number} decimals - Token decimals to convert
* @param {Number} decimalsToShow - Decimals to 5
* @returns {String} - Number of token minimal unit, in render format
* If value is less than 5 precision decimals will show '< 0.00001'
*/
declare function renderFromTokenMinimalUnit(tokenValue: any, decimals: any, decimalsToShow?: number): any;
/**
* Converts token minimal unit to readable string value
*
* @param {number|string|Object} minimalInput - Token minimal unit to convert
* @param {string} decimals - Token decimals to convert
* @returns {string} - String containing the new number
*/
declare function fromTokenMinimalUnit(minimalInput: any, decimals: any): string;
/**
* Converts wei to render format string, showing 5 decimals
*
* @param {Number|String|BN} value - Wei to convert
* @param {Number} decimalsToShow - Decimals to 5
* @returns {String} - Number of token minimal unit, in render format
* If value is less than 5 precision decimals will show '< 0.00001'
*/
declare function renderFromWei(value: any, decimalsToShow?: number): string;
/**
* Converts token BN value to hex string number to be sent
*
* @param {Object} value - BN instance to convert
* @param {number} decimals - Decimals to be considered on the conversion
* @returns {string} - String of the hex token value
*/
declare function calcTokenValueToSend(value: any, decimals: any): string | 0;
/**
* Determines if a string is a valid decimal
*
* @param {string} value - String to check
* @returns {boolean} - True if the string is a valid decimal
*/
declare function isDecimal(value: any): boolean;
/**
* Creates a BN object from a string
*
* @param {string} value - Some numeric value represented as a string
* @returns {Object} - BN instance
*/
declare function toBN(value: any): BN;
/**
* Prefixes a hex string with '0x' or '-0x' and returns it. Idempotent.
*
* @param {string} str - The string to prefix.
* @returns {string} The prefixed string.
*/
declare const addHexPrefix: (str: string) => string;
/**
* Wraps 'numberToBN' method to avoid potential undefined and decimal values
*
* @param {number|string} value - number
* @returns {Object} - The converted value as BN instance
*/
declare function safeNumberToBN(value: number | string): BN;
/**
* Performs a fast string split and returns the first item of the string based on the divider provided
*
* @param {number|string} value - number/string to be splitted
* @param {string} divider - string value to use to split the string (default '.')
* @returns {string} - the selected splitted element
*/
declare function fastSplit(value: any, divider?: string): any;
declare function stripHexPrefix(str: string): string;
declare function numberToBN(arg: any): BN;
/**
* num从base进制转为to指定的进制
* @param {string} numStr
* @param {number} base num的进制
* @param {number} to
* @return {string}
*/
declare function convert({ numStr, base, to, alphabet, }: {
numStr: string;
base: number;
to: number;
alphabet?: string;
}): string;
export { addHexPrefix, calcTokenValueToSend, convert, fastSplit, fromTokenMinimalUnit, isDecimal, numberToBN, renderFromTokenMinimalUnit, renderFromWei, safeNumberToBN, stripHexPrefix, toBN };

176
dist/utils/number.util.js vendored Normal file
View File

@ -0,0 +1,176 @@
// src/utils/number.util.ts
import Web3 from "web3";
import { BN } from "ethereumjs-util";
function renderFromTokenMinimalUnit(tokenValue, decimals, decimalsToShow = 5) {
const minimalUnit = fromTokenMinimalUnit(tokenValue || 0, decimals);
const minimalUnitNumber = parseFloat(minimalUnit);
let renderMinimalUnit;
if (minimalUnitNumber < 1e-5 && minimalUnitNumber > 0) {
renderMinimalUnit = "< 0.00001";
} else {
const base = Math.pow(10, decimalsToShow);
renderMinimalUnit = (Math.round(minimalUnitNumber * base) / base).toString();
}
return renderMinimalUnit;
}
function fromTokenMinimalUnit(minimalInput, decimals) {
minimalInput = addHexPrefix(Number(minimalInput).toString(16));
let minimal = safeNumberToBN(minimalInput);
const negative = minimal.lt(new BN(0));
const base = Web3.utils.toBN(Math.pow(10, decimals).toString());
if (negative) {
minimal = minimal.mul(new BN(-1));
}
let fraction = minimal.mod(base).toString(10);
while (fraction.length < decimals) {
fraction = "0" + fraction;
}
fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
const whole = minimal.div(base).toString(10);
let value = "" + whole + (fraction === "0" ? "" : "." + fraction);
if (negative) {
value = "-" + value;
}
return value;
}
function renderFromWei(value, decimalsToShow = 5) {
let renderWei = "0";
if (value) {
const wei = Web3.utils.fromWei(value);
const weiNumber = parseFloat(wei);
if (weiNumber < 1e-5 && weiNumber > 0) {
renderWei = "< 0.00001";
} else {
const base = Math.pow(10, decimalsToShow);
renderWei = (Math.round(weiNumber * base) / base).toString();
}
}
return renderWei;
}
function calcTokenValueToSend(value, decimals) {
return value ? (value * Math.pow(10, decimals)).toString(16) : 0;
}
function isDecimal(value) {
return Number.isFinite(parseFloat(value)) && !Number.isNaN(parseFloat(value)) && !isNaN(+value);
}
function toBN(value) {
return Web3.utils.toBN(value);
}
var addHexPrefix = (str) => {
if (typeof str !== "string" || str.match(/^-?0x/u)) {
return str;
}
if (str.match(/^-?0X/u)) {
return str.replace("0X", "0x");
}
if (str.startsWith("-")) {
return str.replace("-", "-0x");
}
return `0x${str}`;
};
function safeNumberToBN(value) {
const safeValue = fastSplit(value.toString()) || "0";
return numberToBN(safeValue);
}
function fastSplit(value, divider = ".") {
value += "";
const [from, to] = [value.indexOf(divider), 0];
return value.substring(from, to) || value;
}
function stripHexPrefix(str) {
if (typeof str !== "string") {
return str;
}
return str.slice(0, 2) === "0x" ? str.slice(2) : str;
}
function numberToBN(arg) {
if (typeof arg === "string" || typeof arg === "number") {
var multiplier = Web3.utils.toBN(1);
var formattedString = String(arg).toLowerCase().trim();
var isHexPrefixed = formattedString.substr(0, 2) === "0x" || formattedString.substr(0, 3) === "-0x";
var stringArg = stripHexPrefix(formattedString);
if (stringArg.substr(0, 1) === "-") {
stringArg = stripHexPrefix(stringArg.slice(1));
multiplier = Web3.utils.toBN(-1);
}
stringArg = stringArg === "" ? "0" : stringArg;
if (!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/) || stringArg.match(/^[a-fA-F]+$/) || isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/)) {
return Web3.utils.toBN(stringArg).mul(multiplier);
}
if ((stringArg.match(/^-?[0-9]+$/) || stringArg === "") && isHexPrefixed === false) {
return Web3.utils.toBN(stringArg).mul(multiplier);
}
} else if (typeof arg === "object" && arg.toString && !arg.pop && !arg.push) {
if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) {
return Web3.utils.toBN(arg.toString(10));
}
}
throw new Error(
"[number-to-bn] while converting number " + JSON.stringify(arg) + " to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported."
);
}
function checkRadixLegal(radix) {
return radix >= 2 && radix <= 62;
}
function transformCharToNum(letter, base) {
if (base <= 36) {
letter = letter.toLowerCase();
}
if (letter >= "0" && letter <= "9") {
return parseInt(letter);
}
if (letter >= "a" && letter <= "z") {
return letter.charCodeAt(0) - "a".charCodeAt(0) + 10;
}
if (letter >= "A" && letter <= "Z") {
return letter.charCodeAt(0) - "A".charCodeAt(0) + 36;
}
return 0;
}
function transformNumToChar(num, alphabet) {
alphabet = alphabet || "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return alphabet.charAt(num);
}
function convert({
numStr,
base,
to,
alphabet
}) {
if (base === to || !checkRadixLegal(base) || !checkRadixLegal(to)) {
return numStr;
}
let p = 0;
let number10 = 0;
while (p < numStr.length) {
number10 *= base;
number10 += transformCharToNum(numStr.charAt(p), base);
p++;
}
if (to === 10) {
return number10.toString();
}
let result = "";
let cur;
while (number10) {
cur = number10 % to;
result = transformNumToChar(cur, alphabet) + result;
number10 = Math.floor(number10 / to);
}
return result;
}
export {
addHexPrefix,
calcTokenValueToSend,
convert,
fastSplit,
fromTokenMinimalUnit,
isDecimal,
numberToBN,
renderFromTokenMinimalUnit,
renderFromWei,
safeNumberToBN,
stripHexPrefix,
toBN
};
//# sourceMappingURL=number.util.js.map

1
dist/utils/number.util.js.map vendored Normal file

File diff suppressed because one or more lines are too long

97
dist/utils/promise.util.cjs vendored Normal file
View File

@ -0,0 +1,97 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/promise.util.ts
var promise_util_exports = {};
__export(promise_util_exports, {
Deferred: () => Deferred,
PromiseQueue: () => PromiseQueue,
retry: () => retry
});
module.exports = __toCommonJS(promise_util_exports);
function retry(promiseFn, options) {
let retries = 0;
let defaultOptions = {
maxRetries: 3,
whitelistErrors: []
};
Object.assign(defaultOptions, options);
const { maxRetries, whitelistErrors } = options;
const retryPromise = async () => {
try {
return await promiseFn();
} catch (err) {
if (retries < maxRetries && whitelistErrors.some((whitelistedError) => err instanceof whitelistedError.constructor)) {
retries++;
return retryPromise();
}
throw err;
}
};
return retryPromise();
}
var Deferred = class {
constructor() {
this.promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
resolve(value) {
this._resolve(value);
}
reject(reason) {
this._reject(reason);
}
then(onfulfilled, onrejected) {
return this.promise.then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.promise.catch(onrejected);
}
};
var PromiseQueue = class {
constructor({ concurrency = 2 }) {
this._current = 0;
this._list = [];
this.concurrency = concurrency;
}
add(promiseFn) {
this._list.push(promiseFn);
this.loadNext();
}
loadNext() {
if (this._list.length === 0 || this.concurrency === this._current)
return;
this._current++;
const fn = this._list.shift();
const promise = fn.call(this);
promise.then(this.onLoaded.bind(this)).catch(this.onLoaded.bind(this));
}
onLoaded() {
this._current--;
this.loadNext();
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Deferred,
PromiseQueue,
retry
});
//# sourceMappingURL=promise.util.cjs.map

1
dist/utils/promise.util.cjs.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/utils/promise.util.ts"],"sourcesContent":["type RetryOptions = {\n maxRetries: number\n whitelistErrors: Error[]\n}\n/**\n * 使用:\n * retry(() => fetch(\"https://example.com\"), { maxRetries: 3, whitelistErrors: [] })\n * .then((response) => console.log(response))\n * .catch((error) => console.error(error));\n * @param promiseFn\n * @param options\n * @returns\n */\nexport function retry<T>(promiseFn: () => Promise<T>, options: RetryOptions): Promise<T> {\n let retries = 0\n let defaultOptions = {\n maxRetries: 3,\n whitelistErrors: [],\n }\n Object.assign(defaultOptions, options)\n const { maxRetries, whitelistErrors } = options\n\n const retryPromise = async (): Promise<T> => {\n try {\n return await promiseFn()\n } catch (err) {\n if (\n retries < maxRetries &&\n whitelistErrors.some(whitelistedError => err instanceof whitelistedError.constructor)\n ) {\n retries++\n return retryPromise()\n }\n throw err\n }\n }\n\n return retryPromise()\n}\n/**\n * 构建一个promise, 在\n * usage:\n * function delay(ms: number): Promise<void> {\n const deferred = new Deferred<void>();\n\n setTimeout(() => {\n deferred.resolve();\n }, ms);\n\n return deferred.promise;\n }\n\n console.log(\"start\");\n\n delay(1000).then(() => {\n console.log(\"after 1 second\");\n });\n\n console.log(\"end\");\n */\nexport class Deferred<T = any> {\n private _resolve!: (value: T | PromiseLike<T>) => void\n private _reject!: (reason?: any) => void\n\n public readonly promise: Promise<T>\n\n constructor() {\n this.promise = new Promise<T>((resolve, reject) => {\n this._resolve = resolve\n this._reject = reject\n })\n }\n\n public resolve(value: T | PromiseLike<T>): void {\n this._resolve(value)\n }\n\n public reject(reason?: any): void {\n this._reject(reason)\n }\n\n public then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n return this.promise.then(onfulfilled, onrejected)\n }\n\n public catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined,\n ): Promise<T | TResult> {\n return this.promise.catch(onrejected)\n }\n}\n\n/**\n * 简单限流的 Promise 队列\n * usage:\n const q = new PromiseQueue();\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((v) => {\n q.add(\n () =>\n new Promise((resolve) => {\n setTimeout(() => {\n console.log(v);\n resolve();\n }, 1000);\n })\n );\n});\n */\nexport class PromiseQueue {\n private readonly concurrency: number\n private _current: number = 0\n private _list: (() => Promise<any>)[] = []\n\n constructor({ concurrency = 2 }: { concurrency: number }) {\n this.concurrency = concurrency\n }\n\n add(promiseFn: () => Promise<any>) {\n this._list.push(promiseFn)\n this.loadNext()\n }\n\n loadNext() {\n if (this._list.length === 0 || this.concurrency === this._current) return\n this._current++\n const fn = this._list.shift()!\n const promise = fn.call(this)\n promise.then(this.onLoaded.bind(this)).catch(this.onLoaded.bind(this))\n }\n\n onLoaded() {\n this._current--\n this.loadNext()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaO,SAAS,MAAS,WAA6B,SAAmC;AACvF,MAAI,UAAU;AACd,MAAI,iBAAiB;AAAA,IACnB,YAAY;AAAA,IACZ,iBAAiB,CAAC;AAAA,EACpB;AACA,SAAO,OAAO,gBAAgB,OAAO;AACrC,QAAM,EAAE,YAAY,gBAAgB,IAAI;AAExC,QAAM,eAAe,YAAwB;AAC3C,QAAI;AACF,aAAO,MAAM,UAAU;AAAA,IACzB,SAAS,KAAK;AACZ,UACE,UAAU,cACV,gBAAgB,KAAK,sBAAoB,eAAe,iBAAiB,WAAW,GACpF;AACA;AACA,eAAO,aAAa;AAAA,MACtB;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAEA,SAAO,aAAa;AACtB;AAsBO,IAAM,WAAN,MAAwB;AAAA,EAM7B,cAAc;AACZ,SAAK,UAAU,IAAI,QAAW,CAAC,SAAS,WAAW;AACjD,WAAK,WAAW;AAChB,WAAK,UAAU;AAAA,IACjB,CAAC;AAAA,EACH;AAAA,EAEO,QAAQ,OAAiC;AAC9C,SAAK,SAAS,KAAK;AAAA,EACrB;AAAA,EAEO,OAAO,QAAoB;AAChC,SAAK,QAAQ,MAAM;AAAA,EACrB;AAAA,EAEO,KACL,aACA,YAC8B;AAC9B,WAAO,KAAK,QAAQ,KAAK,aAAa,UAAU;AAAA,EAClD;AAAA,EAEO,MACL,YACsB;AACtB,WAAO,KAAK,QAAQ,MAAM,UAAU;AAAA,EACtC;AACF;AAkBO,IAAM,eAAN,MAAmB;AAAA,EAKxB,YAAY,EAAE,cAAc,EAAE,GAA4B;AAH1D,SAAQ,WAAmB;AAC3B,SAAQ,QAAgC,CAAC;AAGvC,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,IAAI,WAA+B;AACjC,SAAK,MAAM,KAAK,SAAS;AACzB,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,WAAW;AACT,QAAI,KAAK,MAAM,WAAW,KAAK,KAAK,gBAAgB,KAAK;AAAU;AACnE,SAAK;AACL,UAAM,KAAK,KAAK,MAAM,MAAM;AAC5B,UAAM,UAAU,GAAG,KAAK,IAAI;AAC5B,YAAQ,KAAK,KAAK,SAAS,KAAK,IAAI,CAAC,EAAE,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC;AAAA,EACvE;AAAA,EAEA,WAAW;AACT,SAAK;AACL,SAAK,SAAS;AAAA,EAChB;AACF;","names":[]}

74
dist/utils/promise.util.d.cts vendored Normal file
View File

@ -0,0 +1,74 @@
type RetryOptions = {
maxRetries: number;
whitelistErrors: Error[];
};
/**
* 使:
* retry(() => fetch("https://example.com"), { maxRetries: 3, whitelistErrors: [] })
* .then((response) => console.log(response))
* .catch((error) => console.error(error));
* @param promiseFn
* @param options
* @returns
*/
declare function retry<T>(promiseFn: () => Promise<T>, options: RetryOptions): Promise<T>;
/**
* promise,
* usage:
* function delay(ms: number): Promise<void> {
const deferred = new Deferred<void>();
setTimeout(() => {
deferred.resolve();
}, ms);
return deferred.promise;
}
console.log("start");
delay(1000).then(() => {
console.log("after 1 second");
});
console.log("end");
*/
declare class Deferred<T = any> {
private _resolve;
private _reject;
readonly promise: Promise<T>;
constructor();
resolve(value: T | PromiseLike<T>): void;
reject(reason?: any): void;
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined): Promise<T | TResult>;
}
/**
* Promise
* usage:
const q = new PromiseQueue();
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((v) => {
q.add(
() =>
new Promise((resolve) => {
setTimeout(() => {
console.log(v);
resolve();
}, 1000);
})
);
});
*/
declare class PromiseQueue {
private readonly concurrency;
private _current;
private _list;
constructor({ concurrency }: {
concurrency: number;
});
add(promiseFn: () => Promise<any>): void;
loadNext(): void;
onLoaded(): void;
}
export { Deferred, PromiseQueue, retry };

74
dist/utils/promise.util.d.ts vendored Normal file
View File

@ -0,0 +1,74 @@
type RetryOptions = {
maxRetries: number;
whitelistErrors: Error[];
};
/**
* 使:
* retry(() => fetch("https://example.com"), { maxRetries: 3, whitelistErrors: [] })
* .then((response) => console.log(response))
* .catch((error) => console.error(error));
* @param promiseFn
* @param options
* @returns
*/
declare function retry<T>(promiseFn: () => Promise<T>, options: RetryOptions): Promise<T>;
/**
* promise,
* usage:
* function delay(ms: number): Promise<void> {
const deferred = new Deferred<void>();
setTimeout(() => {
deferred.resolve();
}, ms);
return deferred.promise;
}
console.log("start");
delay(1000).then(() => {
console.log("after 1 second");
});
console.log("end");
*/
declare class Deferred<T = any> {
private _resolve;
private _reject;
readonly promise: Promise<T>;
constructor();
resolve(value: T | PromiseLike<T>): void;
reject(reason?: any): void;
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined): Promise<T | TResult>;
}
/**
* Promise
* usage:
const q = new PromiseQueue();
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((v) => {
q.add(
() =>
new Promise((resolve) => {
setTimeout(() => {
console.log(v);
resolve();
}, 1000);
})
);
});
*/
declare class PromiseQueue {
private readonly concurrency;
private _current;
private _list;
constructor({ concurrency }: {
concurrency: number;
});
add(promiseFn: () => Promise<any>): void;
loadNext(): void;
onLoaded(): void;
}
export { Deferred, PromiseQueue, retry };

71
dist/utils/promise.util.js vendored Normal file
View File

@ -0,0 +1,71 @@
// src/utils/promise.util.ts
function retry(promiseFn, options) {
let retries = 0;
let defaultOptions = {
maxRetries: 3,
whitelistErrors: []
};
Object.assign(defaultOptions, options);
const { maxRetries, whitelistErrors } = options;
const retryPromise = async () => {
try {
return await promiseFn();
} catch (err) {
if (retries < maxRetries && whitelistErrors.some((whitelistedError) => err instanceof whitelistedError.constructor)) {
retries++;
return retryPromise();
}
throw err;
}
};
return retryPromise();
}
var Deferred = class {
constructor() {
this.promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
resolve(value) {
this._resolve(value);
}
reject(reason) {
this._reject(reason);
}
then(onfulfilled, onrejected) {
return this.promise.then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.promise.catch(onrejected);
}
};
var PromiseQueue = class {
constructor({ concurrency = 2 }) {
this._current = 0;
this._list = [];
this.concurrency = concurrency;
}
add(promiseFn) {
this._list.push(promiseFn);
this.loadNext();
}
loadNext() {
if (this._list.length === 0 || this.concurrency === this._current)
return;
this._current++;
const fn = this._list.shift();
const promise = fn.call(this);
promise.then(this.onLoaded.bind(this)).catch(this.onLoaded.bind(this));
}
onLoaded() {
this._current--;
this.loadNext();
}
};
export {
Deferred,
PromiseQueue,
retry
};
//# sourceMappingURL=promise.util.js.map

1
dist/utils/promise.util.js.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/utils/promise.util.ts"],"sourcesContent":["type RetryOptions = {\n maxRetries: number\n whitelistErrors: Error[]\n}\n/**\n * 使用:\n * retry(() => fetch(\"https://example.com\"), { maxRetries: 3, whitelistErrors: [] })\n * .then((response) => console.log(response))\n * .catch((error) => console.error(error));\n * @param promiseFn\n * @param options\n * @returns\n */\nexport function retry<T>(promiseFn: () => Promise<T>, options: RetryOptions): Promise<T> {\n let retries = 0\n let defaultOptions = {\n maxRetries: 3,\n whitelistErrors: [],\n }\n Object.assign(defaultOptions, options)\n const { maxRetries, whitelistErrors } = options\n\n const retryPromise = async (): Promise<T> => {\n try {\n return await promiseFn()\n } catch (err) {\n if (\n retries < maxRetries &&\n whitelistErrors.some(whitelistedError => err instanceof whitelistedError.constructor)\n ) {\n retries++\n return retryPromise()\n }\n throw err\n }\n }\n\n return retryPromise()\n}\n/**\n * 构建一个promise, 在\n * usage:\n * function delay(ms: number): Promise<void> {\n const deferred = new Deferred<void>();\n\n setTimeout(() => {\n deferred.resolve();\n }, ms);\n\n return deferred.promise;\n }\n\n console.log(\"start\");\n\n delay(1000).then(() => {\n console.log(\"after 1 second\");\n });\n\n console.log(\"end\");\n */\nexport class Deferred<T = any> {\n private _resolve!: (value: T | PromiseLike<T>) => void\n private _reject!: (reason?: any) => void\n\n public readonly promise: Promise<T>\n\n constructor() {\n this.promise = new Promise<T>((resolve, reject) => {\n this._resolve = resolve\n this._reject = reject\n })\n }\n\n public resolve(value: T | PromiseLike<T>): void {\n this._resolve(value)\n }\n\n public reject(reason?: any): void {\n this._reject(reason)\n }\n\n public then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n return this.promise.then(onfulfilled, onrejected)\n }\n\n public catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined,\n ): Promise<T | TResult> {\n return this.promise.catch(onrejected)\n }\n}\n\n/**\n * 简单限流的 Promise 队列\n * usage:\n const q = new PromiseQueue();\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((v) => {\n q.add(\n () =>\n new Promise((resolve) => {\n setTimeout(() => {\n console.log(v);\n resolve();\n }, 1000);\n })\n );\n});\n */\nexport class PromiseQueue {\n private readonly concurrency: number\n private _current: number = 0\n private _list: (() => Promise<any>)[] = []\n\n constructor({ concurrency = 2 }: { concurrency: number }) {\n this.concurrency = concurrency\n }\n\n add(promiseFn: () => Promise<any>) {\n this._list.push(promiseFn)\n this.loadNext()\n }\n\n loadNext() {\n if (this._list.length === 0 || this.concurrency === this._current) return\n this._current++\n const fn = this._list.shift()!\n const promise = fn.call(this)\n promise.then(this.onLoaded.bind(this)).catch(this.onLoaded.bind(this))\n }\n\n onLoaded() {\n this._current--\n this.loadNext()\n }\n}\n"],"mappings":";AAaO,SAAS,MAAS,WAA6B,SAAmC;AACvF,MAAI,UAAU;AACd,MAAI,iBAAiB;AAAA,IACnB,YAAY;AAAA,IACZ,iBAAiB,CAAC;AAAA,EACpB;AACA,SAAO,OAAO,gBAAgB,OAAO;AACrC,QAAM,EAAE,YAAY,gBAAgB,IAAI;AAExC,QAAM,eAAe,YAAwB;AAC3C,QAAI;AACF,aAAO,MAAM,UAAU;AAAA,IACzB,SAAS,KAAK;AACZ,UACE,UAAU,cACV,gBAAgB,KAAK,sBAAoB,eAAe,iBAAiB,WAAW,GACpF;AACA;AACA,eAAO,aAAa;AAAA,MACtB;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAEA,SAAO,aAAa;AACtB;AAsBO,IAAM,WAAN,MAAwB;AAAA,EAM7B,cAAc;AACZ,SAAK,UAAU,IAAI,QAAW,CAAC,SAAS,WAAW;AACjD,WAAK,WAAW;AAChB,WAAK,UAAU;AAAA,IACjB,CAAC;AAAA,EACH;AAAA,EAEO,QAAQ,OAAiC;AAC9C,SAAK,SAAS,KAAK;AAAA,EACrB;AAAA,EAEO,OAAO,QAAoB;AAChC,SAAK,QAAQ,MAAM;AAAA,EACrB;AAAA,EAEO,KACL,aACA,YAC8B;AAC9B,WAAO,KAAK,QAAQ,KAAK,aAAa,UAAU;AAAA,EAClD;AAAA,EAEO,MACL,YACsB;AACtB,WAAO,KAAK,QAAQ,MAAM,UAAU;AAAA,EACtC;AACF;AAkBO,IAAM,eAAN,MAAmB;AAAA,EAKxB,YAAY,EAAE,cAAc,EAAE,GAA4B;AAH1D,SAAQ,WAAmB;AAC3B,SAAQ,QAAgC,CAAC;AAGvC,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,IAAI,WAA+B;AACjC,SAAK,MAAM,KAAK,SAAS;AACzB,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,WAAW;AACT,QAAI,KAAK,MAAM,WAAW,KAAK,KAAK,gBAAgB,KAAK;AAAU;AACnE,SAAK;AACL,UAAM,KAAK,KAAK,MAAM,MAAM;AAC5B,UAAM,UAAU,GAAG,KAAK,IAAI;AAC5B,YAAQ,KAAK,KAAK,SAAS,KAAK,IAAI,CAAC,EAAE,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC;AAAA,EACvE;AAAA,EAEA,WAAW;AACT,SAAK;AACL,SAAK,SAAS;AAAA,EAChB;AACF;","names":[]}

178
dist/utils/security.util.cjs vendored Normal file
View File

@ -0,0 +1,178 @@
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/security.util.ts
var security_util_exports = {};
__export(security_util_exports, {
aesDecrypt: () => aesDecrypt,
aesEncrypt: () => aesEncrypt,
base58ToHex: () => base58ToHex,
checkSign: () => checkSign,
createSign: () => createSign,
genRandomString: () => genRandomString,
hexToBase32: () => hexToBase32,
hexToBase58: () => hexToBase58,
hmac: () => hmac,
hmacSha256: () => hmacSha256,
md5: () => md5,
sha1: () => sha1,
sha512: () => sha512
});
module.exports = __toCommonJS(security_util_exports);
var import_crypto = __toESM(require("crypto"), 1);
var import_crypto_js = __toESM(require("crypto-js"), 1);
function hmac(input, key, out) {
return out ? import_crypto.default.createHmac("sha1", key).update(input).digest(out) : import_crypto.default.createHmac("sha1", key).update(input).digest("hex");
}
function genRandomString(length) {
return import_crypto.default.randomBytes(Math.ceil(length / 2)).toString("hex").slice(0, length);
}
function sha512(password, salt) {
let hash = import_crypto.default.createHmac("sha512", salt);
hash.update(password);
let value = hash.digest("hex");
return {
salt,
passwordHash: value
};
}
function sha1(str) {
const md5sum = import_crypto.default.createHash("sha1");
md5sum.update(str);
str = md5sum.digest("hex");
return str;
}
function hmacSha256(str, key) {
const md5sum = import_crypto.default.createHmac("sha256", key);
md5sum.update(str);
const data = md5sum.digest("hex");
console.log(`HmacSHA256 rawContent is [${str}], key is [${key}], hash result is [${data}]`);
return data;
}
function md5(str) {
const md5sum = import_crypto.default.createHash("md5");
md5sum.update(str);
str = md5sum.digest("hex");
return str;
}
function createSign(secretKey, paramStr, timestamp) {
paramStr = `${paramStr}:${timestamp}:${secretKey}`;
return sha1(paramStr);
}
function checkSign({
secretKey,
data,
sign,
signKeys
}) {
signKeys.sort();
let signStr = "";
for (let key of signKeys) {
if (signStr.length > 0) {
signStr += "&";
}
signStr += `${key}=${data[key]}`;
}
console.log(signStr);
let sign1 = hmacSha256(signStr, secretKey);
return sign1 === sign;
}
var aesEncrypt = (plaintText, key) => {
key = import_crypto_js.default.SHA1(key).toString().substring(0, 16);
key = import_crypto_js.default.enc.Base64.parse(key);
let encryptedData = import_crypto_js.default.AES.encrypt(plaintText, key, {
mode: import_crypto_js.default.mode.ECB,
padding: import_crypto_js.default.pad.Pkcs7
});
return encryptedData.toString(import_crypto_js.default.format.Hex);
};
var aesDecrypt = (encryptedDataHexStr, key) => {
key = import_crypto_js.default.SHA1(key).toString().substring(0, 16);
key = import_crypto_js.default.enc.Base64.parse(key);
let encryptedHex = import_crypto_js.default.enc.Hex.parse(encryptedDataHexStr);
let encryptedBase64 = import_crypto_js.default.enc.Base64.stringify(encryptedHex);
var decryptedData = import_crypto_js.default.AES.decrypt(encryptedBase64, key, {
mode: import_crypto_js.default.mode.ECB,
padding: import_crypto_js.default.pad.Pkcs7
});
return decryptedData.toString(import_crypto_js.default.enc.Utf8);
};
var base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var hexToBase58 = (hexString) => {
const bytes = hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16));
let base58String = "";
let num = BigInt("0x" + hexString);
while (num > BigInt(0)) {
const remainder = num % BigInt(58);
num = num / BigInt(58);
base58String = base58Alphabet[Number(remainder)] + base58String;
}
return base58String;
};
var base58ToHex = (base58String) => {
const base58Length = base58String.length;
let num = BigInt(0);
let leadingZeros = 0;
for (let i = 0; i < base58Length; i++) {
const charIndex = base58Alphabet.indexOf(base58String[i]);
if (charIndex === -1) {
throw new Error("Invalid Base58 string");
}
num = num * BigInt(58) + BigInt(charIndex);
}
return num.toString(16);
};
var hexToBase32 = (hexString) => {
const bytes = hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16));
const base32Alphabet = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let base32String = "";
let num = BigInt("0x" + hexString);
while (num > BigInt(0)) {
const remainder = num % BigInt(32);
num = num / BigInt(32);
base32String = base32Alphabet[Number(remainder)] + base32String;
}
return base32String;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
aesDecrypt,
aesEncrypt,
base58ToHex,
checkSign,
createSign,
genRandomString,
hexToBase32,
hexToBase58,
hmac,
hmacSha256,
md5,
sha1,
sha512
});
//# sourceMappingURL=security.util.cjs.map

1
dist/utils/security.util.cjs.map vendored Normal file

File diff suppressed because one or more lines are too long

23
dist/utils/security.util.d.cts vendored Normal file
View File

@ -0,0 +1,23 @@
declare function hmac(input: any, key: any, out: any): string;
declare function genRandomString(length: any): string;
declare function sha512(password: string, salt: string): {
salt: string;
passwordHash: string;
};
declare function sha1(str: string): string;
declare function hmacSha256(str: string, key: any): string;
declare function md5(str: string): string;
declare function createSign(secretKey: string, paramStr: string, timestamp: number): string;
declare function checkSign({ secretKey, data, sign, signKeys, }: {
secretKey: string;
data: {};
sign: string;
signKeys: string[];
}): boolean;
declare const aesEncrypt: (plaintText: any, key: any) => any;
declare const aesDecrypt: (encryptedDataHexStr: any, key: any) => any;
declare const hexToBase58: (hexString: string) => string;
declare const base58ToHex: (base58String: string) => string;
declare const hexToBase32: (hexString: string) => string;
export { aesDecrypt, aesEncrypt, base58ToHex, checkSign, createSign, genRandomString, hexToBase32, hexToBase58, hmac, hmacSha256, md5, sha1, sha512 };

23
dist/utils/security.util.d.ts vendored Normal file
View File

@ -0,0 +1,23 @@
declare function hmac(input: any, key: any, out: any): string;
declare function genRandomString(length: any): string;
declare function sha512(password: string, salt: string): {
salt: string;
passwordHash: string;
};
declare function sha1(str: string): string;
declare function hmacSha256(str: string, key: any): string;
declare function md5(str: string): string;
declare function createSign(secretKey: string, paramStr: string, timestamp: number): string;
declare function checkSign({ secretKey, data, sign, signKeys, }: {
secretKey: string;
data: {};
sign: string;
signKeys: string[];
}): boolean;
declare const aesEncrypt: (plaintText: any, key: any) => any;
declare const aesDecrypt: (encryptedDataHexStr: any, key: any) => any;
declare const hexToBase58: (hexString: string) => string;
declare const base58ToHex: (base58String: string) => string;
declare const hexToBase32: (hexString: string) => string;
export { aesDecrypt, aesEncrypt, base58ToHex, checkSign, createSign, genRandomString, hexToBase32, hexToBase58, hmac, hmacSha256, md5, sha1, sha512 };

132
dist/utils/security.util.js vendored Normal file
View File

@ -0,0 +1,132 @@
// src/utils/security.util.ts
import crypto from "crypto";
import CryptoJS from "crypto-js";
function hmac(input, key, out) {
return out ? crypto.createHmac("sha1", key).update(input).digest(out) : crypto.createHmac("sha1", key).update(input).digest("hex");
}
function genRandomString(length) {
return crypto.randomBytes(Math.ceil(length / 2)).toString("hex").slice(0, length);
}
function sha512(password, salt) {
let hash = crypto.createHmac("sha512", salt);
hash.update(password);
let value = hash.digest("hex");
return {
salt,
passwordHash: value
};
}
function sha1(str) {
const md5sum = crypto.createHash("sha1");
md5sum.update(str);
str = md5sum.digest("hex");
return str;
}
function hmacSha256(str, key) {
const md5sum = crypto.createHmac("sha256", key);
md5sum.update(str);
const data = md5sum.digest("hex");
console.log(`HmacSHA256 rawContent is [${str}], key is [${key}], hash result is [${data}]`);
return data;
}
function md5(str) {
const md5sum = crypto.createHash("md5");
md5sum.update(str);
str = md5sum.digest("hex");
return str;
}
function createSign(secretKey, paramStr, timestamp) {
paramStr = `${paramStr}:${timestamp}:${secretKey}`;
return sha1(paramStr);
}
function checkSign({
secretKey,
data,
sign,
signKeys
}) {
signKeys.sort();
let signStr = "";
for (let key of signKeys) {
if (signStr.length > 0) {
signStr += "&";
}
signStr += `${key}=${data[key]}`;
}
console.log(signStr);
let sign1 = hmacSha256(signStr, secretKey);
return sign1 === sign;
}
var aesEncrypt = (plaintText, key) => {
key = CryptoJS.SHA1(key).toString().substring(0, 16);
key = CryptoJS.enc.Base64.parse(key);
let encryptedData = CryptoJS.AES.encrypt(plaintText, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encryptedData.toString(CryptoJS.format.Hex);
};
var aesDecrypt = (encryptedDataHexStr, key) => {
key = CryptoJS.SHA1(key).toString().substring(0, 16);
key = CryptoJS.enc.Base64.parse(key);
let encryptedHex = CryptoJS.enc.Hex.parse(encryptedDataHexStr);
let encryptedBase64 = CryptoJS.enc.Base64.stringify(encryptedHex);
var decryptedData = CryptoJS.AES.decrypt(encryptedBase64, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return decryptedData.toString(CryptoJS.enc.Utf8);
};
var base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var hexToBase58 = (hexString) => {
const bytes = hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16));
let base58String = "";
let num = BigInt("0x" + hexString);
while (num > BigInt(0)) {
const remainder = num % BigInt(58);
num = num / BigInt(58);
base58String = base58Alphabet[Number(remainder)] + base58String;
}
return base58String;
};
var base58ToHex = (base58String) => {
const base58Length = base58String.length;
let num = BigInt(0);
let leadingZeros = 0;
for (let i = 0; i < base58Length; i++) {
const charIndex = base58Alphabet.indexOf(base58String[i]);
if (charIndex === -1) {
throw new Error("Invalid Base58 string");
}
num = num * BigInt(58) + BigInt(charIndex);
}
return num.toString(16);
};
var hexToBase32 = (hexString) => {
const bytes = hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16));
const base32Alphabet = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let base32String = "";
let num = BigInt("0x" + hexString);
while (num > BigInt(0)) {
const remainder = num % BigInt(32);
num = num / BigInt(32);
base32String = base32Alphabet[Number(remainder)] + base32String;
}
return base32String;
};
export {
aesDecrypt,
aesEncrypt,
base58ToHex,
checkSign,
createSign,
genRandomString,
hexToBase32,
hexToBase58,
hmac,
hmacSha256,
md5,
sha1,
sha512
};
//# sourceMappingURL=security.util.js.map

1
dist/utils/security.util.js.map vendored Normal file

File diff suppressed because one or more lines are too long

96
dist/utils/string.util.cjs vendored Normal file
View File

@ -0,0 +1,96 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/string.util.ts
var string_util_exports = {};
__export(string_util_exports, {
generateKeyValStr: () => generateKeyValStr,
isObjectId: () => isObjectId,
isTrue: () => isTrue,
keyValToObject: () => keyValToObject,
string10to62: () => string10to62,
string62to10: () => string62to10
});
module.exports = __toCommonJS(string_util_exports);
function generateKeyValStr(data, ignoreNull = true, splitChar = "&", equalChar = "=") {
const keys = Object.keys(data);
keys.sort();
let result = "";
let i = 0;
for (let key of keys) {
if (ignoreNull && !data[key]) {
return;
}
if (i++ > 0)
result += splitChar;
result += `${key}${equalChar}${data[key]}`;
}
return result;
}
function keyValToObject(str, splitChar = "&", equalChar = "=") {
let result = {};
if (!str) {
return result;
}
let arrs = str.split(splitChar);
for (let sub of arrs) {
let subArr = sub.split(equalChar);
result[subArr[0]] = subArr[1];
}
return result;
}
function isTrue(obj) {
return obj === "true" || obj === "TRUE" || obj === "True" || obj === "on" || obj === "ON" || obj === true || obj === 1 || obj === "1" || obj === "YES" || obj === "yes";
}
function isObjectId(id) {
return /^[a-fA-F0-9]{24}$/.test(id);
}
function string10to62(number) {
const chars = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ".split("");
const radix = chars.length;
let qutient = +number;
const arr = [];
do {
const mod = qutient % radix;
qutient = (qutient - mod) / radix;
arr.unshift(chars[mod]);
} while (qutient);
return arr.join("");
}
function string62to10(numberCode) {
const chars = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
const radix = chars.length;
numberCode = numberCode + "";
const len = numberCode.length;
let i = 0;
let originNumber = 0;
while (i < len) {
originNumber += Math.pow(radix, i++) * (chars.indexOf(numberCode.charAt(len - i)) || 0);
}
return originNumber;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
generateKeyValStr,
isObjectId,
isTrue,
keyValToObject,
string10to62,
string62to10
});
//# sourceMappingURL=string.util.cjs.map

1
dist/utils/string.util.cjs.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/utils/string.util.ts"],"sourcesContent":["/**\n * 根据key升序生成 key1=val1&key2=val2的字符串\n * @param {object} data 需要处理的对象\n * @param {boolean} ignoreNull 是否过滤空值(空格或者null值不参与拼接)\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function generateKeyValStr(data: {}, ignoreNull = true, splitChar: string = '&', equalChar = '=') {\n const keys = Object.keys(data)\n keys.sort()\n let result = ''\n let i = 0\n for (let key of keys) {\n if (ignoreNull && !data[key]) {\n return\n }\n if (i++ > 0) result += splitChar\n result += `${key}${equalChar}${data[key]}`\n }\n return result\n}\n\n/**\n * 将key1=val&key2=val的字符串组装成对象\n * @param str key1=val&key2=val的字符串\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function keyValToObject(str: string, splitChar: string = '&', equalChar = '='): {} {\n let result = {}\n if (!str) {\n return result\n }\n let arrs = str.split(splitChar)\n for (let sub of arrs) {\n let subArr = sub.split(equalChar)\n result[subArr[0]] = subArr[1]\n }\n return result\n}\n\n/**\n * 判断传入的值是否为true\n * @param {Object} obj 传入值为'true','TRUE',1,'1','on','ON','YES','yes'时,返回true,其他值均返回false\n * @return {boolean}\n */\nexport function isTrue(obj) {\n return (\n obj === 'true' ||\n obj === 'TRUE' ||\n obj === 'True' ||\n obj === 'on' ||\n obj === 'ON' ||\n obj === true ||\n obj === 1 ||\n obj === '1' ||\n obj === 'YES' ||\n obj === 'yes'\n )\n}\n\n/**\n * 验证ObjectId格式是否正确\n * @param {string} id\n * @return {boolean}\n */\nexport function isObjectId(id: string): boolean {\n //mongoose.Types.ObjectId.isValid(id)\n return /^[a-fA-F0-9]{24}$/.test(id)\n}\n\n/**\n * 10进制 -> 62进制\n * @param {string | number} number\n * @return {string}\n */\nexport function string10to62(number: string | number) {\n const chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'.split('')\n const radix = chars.length\n let qutient = +number\n const arr = []\n do {\n const mod = qutient % radix\n qutient = (qutient - mod) / radix\n arr.unshift(chars[mod])\n } while (qutient)\n return arr.join('')\n}\n\n/**\n * 62进制 -> 10 进制\n * @param {string} numberCode\n * @return {number}\n */\nexport function string62to10(numberCode: string) {\n const chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'\n const radix = chars.length\n numberCode = numberCode + ''\n const len = numberCode.length\n let i = 0\n let originNumber = 0\n while (i < len) {\n originNumber += Math.pow(radix, i++) * (chars.indexOf(numberCode.charAt(len - i)) || 0)\n }\n return originNumber\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOO,SAAS,kBAAkB,MAAU,aAAa,MAAM,YAAoB,KAAK,YAAY,KAAK;AACvG,QAAM,OAAO,OAAO,KAAK,IAAI;AAC7B,OAAK,KAAK;AACV,MAAI,SAAS;AACb,MAAI,IAAI;AACR,WAAS,OAAO,MAAM;AACpB,QAAI,cAAc,CAAC,KAAK,GAAG,GAAG;AAC5B;AAAA,IACF;AACA,QAAI,MAAM;AAAG,gBAAU;AACvB,cAAU,GAAG,GAAG,GAAG,SAAS,GAAG,KAAK,GAAG,CAAC;AAAA,EAC1C;AACA,SAAO;AACT;AAQO,SAAS,eAAe,KAAa,YAAoB,KAAK,YAAY,KAAS;AACxF,MAAI,SAAS,CAAC;AACd,MAAI,CAAC,KAAK;AACR,WAAO;AAAA,EACT;AACA,MAAI,OAAO,IAAI,MAAM,SAAS;AAC9B,WAAS,OAAO,MAAM;AACpB,QAAI,SAAS,IAAI,MAAM,SAAS;AAChC,WAAO,OAAO,CAAC,CAAC,IAAI,OAAO,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;AAOO,SAAS,OAAO,KAAK;AAC1B,SACE,QAAQ,UACR,QAAQ,UACR,QAAQ,UACR,QAAQ,QACR,QAAQ,QACR,QAAQ,QACR,QAAQ,KACR,QAAQ,OACR,QAAQ,SACR,QAAQ;AAEZ;AAOO,SAAS,WAAW,IAAqB;AAE9C,SAAO,oBAAoB,KAAK,EAAE;AACpC;AAOO,SAAS,aAAa,QAAyB;AACpD,QAAM,QAAQ,iEAAiE,MAAM,EAAE;AACvF,QAAM,QAAQ,MAAM;AACpB,MAAI,UAAU,CAAC;AACf,QAAM,MAAM,CAAC;AACb,KAAG;AACD,UAAM,MAAM,UAAU;AACtB,eAAW,UAAU,OAAO;AAC5B,QAAI,QAAQ,MAAM,GAAG,CAAC;AAAA,EACxB,SAAS;AACT,SAAO,IAAI,KAAK,EAAE;AACpB;AAOO,SAAS,aAAa,YAAoB;AAC/C,QAAM,QAAQ;AACd,QAAM,QAAQ,MAAM;AACpB,eAAa,aAAa;AAC1B,QAAM,MAAM,WAAW;AACvB,MAAI,IAAI;AACR,MAAI,eAAe;AACnB,SAAO,IAAI,KAAK;AACd,oBAAgB,KAAK,IAAI,OAAO,GAAG,KAAK,MAAM,QAAQ,WAAW,OAAO,MAAM,CAAC,CAAC,KAAK;AAAA,EACvF;AACA,SAAO;AACT;","names":[]}

41
dist/utils/string.util.d.cts vendored Normal file
View File

@ -0,0 +1,41 @@
/**
* key升序生成 key1=val1&key2=val2的字符串
* @param {object} data
* @param {boolean} ignoreNull (null值不参与拼接)
* @param splitChar , &
* @param equalChar =
*/
declare function generateKeyValStr(data: {}, ignoreNull?: boolean, splitChar?: string, equalChar?: string): string;
/**
* key1=val&key2=val的字符串组装成对象
* @param str key1=val&key2=val的字符串
* @param splitChar , &
* @param equalChar =
*/
declare function keyValToObject(str: string, splitChar?: string, equalChar?: string): {};
/**
* true
* @param {Object} obj 'true','TRUE',1,'1','on','ON','YES','yes',true,false
* @return {boolean}
*/
declare function isTrue(obj: any): boolean;
/**
* ObjectId格式是否正确
* @param {string} id
* @return {boolean}
*/
declare function isObjectId(id: string): boolean;
/**
* 10 -> 62
* @param {string | number} number
* @return {string}
*/
declare function string10to62(number: string | number): string;
/**
* 62 -> 10
* @param {string} numberCode
* @return {number}
*/
declare function string62to10(numberCode: string): number;
export { generateKeyValStr, isObjectId, isTrue, keyValToObject, string10to62, string62to10 };

41
dist/utils/string.util.d.ts vendored Normal file
View File

@ -0,0 +1,41 @@
/**
* key升序生成 key1=val1&key2=val2的字符串
* @param {object} data
* @param {boolean} ignoreNull (null值不参与拼接)
* @param splitChar , &
* @param equalChar =
*/
declare function generateKeyValStr(data: {}, ignoreNull?: boolean, splitChar?: string, equalChar?: string): string;
/**
* key1=val&key2=val的字符串组装成对象
* @param str key1=val&key2=val的字符串
* @param splitChar , &
* @param equalChar =
*/
declare function keyValToObject(str: string, splitChar?: string, equalChar?: string): {};
/**
* true
* @param {Object} obj 'true','TRUE',1,'1','on','ON','YES','yes',true,false
* @return {boolean}
*/
declare function isTrue(obj: any): boolean;
/**
* ObjectId格式是否正确
* @param {string} id
* @return {boolean}
*/
declare function isObjectId(id: string): boolean;
/**
* 10 -> 62
* @param {string | number} number
* @return {string}
*/
declare function string10to62(number: string | number): string;
/**
* 62 -> 10
* @param {string} numberCode
* @return {number}
*/
declare function string62to10(numberCode: string): number;
export { generateKeyValStr, isObjectId, isTrue, keyValToObject, string10to62, string62to10 };

67
dist/utils/string.util.js vendored Normal file
View File

@ -0,0 +1,67 @@
// src/utils/string.util.ts
function generateKeyValStr(data, ignoreNull = true, splitChar = "&", equalChar = "=") {
const keys = Object.keys(data);
keys.sort();
let result = "";
let i = 0;
for (let key of keys) {
if (ignoreNull && !data[key]) {
return;
}
if (i++ > 0)
result += splitChar;
result += `${key}${equalChar}${data[key]}`;
}
return result;
}
function keyValToObject(str, splitChar = "&", equalChar = "=") {
let result = {};
if (!str) {
return result;
}
let arrs = str.split(splitChar);
for (let sub of arrs) {
let subArr = sub.split(equalChar);
result[subArr[0]] = subArr[1];
}
return result;
}
function isTrue(obj) {
return obj === "true" || obj === "TRUE" || obj === "True" || obj === "on" || obj === "ON" || obj === true || obj === 1 || obj === "1" || obj === "YES" || obj === "yes";
}
function isObjectId(id) {
return /^[a-fA-F0-9]{24}$/.test(id);
}
function string10to62(number) {
const chars = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ".split("");
const radix = chars.length;
let qutient = +number;
const arr = [];
do {
const mod = qutient % radix;
qutient = (qutient - mod) / radix;
arr.unshift(chars[mod]);
} while (qutient);
return arr.join("");
}
function string62to10(numberCode) {
const chars = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
const radix = chars.length;
numberCode = numberCode + "";
const len = numberCode.length;
let i = 0;
let originNumber = 0;
while (i < len) {
originNumber += Math.pow(radix, i++) * (chars.indexOf(numberCode.charAt(len - i)) || 0);
}
return originNumber;
}
export {
generateKeyValStr,
isObjectId,
isTrue,
keyValToObject,
string10to62,
string62to10
};
//# sourceMappingURL=string.util.js.map

1
dist/utils/string.util.js.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/utils/string.util.ts"],"sourcesContent":["/**\n * 根据key升序生成 key1=val1&key2=val2的字符串\n * @param {object} data 需要处理的对象\n * @param {boolean} ignoreNull 是否过滤空值(空格或者null值不参与拼接)\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function generateKeyValStr(data: {}, ignoreNull = true, splitChar: string = '&', equalChar = '=') {\n const keys = Object.keys(data)\n keys.sort()\n let result = ''\n let i = 0\n for (let key of keys) {\n if (ignoreNull && !data[key]) {\n return\n }\n if (i++ > 0) result += splitChar\n result += `${key}${equalChar}${data[key]}`\n }\n return result\n}\n\n/**\n * 将key1=val&key2=val的字符串组装成对象\n * @param str key1=val&key2=val的字符串\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function keyValToObject(str: string, splitChar: string = '&', equalChar = '='): {} {\n let result = {}\n if (!str) {\n return result\n }\n let arrs = str.split(splitChar)\n for (let sub of arrs) {\n let subArr = sub.split(equalChar)\n result[subArr[0]] = subArr[1]\n }\n return result\n}\n\n/**\n * 判断传入的值是否为true\n * @param {Object} obj 传入值为'true','TRUE',1,'1','on','ON','YES','yes'时,返回true,其他值均返回false\n * @return {boolean}\n */\nexport function isTrue(obj) {\n return (\n obj === 'true' ||\n obj === 'TRUE' ||\n obj === 'True' ||\n obj === 'on' ||\n obj === 'ON' ||\n obj === true ||\n obj === 1 ||\n obj === '1' ||\n obj === 'YES' ||\n obj === 'yes'\n )\n}\n\n/**\n * 验证ObjectId格式是否正确\n * @param {string} id\n * @return {boolean}\n */\nexport function isObjectId(id: string): boolean {\n //mongoose.Types.ObjectId.isValid(id)\n return /^[a-fA-F0-9]{24}$/.test(id)\n}\n\n/**\n * 10进制 -> 62进制\n * @param {string | number} number\n * @return {string}\n */\nexport function string10to62(number: string | number) {\n const chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'.split('')\n const radix = chars.length\n let qutient = +number\n const arr = []\n do {\n const mod = qutient % radix\n qutient = (qutient - mod) / radix\n arr.unshift(chars[mod])\n } while (qutient)\n return arr.join('')\n}\n\n/**\n * 62进制 -> 10 进制\n * @param {string} numberCode\n * @return {number}\n */\nexport function string62to10(numberCode: string) {\n const chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'\n const radix = chars.length\n numberCode = numberCode + ''\n const len = numberCode.length\n let i = 0\n let originNumber = 0\n while (i < len) {\n originNumber += Math.pow(radix, i++) * (chars.indexOf(numberCode.charAt(len - i)) || 0)\n }\n return originNumber\n}\n"],"mappings":";AAOO,SAAS,kBAAkB,MAAU,aAAa,MAAM,YAAoB,KAAK,YAAY,KAAK;AACvG,QAAM,OAAO,OAAO,KAAK,IAAI;AAC7B,OAAK,KAAK;AACV,MAAI,SAAS;AACb,MAAI,IAAI;AACR,WAAS,OAAO,MAAM;AACpB,QAAI,cAAc,CAAC,KAAK,GAAG,GAAG;AAC5B;AAAA,IACF;AACA,QAAI,MAAM;AAAG,gBAAU;AACvB,cAAU,GAAG,GAAG,GAAG,SAAS,GAAG,KAAK,GAAG,CAAC;AAAA,EAC1C;AACA,SAAO;AACT;AAQO,SAAS,eAAe,KAAa,YAAoB,KAAK,YAAY,KAAS;AACxF,MAAI,SAAS,CAAC;AACd,MAAI,CAAC,KAAK;AACR,WAAO;AAAA,EACT;AACA,MAAI,OAAO,IAAI,MAAM,SAAS;AAC9B,WAAS,OAAO,MAAM;AACpB,QAAI,SAAS,IAAI,MAAM,SAAS;AAChC,WAAO,OAAO,CAAC,CAAC,IAAI,OAAO,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;AAOO,SAAS,OAAO,KAAK;AAC1B,SACE,QAAQ,UACR,QAAQ,UACR,QAAQ,UACR,QAAQ,QACR,QAAQ,QACR,QAAQ,QACR,QAAQ,KACR,QAAQ,OACR,QAAQ,SACR,QAAQ;AAEZ;AAOO,SAAS,WAAW,IAAqB;AAE9C,SAAO,oBAAoB,KAAK,EAAE;AACpC;AAOO,SAAS,aAAa,QAAyB;AACpD,QAAM,QAAQ,iEAAiE,MAAM,EAAE;AACvF,QAAM,QAAQ,MAAM;AACpB,MAAI,UAAU,CAAC;AACf,QAAM,MAAM,CAAC;AACb,KAAG;AACD,UAAM,MAAM,UAAU;AACtB,eAAW,UAAU,OAAO;AAC5B,QAAI,QAAQ,MAAM,GAAG,CAAC;AAAA,EACxB,SAAS;AACT,SAAO,IAAI,KAAK,EAAE;AACpB;AAOO,SAAS,aAAa,YAAoB;AAC/C,QAAM,QAAQ;AACd,QAAM,QAAQ,MAAM;AACpB,eAAa,aAAa;AAC1B,QAAM,MAAM,WAAW;AACvB,MAAI,IAAI;AACR,MAAI,eAAe;AACnB,SAAO,IAAI,KAAK;AACd,oBAAgB,KAAK,IAAI,OAAO,GAAG,KAAK,MAAM,QAAQ,WAAW,OAAO,MAAM,CAAC,CAAC,KAAK;AAAA,EACvF;AACA,SAAO;AACT;","names":[]}

15564
dist/utils/wallet.util.cjs vendored Normal file

File diff suppressed because it is too large Load Diff

1
dist/utils/wallet.util.cjs.map vendored Normal file

File diff suppressed because one or more lines are too long

51
dist/utils/wallet.util.d.cts vendored Normal file
View File

@ -0,0 +1,51 @@
/**
* Removes IPFS protocol prefix from input string.
*
* @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})
* @returns IPFS content identifier and (possibly) path in a string
* @throws Will throw if the url passed is not IPFS.
*/
declare function removeIpfsProtocolPrefix(ipfsUrl: string): string;
/**
* Extracts content identifier and path from an input string.
*
* @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix
* @returns IFPS content identifier (cid) and sub path as string.
* @throws Will throw if the url passed is not ipfs.
*/
declare function getIpfsCIDv1AndPath(ipfsUrl: string): {
cid: string;
path?: string;
};
/**
* Adds URL protocol prefix to input URL string if missing.
*
* @param urlString - An IPFS URL.
* @returns A URL with a https:// prepended.
*/
declare function addUrlProtocolPrefix(urlString: string): string;
/**
* Formats URL correctly for use retrieving assets hosted on IPFS.
*
* @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).
* @param ipfsUrl - The IFPS URL pointed at the asset.
* @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.
* @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.
*/
declare function getFormattedIpfsUrl(ipfsGateway: string, ipfsUrl: string, subdomainSupported: boolean): string;
/**
* Returns whether the given code corresponds to a smart contract.
*
* @param code - The potential smart contract code.
* @returns Whether the code was smart contract code or not.
*/
declare function isSmartContractCode(code: string): boolean;
declare function formatAddress(address: string): string;
declare function formatMoney(balance: number | string, symbol: string): string;
/**
* bytes32的字符串
* @returns
*/
declare function generateRandomBytes32(): string;
export { addUrlProtocolPrefix, formatAddress, formatMoney, generateRandomBytes32, getFormattedIpfsUrl, getIpfsCIDv1AndPath, isSmartContractCode, removeIpfsProtocolPrefix };

51
dist/utils/wallet.util.d.ts vendored Normal file
View File

@ -0,0 +1,51 @@
/**
* Removes IPFS protocol prefix from input string.
*
* @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})
* @returns IPFS content identifier and (possibly) path in a string
* @throws Will throw if the url passed is not IPFS.
*/
declare function removeIpfsProtocolPrefix(ipfsUrl: string): string;
/**
* Extracts content identifier and path from an input string.
*
* @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix
* @returns IFPS content identifier (cid) and sub path as string.
* @throws Will throw if the url passed is not ipfs.
*/
declare function getIpfsCIDv1AndPath(ipfsUrl: string): {
cid: string;
path?: string;
};
/**
* Adds URL protocol prefix to input URL string if missing.
*
* @param urlString - An IPFS URL.
* @returns A URL with a https:// prepended.
*/
declare function addUrlProtocolPrefix(urlString: string): string;
/**
* Formats URL correctly for use retrieving assets hosted on IPFS.
*
* @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).
* @param ipfsUrl - The IFPS URL pointed at the asset.
* @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.
* @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.
*/
declare function getFormattedIpfsUrl(ipfsGateway: string, ipfsUrl: string, subdomainSupported: boolean): string;
/**
* Returns whether the given code corresponds to a smart contract.
*
* @param code - The potential smart contract code.
* @returns Whether the code was smart contract code or not.
*/
declare function isSmartContractCode(code: string): boolean;
declare function formatAddress(address: string): string;
declare function formatMoney(balance: number | string, symbol: string): string;
/**
* bytes32的字符串
* @returns
*/
declare function generateRandomBytes32(): string;
export { addUrlProtocolPrefix, formatAddress, formatMoney, generateRandomBytes32, getFormattedIpfsUrl, getIpfsCIDv1AndPath, isSmartContractCode, removeIpfsProtocolPrefix };

15551
dist/utils/wallet.util.js vendored Normal file

File diff suppressed because it is too large Load Diff

1
dist/utils/wallet.util.js.map vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -2,16 +2,17 @@
"name": "zutils",
"version": "1.0.0",
"description": "",
"main": "./dist/index.js",
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
},
"./common/ZError": {
"require": "./dist/common/ZError.js",
"import": "./dist/common/ZError.js",
"types": "./dist/common/ZError.d.ts"
"./utils/bn.util": {
"import": "./dist/utils/bn.util.js",
"require": "./dist/common/bn.util.cjs",
"types": "./dist/common/bn.util.d.ts"
}
},
"type": "module",

View File

@ -1,2 +1 @@
export * from './utils/bn.util'
export * from './utils/date.util'
export { ZError } from './common/ZError'

View File

@ -1,10 +1,10 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts", "src/common/ZError.ts"],
entry: ["src/index.ts", "src/common/*.ts", "src/utils/*.ts"],
format: ["cjs", "esm"], // Build for commonJS and ESmodules
dts: true, // Generate declaration file (.d.ts)
splitting: true,
splitting: false,
sourcemap: true,
clean: true,
});