@swapkit/helpers
Advanced tools
Comparing version 1.0.0-rc.2 to 1.0.0-rc.3
@@ -24,2 +24,16 @@ import { Chain } from '@swapkit/types'; | ||
export declare class AssetValue extends BigIntArithmetics { | ||
address?: string; | ||
chain: Chain; | ||
isSynthetic: boolean; | ||
isGasAsset: boolean; | ||
symbol: string; | ||
ticker: string; | ||
type: ReturnType<typeof getAssetType>; | ||
constructor(params: AssetValueParams); | ||
get assetValue(): string; | ||
toString(): string; | ||
eq({ chain, symbol }: { | ||
chain: Chain; | ||
symbol: string; | ||
}): boolean; | ||
static fromString(assetString: string, value?: number | string): Promise<AssetValue>; | ||
@@ -39,16 +53,2 @@ static fromStringSync(assetString: string, value?: number | string): AssetValue | undefined; | ||
}>; | ||
address?: string; | ||
chain: Chain; | ||
isSynthetic: boolean; | ||
isGasAsset: boolean; | ||
symbol: string; | ||
ticker: string; | ||
type: ReturnType<typeof getAssetType>; | ||
constructor(params: AssetValueParams); | ||
get assetValue(): string; | ||
toString(): string; | ||
eq({ chain, symbol }: { | ||
chain: Chain; | ||
symbol: string; | ||
}): boolean; | ||
} | ||
@@ -66,3 +66,3 @@ | ||
declare class BigIntArithmetics { | ||
export declare class BigIntArithmetics { | ||
@@ -74,25 +74,23 @@ decimalMultiplier: bigint; | ||
static shiftDecimals({ value, from, to, }: { | ||
value: BigIntArithmetics | string | number; | ||
value: InitialisationValueType; | ||
from: number; | ||
to: number; | ||
}): BigIntArithmetics; | ||
constructor(valueOrParams: BigIntArithmetics | string | number | { | ||
decimal?: number; | ||
value: number | string; | ||
}); | ||
get unsafeNumber(): number; | ||
constructor(params: SKBigIntParams); | ||
get baseValue(): string; | ||
get baseValueNumber(): number; | ||
get baseValueBigInt(): bigint; | ||
get value(): string; | ||
add(...args: (BigIntArithmetics | string | number)[]): this; | ||
sub(...args: (BigIntArithmetics | string | number)[]): this; | ||
mul(...args: (BigIntArithmetics | string | number)[]): this; | ||
div(...args: (BigIntArithmetics | string | number)[]): this; | ||
gt(value: BigIntArithmetics | string | number): boolean; | ||
gte(value: BigIntArithmetics | string | number): boolean; | ||
lt(value: BigIntArithmetics | string | number): boolean; | ||
lte(value: BigIntArithmetics | string | number): boolean; | ||
eqValue(value: BigIntArithmetics | string | number): boolean; | ||
getBigIntValue(value: BigIntArithmetics | string | number, decimal?: number): bigint; | ||
set(value: SKBigIntParams): any; | ||
add(...args: InitialisationValueType[]): this; | ||
sub(...args: InitialisationValueType[]): this; | ||
mul(...args: InitialisationValueType[]): this; | ||
div(...args: InitialisationValueType[]): this; | ||
gt(value: InitialisationValueType): boolean; | ||
gte(value: InitialisationValueType): boolean; | ||
lt(value: InitialisationValueType): boolean; | ||
lte(value: InitialisationValueType): boolean; | ||
eqValue(value: InitialisationValueType): boolean; | ||
getValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T]; | ||
getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T]; | ||
getBigIntValue(value: InitialisationValueType, decimal?: number): bigint; | ||
formatBigIntToSafeValue(value: bigint, decimal?: number): string; | ||
@@ -104,4 +102,2 @@ toSignificant(significantDigits?: number): string; | ||
export declare const DEFAULT_DECIMAL = 8; | ||
export declare const derivationPathToString: ([network, chainId, account, change, index]: number[]) => string; | ||
@@ -167,7 +163,7 @@ | ||
export declare const formatBigIntToSafeValue: ({ value, bigIntDecimal, decimal, }: { | ||
export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: { | ||
value: bigint; | ||
bigIntDecimal?: number | undefined; | ||
decimal?: number | undefined; | ||
}) => string; | ||
bigIntDecimal?: number; | ||
decimal?: number; | ||
}): string; | ||
@@ -255,2 +251,4 @@ export declare const gasFeeMultiplier: Record<FeeOption, number>; | ||
declare type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber; | ||
export declare const isGasAsset: ({ chain, symbol }: { | ||
@@ -292,2 +290,10 @@ chain: Chain; | ||
declare type NumberPrimitives = bigint | number | string; | ||
declare type NumberPrimitivesType = { | ||
bigint: bigint; | ||
number: number; | ||
string: string; | ||
}; | ||
declare type PoolParams<T = {}> = T & { | ||
@@ -307,2 +313,7 @@ runeAmount: string; | ||
declare type SKBigIntParams = InitialisationValueType | { | ||
decimal?: number; | ||
value: number | string; | ||
}; | ||
export declare class SwapKitError extends Error { | ||
@@ -314,6 +325,5 @@ constructor(errorKey: Keys, sourceError?: any); | ||
eq(value: SwapKitValueType): boolean; | ||
toString(): string; | ||
} | ||
declare type SwapKitValueType = BigIntArithmetics | string | number; | ||
export declare type SwapKitValueType = BigIntArithmetics | string | number; | ||
@@ -320,0 +330,0 @@ declare type TCTokenNames = (typeof ThorchainList)['tokens'][number]['identifier']; |
@@ -1,8 +0,8 @@ | ||
var rt = Object.defineProperty; | ||
var st = (n, t, e) => t in n ? rt(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e; | ||
var _ = (n, t, e) => (st(n, typeof t != "symbol" ? t + "" : t, e), e), it = (n, t, e) => { | ||
var nt = Object.defineProperty; | ||
var rt = (n, t, e) => t in n ? nt(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e; | ||
var g = (n, t, e) => (rt(n, typeof t != "symbol" ? t + "" : t, e), e), st = (n, t, e) => { | ||
if (!t.has(n)) | ||
throw TypeError("Cannot " + e); | ||
}; | ||
var p = (n, t, e) => { | ||
var $ = (n, t, e) => { | ||
if (t.has(n)) | ||
@@ -12,9 +12,9 @@ throw TypeError("Cannot add the same private member more than once"); | ||
}; | ||
var d = (n, t, e) => (it(n, t, "access private method"), e); | ||
import { FeeOption as x, BaseDecimal as h, Chain as i, ChainToRPC as at, MemoType as f } from "@swapkit/types"; | ||
const vt = (n) => { | ||
var _ = (n, t, e) => (st(n, t, "access private method"), e); | ||
import { FeeOption as H, BaseDecimal as m, Chain as i, ChainToRPC as it, MemoType as p } from "@swapkit/types"; | ||
const St = (n) => { | ||
if (n < 0) | ||
throw new Error("Invalid number of year"); | ||
return 10 + n; | ||
}, Ct = (n) => { | ||
}, vt = (n) => { | ||
if (n.length > 30) | ||
@@ -24,26 +24,34 @@ return !1; | ||
return !!n.match(t); | ||
}, Tt = ([n, t, e, r, s]) => `${n}'/${t}'/${e}'/${r}${typeof s != "number" ? "" : `/${s}`}`, Bt = async (n, t) => { | ||
const e = Object.entries(t || {}).reduce( | ||
(s, [a, c]) => (c && (s[a] = c), s), | ||
{} | ||
); | ||
return (await fetch( | ||
`${n}${t ? `?${new URLSearchParams(e).toString()}` : ""}`, | ||
{ method: "GET", mode: "cors", credentials: "omit", referrer: "https://sk.thorswap.net" } | ||
)).json(); | ||
}, ct = async (n, t, e, r = !1) => { | ||
const s = await fetch(`${n}`, { | ||
body: t, | ||
headers: e, | ||
method: "POST", | ||
referrer: "https://sk.thorswap.net" | ||
}); | ||
return r ? s.text() : s.json(); | ||
}, ot = "0x313ce567", K = async ({ chain: n, to: t }) => { | ||
}, Vt = ([n, t, e, r, s]) => `${n}'/${t}'/${e}'/${r}${typeof s != "number" ? "" : `/${s}`}`, Bt = async (n, t) => { | ||
try { | ||
const e = await ct( | ||
at[n], | ||
const e = Object.entries(t || {}).reduce( | ||
(s, [a, c]) => (c && (s[a] = c), s), | ||
{} | ||
); | ||
return (await fetch( | ||
`${n}${t ? `?${new URLSearchParams(e).toString()}` : ""}`, | ||
{ method: "GET", mode: "cors", credentials: "omit", referrer: "https://sk.thorswap.net" } | ||
)).json(); | ||
} catch (e) { | ||
return console.error(e), {}; | ||
} | ||
}, at = async (n, t, e, r = !1) => { | ||
try { | ||
const s = await fetch(`${n}`, { | ||
body: t, | ||
headers: e, | ||
method: "POST", | ||
referrer: "https://sk.thorswap.net" | ||
}); | ||
return r ? s.text() : s.json(); | ||
} catch { | ||
return {}; | ||
} | ||
}, ct = "0x313ce567", Y = async ({ chain: n, to: t }) => { | ||
try { | ||
const e = await at( | ||
it[n], | ||
JSON.stringify({ | ||
method: "eth_call", | ||
params: [{ to: t.toLowerCase(), data: ot }, "latest"], | ||
params: [{ to: t.toLowerCase(), data: ct }, "latest"], | ||
id: 44, | ||
@@ -57,28 +65,28 @@ jsonrpc: "2.0" | ||
} catch (e) { | ||
return console.error(e), h[n]; | ||
return console.error(e), m[n]; | ||
} | ||
}, ut = async (n) => { | ||
}, ot = async (n) => { | ||
if (n === i.Ethereum) | ||
return h.ETH; | ||
return m.ETH; | ||
const [, t] = n.split("-"); | ||
return t != null && t.startsWith("0x") ? K({ chain: i.Ethereum, to: t }) : h.ETH; | ||
}, lt = async (n) => { | ||
return t != null && t.startsWith("0x") ? Y({ chain: i.Ethereum, to: t }) : m.ETH; | ||
}, ut = async (n) => { | ||
const [, t] = n.split("-"); | ||
return t != null && t.startsWith("0x") ? K({ chain: i.Avalanche, to: t.toLowerCase() }) : h.AVAX; | ||
}, dt = async (n) => n === i.BinanceSmartChain ? h.BSC : h.BSC, J = async ({ chain: n, symbol: t }) => { | ||
return t != null && t.startsWith("0x") ? Y({ chain: i.Avalanche, to: t.toLowerCase() }) : m.AVAX; | ||
}, lt = async (n) => n === i.BinanceSmartChain ? m.BSC : m.BSC, K = async ({ chain: n, symbol: t }) => { | ||
switch (n) { | ||
case i.Ethereum: | ||
return ot(t); | ||
case i.Avalanche: | ||
return ut(t); | ||
case i.Avalanche: | ||
case i.BinanceSmartChain: | ||
return lt(t); | ||
case i.BinanceSmartChain: | ||
return dt(t); | ||
default: | ||
return h[n]; | ||
return m[n]; | ||
} | ||
}, yt = { | ||
[x.Average]: 1.2, | ||
[x.Fast]: 1.5, | ||
[x.Fastest]: 2 | ||
}, mt = ({ chain: n, symbol: t }) => { | ||
}, Ct = { | ||
[H.Average]: 1.2, | ||
[H.Fast]: 1.5, | ||
[H.Fastest]: 2 | ||
}, dt = ({ chain: n, symbol: t }) => { | ||
switch (n) { | ||
@@ -116,9 +124,9 @@ case i.Bitcoin: | ||
case i.Cosmos: | ||
return { identifier: "GAIA.ATOM", decimal: h[n] }; | ||
return { identifier: "GAIA.ATOM", decimal: m[n] }; | ||
case i.THORChain: | ||
return { identifier: "THOR.RUNE", decimal: h[n] }; | ||
return { identifier: "THOR.RUNE", decimal: m[n] }; | ||
case i.BinanceSmartChain: | ||
return { identifier: "BSC.BNB", decimal: h[n] }; | ||
return { identifier: "BSC.BNB", decimal: m[n] }; | ||
case i.Maya: | ||
return { identifier: "MAYA.CACAO", decimal: h.MAYA }; | ||
return { identifier: "MAYA.CACAO", decimal: m.MAYA }; | ||
case "MAYA.MAYA": | ||
@@ -137,5 +145,5 @@ return { identifier: "MAYA.MAYA", decimal: 4 }; | ||
case i.Ethereum: | ||
return { identifier: `${n}.${n}`, decimal: h[n] }; | ||
return { identifier: `${n}.${n}`, decimal: m[n] }; | ||
} | ||
}, _t = ({ chain: n, symbol: t }) => { | ||
}, mt = ({ chain: n, symbol: t }) => { | ||
if (t.includes("/")) | ||
@@ -170,7 +178,7 @@ return "Synth"; | ||
} | ||
}, Mt = (n) => { | ||
}, yt = (n) => { | ||
var c; | ||
const [t, ...e] = n.split("."), r = n.includes("/"), s = e.join("."), a = (c = s == null ? void 0 : s.split("-")) == null ? void 0 : c[0]; | ||
return { chain: t, symbol: s, ticker: a, synth: r }; | ||
}, gt = ({ | ||
}, _t = ({ | ||
liquidityUnits: n, | ||
@@ -180,5 +188,5 @@ poolUnits: t, | ||
}) => { | ||
const r = m(n), s = m(t), a = m(e), c = r.mul(a), o = s.mul(s).mul(2), l = s.mul(r).mul(2), u = r.mul(r), g = s.mul(s).mul(s); | ||
return c.mul(o.sub(l).add(u)).div(g); | ||
}, pt = ({ | ||
const r = h(n), s = h(t), a = h(e), c = r.mul(a), o = s.mul(s).mul(2), u = s.mul(r).mul(2), l = r.mul(r), d = s.mul(s).mul(s); | ||
return c.mul(o.sub(u).add(l)).div(d); | ||
}, gt = ({ | ||
liquidityUnits: n, | ||
@@ -188,5 +196,5 @@ poolUnits: t, | ||
}) => { | ||
const r = m(n), s = m(t), a = m(e), c = r.mul(a), o = s.mul(s).mul(2), l = s.mul(r).mul(2), u = r.mul(r), g = c.mul(o.sub(l).add(u)), $ = s.mul(s).mul(s); | ||
return g.div($); | ||
}, Et = ({ | ||
const r = h(n), s = h(t), a = h(e), c = r.mul(a), o = s.mul(s).mul(2), u = s.mul(r).mul(2), l = r.mul(r), d = c.mul(o.sub(u).add(l)), A = s.mul(s).mul(s); | ||
return d.div(A); | ||
}, Tt = ({ | ||
percent: n, | ||
@@ -196,3 +204,3 @@ runeDepth: t, | ||
poolUnits: r | ||
}) => gt({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), Ot = ({ | ||
}) => _t({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), Et = ({ | ||
percent: n, | ||
@@ -202,3 +210,3 @@ assetDepth: t, | ||
poolUnits: r | ||
}) => pt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), m = (n) => new bt({ value: n, decimal: h.THOR }), ft = ({ | ||
}) => gt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), h = (n) => new wt({ value: n, decimal: m.THOR }), pt = ({ | ||
liquidityUnits: n, | ||
@@ -209,5 +217,5 @@ poolUnits: t, | ||
}) => ({ | ||
assetAmount: m(r).mul(n).div(t), | ||
runeAmount: m(e).mul(n).div(t) | ||
}), Vt = ({ | ||
assetAmount: h(r).mul(n).div(t), | ||
runeAmount: h(e).mul(n).div(t) | ||
}), Ot = ({ | ||
liquidityUnits: n, | ||
@@ -219,6 +227,6 @@ poolUnits: t, | ||
}) => Object.fromEntries( | ||
Object.entries(ft({ liquidityUnits: n, poolUnits: t, runeDepth: e, assetDepth: r })).map( | ||
Object.entries(pt({ liquidityUnits: n, poolUnits: t, runeDepth: e, assetDepth: r })).map( | ||
([a, c]) => [a, c.mul(s)] | ||
) | ||
), Nt = ({ | ||
), Mt = ({ | ||
runeDepth: n, | ||
@@ -231,8 +239,8 @@ poolUnits: t, | ||
}) => { | ||
const c = m(n), o = m(e), l = m(t), u = m(s), g = m(a), $ = u.mul(o), v = g.mul(c), D = u.mul(g), Z = c.mul(o), tt = l.mul($.add(v.add(D.mul(2)))), et = $.add(v.add(Z.mul(2))), U = tt.div(et), H = m(r).add(U); | ||
const c = h(n), o = h(e), u = h(t), l = h(s), d = h(a), A = l.mul(o), S = d.mul(c), R = l.mul(d), Q = c.mul(o), Z = u.mul(A.add(S.add(R.mul(2)))), tt = A.add(S.add(Q.mul(2))), U = Z.div(tt), k = h(r).add(U); | ||
if (U.baseValueNumber === 0) | ||
return H.div(l).baseValueNumber; | ||
const nt = l.add(H); | ||
return H.div(nt).baseValueNumber; | ||
}, Rt = ({ | ||
return k.div(u).baseValueNumber; | ||
const et = u.add(k); | ||
return k.div(et).baseValueNumber; | ||
}, Nt = ({ | ||
runeAmount: n, | ||
@@ -243,33 +251,33 @@ assetAmount: t, | ||
}) => { | ||
const s = m(e), a = m(r), c = m(t), o = m(n), l = c.mul(s).sub(a.mul(o)), u = a.mul(o).add(s.mul(a)); | ||
return Math.abs(l.div(u).baseValueNumber); | ||
}, At = ({ | ||
const s = h(e), a = h(r), c = h(t), o = h(n), u = c.mul(s).sub(a.mul(o)), l = a.mul(o).add(s.mul(a)); | ||
return Math.abs(u.div(l).baseValueNumber); | ||
}, ft = ({ | ||
symbol: n, | ||
ticker: t, | ||
chain: e | ||
}) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n, kt = (n, t) => { | ||
}) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n, Rt = (n, t) => { | ||
switch (n) { | ||
case f.LEAVE: | ||
case f.BOND: { | ||
case p.LEAVE: | ||
case p.BOND: { | ||
const { address: e } = t; | ||
return `${n}:${e}`; | ||
} | ||
case f.UNBOND: { | ||
case p.UNBOND: { | ||
const { address: e, unbondAmount: r } = t; | ||
return `${n}:${e}:${r * 10 ** 8}`; | ||
} | ||
case f.THORNAME_REGISTER: { | ||
case p.THORNAME_REGISTER: { | ||
const { name: e, chain: r, address: s, owner: a } = t; | ||
return `${n}:${e}:${r}:${s}${a ? `:${a}` : ""}`; | ||
} | ||
case f.DEPOSIT: { | ||
case p.DEPOSIT: { | ||
const { chain: e, symbol: r, address: s, singleSide: a } = t; | ||
return a ? `${n}:${e}/${r}::t:0` : `${n}:${e}.${r}:${s || ""}:t:0`; | ||
} | ||
case f.WITHDRAW: { | ||
const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, l = !o && c ? `:${c}` : "", u = At({ chain: e, symbol: s, ticker: r }); | ||
return `${n}:${e}${o ? "/" : "."}${u}:${a}${l}`; | ||
case p.WITHDRAW: { | ||
const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, u = !o && c ? `:${c}` : "", l = ft({ chain: e, symbol: s, ticker: r }); | ||
return `${n}:${e}${o ? "/" : "."}${l}:${a}${u}`; | ||
} | ||
case f.OPEN_LOAN: | ||
case f.CLOSE_LOAN: { | ||
case p.OPEN_LOAN: | ||
case p.CLOSE_LOAN: { | ||
const { asset: e, address: r } = t; | ||
@@ -281,7 +289,18 @@ return `${n}:${e}:${r}`; | ||
} | ||
}, y = 8, G = ({ | ||
}, F = Object.values(i), At = (n = "") => { | ||
const t = n.toUpperCase(), [e] = t.split("."); | ||
if (F.includes(e)) | ||
return !0; | ||
const [r] = t.split("/"); | ||
if (F.includes(r)) | ||
return !0; | ||
throw new Error( | ||
`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>` | ||
); | ||
}, C = 8, I = (n) => 10n ** BigInt(n), v = (n) => Math.log10(parseFloat(n.toString())); | ||
function G({ | ||
value: n, | ||
bigIntDecimal: t = y, | ||
decimal: e = y | ||
}) => { | ||
bigIntDecimal: t = C, | ||
decimal: e = C | ||
}) { | ||
const r = n < 0n; | ||
@@ -297,33 +316,22 @@ let s = n.toString().substring(r ? 1 : 0); | ||
); | ||
}, W = Object.values(i), $t = (n = "") => { | ||
const t = n.toUpperCase(), [e] = t.split("."); | ||
if (W.includes(e)) | ||
return !0; | ||
const [r] = t.split("/"); | ||
if (W.includes(r)) | ||
return !0; | ||
throw new Error( | ||
`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>` | ||
); | ||
}, I = (n) => 10n ** BigInt(n), C = (n) => Math.log10(parseFloat(n.toString())); | ||
var w, T, R, z, k, X, O, L, b, B, V, j, S, N; | ||
const M = class M { | ||
} | ||
var w, V, M, J, N, z, E, L, b, B, O, x; | ||
const y = class y { | ||
constructor(t) { | ||
p(this, w); | ||
p(this, R); | ||
p(this, k); | ||
p(this, O); | ||
p(this, b); | ||
p(this, V); | ||
p(this, S); | ||
_(this, "decimalMultiplier", 10n ** 8n); | ||
_(this, "bigIntValue", 0n); | ||
_(this, "decimal"); | ||
const e = typeof t == "object", r = e ? t.value : t; | ||
this.decimal = e ? t.decimal : void 0, this.decimalMultiplier = I( | ||
Math.max(d(this, V, j).call(this, d(this, b, B).call(this, r)), this.decimal || 0) | ||
), d(this, R, z).call(this, r); | ||
$(this, w); | ||
$(this, M); | ||
$(this, N); | ||
$(this, E); | ||
$(this, b); | ||
$(this, O); | ||
g(this, "decimalMultiplier", 10n ** 8n); | ||
g(this, "bigIntValue", 0n); | ||
g(this, "decimal"); | ||
const e = P(t); | ||
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = I( | ||
Math.max(_(this, O, x).call(this, _(this, b, B).call(this, e)), this.decimal || 0) | ||
), _(this, M, J).call(this, e); | ||
} | ||
static fromBigInt(t, e) { | ||
return new M({ | ||
return new y({ | ||
decimal: e, | ||
@@ -338,36 +346,30 @@ value: G({ value: t, bigIntDecimal: e, decimal: e }) | ||
}) { | ||
return M.fromBigInt( | ||
new M(t).bigIntValue * I(r) / I(e), | ||
return y.fromBigInt( | ||
new y(t).bigIntValue * I(r) / I(e), | ||
r | ||
); | ||
} | ||
get unsafeNumber() { | ||
return parseFloat((this.bigIntValue / this.decimalMultiplier).toString()); | ||
} | ||
get baseValue() { | ||
return d(this, S, N).call(this, "string"); | ||
return this.getBaseValue("string"); | ||
} | ||
get baseValueNumber() { | ||
return d(this, S, N).call(this, "number"); | ||
return this.getBaseValue("number"); | ||
} | ||
get baseValueBigInt() { | ||
return d(this, S, N).call(this, "number"); | ||
return this.getBaseValue("bigint"); | ||
} | ||
get value() { | ||
return this.formatBigIntToSafeValue( | ||
this.bigIntValue, | ||
this.decimal || C(this.decimalMultiplier) | ||
); | ||
set(t) { | ||
return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() }); | ||
} | ||
add(...t) { | ||
return d(this, w, T).call(this, "add", ...t); | ||
return _(this, w, V).call(this, "add", ...t); | ||
} | ||
sub(...t) { | ||
return d(this, w, T).call(this, "sub", ...t); | ||
return _(this, w, V).call(this, "sub", ...t); | ||
} | ||
mul(...t) { | ||
return d(this, w, T).call(this, "mul", ...t); | ||
return _(this, w, V).call(this, "mul", ...t); | ||
} | ||
div(...t) { | ||
return d(this, w, T).call(this, "div", ...t); | ||
return _(this, w, V).call(this, "div", ...t); | ||
} | ||
@@ -389,35 +391,78 @@ gt(t) { | ||
} | ||
getValue(t) { | ||
const e = this.formatBigIntToSafeValue( | ||
this.bigIntValue, | ||
this.decimal || v(this.decimalMultiplier) | ||
); | ||
switch (t) { | ||
case "number": | ||
return Number(e); | ||
case "string": | ||
return e; | ||
default: | ||
return this.bigIntValue; | ||
} | ||
} | ||
getBaseValue(t) { | ||
const e = this.decimalMultiplier / I(this.decimal || 0), r = this.bigIntValue / e; | ||
switch (t) { | ||
case "number": | ||
return Number(r); | ||
case "string": | ||
return r.toString(); | ||
default: | ||
return this.bigIntValue; | ||
} | ||
} | ||
getBigIntValue(t, e) { | ||
return !e && typeof t == "object" ? t.bigIntValue : (t = typeof t == "object" ? t.value : t, d(this, O, L).call(this, d(this, b, B).call(this, t), e)); | ||
return !e && typeof t == "object" ? t.bigIntValue : _(this, E, L).call(this, _(this, b, B).call(this, P(t)), e); | ||
} | ||
formatBigIntToSafeValue(t, e) { | ||
const r = e || this.decimal || y, s = Math.max( | ||
const r = e || this.decimal || C, s = Math.max( | ||
r, | ||
C(this.decimalMultiplier) | ||
), a = t < 0n; | ||
let c = t.toString().substring(a ? 1 : 0); | ||
const o = s - (c.length - 1); | ||
o > 0 && (c = "0".repeat(o) + c); | ||
const l = c.length - s; | ||
let u = c.slice(-s); | ||
return parseInt(u[r]) >= 5 ? u = `${u.substring(0, r - 1)}${(parseInt(u[r - 1]) + 1).toString()}` : u = u.substring(0, r), `${a ? "-" : ""}${c.slice(0, l)}.${u}`.replace( | ||
/\.?0*$/, | ||
"" | ||
); | ||
v(this.decimalMultiplier) | ||
), a = t < 0n, c = t.toString().substring(a ? 1 : 0), o = s - (c.length - 1), u = o > 0 ? "0".repeat(o) + c : c, l = u.length - s; | ||
let d = u.slice(-s); | ||
return parseInt(d[r]) >= 5 ? d = `${d.substring(0, r - 1)}${(parseInt(d[r - 1]) + 1).toString()}` : d = d.substring(0, r), `${a ? "-" : ""}${u.slice( | ||
0, | ||
l | ||
)}.${d}`.replace(/\.?0*$/, ""); | ||
} | ||
toSignificant(t) { | ||
const e = this.value.split("."), r = e[0], s = e[1]; | ||
return s ? `${r}.${s.slice(0, t || this.decimal)}`.replace( | ||
/\.?0*$/, | ||
"" | ||
) : r; | ||
toSignificant(t = 6) { | ||
const [e, r] = this.getValue("string").split("."), s = e || "", a = r || "", c = parseInt(s) ? s.length + a.length : a.length; | ||
if (c <= t) | ||
return this.getValue("string"); | ||
if (s.length >= t) | ||
return s.slice(0, t).padEnd(s.length, "0"); | ||
if (parseInt(s)) | ||
return `${s}.${a.slice(0, t - s.length)}`.padEnd( | ||
c - t, | ||
"0" | ||
); | ||
const o = parseInt(a), u = `${o}`.slice(0, t); | ||
return `0.${u.padStart( | ||
a.length - `${o}`.length + u.length, | ||
"0" | ||
)}`; | ||
} | ||
}; | ||
w = new WeakSet(), T = function(t, ...e) { | ||
const r = d(this, k, X).call(this, this, ...e), s = I(r), a = e.reduce( | ||
(o, l) => { | ||
const u = this.getBigIntValue(l, r); | ||
if (t === "div" && u === 0n) | ||
throw new RangeError("Division by zero"); | ||
return t === "add" ? o + u : t === "sub" ? o - u : t === "mul" ? o * u / s : o * s / u; | ||
w = new WeakSet(), V = function(t, ...e) { | ||
const r = _(this, N, z).call(this, this, ...e), s = I(r), a = e.reduce( | ||
(o, u) => { | ||
const l = this.getBigIntValue(u, r); | ||
switch (t) { | ||
case "add": | ||
return o + l; | ||
case "sub": | ||
return o - l; | ||
case "mul": | ||
return o * l / s; | ||
case "div": { | ||
if (l === 0n) | ||
throw new RangeError("Division by zero"); | ||
return o * s / l; | ||
} | ||
default: | ||
return o; | ||
} | ||
}, | ||
@@ -428,16 +473,16 @@ //normalize is to precision multiplier base | ||
bigIntDecimal: r, | ||
decimal: Math.max(r, C(this.decimalMultiplier)), | ||
decimal: Math.max(r, v(this.decimalMultiplier)), | ||
value: a | ||
}); | ||
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() }); | ||
}, R = new WeakSet(), z = function(t, e) { | ||
const r = d(this, b, B).call(this, t) || "0"; | ||
this.bigIntValue = e || d(this, O, L).call(this, r); | ||
}, k = new WeakSet(), X = function(...t) { | ||
}, M = new WeakSet(), J = function(t) { | ||
const e = _(this, b, B).call(this, t) || "0"; | ||
this.bigIntValue = _(this, E, L).call(this, e); | ||
}, N = new WeakSet(), z = function(...t) { | ||
const e = t.map( | ||
(r) => typeof r == "object" ? r.decimal || C(r.decimalMultiplier) : d(this, V, j).call(this, d(this, b, B).call(this, r)) | ||
(r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : _(this, O, x).call(this, _(this, b, B).call(this, r)) | ||
).filter(Boolean); | ||
return Math.max(...e, y); | ||
}, O = new WeakSet(), L = function(t, e) { | ||
const r = e ? I(e) : this.decimalMultiplier, s = C(r), [a, c = ""] = t.split("."); | ||
return Math.max(...e, C); | ||
}, E = new WeakSet(), L = function(t, e) { | ||
const r = e ? I(e) : this.decimalMultiplier, s = v(r), [a, c = ""] = t.split("."); | ||
return BigInt(`${a}${c.padEnd(s, "0")}`); | ||
@@ -448,75 +493,78 @@ }, b = new WeakSet(), B = function(t) { | ||
maximumFractionDigits: 20 | ||
}) : t}`.replaceAll(",", ".").split("."); | ||
}) : P(t)}`.replaceAll(",", ".").split("."); | ||
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0]; | ||
}, V = new WeakSet(), j = function(t) { | ||
}, O = new WeakSet(), x = function(t) { | ||
var r; | ||
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0; | ||
return Math.max(e, y); | ||
}, S = new WeakSet(), N = function(t) { | ||
const e = this.decimalMultiplier / I(this.decimal || 0), r = this.bigIntValue / e; | ||
switch (t) { | ||
case "number": | ||
return Number(r); | ||
case "string": | ||
return r.toString(); | ||
default: | ||
return r; | ||
} | ||
return Math.max(e, C); | ||
}; | ||
let E = M, q; | ||
const P = (n) => { | ||
if (!q) | ||
let T = y; | ||
function P(n) { | ||
return typeof n == "object" ? "getValue" in n ? n.getValue("string") : n.value : n; | ||
} | ||
let j; | ||
const D = (n) => { | ||
if (!j) | ||
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first"); | ||
return q.get(n.toUpperCase()) || { decimal: h.THOR, identifier: "" }; | ||
}, Y = async (n, t = 0) => { | ||
$t(n); | ||
const e = await J(F(n)); | ||
return new A({ decimal: e, value: t, identifier: n }); | ||
return j.get(n.toUpperCase()) || { decimal: m.THOR, identifier: "" }; | ||
}, W = async (n, t = 0) => { | ||
At(n); | ||
const e = await K(q(n)); | ||
return new f({ decimal: e, value: t, identifier: n }); | ||
}; | ||
class A extends E { | ||
class f extends T { | ||
constructor(e) { | ||
super( | ||
e.value instanceof E ? e.value : { decimal: e.decimal, value: e.value } | ||
e.value instanceof T ? e.value : { decimal: e.decimal, value: e.value } | ||
); | ||
_(this, "address"); | ||
_(this, "chain"); | ||
_(this, "isSynthetic", !1); | ||
_(this, "isGasAsset", !1); | ||
_(this, "symbol"); | ||
_(this, "ticker"); | ||
_(this, "type"); | ||
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, s = F(r); | ||
this.type = _t(s), this.chain = s.chain, this.ticker = s.ticker, this.symbol = s.symbol, this.address = s.address, this.isSynthetic = s.isSynthetic, this.isGasAsset = s.isGasAsset; | ||
g(this, "address"); | ||
g(this, "chain"); | ||
g(this, "isSynthetic", !1); | ||
g(this, "isGasAsset", !1); | ||
g(this, "symbol"); | ||
g(this, "ticker"); | ||
g(this, "type"); | ||
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, s = q(r); | ||
this.type = mt(s), this.chain = s.chain, this.ticker = s.ticker, this.symbol = s.symbol, this.address = s.address, this.isSynthetic = s.isSynthetic, this.isGasAsset = s.isGasAsset; | ||
} | ||
get assetValue() { | ||
return `${this.getValue("string")} ${this.ticker}`; | ||
} | ||
toString() { | ||
return `${this.chain}.${this.symbol}`; | ||
} | ||
eq({ chain: e, symbol: r }) { | ||
return this.chain === e && this.symbol === r; | ||
} | ||
static async fromString(e, r = 0) { | ||
return Y(e, r); | ||
return W(e, r); | ||
} | ||
static fromStringSync(e, r = 0) { | ||
const { decimal: s, identifier: a } = P( | ||
const { decimal: s, identifier: a } = D( | ||
e | ||
); | ||
return a ? new A({ decimal: s, identifier: a, value: r }) : void 0; | ||
return a ? new f({ decimal: s, identifier: a, value: r }) : void 0; | ||
} | ||
static async fromIdentifier(e, r = 0) { | ||
return Y(e, r); | ||
return W(e, r); | ||
} | ||
static fromIdentifierSync(e, r = 0) { | ||
const { decimal: s, identifier: a } = P(e); | ||
return new A({ decimal: s, identifier: a, value: r }); | ||
const { decimal: s, identifier: a } = D(e); | ||
return new f({ decimal: s, identifier: a, value: r }); | ||
} | ||
static fromChainOrSignature(e, r = 0) { | ||
const { decimal: s, identifier: a } = ht(e); | ||
return new A({ value: r, decimal: s, identifier: a }); | ||
return new f({ value: r, decimal: s, identifier: a }); | ||
} | ||
static async fromTCQuote(e, r = 0) { | ||
const s = await J(F(e)), a = this.shiftDecimals({ value: r, from: h.THOR, to: s }); | ||
return new A({ value: a, identifier: e, decimal: s }); | ||
const s = await K(q(e)), a = this.shiftDecimals({ value: r, from: m.THOR, to: s }); | ||
return new f({ value: a, identifier: e, decimal: s }); | ||
} | ||
static fromTCQuoteStatic(e, r = 0) { | ||
const s = P(e), a = this.shiftDecimals({ | ||
const s = D(e), a = this.shiftDecimals({ | ||
value: r, | ||
from: h.THOR, | ||
from: m.THOR, | ||
to: s.decimal | ||
}); | ||
return new A({ ...s, value: a }); | ||
return new f({ ...s, value: a }); | ||
} | ||
@@ -534,7 +582,7 @@ static async loadStaticAssets() { | ||
} = await import("@swapkit/tokens"); | ||
q = [a, ...Object.values(c)].reduce( | ||
(l, { tokens: u }) => (u.forEach(({ identifier: g, chain: $, ...v }) => { | ||
const D = "decimals" in v ? v.decimals : h[$]; | ||
l.set(g, { identifier: g, decimal: D }); | ||
}), l), | ||
j = [a, ...Object.values(c)].reduce( | ||
(u, { tokens: l }) => (l.forEach(({ identifier: d, chain: A, ...S }) => { | ||
const R = "decimals" in S ? S.decimals : m[A]; | ||
u.set(d, { identifier: d, decimal: R }); | ||
}), u), | ||
/* @__PURE__ */ new Map() | ||
@@ -552,14 +600,5 @@ ), e({ ok: !0 }); | ||
} | ||
get assetValue() { | ||
return `${this.value} ${this.ticker}`; | ||
} | ||
toString() { | ||
return `${this.chain}.${this.symbol}`; | ||
} | ||
eq({ chain: e, symbol: r }) { | ||
return this.chain === e && this.symbol === r; | ||
} | ||
} | ||
const Dt = (n) => { | ||
const t = A.fromChainOrSignature(n); | ||
const kt = (n) => { | ||
const t = f.fromChainOrSignature(n); | ||
switch (n) { | ||
@@ -581,3 +620,3 @@ case i.Bitcoin: | ||
} | ||
}, F = (n) => { | ||
}, q = (n) => { | ||
const t = n.slice(0, 14).includes("/"), e = n.includes(".") ? n : `${i.THORChain}.${n}`, [r, s] = e.split("."), [a, c] = s.split("-"); | ||
@@ -587,3 +626,3 @@ return { | ||
chain: r, | ||
isGasAsset: mt({ chain: r, symbol: s }), | ||
isGasAsset: dt({ chain: r, symbol: s }), | ||
isSynthetic: t, | ||
@@ -593,3 +632,3 @@ symbol: c ? `${a}-${(c == null ? void 0 : c.toLowerCase()) ?? ""}` : s, | ||
}; | ||
}, wt = { | ||
}, $t = { | ||
/** | ||
@@ -651,42 +690,39 @@ * Core | ||
}; | ||
class Q extends Error { | ||
class X extends Error { | ||
constructor(t, e) { | ||
console.error(e), super(t, { cause: { code: wt[t], message: t } }), Object.setPrototypeOf(this, Q.prototype); | ||
console.error(e), super(t, { cause: { code: $t[t], message: t } }), Object.setPrototypeOf(this, X.prototype); | ||
} | ||
} | ||
class bt extends E { | ||
class wt extends T { | ||
eq(t) { | ||
return this.eqValue(t); | ||
} | ||
toString() { | ||
return this.value; | ||
} | ||
} | ||
export { | ||
A as AssetValue, | ||
y as DEFAULT_DECIMAL, | ||
Q as SwapKitError, | ||
bt as SwapKitNumber, | ||
Mt as assetFromString, | ||
Tt as derivationPathToString, | ||
f as AssetValue, | ||
T as BigIntArithmetics, | ||
X as SwapKitError, | ||
wt as SwapKitNumber, | ||
yt as assetFromString, | ||
Vt as derivationPathToString, | ||
G as formatBigIntToSafeValue, | ||
yt as gasFeeMultiplier, | ||
_t as getAssetType, | ||
pt as getAsymmetricAssetShare, | ||
Ot as getAsymmetricAssetWithdrawAmount, | ||
gt as getAsymmetricRuneShare, | ||
Et as getAsymmetricRuneWithdrawAmount, | ||
Ct as gasFeeMultiplier, | ||
mt as getAssetType, | ||
gt as getAsymmetricAssetShare, | ||
Et as getAsymmetricAssetWithdrawAmount, | ||
_t as getAsymmetricRuneShare, | ||
Tt as getAsymmetricRuneWithdrawAmount, | ||
ht as getCommonAssetInfo, | ||
J as getDecimal, | ||
Nt as getEstimatedPoolShare, | ||
Rt as getLiquiditySlippage, | ||
kt as getMemoFor, | ||
Dt as getMinAmountByChain, | ||
K as getDecimal, | ||
Mt as getEstimatedPoolShare, | ||
Nt as getLiquiditySlippage, | ||
Rt as getMemoFor, | ||
kt as getMinAmountByChain, | ||
Bt as getRequest, | ||
ft as getSymmetricPoolShare, | ||
Vt as getSymmetricWithdraw, | ||
vt as getTHORNameCost, | ||
mt as isGasAsset, | ||
ct as postRequest, | ||
Ct as validateTHORName | ||
pt as getSymmetricPoolShare, | ||
Ot as getSymmetricWithdraw, | ||
St as getTHORNameCost, | ||
dt as isGasAsset, | ||
at as postRequest, | ||
vt as validateTHORName | ||
}; |
@@ -9,4 +9,4 @@ { | ||
"@internal/config": "0.0.0-internal.0", | ||
"@swapkit/tokens": "1.0.0-rc.1", | ||
"@swapkit/types": "1.0.0-rc.1" | ||
"@swapkit/tokens": "1.0.0-rc.2", | ||
"@swapkit/types": "1.0.0-rc.2" | ||
}, | ||
@@ -17,4 +17,4 @@ "eslintConfig": { | ||
"peerDependencies": { | ||
"@swapkit/tokens": "1.0.0-rc.1", | ||
"@swapkit/types": "1.0.0-rc.1" | ||
"@swapkit/tokens": "1.0.0-rc.2", | ||
"@swapkit/types": "1.0.0-rc.2" | ||
}, | ||
@@ -44,3 +44,3 @@ "exports": { | ||
"types": "./dist/index.d.ts", | ||
"version": "1.0.0-rc.2", | ||
"version": "1.0.0-rc.3", | ||
"scripts": { | ||
@@ -47,0 +47,0 @@ "build": "vite build", |
@@ -26,19 +26,24 @@ // 10 rune for register, 1 rune per year | ||
): Promise<T> => { | ||
const queryParams = Object.entries(params || {}).reduce( | ||
(acc, [key, value]) => { | ||
if (value) { | ||
acc[key] = value; | ||
} | ||
try { | ||
const queryParams = Object.entries(params || {}).reduce( | ||
(acc, [key, value]) => { | ||
if (value) { | ||
acc[key] = value; | ||
} | ||
return acc; | ||
}, | ||
{} as { [key in string]: any }, | ||
); | ||
return acc; | ||
}, | ||
{} as { [key in string]: any }, | ||
); | ||
const response = await fetch( | ||
`${url}${params ? `?${new URLSearchParams(queryParams).toString()}` : ''}`, | ||
{ method: 'GET', mode: 'cors', credentials: 'omit', referrer: 'https://sk.thorswap.net' }, | ||
); | ||
const response = await fetch( | ||
`${url}${params ? `?${new URLSearchParams(queryParams).toString()}` : ''}`, | ||
{ method: 'GET', mode: 'cors', credentials: 'omit', referrer: 'https://sk.thorswap.net' }, | ||
); | ||
return response.json(); | ||
return response.json(); | ||
} catch (error) { | ||
console.error(error); | ||
return {} as T; | ||
} | ||
}; | ||
@@ -52,10 +57,14 @@ | ||
): Promise<T> => { | ||
const response = await fetch(`${url}`, { | ||
body, | ||
headers, | ||
method: 'POST', | ||
referrer: 'https://sk.thorswap.net', | ||
}); | ||
try { | ||
const response = await fetch(`${url}`, { | ||
body, | ||
headers, | ||
method: 'POST', | ||
referrer: 'https://sk.thorswap.net', | ||
}); | ||
return parseAsString ? response.text() : response.json(); | ||
return parseAsString ? response.text() : response.json(); | ||
} catch (error) { | ||
return {} as T; | ||
} | ||
}; |
@@ -7,3 +7,2 @@ /** | ||
export * from './helpers/memo.ts'; | ||
export * from './helpers/number.ts'; | ||
export * from './helpers/others.ts'; | ||
@@ -14,4 +13,5 @@ | ||
*/ | ||
export { AssetValue, getMinAmountByChain } from './modules/assetValue.ts'; | ||
export { type Keys, SwapKitError } from './modules/swapKitError.ts'; | ||
export { SwapKitNumber } from './modules/swapKitNumber.ts'; | ||
export * from './modules/assetValue.ts'; | ||
export * from './modules/bigIntArithmetics.ts'; | ||
export * from './modules/swapKitError.ts'; | ||
export * from './modules/swapKitNumber.ts'; |
@@ -9,28 +9,28 @@ import { describe, expect, test } from 'vitest'; | ||
const skNumber1 = new SwapKitNumber(1); | ||
expect(skNumber1.value).toBe('1'); | ||
expect(skNumber1.bigIntValue).toBe(100000000n); | ||
expect(skNumber1.getValue('string')).toBe('1'); | ||
expect(skNumber1.getValue('number')).toBe(1); | ||
expect(skNumber1.getValue('bigint')).toBe(100000000n); | ||
const skNumber2 = new SwapKitNumber('1'); | ||
expect(skNumber2.value).toBe('1'); | ||
expect(skNumber2.bigIntValue).toBe(100000000n); | ||
expect(skNumber2.getValue('string')).toBe('1'); | ||
expect(skNumber2.getValue('bigint')).toBe(100000000n); | ||
const skNumber3 = new SwapKitNumber('0.0000000001'); | ||
expect(skNumber3.value).toBe('0.0000000001'); | ||
expect(skNumber3.bigIntValue).toBe(1n); | ||
expect(skNumber3.getValue('string')).toBe('0.0000000001'); | ||
expect(skNumber3.getValue('bigint')).toBe(1n); | ||
const skNumber4 = new SwapKitNumber(0.000000001); | ||
expect(skNumber4.value).toBe('0.000000001'); | ||
expect(skNumber4.bigIntValue).toBe(1n); | ||
expect(skNumber4.getValue('string')).toBe('0.000000001'); | ||
expect(skNumber4.getValue('bigint')).toBe(1n); | ||
const skNumber6 = new SwapKitNumber({ value: 0.1005, decimal: 3 }); | ||
expect(skNumber6.value).toBe('0.101'); | ||
expect(skNumber6.bigIntValue).toBe(10050000n); | ||
expect(skNumber6.getValue('string')).toBe('0.101'); | ||
expect(skNumber6.getValue('bigint')).toBe(10050000n); | ||
const skNumber7 = new SwapKitNumber({ value: -0.1005, decimal: 3 }); | ||
expect(skNumber7.value).toBe('-0.101'); | ||
expect(skNumber7.bigIntValue).toBe(-10050000n); | ||
expect(skNumber7.getValue('string')).toBe('-0.101'); | ||
expect(skNumber7.getValue('bigint')).toBe(-10050000n); | ||
expect(skNumber7.decimal).toBe(3); | ||
expect(skNumber7.unsafeNumber).toBe(0); | ||
expect(skNumber7.getValue('number')).toBe(-0.101); | ||
expect(skNumber7.decimalMultiplier).toBe(100000000n); | ||
expect(skNumber7.toString()).toBe('-0.101'); | ||
}); | ||
@@ -41,4 +41,4 @@ | ||
expect(skNumber.value).toBe('12.345678901234'); | ||
expect(skNumber.bigIntValue).toBe(12345678901234n); | ||
expect(skNumber.getValue('string')).toBe('12.345678901234'); | ||
expect(skNumber.getValue('bigint')).toBe(12345678901234n); | ||
}); | ||
@@ -50,4 +50,4 @@ }); | ||
const skNumber = new SwapKitNumber(1); | ||
expect(skNumber.value).toBe('1'); | ||
expect(skNumber.bigIntValue).toBe(100000000n); | ||
expect(skNumber.getValue('string')).toBe('1'); | ||
expect(skNumber.getValue('bigint')).toBe(100000000n); | ||
@@ -60,10 +60,10 @@ const shiftedSkNumber = SwapKitNumber.shiftDecimals({ | ||
expect(shiftedSkNumber.value).toBe('100'); | ||
expect(shiftedSkNumber.bigIntValue).toBe(10000000000n); | ||
expect(shiftedSkNumber.getValue('string')).toBe('100'); | ||
expect(shiftedSkNumber.getValue('bigint')).toBe(10000000000n); | ||
}); | ||
test.skip('shifts down and rounds down number', () => { | ||
test('shifts down and rounds down number', () => { | ||
const skNumber = new SwapKitNumber(2.12345678); | ||
expect(skNumber.value).toBe('2.12345678'); | ||
expect(skNumber.bigIntValue).toBe(212345678n); | ||
expect(skNumber.getValue('string')).toBe('2.12345678'); | ||
expect(skNumber.getValue('bigint')).toBe(212345678n); | ||
@@ -76,7 +76,83 @@ const shiftedSkNumber = SwapKitNumber.shiftDecimals({ | ||
expect(shiftedSkNumber.value).toBe('2.123456'); | ||
expect(shiftedSkNumber.bigIntValue).toBe(2123456n); | ||
expect(shiftedSkNumber.getValue('string')).toBe('2.123456'); | ||
expect(shiftedSkNumber.getValue('bigint')).toBe(212345600n); | ||
}); | ||
}); | ||
describe('getValue', () => { | ||
describe('string', () => { | ||
test('returns string value', () => { | ||
const skNumber = new SwapKitNumber(1); | ||
expect(skNumber.getValue('string')).toBe('1'); | ||
}); | ||
test('returns string value with decimals', () => { | ||
const skNumber = new SwapKitNumber(0.01); | ||
expect(skNumber.getValue('string')).toBe('0.01'); | ||
}); | ||
}); | ||
describe('number', () => { | ||
test('returns number value', () => { | ||
const skNumber = new SwapKitNumber(1); | ||
expect(skNumber.getValue('number')).toBe(1); | ||
}); | ||
test('returns number value with decimals', () => { | ||
const skNumber = new SwapKitNumber(0.01); | ||
expect(skNumber.getValue('number')).toBe(0.01); | ||
}); | ||
}); | ||
describe('bigint', () => { | ||
test('returns bigint value', () => { | ||
const skNumber = new SwapKitNumber(1); | ||
expect(skNumber.getValue('bigint')).toBe(100000000n); | ||
}); | ||
}); | ||
}); | ||
describe('toSignificant', () => { | ||
describe('normal cases', () => { | ||
test('returns first significant number of digits', () => { | ||
const usdLikeNumber = new SwapKitNumber(1234.5678); | ||
expect(usdLikeNumber.toSignificant(2)).toBe('1200'); | ||
expect(usdLikeNumber.toSignificant(3)).toBe('1230'); | ||
expect(usdLikeNumber.toSignificant(4)).toBe('1234'); | ||
expect(usdLikeNumber.toSignificant(5)).toBe('1234.5'); | ||
expect(usdLikeNumber.toSignificant(6)).toBe('1234.56'); | ||
expect(usdLikeNumber.toSignificant(7)).toBe('1234.567'); | ||
expect(usdLikeNumber.toSignificant(8)).toBe('1234.5678'); | ||
const btcLikeNumber = new SwapKitNumber(0.00005678); | ||
expect(btcLikeNumber.toSignificant(2)).toBe('0.000056'); | ||
expect(btcLikeNumber.toSignificant(3)).toBe('0.0000567'); | ||
expect(btcLikeNumber.toSignificant(4)).toBe('0.00005678'); | ||
expect(btcLikeNumber.toSignificant(5)).toBe('0.00005678'); | ||
expect(btcLikeNumber.toSignificant(8)).toBe('0.00005678'); | ||
}); | ||
}); | ||
describe('custom decimals', () => { | ||
test('returns first significant number of digits', () => { | ||
const usdLikeNumber = new SwapKitNumber({ value: 1234.5678, decimal: 2 }); | ||
expect(usdLikeNumber.toSignificant(2)).toBe('1200'); | ||
expect(usdLikeNumber.toSignificant(3)).toBe('1230'); | ||
expect(usdLikeNumber.toSignificant(4)).toBe('1234'); | ||
expect(usdLikeNumber.toSignificant(5)).toBe('1234.5'); | ||
expect(usdLikeNumber.toSignificant(6)).toBe('1234.57'); | ||
expect(usdLikeNumber.toSignificant(7)).toBe('1234.57'); | ||
expect(usdLikeNumber.toSignificant(8)).toBe('1234.57'); | ||
const ethLikeNumber = new SwapKitNumber({ value: 0.00005678, decimal: 18 }); | ||
expect(ethLikeNumber.toSignificant(2)).toBe('0.000056'); | ||
expect(ethLikeNumber.toSignificant(3)).toBe('0.0000567'); | ||
expect(ethLikeNumber.toSignificant(4)).toBe('0.00005678'); | ||
expect(ethLikeNumber.toSignificant(5)).toBe('0.00005678'); | ||
expect(ethLikeNumber.toSignificant(8)).toBe('0.00005678'); | ||
expect(ethLikeNumber.toSignificant(18)).toBe('0.00005678'); | ||
}); | ||
}); | ||
}); | ||
describe('add', () => { | ||
@@ -89,4 +165,4 @@ test('adds same type numbers correctly', () => { | ||
expect(result.value).toBe('15.5'); | ||
expect(result.bigIntValue).toBe(1550000000n); | ||
expect(result.getValue('string')).toBe('15.5'); | ||
expect(result.getValue('bigint')).toBe(1550000000n); | ||
}); | ||
@@ -98,4 +174,4 @@ | ||
expect(result.value).toBe('16.5'); | ||
expect(result.bigIntValue).toBe(1650000000n); | ||
expect(result.getValue('string')).toBe('16.5'); | ||
expect(result.getValue('bigint')).toBe(1650000000n); | ||
}); | ||
@@ -106,4 +182,4 @@ | ||
const result = skNumber1.add(6.000000000001, '0.0000000000000005'); | ||
expect(result.value).toBe('6.0000000001010005'); | ||
expect(result.bigIntValue).toBe(60000000001010005n); | ||
expect(result.getValue('string')).toBe('6.0000000001010005'); | ||
expect(result.getValue('bigint')).toBe(60000000001010005n); | ||
}); | ||
@@ -119,4 +195,4 @@ }); | ||
expect(result.value).toBe('4.5'); | ||
expect(result.bigIntValue).toBe(450000000n); | ||
expect(result.getValue('string')).toBe('4.5'); | ||
expect(result.getValue('bigint')).toBe(450000000n); | ||
}); | ||
@@ -128,4 +204,4 @@ | ||
expect(result.value).toBe('3.5'); | ||
expect(result.bigIntValue).toBe(350000000n); | ||
expect(result.getValue('string')).toBe('3.5'); | ||
expect(result.getValue('bigint')).toBe(350000000n); | ||
}); | ||
@@ -138,6 +214,6 @@ | ||
expect(result0.value).toBe('0'); | ||
expect(resultMinus.value).toBe('-10'); | ||
expect(result0.bigIntValue).toBe(0n); | ||
expect(resultMinus.bigIntValue).toBe(-1000000000n); | ||
expect(result0.getValue('string')).toBe('0'); | ||
expect(resultMinus.getValue('string')).toBe('-10'); | ||
expect(result0.getValue('bigint')).toBe(0n); | ||
expect(resultMinus.getValue('bigint')).toBe(-1000000000n); | ||
}); | ||
@@ -153,4 +229,4 @@ }); | ||
expect(result.value).toBe('25'); | ||
expect(result.bigIntValue).toBe(2500000000n); | ||
expect(result.getValue('string')).toBe('25'); | ||
expect(result.getValue('bigint')).toBe(2500000000n); | ||
}); | ||
@@ -162,4 +238,4 @@ | ||
expect(result.value).toBe('30'); | ||
expect(result.bigIntValue).toBe(3000000000n); | ||
expect(result.getValue('string')).toBe('30'); | ||
expect(result.getValue('bigint')).toBe(3000000000n); | ||
}); | ||
@@ -171,4 +247,4 @@ | ||
expect(result.value).toBe('10'); | ||
expect(result.bigIntValue).toBe(1000000000n); | ||
expect(result.getValue('string')).toBe('10'); | ||
expect(result.getValue('bigint')).toBe(1000000000n); | ||
}); | ||
@@ -184,4 +260,4 @@ | ||
// If we round it to 2 decimal places, we should get 5.61 | ||
expect(result.value).toBe('5.61'); | ||
expect(result.bigIntValue).toBe(560880000n); | ||
expect(result.getValue('string')).toBe('5.61'); | ||
expect(result.getValue('bigint')).toBe(560880000n); | ||
@@ -195,4 +271,4 @@ const skNumber3 = new SwapKitNumber({ decimal: 2, value: 1.23 }); | ||
// If we round it to 2 decimal places, we should get 5.61 | ||
expect(result2.value).toBe('-1.52'); | ||
expect(result2.bigIntValue).toBe(-1518518505n); | ||
expect(result2.getValue('string')).toBe('-1.52'); | ||
expect(result2.getValue('bigint')).toBe(-1518518505n); | ||
}); | ||
@@ -208,4 +284,4 @@ }); | ||
expect(result.value).toBe('4'); | ||
expect(result.bigIntValue).toBe(400000000n); | ||
expect(result.getValue('string')).toBe('4'); | ||
expect(result.getValue('bigint')).toBe(400000000n); | ||
@@ -215,4 +291,4 @@ const skNumber4 = new SwapKitNumber(10.12); | ||
expect(result2.value).toBe('101200'); | ||
expect(result2.bigIntValue).toBe(10120000000000n); | ||
expect(result2.getValue('string')).toBe('101200'); | ||
expect(result2.getValue('bigint')).toBe(10120000000000n); | ||
}); | ||
@@ -224,4 +300,4 @@ | ||
expect(result.value).toBe('8'); | ||
expect(result.bigIntValue).toBe(800000000n); | ||
expect(result.getValue('string')).toBe('8'); | ||
expect(result.getValue('bigint')).toBe(800000000n); | ||
}); | ||
@@ -233,4 +309,4 @@ | ||
expect(result.value).toBe('1200'); | ||
expect(result.bigIntValue).toBe(120000000000n); | ||
expect(result.getValue('string')).toBe('1200'); | ||
expect(result.getValue('bigint')).toBe(120000000000n); | ||
}); | ||
@@ -242,4 +318,4 @@ | ||
expect(result.value).toBe('0.5'); | ||
expect(result.bigIntValue).toBe(50000000n); | ||
expect(result.getValue('string')).toBe('0.5'); | ||
expect(result.getValue('bigint')).toBe(50000000n); | ||
}); | ||
@@ -254,4 +330,4 @@ | ||
// The exact result of 1.000000000000000010 / -2 is -0.500000000000000005 | ||
expect(result.value).toBe('-0.500000000000000005'); | ||
expect(result.bigIntValue).toBe(-500000000000000005n); | ||
expect(result.getValue('string')).toBe('-0.500000000000000005'); | ||
expect(result.getValue('bigint')).toBe(-500000000000000005n); | ||
}); | ||
@@ -266,4 +342,4 @@ | ||
// The exact result of 2 / -0.000005 is -400000 | ||
expect(result.value).toBe('-400000'); | ||
expect(result.bigIntValue).toBe(-40000000000000n); | ||
expect(result.getValue('string')).toBe('-400000'); | ||
expect(result.getValue('bigint')).toBe(-40000000000000n); | ||
}); | ||
@@ -278,4 +354,4 @@ }); | ||
const result = skNumber1.mul(skNumber2); | ||
expect(result.value).toBe('987654321000000987654321000'); | ||
expect(result.bigIntValue).toBe(987654321000000987654321000000000000000000000n); | ||
expect(result.getValue('string')).toBe('987654321000000987654321000'); | ||
expect(result.getValue('bigint')).toBe(987654321000000987654321000000000000000000000n); | ||
}); | ||
@@ -288,4 +364,4 @@ | ||
const result = skNumber1.div(skNumber2); | ||
expect(result.value).toBe('1012.4999999873447625'); | ||
expect(result.bigIntValue).toBe(1012499999987344762500n); | ||
expect(result.getValue('string')).toBe('1012.4999999873447625'); | ||
expect(result.getValue('bigint')).toBe(1012499999987344762500n); | ||
}); | ||
@@ -292,0 +368,0 @@ }); |
@@ -62,2 +62,42 @@ import type { | ||
export class AssetValue extends BigIntArithmetics { | ||
address?: string; | ||
chain: Chain; | ||
isSynthetic = false; | ||
isGasAsset = false; | ||
symbol: string; | ||
ticker: string; | ||
type: ReturnType<typeof getAssetType>; | ||
constructor(params: AssetValueParams) { | ||
super( | ||
params.value instanceof BigIntArithmetics | ||
? params.value | ||
: { decimal: params.decimal, value: params.value }, | ||
); | ||
const identifier = | ||
'identifier' in params ? params.identifier : `${params.chain}.${params.symbol}`; | ||
const assetInfo = getAssetInfo(identifier); | ||
this.type = getAssetType(assetInfo); | ||
this.chain = assetInfo.chain; | ||
this.ticker = assetInfo.ticker; | ||
this.symbol = assetInfo.symbol; | ||
this.address = assetInfo.address; | ||
this.isSynthetic = assetInfo.isSynthetic; | ||
this.isGasAsset = assetInfo.isGasAsset; | ||
} | ||
get assetValue() { | ||
return `${this.getValue('string')} ${this.ticker}`; | ||
} | ||
toString() { | ||
return `${this.chain}.${this.symbol}`; | ||
} | ||
eq({ chain, symbol }: { chain: Chain; symbol: string }) { | ||
return this.chain === chain && this.symbol === symbol; | ||
} | ||
static async fromString(assetString: string, value: number | string = 0) { | ||
@@ -153,42 +193,2 @@ return createAssetValue(assetString, value); | ||
} | ||
address?: string; | ||
chain: Chain; | ||
isSynthetic = false; | ||
isGasAsset = false; | ||
symbol: string; | ||
ticker: string; | ||
type: ReturnType<typeof getAssetType>; | ||
constructor(params: AssetValueParams) { | ||
super( | ||
params.value instanceof BigIntArithmetics | ||
? params.value | ||
: { decimal: params.decimal, value: params.value }, | ||
); | ||
const identifier = | ||
'identifier' in params ? params.identifier : `${params.chain}.${params.symbol}`; | ||
const assetInfo = getAssetInfo(identifier); | ||
this.type = getAssetType(assetInfo); | ||
this.chain = assetInfo.chain; | ||
this.ticker = assetInfo.ticker; | ||
this.symbol = assetInfo.symbol; | ||
this.address = assetInfo.address; | ||
this.isSynthetic = assetInfo.isSynthetic; | ||
this.isGasAsset = assetInfo.isGasAsset; | ||
} | ||
get assetValue() { | ||
return `${this.value} ${this.ticker}`; | ||
} | ||
toString() { | ||
return `${this.chain}.${this.symbol}`; | ||
} | ||
eq({ chain, symbol }: { chain: Chain; symbol: string }) { | ||
return this.chain === chain && this.symbol === symbol; | ||
} | ||
} | ||
@@ -195,0 +195,0 @@ |
@@ -1,9 +0,55 @@ | ||
import { DEFAULT_DECIMAL, formatBigIntToSafeValue } from '../helpers/number.ts'; | ||
import type { SwapKitNumber } from './swapKitNumber.ts'; | ||
type AllowedValueType = bigint | number | string; | ||
type ArithmeticMethod = 'add' | 'sub' | 'mul' | 'div'; | ||
type NumberPrimitivesType = { | ||
bigint: bigint; | ||
number: number; | ||
string: string; | ||
}; | ||
type NumberPrimitives = bigint | number | string; | ||
type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber; | ||
type SKBigIntParams = InitialisationValueType | { decimal?: number; value: number | string }; | ||
const DEFAULT_DECIMAL = 8; | ||
const toMultiplier = (decimal: number) => 10n ** BigInt(decimal); | ||
const decimalFromMultiplier = (multiplier: bigint) => Math.log10(parseFloat(multiplier.toString())); | ||
export function formatBigIntToSafeValue({ | ||
value, | ||
bigIntDecimal = DEFAULT_DECIMAL, | ||
decimal = DEFAULT_DECIMAL, | ||
}: { | ||
value: bigint; | ||
bigIntDecimal?: number; | ||
decimal?: number; | ||
}) { | ||
const isNegative = value < 0n; | ||
let valueString = value.toString().substring(isNegative ? 1 : 0); | ||
const padLength = decimal - (valueString.length - 1); | ||
if (padLength > 0) { | ||
valueString = '0'.repeat(padLength) + valueString; | ||
} | ||
const decimalIndex = valueString.length - decimal; | ||
let decimalString = valueString.slice(-decimal); | ||
// Check if we need to round up | ||
if (parseInt(decimalString[bigIntDecimal]) >= 5) { | ||
// Increment the last decimal place and slice off the rest | ||
decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${( | ||
parseInt(decimalString[bigIntDecimal - 1]) + 1 | ||
).toString()}`; | ||
} else { | ||
// Just slice off the extra digits | ||
decimalString = decimalString.substring(0, bigIntDecimal); | ||
} | ||
return `${isNegative ? '-' : ''}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace( | ||
/\.?0*$/, | ||
'', | ||
); | ||
} | ||
export class BigIntArithmetics { | ||
@@ -26,3 +72,3 @@ decimalMultiplier: bigint = 10n ** 8n; | ||
}: { | ||
value: BigIntArithmetics | string | number; | ||
value: InitialisationValueType; | ||
from: number; | ||
@@ -37,12 +83,5 @@ to: number; | ||
constructor( | ||
valueOrParams: | ||
| BigIntArithmetics | ||
| string | ||
| number | ||
| { decimal?: number; value: number | string }, | ||
) { | ||
const complexInit = typeof valueOrParams === 'object'; | ||
const value = complexInit ? valueOrParams.value : valueOrParams; | ||
this.decimal = complexInit ? valueOrParams.decimal : undefined; | ||
constructor(params: SKBigIntParams) { | ||
const value = getStringValue(params); | ||
this.decimal = typeof params === 'object' ? params.decimal : undefined; | ||
@@ -56,54 +95,84 @@ // use the multiplier to keep track of decimal point - defaults to 8 if lower than 8 | ||
get unsafeNumber() { | ||
return parseFloat((this.bigIntValue / this.decimalMultiplier).toString()); | ||
} | ||
get baseValue() { | ||
return this.#getBaseValue('string') as string; | ||
return this.getBaseValue('string') as string; | ||
} | ||
get baseValueNumber() { | ||
return this.#getBaseValue('number') as number; | ||
return this.getBaseValue('number') as number; | ||
} | ||
get baseValueBigInt() { | ||
return this.#getBaseValue('number') as bigint; | ||
return this.getBaseValue('bigint') as bigint; | ||
} | ||
get value() { | ||
return this.formatBigIntToSafeValue( | ||
this.bigIntValue, | ||
this.decimal || decimalFromMultiplier(this.decimalMultiplier), | ||
); | ||
set(value: SKBigIntParams) { | ||
// @ts-expect-error False positive | ||
return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() }); | ||
} | ||
add(...args: (BigIntArithmetics | string | number)[]) { | ||
add(...args: InitialisationValueType[]) { | ||
return this.#arithmetics('add', ...args); | ||
} | ||
sub(...args: (BigIntArithmetics | string | number)[]) { | ||
sub(...args: InitialisationValueType[]) { | ||
return this.#arithmetics('sub', ...args); | ||
} | ||
mul(...args: (BigIntArithmetics | string | number)[]) { | ||
mul(...args: InitialisationValueType[]) { | ||
return this.#arithmetics('mul', ...args); | ||
} | ||
div(...args: (BigIntArithmetics | string | number)[]) { | ||
div(...args: InitialisationValueType[]) { | ||
return this.#arithmetics('div', ...args); | ||
} | ||
gt(value: BigIntArithmetics | string | number) { | ||
gt(value: InitialisationValueType) { | ||
return this.bigIntValue > this.getBigIntValue(value); | ||
} | ||
gte(value: BigIntArithmetics | string | number) { | ||
gte(value: InitialisationValueType) { | ||
return this.bigIntValue >= this.getBigIntValue(value); | ||
} | ||
lt(value: BigIntArithmetics | string | number) { | ||
lt(value: InitialisationValueType) { | ||
return this.bigIntValue < this.getBigIntValue(value); | ||
} | ||
lte(value: BigIntArithmetics | string | number) { | ||
lte(value: InitialisationValueType) { | ||
return this.bigIntValue <= this.getBigIntValue(value); | ||
} | ||
eqValue(value: BigIntArithmetics | string | number) { | ||
eqValue(value: InitialisationValueType) { | ||
return this.bigIntValue === this.getBigIntValue(value); | ||
} | ||
getBigIntValue(value: BigIntArithmetics | string | number, decimal?: number) { | ||
getValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T] { | ||
const value = this.formatBigIntToSafeValue( | ||
this.bigIntValue, | ||
this.decimal || decimalFromMultiplier(this.decimalMultiplier), | ||
); | ||
switch (type) { | ||
case 'number': | ||
// @ts-expect-error False positive | ||
return Number(value); | ||
case 'string': | ||
// @ts-expect-error False positive | ||
return value; | ||
default: | ||
// @ts-expect-error False positive | ||
return this.bigIntValue; | ||
} | ||
} | ||
getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T] { | ||
const divisor = this.decimalMultiplier / toMultiplier(this.decimal || 0); | ||
const baseValue = this.bigIntValue / divisor; | ||
switch (type) { | ||
case 'number': | ||
// @ts-expect-error False positive | ||
return Number(baseValue); | ||
case 'string': | ||
// @ts-expect-error False positive | ||
return baseValue.toString(); | ||
default: | ||
// @ts-expect-error False positive | ||
return this.bigIntValue; | ||
} | ||
} | ||
getBigIntValue(value: InitialisationValueType, decimal?: number) { | ||
if (!decimal && typeof value === 'object') return value.bigIntValue; | ||
value = typeof value === 'object' ? value.value : value; | ||
return this.#toBigInt(this.#toSafeValue(value), decimal); | ||
return this.#toBigInt(this.#toSafeValue(getStringValue(value)), decimal); | ||
} | ||
@@ -119,12 +188,9 @@ | ||
let valueString = value.toString().substring(isNegative ? 1 : 0); | ||
const valueString = value.toString().substring(isNegative ? 1 : 0); | ||
const padLength = decimalToUseForConversion - (valueString.length - 1); | ||
if (padLength > 0) { | ||
valueString = '0'.repeat(padLength) + valueString; | ||
} | ||
const parsedValueString = padLength > 0 ? '0'.repeat(padLength) + valueString : valueString; | ||
const decimalIndex = valueString.length - decimalToUseForConversion; | ||
let decimalString = valueString.slice(-decimalToUseForConversion); | ||
const decimalIndex = parsedValueString.length - decimalToUseForConversion; | ||
let decimalString = parsedValueString.slice(-decimalToUseForConversion); | ||
@@ -142,24 +208,39 @@ // Check if we need to round up | ||
return `${isNegative ? '-' : ''}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace( | ||
/\.?0*$/, | ||
'', | ||
); | ||
return `${isNegative ? '-' : ''}${parsedValueString.slice( | ||
0, | ||
decimalIndex, | ||
)}.${decimalString}`.replace(/\.?0*$/, ''); | ||
} | ||
toSignificant(significantDigits?: number) { | ||
const value = this.value.split('.'); | ||
const integer = value[0]; | ||
const decimal = value[1]; | ||
toSignificant(significantDigits: number = 6) { | ||
const [int, dec] = this.getValue('string').split('.'); | ||
const integer = int || ''; | ||
const decimal = dec || ''; | ||
const valueLength = parseInt(integer) ? integer.length + decimal.length : decimal.length; | ||
if (decimal) { | ||
return `${integer}.${decimal.slice(0, significantDigits || this.decimal)}`.replace( | ||
/\.?0*$/, | ||
'', | ||
if (valueLength <= significantDigits) { | ||
return this.getValue('string'); | ||
} | ||
if (integer.length >= significantDigits) { | ||
return integer.slice(0, significantDigits).padEnd(integer.length, '0'); | ||
} | ||
if (parseInt(integer)) { | ||
return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd( | ||
valueLength - significantDigits, | ||
'0', | ||
); | ||
} | ||
return integer; | ||
const trimmedDecimal = parseInt(decimal); | ||
const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits); | ||
return `0.${slicedDecimal.padStart( | ||
decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, | ||
'0', | ||
)}`; | ||
} | ||
#arithmetics(method: ArithmeticMethod, ...args: (BigIntArithmetics | string | number)[]): this { | ||
#arithmetics(method: 'add' | 'sub' | 'mul' | 'div', ...args: InitialisationValueType[]): this { | ||
const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args); | ||
@@ -169,24 +250,27 @@ const precisionDecimalMultiplier = toMultiplier(precisionDecimal); | ||
const result = args.reduce( | ||
(acc, arg) => { | ||
(acc: bigint, arg) => { | ||
const value = this.getBigIntValue(arg, precisionDecimal); | ||
if ('div' === method && value === 0n) throw new RangeError('Division by zero'); | ||
/** | ||
* Normal arithmetic - add & sub => 200000000n +- 200000000n | ||
*/ | ||
if ('add' === method) return acc + value; | ||
if ('sub' === method) return acc - value; | ||
/** | ||
* Multiplication & division would end up with wrong result if we don't adjust the value | ||
* 200000000n * 200000000n => 40000000000000000n | ||
* 200000000n / 200000000n => 1n | ||
* So we do the following: | ||
* 200000000n * 200000000n = 40000000000000000n / 100000000n (decimals) => 400000000n | ||
* (200000000n * 100000000n (decimals)) / 200000000n => 100000000n | ||
*/ | ||
if ('mul' === method) return (acc * value) / precisionDecimalMultiplier; | ||
// 'div' === method | ||
return (acc * precisionDecimalMultiplier) / value; | ||
switch (method) { | ||
case 'add': | ||
return acc + value; | ||
case 'sub': | ||
return acc - value; | ||
/** | ||
* Multiplication & division would end up with wrong result if we don't adjust the value | ||
* 200000000n * 200000000n => 40000000000000000n | ||
* 200000000n / 200000000n => 1n | ||
* So we do the following: | ||
* 200000000n * 200000000n = 40000000000000000n / 100000000n (decimals) => 400000000n | ||
* (200000000n * 100000000n (decimals)) / 200000000n => 100000000n | ||
*/ | ||
case 'mul': | ||
return (acc * value) / precisionDecimalMultiplier; | ||
case 'div': { | ||
if (value === 0n) throw new RangeError('Division by zero'); | ||
return (acc * precisionDecimalMultiplier) / value; | ||
} | ||
default: | ||
return acc; | ||
} | ||
}, | ||
@@ -203,12 +287,12 @@ //normalize is to precision multiplier base | ||
// @ts-expect-error - we know that the constructor is the same as the current class | ||
// @ts-expect-error False positive | ||
return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() }); | ||
} | ||
#setValue(value: AllowedValueType, bigIntValue?: bigint) { | ||
#setValue(value: InitialisationValueType) { | ||
const safeValue = this.#toSafeValue(value) || '0'; | ||
this.bigIntValue = bigIntValue || this.#toBigInt(safeValue); | ||
this.bigIntValue = this.#toBigInt(safeValue); | ||
} | ||
#retrievePrecisionDecimal(...args: (BigIntArithmetics | AllowedValueType)[]) { | ||
#retrievePrecisionDecimal(...args: InitialisationValueType[]) { | ||
const decimals = args | ||
@@ -232,3 +316,3 @@ .map((arg) => | ||
#toSafeValue(value: AllowedValueType) { | ||
#toSafeValue(value: InitialisationValueType) { | ||
const parsedValue = | ||
@@ -240,3 +324,3 @@ typeof value === 'number' | ||
}) | ||
: value; | ||
: getStringValue(value); | ||
@@ -254,16 +338,10 @@ const splitValue = `${parsedValue}`.replaceAll(',', '.').split('.'); | ||
} | ||
} | ||
#getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T) { | ||
const divisor = this.decimalMultiplier / toMultiplier(this.decimal || 0); | ||
const baseValue = this.bigIntValue / divisor; | ||
switch (type) { | ||
case 'number': | ||
return Number(baseValue); | ||
case 'string': | ||
return baseValue.toString(); | ||
default: | ||
return baseValue; | ||
} | ||
} | ||
function getStringValue(value: SKBigIntParams) { | ||
return typeof value === 'object' | ||
? 'getValue' in value | ||
? value.getValue('string') | ||
: value.value | ||
: value; | ||
} |
@@ -9,6 +9,2 @@ import { BigIntArithmetics } from './bigIntArithmetics.ts'; | ||
} | ||
toString() { | ||
return this.value; | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
152829
3001
21