@swapkit/helpers
Advanced tools
Comparing version 1.0.0-rc.10 to 1.0.0-rc.11
@@ -39,9 +39,9 @@ import { Chain } from '@swapkit/types'; | ||
}): boolean; | ||
static fromString(assetString: string, value?: number | string): Promise<AssetValue>; | ||
static fromStringSync(assetString: string, value?: number | string): AssetValue | undefined; | ||
static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: number | string): Promise<AssetValue>; | ||
static fromIdentifierSync(identifier: TokenNames, value?: number | string): AssetValue; | ||
static fromChainOrSignature(assetString: CommonAssetString, value?: number | string): AssetValue; | ||
static fromTCQuote(identifier: TCTokenNames, value?: number | string): Promise<AssetValue>; | ||
static fromTCQuoteStatic(identifier: TCTokenNames, value?: number | string): AssetValue; | ||
static fromString(assetString: string, value?: NumberPrimitives): Promise<AssetValue>; | ||
static fromStringSync(assetString: string, value?: NumberPrimitives): AssetValue | undefined; | ||
static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: NumberPrimitives): Promise<AssetValue>; | ||
static fromIdentifierSync(identifier: TokenNames, value?: NumberPrimitives): AssetValue; | ||
static fromChainOrSignature(assetString: CommonAssetString, value?: NumberPrimitives): AssetValue; | ||
static fromTCQuote(identifier: TCTokenNames, value?: NumberPrimitives): Promise<AssetValue>; | ||
static fromTCQuoteStatic(identifier: TCTokenNames, value?: NumberPrimitives): AssetValue; | ||
static loadStaticAssets(): Promise<{ | ||
@@ -293,3 +293,3 @@ ok: true; | ||
declare type NumberPrimitives = bigint | number | string; | ||
export declare type NumberPrimitives = bigint | number | string; | ||
@@ -330,2 +330,3 @@ declare type NumberPrimitivesType = { | ||
eq(value: SwapKitValueType): boolean; | ||
static fromBigInt(value: bigint, decimal?: number): SwapKitNumber; | ||
} | ||
@@ -332,0 +333,0 @@ |
@@ -1,4 +0,4 @@ | ||
var _t = Object.defineProperty; | ||
var gt = (s, t, e) => t in s ? _t(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e; | ||
var p = (s, t, e) => (gt(s, typeof t != "symbol" ? t + "" : t, e), e), bt = (s, t, e) => { | ||
var bt = Object.defineProperty; | ||
var yt = (s, t, e) => t in s ? bt(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e; | ||
var p = (s, t, e) => (yt(s, typeof t != "symbol" ? t + "" : t, e), e), wt = (s, t, e) => { | ||
if (!t.has(s)) | ||
@@ -12,7 +12,7 @@ throw TypeError("Cannot " + e); | ||
}; | ||
var f = (s, t, e) => (bt(s, t, "access private method"), e); | ||
import { FeeOption as H, BaseDecimal as m, Chain as o, ChainToRPC as yt, MemoType as g } from "@swapkit/types"; | ||
const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => { | ||
var f = (s, t, e) => (wt(s, t, "access private method"), e); | ||
import { FeeOption as D, BaseDecimal as m, Chain as o, ChainToRPC as At, MemoType as g } from "@swapkit/types"; | ||
const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => { | ||
try { | ||
const { result: e } = await zt.post(yt[s], { | ||
const { result: e } = await Kt.post(At[s], { | ||
headers: { accept: "*/*", "cache-control": "no-cache" }, | ||
@@ -23,3 +23,3 @@ body: JSON.stringify({ | ||
method: "eth_call", | ||
params: [{ to: t.toLowerCase(), data: wt }, "latest"] | ||
params: [{ to: t.toLowerCase(), data: Tt }, "latest"] | ||
}) | ||
@@ -31,26 +31,26 @@ }); | ||
} | ||
}, At = async (s) => { | ||
}, vt = async (s) => { | ||
if (s === o.Ethereum) | ||
return m.ETH; | ||
const [, t] = s.split("-"); | ||
return t != null && t.startsWith("0x") ? rt({ chain: o.Ethereum, to: t }) : m.ETH; | ||
}, Tt = async (s) => { | ||
return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : m.ETH; | ||
}, Rt = async (s) => { | ||
const [, t] = s.split("-"); | ||
return t != null && t.startsWith("0x") ? rt({ chain: o.Avalanche, to: t.toLowerCase() }) : m.AVAX; | ||
}, Rt = async (s) => s === o.BinanceSmartChain ? m.BSC : m.BSC, st = async ({ chain: s, symbol: t }) => { | ||
return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : m.AVAX; | ||
}, St = async (s) => s === o.BinanceSmartChain ? m.BSC : m.BSC, it = async ({ chain: s, symbol: t }) => { | ||
switch (s) { | ||
case o.Ethereum: | ||
return At(t); | ||
return vt(t); | ||
case o.Avalanche: | ||
return Tt(t); | ||
return Rt(t); | ||
case o.BinanceSmartChain: | ||
return Rt(t); | ||
return St(t); | ||
default: | ||
return m[s]; | ||
} | ||
}, te = { | ||
[H.Average]: 1.2, | ||
[H.Fast]: 1.5, | ||
[H.Fastest]: 2 | ||
}, St = ({ chain: s, symbol: t }) => { | ||
}, ee = { | ||
[D.Average]: 1.2, | ||
[D.Fast]: 1.5, | ||
[D.Fastest]: 2 | ||
}, Ct = ({ chain: s, symbol: t }) => { | ||
switch (s) { | ||
@@ -81,3 +81,3 @@ case o.Bitcoin: | ||
} | ||
}, vt = (s) => { | ||
}, $t = (s) => { | ||
switch (s) { | ||
@@ -111,3 +111,3 @@ case "ETH.THOR": | ||
} | ||
}, Ct = ({ chain: s, symbol: t }) => { | ||
}, It = ({ chain: s, symbol: t }) => { | ||
if (t.includes("/")) | ||
@@ -142,12 +142,12 @@ return "Synth"; | ||
} | ||
}, ee = (s) => { | ||
}, re = (s) => { | ||
var a; | ||
const [t, ...e] = s.split("."), r = s.includes("/"), n = e.join("."), i = (a = n == null ? void 0 : n.split("-")) == null ? void 0 : a[0]; | ||
return { chain: t, symbol: n, ticker: i, synth: r }; | ||
}, $t = new RegExp( | ||
}, Et = new RegExp( | ||
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/, | ||
"gmi" | ||
), re = (s) => s.filter( | ||
(t) => !$t.test(t.toString()) && !t.toString().includes("undefined") | ||
), It = ({ | ||
), se = (s) => s.filter( | ||
(t) => !Et.test(t.toString()) && !t.toString().includes("undefined") | ||
), Ot = ({ | ||
liquidityUnits: s, | ||
@@ -159,3 +159,3 @@ poolUnits: t, | ||
return a.mul(c.sub(u).add(l)).div(h); | ||
}, Et = ({ | ||
}, Vt = ({ | ||
liquidityUnits: s, | ||
@@ -167,3 +167,3 @@ poolUnits: t, | ||
return h.div(_); | ||
}, se = ({ | ||
}, ne = ({ | ||
percent: s, | ||
@@ -173,3 +173,3 @@ runeDepth: t, | ||
poolUnits: r | ||
}) => It({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), ne = ({ | ||
}) => Ot({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), ie = ({ | ||
percent: s, | ||
@@ -179,3 +179,3 @@ assetDepth: t, | ||
poolUnits: r | ||
}) => Et({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), d = (s) => new Qt({ value: s, decimal: m.THOR }), Ot = ({ | ||
}) => Vt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), d = (s) => new Q({ value: s, decimal: m.THOR }), Bt = ({ | ||
liquidityUnits: s, | ||
@@ -188,3 +188,3 @@ poolUnits: t, | ||
runeAmount: d(e).mul(s).div(t) | ||
}), ie = ({ | ||
}), oe = ({ | ||
liquidityUnits: s, | ||
@@ -196,6 +196,6 @@ poolUnits: t, | ||
}) => Object.fromEntries( | ||
Object.entries(Ot({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map( | ||
Object.entries(Bt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map( | ||
([i, a]) => [i, a.mul(n)] | ||
) | ||
), oe = ({ | ||
), ae = ({ | ||
runeDepth: s, | ||
@@ -208,8 +208,8 @@ poolUnits: t, | ||
}) => { | ||
const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i), _ = l.mul(c), T = h.mul(a), P = l.mul(h), dt = a.mul(c), mt = u.mul(_.add(T.add(P.mul(2)))), ft = _.add(T.add(dt.mul(2))), J = mt.div(ft), N = d(r).add(J); | ||
if (J.baseValueNumber === 0) | ||
return N.div(u).baseValueNumber; | ||
const pt = u.add(N); | ||
return N.div(pt).baseValueNumber; | ||
}, ae = ({ | ||
const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i), _ = l.mul(c), T = h.mul(a), H = l.mul(h), ft = a.mul(c), pt = u.mul(_.add(T.add(H.mul(2)))), _t = _.add(T.add(ft.mul(2))), X = pt.div(_t), j = d(r).add(X); | ||
if (X.baseValueNumber === 0) | ||
return j.div(u).baseValueNumber; | ||
const gt = u.add(j); | ||
return j.div(gt).baseValueNumber; | ||
}, ce = ({ | ||
runeAmount: s, | ||
@@ -226,3 +226,3 @@ assetAmount: t, | ||
chain: e | ||
}) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, ce = (s, t) => { | ||
}) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, ue = (s, t) => { | ||
switch (s) { | ||
@@ -258,7 +258,7 @@ case g.LEAVE: | ||
} | ||
}, ue = (s) => { | ||
}, le = (s) => { | ||
if (s < 0) | ||
throw new Error("Invalid number of year"); | ||
return 10 + s; | ||
}, le = (s) => { | ||
}, he = (s) => { | ||
if (s.length > 30) | ||
@@ -268,4 +268,4 @@ return !1; | ||
return !!s.match(t); | ||
}, he = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`; | ||
class K extends Error { | ||
}, de = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`; | ||
class Z extends Error { | ||
constructor(t, e, r) { | ||
@@ -291,3 +291,3 @@ const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", a = `${n} ${i}`.trim(), c = a ? `status code ${a}` : "an unknown error"; | ||
} | ||
class nt extends Error { | ||
class ot extends Error { | ||
constructor(t) { | ||
@@ -302,8 +302,8 @@ super("Request timed out"), Object.defineProperty(this, "request", { | ||
} | ||
const V = (s) => s !== null && typeof s == "object", B = (...s) => { | ||
const B = (s) => s !== null && typeof s == "object", V = (...s) => { | ||
for (const t of s) | ||
if ((!V(t) || Array.isArray(t)) && t !== void 0) | ||
if ((!B(t) || Array.isArray(t)) && t !== void 0) | ||
throw new TypeError("The `options` argument must be an object"); | ||
return z({}, ...s); | ||
}, it = (s = {}, t = {}) => { | ||
return K({}, ...s); | ||
}, at = (s = {}, t = {}) => { | ||
const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t); | ||
@@ -313,3 +313,3 @@ for (const [i, a] of n.entries()) | ||
return e; | ||
}, z = (...s) => { | ||
}, K = (...s) => { | ||
let t = {}, e = {}; | ||
@@ -319,9 +319,9 @@ for (const r of s) | ||
Array.isArray(t) || (t = []), t = [...t, ...r]; | ||
else if (V(r)) { | ||
else if (B(r)) { | ||
for (let [n, i] of Object.entries(r)) | ||
V(i) && n in t && (i = z(t[n], i)), t = { ...t, [n]: i }; | ||
V(r.headers) && (e = it(e, r.headers), t.headers = e); | ||
B(i) && n in t && (i = K(t[n], i)), t = { ...t, [n]: i }; | ||
B(r.headers) && (e = at(e, r.headers), t.headers = e); | ||
} | ||
return t; | ||
}, Bt = (() => { | ||
}, qt = (() => { | ||
let s = !1, t = !1; | ||
@@ -337,3 +337,3 @@ const e = typeof globalThis.ReadableStream == "function", r = typeof globalThis.Request == "function"; | ||
}).headers.has("Content-Type")), s && !t; | ||
})(), Vt = typeof globalThis.AbortController == "function", qt = typeof globalThis.ReadableStream == "function", Mt = typeof globalThis.FormData == "function", ot = ["get", "post", "put", "patch", "head", "delete"], xt = { | ||
})(), Mt = typeof globalThis.AbortController == "function", xt = typeof globalThis.ReadableStream == "function", Pt = typeof globalThis.FormData == "function", ct = ["get", "post", "put", "patch", "head", "delete"], Nt = { | ||
json: "application/json", | ||
@@ -344,3 +344,3 @@ text: "text/*", | ||
blob: "*/*" | ||
}, j = 2147483647, at = Symbol("stop"), Pt = { | ||
}, L = 2147483647, ut = Symbol("stop"), Ht = { | ||
json: !0, | ||
@@ -356,3 +356,3 @@ parseJson: !0, | ||
fetch: !0 | ||
}, Nt = { | ||
}, jt = { | ||
method: !0, | ||
@@ -373,14 +373,14 @@ headers: !0, | ||
duplex: !0 | ||
}, Ht = (s) => ot.includes(s) ? s.toUpperCase() : s, jt = ["get", "put", "head", "delete", "options", "trace"], Lt = [408, 413, 429, 500, 502, 503, 504], ct = [413, 429, 503], Q = { | ||
}, Dt = (s) => ct.includes(s) ? s.toUpperCase() : s, Lt = ["get", "put", "head", "delete", "options", "trace"], Ut = [408, 413, 429, 500, 502, 503, 504], lt = [413, 429, 503], tt = { | ||
limit: 2, | ||
methods: jt, | ||
statusCodes: Lt, | ||
afterStatusCodes: ct, | ||
methods: Lt, | ||
statusCodes: Ut, | ||
afterStatusCodes: lt, | ||
maxRetryAfter: Number.POSITIVE_INFINITY, | ||
backoffLimit: Number.POSITIVE_INFINITY, | ||
delay: (s) => 0.3 * 2 ** (s - 1) * 1e3 | ||
}, Dt = (s = {}) => { | ||
}, Ft = (s = {}) => { | ||
if (typeof s == "number") | ||
return { | ||
...Q, | ||
...tt, | ||
limit: s | ||
@@ -393,11 +393,11 @@ }; | ||
return { | ||
...Q, | ||
...tt, | ||
...s, | ||
afterStatusCodes: ct | ||
afterStatusCodes: lt | ||
}; | ||
}; | ||
async function Ut(s, t, e, r) { | ||
async function Wt(s, t, e, r) { | ||
return new Promise((n, i) => { | ||
const a = setTimeout(() => { | ||
e && e.abort(), i(new nt(s)); | ||
e && e.abort(), i(new ot(s)); | ||
}, r.timeout); | ||
@@ -409,3 +409,3 @@ r.fetch(s, t).then(n).catch(i).then(() => { | ||
} | ||
async function Ft(s, { signal: t }) { | ||
async function Gt(s, { signal: t }) { | ||
return new Promise((e, r) => { | ||
@@ -421,6 +421,6 @@ t && (t.throwIfAborted(), t.addEventListener("abort", n, { once: !0 })); | ||
} | ||
const Wt = (s, t) => { | ||
const Yt = (s, t) => { | ||
const e = {}; | ||
for (const r in t) | ||
!(r in Nt) && !(r in Pt) && !(r in s) && (e[r] = t[r]); | ||
!(r in jt) && !(r in Ht) && !(r in s) && (e[r] = t[r]); | ||
return e; | ||
@@ -431,4 +431,4 @@ }; | ||
const r = new q(t, e), n = async () => { | ||
if (typeof r._options.timeout == "number" && r._options.timeout > j) | ||
throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`); | ||
if (typeof r._options.timeout == "number" && r._options.timeout > L) | ||
throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`); | ||
await Promise.resolve(); | ||
@@ -441,3 +441,3 @@ let c = await r._fetch(); | ||
if (r._decorateResponse(c), !c.ok && r._options.throwHttpErrors) { | ||
let u = new K(c, r.request, r._options); | ||
let u = new Z(c, r.request, r._options); | ||
for (const l of r._options.hooks.beforeError) | ||
@@ -450,3 +450,3 @@ u = await l(u); | ||
throw new TypeError("The `onDownloadProgress` option must be a function"); | ||
if (!qt) | ||
if (!xt) | ||
throw new Error("Streams are not supported in your environment. `ReadableStream` is missing."); | ||
@@ -457,3 +457,3 @@ return r._stream(c.clone(), r._options.onDownloadProgress); | ||
}, a = r._options.retry.methods.includes(r.request.method.toLowerCase()) ? r._retry(n) : n(); | ||
for (const [c, u] of Object.entries(xt)) | ||
for (const [c, u] of Object.entries(Nt)) | ||
a[c] = async () => { | ||
@@ -503,4 +503,4 @@ r.request.headers.set("accept", r.request.headers.get("accept") || u); | ||
...e, | ||
headers: it(this._input.headers, e.headers), | ||
hooks: z({ | ||
headers: at(this._input.headers, e.headers), | ||
hooks: K({ | ||
beforeRequest: [], | ||
@@ -511,6 +511,6 @@ beforeRetry: [], | ||
}, e.hooks), | ||
method: Ht(e.method ?? this._input.method), | ||
method: Dt(e.method ?? this._input.method), | ||
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing | ||
prefixUrl: String(e.prefixUrl || ""), | ||
retry: Dt(e.retry), | ||
retry: Ft(e.retry), | ||
throwHttpErrors: e.throwHttpErrors !== !1, | ||
@@ -526,3 +526,3 @@ timeout: e.timeout ?? 1e4, | ||
} | ||
if (Vt) { | ||
if (Mt) { | ||
if (this.abortController = new globalThis.AbortController(), this._options.signal) { | ||
@@ -536,5 +536,5 @@ const r = this._options.signal; | ||
} | ||
if (Bt && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) { | ||
if (qt && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) { | ||
const n = "?" + (typeof this._options.searchParams == "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString()), i = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, n); | ||
(Mt && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"]) && this.request.headers.delete("content-type"), this.request = new globalThis.Request(new globalThis.Request(i, { ...this.request }), this._options); | ||
(Pt && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"]) && this.request.headers.delete("content-type"), this.request = new globalThis.Request(new globalThis.Request(i, { ...this.request }), this._options); | ||
} | ||
@@ -544,4 +544,4 @@ this._options.json !== void 0 && (this._options.body = JSON.stringify(this._options.json), this.request.headers.set("content-type", this._options.headers.get("content-type") ?? "application/json"), this.request = new globalThis.Request(this.request, { body: this._options.body })); | ||
_calculateRetryDelay(t) { | ||
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof nt)) { | ||
if (t instanceof K) { | ||
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof ot)) { | ||
if (t instanceof Z) { | ||
if (!this._options.retry.statusCodes.includes(t.response.status)) | ||
@@ -569,5 +569,5 @@ return 0; | ||
} catch (e) { | ||
const r = Math.min(this._calculateRetryDelay(e), j); | ||
const r = Math.min(this._calculateRetryDelay(e), L); | ||
if (r !== 0 && this._retryCount > 0) { | ||
await Ft(r, { signal: this._options.signal }); | ||
await Gt(r, { signal: this._options.signal }); | ||
for (const n of this._options.hooks.beforeRetry) | ||
@@ -579,3 +579,3 @@ if (await n({ | ||
retryCount: this._retryCount | ||
}) === at) | ||
}) === ut) | ||
return; | ||
@@ -597,4 +597,4 @@ return this._retry(t); | ||
} | ||
const t = Wt(this.request, this._options); | ||
return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Ut(this.request.clone(), t, this.abortController, this._options); | ||
const t = Yt(this.request, this._options); | ||
return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Wt(this.request.clone(), t, this.abortController, this._options); | ||
} | ||
@@ -636,8 +636,8 @@ /* istanbul ignore next */ | ||
/*! MIT License © Sindre Sorhus */ | ||
const U = (s) => { | ||
const t = (e, r) => q.create(e, B(s, r)); | ||
for (const e of ot) | ||
t[e] = (r, n) => q.create(r, B(s, n, { method: e })); | ||
return t.create = (e) => U(B(e)), t.extend = (e) => U(B(s, e)), t.stop = at, t; | ||
}, Gt = U(), Yt = Gt, X = Yt.create({ | ||
const W = (s) => { | ||
const t = (e, r) => q.create(e, V(s, r)); | ||
for (const e of ct) | ||
t[e] = (r, n) => q.create(r, V(s, n, { method: e })); | ||
return t.create = (e) => W(V(e)), t.extend = (e) => W(V(s, e)), t.stop = ut, t; | ||
}, zt = W(), Jt = zt, et = Jt.create({ | ||
headers: { | ||
@@ -648,11 +648,11 @@ referrer: "https://sk.thorswap.net", | ||
} | ||
}), zt = { | ||
get: (s, t) => X.get(s, t).json(), | ||
post: (s, t) => X.post(s, t).json() | ||
}, Z = Object.values(o), Jt = (s = "") => { | ||
}), Kt = { | ||
get: (s, t) => et.get(s, t).json(), | ||
post: (s, t) => et.post(s, t).json() | ||
}, rt = Object.values(o), Qt = (s = "") => { | ||
const t = s.toUpperCase(), [e] = t.split("."); | ||
if (Z.includes(e)) | ||
if (rt.includes(e)) | ||
return !0; | ||
const [r] = t.split("/"); | ||
if (Z.includes(r)) | ||
if (rt.includes(r)) | ||
return !0; | ||
@@ -662,4 +662,4 @@ throw new Error( | ||
); | ||
}, $ = 8, R = (s) => 10n ** BigInt(s), S = (s) => Math.log10(parseFloat(s.toString())); | ||
function tt({ | ||
}, $ = 8, v = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString())); | ||
function M({ | ||
value: s, | ||
@@ -680,23 +680,23 @@ bigIntDecimal: t = $, | ||
} | ||
var w, v, M, ut, x, lt, O, F, A, C, k, W; | ||
const I = class I { | ||
var w, S, x, ht, P, dt, E, G, A, C, O, Y; | ||
const N = class N { | ||
constructor(t) { | ||
y(this, w); | ||
y(this, M); | ||
y(this, x); | ||
y(this, P); | ||
y(this, E); | ||
y(this, A); | ||
y(this, O); | ||
y(this, A); | ||
y(this, k); | ||
p(this, "decimalMultiplier", 10n ** 8n); | ||
p(this, "bigIntValue", 0n); | ||
p(this, "decimal"); | ||
const e = L(t); | ||
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = R( | ||
Math.max(f(this, k, W).call(this, f(this, A, C).call(this, e)), this.decimal || 0) | ||
), f(this, M, ut).call(this, e); | ||
const e = U(t); | ||
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v( | ||
Math.max(f(this, O, Y).call(this, f(this, A, C).call(this, e)), this.decimal || 0) | ||
), f(this, x, ht).call(this, e); | ||
} | ||
static fromBigInt(t, e) { | ||
return new I({ | ||
return new N({ | ||
decimal: e, | ||
value: tt({ value: t, bigIntDecimal: e, decimal: e }) | ||
value: M({ value: t, bigIntDecimal: e, decimal: e }) | ||
}); | ||
@@ -709,4 +709,4 @@ } | ||
}) { | ||
return I.fromBigInt( | ||
new I(t).bigIntValue * R(r) / R(e), | ||
return this.fromBigInt( | ||
new N(t).bigIntValue * v(r) / v(e), | ||
r | ||
@@ -737,12 +737,12 @@ ); | ||
add(...t) { | ||
return f(this, w, v).call(this, "add", ...t); | ||
return f(this, w, S).call(this, "add", ...t); | ||
} | ||
sub(...t) { | ||
return f(this, w, v).call(this, "sub", ...t); | ||
return f(this, w, S).call(this, "sub", ...t); | ||
} | ||
mul(...t) { | ||
return f(this, w, v).call(this, "mul", ...t); | ||
return f(this, w, S).call(this, "mul", ...t); | ||
} | ||
div(...t) { | ||
return f(this, w, v).call(this, "div", ...t); | ||
return f(this, w, S).call(this, "div", ...t); | ||
} | ||
@@ -767,3 +767,3 @@ gt(t) { | ||
this.bigIntValue, | ||
this.decimal || S(this.decimalMultiplier) | ||
this.decimal || R(this.decimalMultiplier) | ||
); | ||
@@ -780,3 +780,3 @@ switch (t) { | ||
getBaseValue(t) { | ||
const e = this.decimalMultiplier / R(this.decimal || m.THOR), r = this.bigIntValue / e; | ||
const e = this.decimalMultiplier / v(this.decimal || m.THOR), r = this.bigIntValue / e; | ||
switch (t) { | ||
@@ -794,4 +794,4 @@ case "number": | ||
return t.bigIntValue; | ||
const r = L(t), n = f(this, A, C).call(this, r); | ||
return n === "0" || n === "undefined" ? 0n : f(this, O, F).call(this, n, e); | ||
const r = U(t), n = f(this, A, C).call(this, r); | ||
return n === "0" || n === "undefined" ? 0n : f(this, E, G).call(this, n, e); | ||
} | ||
@@ -801,3 +801,3 @@ formatBigIntToSafeValue(t, e) { | ||
r, | ||
S(this.decimalMultiplier) | ||
R(this.decimalMultiplier) | ||
), i = t < 0n, a = t.toString().substring(i ? 1 : 0), c = n - (a.length - 1), u = c > 0 ? "0".repeat(c) + a : a, l = u.length - n; | ||
@@ -838,4 +838,4 @@ let h = u.slice(-n); | ||
}; | ||
w = new WeakSet(), v = function(t, ...e) { | ||
const r = f(this, x, lt).call(this, this, ...e), n = R(r), i = e.reduce( | ||
w = new WeakSet(), S = function(t, ...e) { | ||
const r = f(this, P, dt).call(this, this, ...e), n = v(r), i = e.reduce( | ||
(c, u) => { | ||
@@ -861,18 +861,18 @@ const l = this.getBigIntValue(u, r); | ||
this.bigIntValue * n / this.decimalMultiplier | ||
), a = tt({ | ||
), a = M({ | ||
bigIntDecimal: r, | ||
decimal: Math.max(r, S(this.decimalMultiplier)), | ||
decimal: Math.max(r, R(this.decimalMultiplier)), | ||
value: i | ||
}); | ||
return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() }); | ||
}, M = new WeakSet(), ut = function(t) { | ||
}, x = new WeakSet(), ht = function(t) { | ||
const e = f(this, A, C).call(this, t) || "0"; | ||
this.bigIntValue = f(this, O, F).call(this, e); | ||
}, x = new WeakSet(), lt = function(...t) { | ||
this.bigIntValue = f(this, E, G).call(this, e); | ||
}, P = new WeakSet(), dt = function(...t) { | ||
const e = t.map( | ||
(r) => typeof r == "object" ? r.decimal || S(r.decimalMultiplier) : f(this, k, W).call(this, f(this, A, C).call(this, r)) | ||
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O, Y).call(this, f(this, A, C).call(this, r)) | ||
).filter(Boolean); | ||
return Math.max(...e, $); | ||
}, O = new WeakSet(), F = function(t, e) { | ||
const r = e ? R(e) : this.decimalMultiplier, n = S(r), [i = "", a = ""] = t.split("."); | ||
}, E = new WeakSet(), G = function(t, e) { | ||
const r = e ? v(e) : this.decimalMultiplier, n = R(r), [i = "", a = ""] = t.split("."); | ||
return BigInt(`${i}${a.padEnd(n, "0")}`); | ||
@@ -883,5 +883,5 @@ }, A = new WeakSet(), C = function(t) { | ||
maximumFractionDigits: 20 | ||
}) : L(t)}`.replaceAll(",", ".").split("."); | ||
}) : U(t)}`.replaceAll(",", ".").split("."); | ||
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0]; | ||
}, k = new WeakSet(), W = function(t) { | ||
}, O = new WeakSet(), Y = function(t) { | ||
var r; | ||
@@ -891,20 +891,21 @@ const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0; | ||
}; | ||
let E = I; | ||
function L(s) { | ||
let I = N; | ||
function U(s) { | ||
return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s; | ||
} | ||
let G; | ||
const D = (s) => { | ||
if (!G) | ||
const k = (s, t) => typeof s == "bigint" ? M({ value: s, bigIntDecimal: t, decimal: t }) : s; | ||
let z; | ||
const F = (s) => { | ||
if (!z) | ||
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first"); | ||
return G.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" }; | ||
}, et = async (s, t = 0) => { | ||
Jt(s); | ||
const e = await st(Y(s)); | ||
return new b({ decimal: e, value: t, identifier: s }); | ||
return z.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" }; | ||
}, st = async (s, t = 0) => { | ||
Qt(s); | ||
const e = await it(J(s)), r = k(t, e); | ||
return new b({ decimal: e, value: r, identifier: s }); | ||
}; | ||
class b extends E { | ||
class b extends I { | ||
constructor(e) { | ||
super( | ||
e.value instanceof E ? e.value : { decimal: e.decimal, value: e.value } | ||
e.value instanceof I ? e.value : { decimal: e.decimal, value: e.value } | ||
); | ||
@@ -918,4 +919,4 @@ p(this, "address"); | ||
p(this, "type"); | ||
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = Y(r); | ||
this.type = Ct(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset; | ||
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = J(r); | ||
this.type = It(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset; | ||
} | ||
@@ -936,27 +937,27 @@ get assetValue() { | ||
static async fromString(e, r = 0) { | ||
return et(e, r); | ||
return st(e, r); | ||
} | ||
static fromStringSync(e, r = 0) { | ||
const { decimal: n, identifier: i } = D( | ||
const { decimal: n, identifier: i } = F( | ||
e | ||
); | ||
return i ? new b({ decimal: n, identifier: i, value: r }) : void 0; | ||
), a = k(r, n); | ||
return i ? new b({ decimal: n, identifier: i, value: a }) : void 0; | ||
} | ||
static async fromIdentifier(e, r = 0) { | ||
return et(e, r); | ||
return st(e, r); | ||
} | ||
static fromIdentifierSync(e, r = 0) { | ||
const { decimal: n, identifier: i } = D(e); | ||
return new b({ decimal: n, identifier: i, value: r }); | ||
const { decimal: n, identifier: i } = F(e), a = k(r, n); | ||
return new b({ decimal: n, identifier: i, value: a }); | ||
} | ||
static fromChainOrSignature(e, r = 0) { | ||
const { decimal: n, identifier: i } = vt(e); | ||
return new b({ value: r, decimal: n, identifier: i }); | ||
const { decimal: n, identifier: i } = $t(e), a = k(r, n); | ||
return new b({ value: a, decimal: n, identifier: i }); | ||
} | ||
static async fromTCQuote(e, r = 0) { | ||
const n = await st(Y(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n }); | ||
const n = await it(J(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n }); | ||
return new b({ value: i, identifier: e, decimal: n }); | ||
} | ||
static fromTCQuoteStatic(e, r = 0) { | ||
const n = D(e), i = this.shiftDecimals({ | ||
const n = F(e), i = this.shiftDecimals({ | ||
value: r, | ||
@@ -979,6 +980,6 @@ from: m.THOR, | ||
} = await import("@swapkit/tokens"); | ||
G = [i, ...Object.values(a)].reduce( | ||
z = [i, ...Object.values(a)].reduce( | ||
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...T }) => { | ||
const P = "decimals" in T ? T.decimals : m[_]; | ||
u.set(h, { identifier: h, decimal: P }); | ||
const H = "decimals" in T ? T.decimals : m[_]; | ||
u.set(h, { identifier: h, decimal: H }); | ||
}), u), | ||
@@ -998,3 +999,3 @@ /* @__PURE__ */ new Map() | ||
} | ||
const de = (s) => { | ||
const me = (s) => { | ||
const t = b.fromChainOrSignature(s); | ||
@@ -1017,3 +1018,3 @@ switch (s) { | ||
} | ||
}, Y = (s) => { | ||
}, J = (s) => { | ||
const t = s.slice(0, 14).includes("/"), e = s.includes(".") ? s : `${o.THORChain}.${s}`, [r, n] = e.split("."), [i, a] = n.split("-"); | ||
@@ -1023,3 +1024,3 @@ return { | ||
chain: r, | ||
isGasAsset: St({ chain: r, symbol: n }), | ||
isGasAsset: Ct({ chain: r, symbol: n }), | ||
isSynthetic: t, | ||
@@ -1029,3 +1030,3 @@ symbol: a ? `${i}-${(a == null ? void 0 : a.toLowerCase()) ?? ""}` : n, | ||
}; | ||
}, Kt = { | ||
}, Xt = { | ||
/** | ||
@@ -1087,39 +1088,45 @@ * Core | ||
}; | ||
class ht extends Error { | ||
class mt extends Error { | ||
constructor(t, e) { | ||
console.error(e), super(t, { cause: { code: Kt[t], message: t } }), Object.setPrototypeOf(this, ht.prototype); | ||
console.error(e), super(t, { cause: { code: Xt[t], message: t } }), Object.setPrototypeOf(this, mt.prototype); | ||
} | ||
} | ||
class Qt extends E { | ||
class Q extends I { | ||
eq(t) { | ||
return this.eqValue(t); | ||
} | ||
static fromBigInt(t, e) { | ||
return new Q({ | ||
decimal: e, | ||
value: M({ value: t, bigIntDecimal: e, decimal: e }) | ||
}); | ||
} | ||
} | ||
export { | ||
b as AssetValue, | ||
E as BigIntArithmetics, | ||
zt as RequestClient, | ||
ht as SwapKitError, | ||
Qt as SwapKitNumber, | ||
ee as assetFromString, | ||
he as derivationPathToString, | ||
re as filterAssets, | ||
tt as formatBigIntToSafeValue, | ||
te as gasFeeMultiplier, | ||
Ct as getAssetType, | ||
Et as getAsymmetricAssetShare, | ||
ne as getAsymmetricAssetWithdrawAmount, | ||
It as getAsymmetricRuneShare, | ||
se as getAsymmetricRuneWithdrawAmount, | ||
vt as getCommonAssetInfo, | ||
st as getDecimal, | ||
oe as getEstimatedPoolShare, | ||
ae as getLiquiditySlippage, | ||
ce as getMemoFor, | ||
de as getMinAmountByChain, | ||
Ot as getSymmetricPoolShare, | ||
ie as getSymmetricWithdraw, | ||
ue as getTHORNameCost, | ||
St as isGasAsset, | ||
le as validateTHORName | ||
I as BigIntArithmetics, | ||
Kt as RequestClient, | ||
mt as SwapKitError, | ||
Q as SwapKitNumber, | ||
re as assetFromString, | ||
de as derivationPathToString, | ||
se as filterAssets, | ||
M as formatBigIntToSafeValue, | ||
ee as gasFeeMultiplier, | ||
It as getAssetType, | ||
Vt as getAsymmetricAssetShare, | ||
ie as getAsymmetricAssetWithdrawAmount, | ||
Ot as getAsymmetricRuneShare, | ||
ne as getAsymmetricRuneWithdrawAmount, | ||
$t as getCommonAssetInfo, | ||
it as getDecimal, | ||
ae as getEstimatedPoolShare, | ||
ce as getLiquiditySlippage, | ||
ue as getMemoFor, | ||
me as getMinAmountByChain, | ||
Bt as getSymmetricPoolShare, | ||
oe as getSymmetricWithdraw, | ||
le as getTHORNameCost, | ||
Ct as isGasAsset, | ||
he as validateTHORName | ||
}; |
@@ -45,3 +45,3 @@ { | ||
"types": "./dist/index.d.ts", | ||
"version": "1.0.0-rc.10", | ||
"version": "1.0.0-rc.11", | ||
"scripts": { | ||
@@ -48,0 +48,0 @@ "build": "vite build", |
@@ -80,2 +80,12 @@ import { BaseDecimal, Chain } from '@swapkit/types'; | ||
describe('from bigint', () => { | ||
test('returns asset value with correct decimal', async () => { | ||
const avaxUSDCAsset = await AssetValue.fromIdentifier( | ||
`${Chain.Avalanche}.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e`, | ||
1234567800n, | ||
); | ||
expect(avaxUSDCAsset.getValue('string')).toBe('1234.5678'); | ||
}); | ||
}); | ||
describe('toString', () => { | ||
@@ -82,0 +92,0 @@ test('returns asset value string/identifier', async () => { |
@@ -20,5 +20,11 @@ import type { | ||
import { BigIntArithmetics } from './bigIntArithmetics.ts'; | ||
import type { NumberPrimitives } from './bigIntArithmetics.ts'; | ||
import { BigIntArithmetics, formatBigIntToSafeValue } from './bigIntArithmetics.ts'; | ||
import type { SwapKitValueType } from './swapKitNumber.ts'; | ||
const safeValue = (value: NumberPrimitives, decimal: number) => | ||
typeof value === 'bigint' | ||
? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) | ||
: value; | ||
type AssetValueParams = { decimal: number; value: SwapKitValueType } & ( | ||
@@ -55,7 +61,9 @@ | { chain: Chain; symbol: string } | ||
const createAssetValue = async (assetString: string, value: number | string = 0) => { | ||
const createAssetValue = async (assetString: string, value: NumberPrimitives = 0) => { | ||
validateIdentifier(assetString); | ||
const decimal = await getDecimal(getAssetInfo(assetString)); | ||
return new AssetValue({ decimal, value, identifier: assetString }); | ||
const parsedValue = safeValue(value, decimal); | ||
return new AssetValue({ decimal, value: parsedValue, identifier: assetString }); | ||
}; | ||
@@ -110,7 +118,7 @@ | ||
static async fromString(assetString: string, value: number | string = 0) { | ||
static async fromString(assetString: string, value: NumberPrimitives = 0) { | ||
return createAssetValue(assetString, value); | ||
} | ||
static fromStringSync(assetString: string, value: number | string = 0) { | ||
static fromStringSync(assetString: string, value: NumberPrimitives = 0) { | ||
const { decimal, identifier: tokenIdentifier } = getStaticToken( | ||
@@ -120,4 +128,6 @@ assetString as unknown as TokenNames, | ||
const parsedValue = safeValue(value, decimal); | ||
return tokenIdentifier | ||
? new AssetValue({ decimal, identifier: tokenIdentifier, value }) | ||
? new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue }) | ||
: undefined; | ||
@@ -128,3 +138,3 @@ } | ||
assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, | ||
value: number | string = 0, | ||
value: NumberPrimitives = 0, | ||
) { | ||
@@ -134,15 +144,17 @@ return createAssetValue(assetString, value); | ||
static fromIdentifierSync(identifier: TokenNames, value: number | string = 0) { | ||
static fromIdentifierSync(identifier: TokenNames, value: NumberPrimitives = 0) { | ||
const { decimal, identifier: tokenIdentifier } = getStaticToken(identifier); | ||
const parsedValue = safeValue(value, decimal); | ||
return new AssetValue({ decimal, identifier: tokenIdentifier, value }); | ||
return new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue }); | ||
} | ||
static fromChainOrSignature(assetString: CommonAssetString, value: number | string = 0) { | ||
static fromChainOrSignature(assetString: CommonAssetString, value: NumberPrimitives = 0) { | ||
const { decimal, identifier } = getCommonAssetInfo(assetString); | ||
const parsedValue = safeValue(value, decimal); | ||
return new AssetValue({ value, decimal, identifier }); | ||
return new AssetValue({ value: parsedValue, decimal, identifier }); | ||
} | ||
static async fromTCQuote(identifier: TCTokenNames, value: number | string = 0) { | ||
static async fromTCQuote(identifier: TCTokenNames, value: NumberPrimitives = 0) { | ||
const decimal = await getDecimal(getAssetInfo(identifier)); | ||
@@ -154,3 +166,3 @@ const shiftedValue = this.shiftDecimals({ value, from: BaseDecimal.THOR, to: decimal }); | ||
static fromTCQuoteStatic(identifier: TCTokenNames, value: number | string = 0) { | ||
static fromTCQuoteStatic(identifier: TCTokenNames, value: NumberPrimitives = 0) { | ||
const tokenInfo = getStaticToken(identifier); | ||
@@ -157,0 +169,0 @@ const shiftedValue = this.shiftDecimals({ |
@@ -10,3 +10,3 @@ import { BaseDecimal } from '@swapkit/types'; | ||
}; | ||
type NumberPrimitives = bigint | number | string; | ||
export type NumberPrimitives = bigint | number | string; | ||
type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber; | ||
@@ -79,3 +79,3 @@ | ||
}) { | ||
return BigIntArithmetics.fromBigInt( | ||
return this.fromBigInt( | ||
(new BigIntArithmetics(value).bigIntValue * toMultiplier(to)) / toMultiplier(from), | ||
@@ -82,0 +82,0 @@ to, |
@@ -1,2 +0,2 @@ | ||
import { BigIntArithmetics } from './bigIntArithmetics.ts'; | ||
import { BigIntArithmetics, formatBigIntToSafeValue } from './bigIntArithmetics.ts'; | ||
@@ -9,2 +9,9 @@ export type SwapKitValueType = BigIntArithmetics | string | number; | ||
} | ||
static fromBigInt(value: bigint, decimal?: number) { | ||
return new SwapKitNumber({ | ||
decimal, | ||
value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }), | ||
}); | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
189996
3507