@swapkit/helpers
Advanced tools
Comparing version 1.0.0-rc.8 to 1.0.0-rc.9
@@ -6,2 +6,3 @@ import { Chain } from '@swapkit/types'; | ||
import { MemoType } from '@swapkit/types'; | ||
import type { Options } from 'ky'; | ||
import type { PancakeswapETHList } from '@swapkit/tokens'; | ||
@@ -235,6 +236,2 @@ import type { PancakeswapList } from '@swapkit/tokens'; | ||
export declare const getRequest: <T>(url: string, params?: { | ||
[x: string]: any; | ||
} | undefined) => Promise<T>; | ||
export declare const getSymmetricPoolShare: ({ liquidityUnits, poolUnits, runeDepth, assetDepth, }: ShareParams<{ | ||
@@ -311,3 +308,6 @@ runeDepth: string; | ||
export declare const postRequest: <T>(url: string, body: string, headers?: Record<string, string>, parseAsString?: boolean) => Promise<T>; | ||
export declare const RequestClient: { | ||
get: <T>(url: string | URL | Request, options?: Options) => Promise<T>; | ||
post: <T_1>(url: string | URL | Request, options?: Options) => Promise<T_1>; | ||
}; | ||
@@ -314,0 +314,0 @@ declare type ShareParams<T = {}> = T & { |
1084
dist/index.es.js
@@ -1,116 +0,80 @@ | ||
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 _ = (n, t, e) => (rt(n, typeof t != "symbol" ? t + "" : t, e), e), st = (n, t, e) => { | ||
if (!t.has(n)) | ||
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) => { | ||
if (!t.has(s)) | ||
throw TypeError("Cannot " + e); | ||
}; | ||
var $ = (n, t, e) => { | ||
if (t.has(n)) | ||
var y = (s, t, e) => { | ||
if (t.has(s)) | ||
throw TypeError("Cannot add the same private member more than once"); | ||
t instanceof WeakSet ? t.add(n) : t.set(n, e); | ||
t instanceof WeakSet ? t.add(s) : t.set(s, e); | ||
}; | ||
var g = (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 vt = (n) => { | ||
if (n < 0) | ||
throw new Error("Invalid number of year"); | ||
return 10 + n; | ||
}, Ct = (n) => { | ||
if (n.length > 30) | ||
return !1; | ||
const t = /^[a-zA-Z0-9+_-]+$/g; | ||
return !!n.match(t); | ||
}, Vt = ([n, t, e, r, s]) => `${n}'/${t}'/${e}'/${r}${typeof s != "number" ? "" : `/${s}`}`, Tt = async (n, t) => { | ||
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 }) => { | ||
try { | ||
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" | ||
const { result: e } = await zt.post(yt[s], { | ||
headers: { accept: "*/*", "cache-control": "no-cache" }, | ||
body: JSON.stringify({ | ||
id: 44, | ||
jsonrpc: "2.0", | ||
method: "eth_call", | ||
params: [{ to: t.toLowerCase(), data: wt }, "latest"] | ||
}) | ||
}); | ||
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: ct }, "latest"], | ||
id: 44, | ||
jsonrpc: "2.0" | ||
}), | ||
{ accept: "*/*", "cache-control": "no-cache", "content-type": "application/json" }, | ||
!0 | ||
), { result: r } = JSON.parse(e); | ||
return parseInt(BigInt(r).toString()); | ||
return parseInt(BigInt(e).toString()); | ||
} catch (e) { | ||
return console.error(e), m[n]; | ||
return console.error(e), m[s]; | ||
} | ||
}, ot = async (n) => { | ||
if (n === i.Ethereum) | ||
}, At = async (s) => { | ||
if (s === o.Ethereum) | ||
return m.ETH; | ||
const [, t] = n.split("-"); | ||
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") ? 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.BinanceSmartChain: | ||
return lt(t); | ||
const [, t] = s.split("-"); | ||
return t != null && t.startsWith("0x") ? rt({ chain: o.Ethereum, to: t }) : m.ETH; | ||
}, Tt = 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 }) => { | ||
switch (s) { | ||
case o.Ethereum: | ||
return At(t); | ||
case o.Avalanche: | ||
return Tt(t); | ||
case o.BinanceSmartChain: | ||
return Rt(t); | ||
default: | ||
return m[n]; | ||
return m[s]; | ||
} | ||
}, Bt = { | ||
}, te = { | ||
[H.Average]: 1.2, | ||
[H.Fast]: 1.5, | ||
[H.Fastest]: 2 | ||
}, dt = ({ chain: n, symbol: t }) => { | ||
switch (n) { | ||
case i.Bitcoin: | ||
case i.BitcoinCash: | ||
case i.Litecoin: | ||
case i.Dogecoin: | ||
case i.Binance: | ||
case i.Ethereum: | ||
case i.Avalanche: | ||
return t === n; | ||
case i.Arbitrum: | ||
case i.Optimism: | ||
}, St = ({ chain: s, symbol: t }) => { | ||
switch (s) { | ||
case o.Bitcoin: | ||
case o.BitcoinCash: | ||
case o.Litecoin: | ||
case o.Dogecoin: | ||
case o.Binance: | ||
case o.Ethereum: | ||
case o.Avalanche: | ||
return t === s; | ||
case o.Arbitrum: | ||
case o.Optimism: | ||
return t === "ETH"; | ||
case i.Maya: | ||
case o.Maya: | ||
return t === "CACAO"; | ||
case i.Kujira: | ||
case o.Kujira: | ||
return t === "KUJI"; | ||
case i.Cosmos: | ||
case o.Cosmos: | ||
return t === "ATOM"; | ||
case i.Polygon: | ||
case o.Polygon: | ||
return t === "MATIC"; | ||
case i.BinanceSmartChain: | ||
case o.BinanceSmartChain: | ||
return t === "BNB"; | ||
case i.THORChain: | ||
case o.THORChain: | ||
return t === "RUNE"; | ||
} | ||
}, ht = (n) => { | ||
switch (n) { | ||
}, vt = (s) => { | ||
switch (s) { | ||
case "ETH.THOR": | ||
@@ -120,90 +84,90 @@ return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 }; | ||
return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 }; | ||
case i.Cosmos: | ||
return { identifier: "GAIA.ATOM", decimal: m[n] }; | ||
case i.THORChain: | ||
return { identifier: "THOR.RUNE", decimal: m[n] }; | ||
case i.BinanceSmartChain: | ||
return { identifier: "BSC.BNB", decimal: m[n] }; | ||
case i.Maya: | ||
case o.Cosmos: | ||
return { identifier: "GAIA.ATOM", decimal: m[s] }; | ||
case o.THORChain: | ||
return { identifier: "THOR.RUNE", decimal: m[s] }; | ||
case o.BinanceSmartChain: | ||
return { identifier: "BSC.BNB", decimal: m[s] }; | ||
case o.Maya: | ||
return { identifier: "MAYA.CACAO", decimal: m.MAYA }; | ||
case "MAYA.MAYA": | ||
return { identifier: "MAYA.MAYA", decimal: 4 }; | ||
case i.Kujira: | ||
case i.Arbitrum: | ||
case i.Optimism: | ||
case i.BitcoinCash: | ||
case i.Litecoin: | ||
case i.Dogecoin: | ||
case i.Binance: | ||
case i.Avalanche: | ||
case i.Polygon: | ||
case i.Bitcoin: | ||
case i.Ethereum: | ||
return { identifier: `${n}.${n}`, decimal: m[n] }; | ||
case o.Kujira: | ||
case o.Arbitrum: | ||
case o.Optimism: | ||
case o.BitcoinCash: | ||
case o.Litecoin: | ||
case o.Dogecoin: | ||
case o.Binance: | ||
case o.Avalanche: | ||
case o.Polygon: | ||
case o.Bitcoin: | ||
case o.Ethereum: | ||
return { identifier: `${s}.${s}`, decimal: m[s] }; | ||
} | ||
}, mt = ({ chain: n, symbol: t }) => { | ||
}, Ct = ({ chain: s, symbol: t }) => { | ||
if (t.includes("/")) | ||
return "Synth"; | ||
switch (n) { | ||
case i.Bitcoin: | ||
case i.BitcoinCash: | ||
case i.Dogecoin: | ||
case i.Litecoin: | ||
case i.Maya: | ||
case i.THORChain: | ||
switch (s) { | ||
case o.Bitcoin: | ||
case o.BitcoinCash: | ||
case o.Dogecoin: | ||
case o.Litecoin: | ||
case o.Maya: | ||
case o.THORChain: | ||
return "Native"; | ||
case i.Cosmos: | ||
return t === "ATOM" ? "Native" : i.Cosmos; | ||
case i.Kujira: | ||
return t === i.Kujira ? "Native" : i.Kujira; | ||
case i.Binance: | ||
return t === i.Binance ? "Native" : "BEP2"; | ||
case i.BinanceSmartChain: | ||
return t === i.Binance ? "Native" : "BEP20"; | ||
case i.Ethereum: | ||
return t === i.Ethereum ? "Native" : "ERC20"; | ||
case i.Avalanche: | ||
return t === i.Avalanche ? "Native" : i.Avalanche; | ||
case i.Polygon: | ||
return t === i.Polygon ? "Native" : "POLYGON"; | ||
case i.Arbitrum: | ||
return [i.Ethereum, i.Arbitrum].includes(t) ? "Native" : "ARBITRUM"; | ||
case i.Optimism: | ||
return [i.Ethereum, i.Optimism].includes(t) ? "Native" : "OPTIMISM"; | ||
case o.Cosmos: | ||
return t === "ATOM" ? "Native" : o.Cosmos; | ||
case o.Kujira: | ||
return t === o.Kujira ? "Native" : o.Kujira; | ||
case o.Binance: | ||
return t === o.Binance ? "Native" : "BEP2"; | ||
case o.BinanceSmartChain: | ||
return t === o.Binance ? "Native" : "BEP20"; | ||
case o.Ethereum: | ||
return t === o.Ethereum ? "Native" : "ERC20"; | ||
case o.Avalanche: | ||
return t === o.Avalanche ? "Native" : o.Avalanche; | ||
case o.Polygon: | ||
return t === o.Polygon ? "Native" : "POLYGON"; | ||
case o.Arbitrum: | ||
return [o.Ethereum, o.Arbitrum].includes(t) ? "Native" : "ARBITRUM"; | ||
case o.Optimism: | ||
return [o.Ethereum, o.Optimism].includes(t) ? "Native" : "OPTIMISM"; | ||
} | ||
}, 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 = new RegExp( | ||
}, ee = (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( | ||
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/, | ||
"gmi" | ||
), Et = (n) => n.filter( | ||
(t) => !gt.test(t.toString()) && !t.toString().includes("undefined") | ||
), _t = ({ | ||
liquidityUnits: n, | ||
), re = (s) => s.filter( | ||
(t) => !$t.test(t.toString()) && !t.toString().includes("undefined") | ||
), It = ({ | ||
liquidityUnits: s, | ||
poolUnits: t, | ||
runeDepth: e | ||
}) => { | ||
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); | ||
}, pt = ({ | ||
liquidityUnits: n, | ||
const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = n.mul(n).mul(n); | ||
return a.mul(c.sub(u).add(l)).div(h); | ||
}, Et = ({ | ||
liquidityUnits: s, | ||
poolUnits: t, | ||
assetDepth: e | ||
}) => { | ||
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); | ||
}, Ot = ({ | ||
percent: n, | ||
const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = a.mul(c.sub(u).add(l)), _ = n.mul(n).mul(n); | ||
return h.div(_); | ||
}, se = ({ | ||
percent: s, | ||
runeDepth: t, | ||
liquidityUnits: e, | ||
poolUnits: r | ||
}) => _t({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), Mt = ({ | ||
percent: n, | ||
}) => It({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), ne = ({ | ||
percent: s, | ||
assetDepth: t, | ||
liquidityUnits: e, | ||
poolUnits: r | ||
}) => pt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), h = (n) => new bt({ value: n, decimal: m.THOR }), ft = ({ | ||
liquidityUnits: n, | ||
}) => Et({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), d = (s) => new Qt({ value: s, decimal: m.THOR }), Ot = ({ | ||
liquidityUnits: s, | ||
poolUnits: t, | ||
@@ -213,29 +177,29 @@ runeDepth: e, | ||
}) => ({ | ||
assetAmount: h(r).mul(n).div(t), | ||
runeAmount: h(e).mul(n).div(t) | ||
}), Nt = ({ | ||
liquidityUnits: n, | ||
assetAmount: d(r).mul(s).div(t), | ||
runeAmount: d(e).mul(s).div(t) | ||
}), ie = ({ | ||
liquidityUnits: s, | ||
poolUnits: t, | ||
runeDepth: e, | ||
assetDepth: r, | ||
percent: s | ||
percent: n | ||
}) => Object.fromEntries( | ||
Object.entries(ft({ liquidityUnits: n, poolUnits: t, runeDepth: e, assetDepth: r })).map( | ||
([a, c]) => [a, c.mul(s)] | ||
Object.entries(Ot({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map( | ||
([i, a]) => [i, a.mul(n)] | ||
) | ||
), Rt = ({ | ||
runeDepth: n, | ||
), oe = ({ | ||
runeDepth: s, | ||
poolUnits: t, | ||
assetDepth: e, | ||
liquidityUnits: r, | ||
runeAmount: n, | ||
assetAmount: i | ||
}) => { | ||
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 = ({ | ||
runeAmount: s, | ||
assetAmount: a | ||
}) => { | ||
const c = h(n), o = h(e), u = h(t), l = h(s), d = h(a), A = l.mul(o), I = d.mul(c), R = l.mul(d), X = c.mul(o), Z = u.mul(A.add(I.add(R.mul(2)))), tt = A.add(I.add(X.mul(2))), F = Z.div(tt), k = h(r).add(F); | ||
if (F.baseValueNumber === 0) | ||
return k.div(u).baseValueNumber; | ||
const et = u.add(k); | ||
return k.div(et).baseValueNumber; | ||
}, kt = ({ | ||
runeAmount: n, | ||
assetAmount: t, | ||
@@ -245,35 +209,35 @@ runeDepth: e, | ||
}) => { | ||
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)); | ||
const n = d(e), i = d(r), a = d(t), c = d(s), u = a.mul(n).sub(i.mul(c)), l = i.mul(c).add(n.mul(i)); | ||
return Math.abs(u.div(l).baseValueNumber); | ||
}, At = ({ | ||
symbol: n, | ||
}, kt = ({ | ||
symbol: s, | ||
ticker: t, | ||
chain: e | ||
}) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n, Ht = (n, t) => { | ||
switch (n) { | ||
case p.LEAVE: | ||
case p.BOND: { | ||
}) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, ce = (s, t) => { | ||
switch (s) { | ||
case g.LEAVE: | ||
case g.BOND: { | ||
const { address: e } = t; | ||
return `${n}:${e}`; | ||
return `${s}:${e}`; | ||
} | ||
case p.UNBOND: { | ||
case g.UNBOND: { | ||
const { address: e, unbondAmount: r } = t; | ||
return `${n}:${e}:${r * 10 ** 8}`; | ||
return `${s}:${e}:${r * 10 ** 8}`; | ||
} | ||
case p.THORNAME_REGISTER: { | ||
const { name: e, chain: r, address: s, owner: a } = t; | ||
return `${n}:${e}:${r}:${s}${a ? `:${a}` : ""}`; | ||
case g.THORNAME_REGISTER: { | ||
const { name: e, chain: r, address: n, owner: i } = t; | ||
return `${s}:${e}:${r}:${n}${i ? `:${i}` : ""}`; | ||
} | ||
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 g.DEPOSIT: { | ||
const { chain: e, symbol: r, address: n, singleSide: i } = t; | ||
return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`; | ||
} | ||
case p.WITHDRAW: { | ||
const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, u = !o && c ? `:${c}` : "", l = At({ chain: e, symbol: s, ticker: r }); | ||
return `${n}:${e}${o ? "/" : "."}${l}:${a}${u}`; | ||
case g.WITHDRAW: { | ||
const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: a, singleSide: c } = t, u = !c && a ? `:${a}` : "", l = kt({ chain: e, symbol: n, ticker: r }); | ||
return `${s}:${e}${c ? "/" : "."}${l}:${i}${u}`; | ||
} | ||
case p.OPEN_LOAN: | ||
case p.CLOSE_LOAN: { | ||
case g.OPEN_LOAN: | ||
case g.CLOSE_LOAN: { | ||
const { asset: e, address: r } = t; | ||
return `${n}:${e}:${r}`; | ||
return `${s}:${e}:${r}`; | ||
} | ||
@@ -283,25 +247,392 @@ default: | ||
} | ||
}, G = Object.values(i), $t = (n = "") => { | ||
const t = n.toUpperCase(), [e] = t.split("."); | ||
if (G.includes(e)) | ||
}, ue = (s) => { | ||
if (s < 0) | ||
throw new Error("Invalid number of year"); | ||
return 10 + s; | ||
}, le = (s) => { | ||
if (s.length > 30) | ||
return !1; | ||
const t = /^[a-zA-Z0-9+_-]+$/g; | ||
return !!s.match(t); | ||
}, he = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`; | ||
class K extends Error { | ||
constructor(t, e, r) { | ||
const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", a = `${n} ${i}`.trim(), c = a ? `status code ${a}` : "an unknown error"; | ||
super(`Request failed with ${c}`), Object.defineProperty(this, "response", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: void 0 | ||
}), Object.defineProperty(this, "request", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: void 0 | ||
}), Object.defineProperty(this, "options", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: void 0 | ||
}), this.name = "HTTPError", this.response = t, this.request = e, this.options = r; | ||
} | ||
} | ||
class nt extends Error { | ||
constructor(t) { | ||
super("Request timed out"), Object.defineProperty(this, "request", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: void 0 | ||
}), this.name = "TimeoutError", this.request = t; | ||
} | ||
} | ||
const V = (s) => s !== null && typeof s == "object", B = (...s) => { | ||
for (const t of s) | ||
if ((!V(t) || Array.isArray(t)) && t !== void 0) | ||
throw new TypeError("The `options` argument must be an object"); | ||
return z({}, ...s); | ||
}, it = (s = {}, t = {}) => { | ||
const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t); | ||
for (const [i, a] of n.entries()) | ||
r && a === "undefined" || a === void 0 ? e.delete(i) : e.set(i, a); | ||
return e; | ||
}, z = (...s) => { | ||
let t = {}, e = {}; | ||
for (const r of s) | ||
if (Array.isArray(r)) | ||
Array.isArray(t) || (t = []), t = [...t, ...r]; | ||
else if (V(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); | ||
} | ||
return t; | ||
}, Bt = (() => { | ||
let s = !1, t = !1; | ||
const e = typeof globalThis.ReadableStream == "function", r = typeof globalThis.Request == "function"; | ||
return e && r && (t = new globalThis.Request("https://empty.invalid", { | ||
body: new globalThis.ReadableStream(), | ||
method: "POST", | ||
// @ts-expect-error - Types are outdated. | ||
get duplex() { | ||
return s = !0, "half"; | ||
} | ||
}).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 = { | ||
json: "application/json", | ||
text: "text/*", | ||
formData: "multipart/form-data", | ||
arrayBuffer: "*/*", | ||
blob: "*/*" | ||
}, j = 2147483647, at = Symbol("stop"), Pt = { | ||
json: !0, | ||
parseJson: !0, | ||
searchParams: !0, | ||
prefixUrl: !0, | ||
retry: !0, | ||
timeout: !0, | ||
hooks: !0, | ||
throwHttpErrors: !0, | ||
onDownloadProgress: !0, | ||
fetch: !0 | ||
}, Nt = { | ||
method: !0, | ||
headers: !0, | ||
body: !0, | ||
mode: !0, | ||
credentials: !0, | ||
cache: !0, | ||
redirect: !0, | ||
referrer: !0, | ||
referrerPolicy: !0, | ||
integrity: !0, | ||
keepalive: !0, | ||
signal: !0, | ||
window: !0, | ||
dispatcher: !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 = { | ||
limit: 2, | ||
methods: jt, | ||
statusCodes: Lt, | ||
afterStatusCodes: ct, | ||
maxRetryAfter: Number.POSITIVE_INFINITY, | ||
backoffLimit: Number.POSITIVE_INFINITY, | ||
delay: (s) => 0.3 * 2 ** (s - 1) * 1e3 | ||
}, Dt = (s = {}) => { | ||
if (typeof s == "number") | ||
return { | ||
...Q, | ||
limit: s | ||
}; | ||
if (s.methods && !Array.isArray(s.methods)) | ||
throw new Error("retry.methods must be an array"); | ||
if (s.statusCodes && !Array.isArray(s.statusCodes)) | ||
throw new Error("retry.statusCodes must be an array"); | ||
return { | ||
...Q, | ||
...s, | ||
afterStatusCodes: ct | ||
}; | ||
}; | ||
async function Ut(s, t, e, r) { | ||
return new Promise((n, i) => { | ||
const a = setTimeout(() => { | ||
e && e.abort(), i(new nt(s)); | ||
}, r.timeout); | ||
r.fetch(s, t).then(n).catch(i).then(() => { | ||
clearTimeout(a); | ||
}); | ||
}); | ||
} | ||
async function Ft(s, { signal: t }) { | ||
return new Promise((e, r) => { | ||
t && (t.throwIfAborted(), t.addEventListener("abort", n, { once: !0 })); | ||
function n() { | ||
clearTimeout(i), r(t.reason); | ||
} | ||
const i = setTimeout(() => { | ||
t == null || t.removeEventListener("abort", n), e(); | ||
}, s); | ||
}); | ||
} | ||
const Wt = (s, t) => { | ||
const e = {}; | ||
for (const r in t) | ||
!(r in Nt) && !(r in Pt) && !(r in s) && (e[r] = t[r]); | ||
return e; | ||
}; | ||
class q { | ||
static create(t, e) { | ||
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}`); | ||
await Promise.resolve(); | ||
let c = await r._fetch(); | ||
for (const u of r._options.hooks.afterResponse) { | ||
const l = await u(r.request, r._options, r._decorateResponse(c.clone())); | ||
l instanceof globalThis.Response && (c = l); | ||
} | ||
if (r._decorateResponse(c), !c.ok && r._options.throwHttpErrors) { | ||
let u = new K(c, r.request, r._options); | ||
for (const l of r._options.hooks.beforeError) | ||
u = await l(u); | ||
throw u; | ||
} | ||
if (r._options.onDownloadProgress) { | ||
if (typeof r._options.onDownloadProgress != "function") | ||
throw new TypeError("The `onDownloadProgress` option must be a function"); | ||
if (!qt) | ||
throw new Error("Streams are not supported in your environment. `ReadableStream` is missing."); | ||
return r._stream(c.clone(), r._options.onDownloadProgress); | ||
} | ||
return c; | ||
}, a = r._options.retry.methods.includes(r.request.method.toLowerCase()) ? r._retry(n) : n(); | ||
for (const [c, u] of Object.entries(xt)) | ||
a[c] = async () => { | ||
r.request.headers.set("accept", r.request.headers.get("accept") || u); | ||
const h = (await a).clone(); | ||
if (c === "json") { | ||
if (h.status === 204 || (await h.clone().arrayBuffer()).byteLength === 0) | ||
return ""; | ||
if (e.parseJson) | ||
return e.parseJson(await h.text()); | ||
} | ||
return h[c](); | ||
}; | ||
return a; | ||
} | ||
// eslint-disable-next-line complexity | ||
constructor(t, e = {}) { | ||
if (Object.defineProperty(this, "request", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: void 0 | ||
}), Object.defineProperty(this, "abortController", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: void 0 | ||
}), Object.defineProperty(this, "_retryCount", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: 0 | ||
}), Object.defineProperty(this, "_input", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: void 0 | ||
}), Object.defineProperty(this, "_options", { | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0, | ||
value: void 0 | ||
}), this._input = t, this._options = { | ||
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208 | ||
credentials: this._input.credentials || "same-origin", | ||
...e, | ||
headers: it(this._input.headers, e.headers), | ||
hooks: z({ | ||
beforeRequest: [], | ||
beforeRetry: [], | ||
beforeError: [], | ||
afterResponse: [] | ||
}, e.hooks), | ||
method: Ht(e.method ?? this._input.method), | ||
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing | ||
prefixUrl: String(e.prefixUrl || ""), | ||
retry: Dt(e.retry), | ||
throwHttpErrors: e.throwHttpErrors !== !1, | ||
timeout: e.timeout ?? 1e4, | ||
fetch: e.fetch ?? globalThis.fetch.bind(globalThis) | ||
}, typeof this._input != "string" && !(this._input instanceof URL || this._input instanceof globalThis.Request)) | ||
throw new TypeError("`input` must be a string, URL, or Request"); | ||
if (this._options.prefixUrl && typeof this._input == "string") { | ||
if (this._input.startsWith("/")) | ||
throw new Error("`input` must not begin with a slash when using `prefixUrl`"); | ||
this._options.prefixUrl.endsWith("/") || (this._options.prefixUrl += "/"), this._input = this._options.prefixUrl + this._input; | ||
} | ||
if (Vt) { | ||
if (this.abortController = new globalThis.AbortController(), this._options.signal) { | ||
const r = this._options.signal; | ||
this._options.signal.addEventListener("abort", () => { | ||
this.abortController.abort(r.reason); | ||
}); | ||
} | ||
this._options.signal = this.abortController.signal; | ||
} | ||
if (Bt && (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); | ||
} | ||
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._options.retry.statusCodes.includes(t.response.status)) | ||
return 0; | ||
const r = t.response.headers.get("Retry-After"); | ||
if (r && this._options.retry.afterStatusCodes.includes(t.response.status)) { | ||
let n = Number(r); | ||
return Number.isNaN(n) ? n = Date.parse(r) - Date.now() : n *= 1e3, this._options.retry.maxRetryAfter !== void 0 && n > this._options.retry.maxRetryAfter ? 0 : n; | ||
} | ||
if (t.response.status === 413) | ||
return 0; | ||
} | ||
const e = this._options.retry.delay(this._retryCount); | ||
return Math.min(this._options.retry.backoffLimit, e); | ||
} | ||
return 0; | ||
} | ||
_decorateResponse(t) { | ||
return this._options.parseJson && (t.json = async () => this._options.parseJson(await t.text())), t; | ||
} | ||
async _retry(t) { | ||
try { | ||
return await t(); | ||
} catch (e) { | ||
const r = Math.min(this._calculateRetryDelay(e), j); | ||
if (r !== 0 && this._retryCount > 0) { | ||
await Ft(r, { signal: this._options.signal }); | ||
for (const n of this._options.hooks.beforeRetry) | ||
if (await n({ | ||
request: this.request, | ||
options: this._options, | ||
error: e, | ||
retryCount: this._retryCount | ||
}) === at) | ||
return; | ||
return this._retry(t); | ||
} | ||
throw e; | ||
} | ||
} | ||
async _fetch() { | ||
for (const e of this._options.hooks.beforeRequest) { | ||
const r = await e(this.request, this._options); | ||
if (r instanceof Request) { | ||
this.request = r; | ||
break; | ||
} | ||
if (r instanceof Response) | ||
return r; | ||
} | ||
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); | ||
} | ||
/* istanbul ignore next */ | ||
_stream(t, e) { | ||
const r = Number(t.headers.get("content-length")) || 0; | ||
let n = 0; | ||
return t.status === 204 ? (e && e({ percent: 1, totalBytes: r, transferredBytes: n }, new Uint8Array()), new globalThis.Response(null, { | ||
status: t.status, | ||
statusText: t.statusText, | ||
headers: t.headers | ||
})) : new globalThis.Response(new globalThis.ReadableStream({ | ||
async start(i) { | ||
const a = t.body.getReader(); | ||
e && e({ percent: 0, transferredBytes: 0, totalBytes: r }, new Uint8Array()); | ||
async function c() { | ||
const { done: u, value: l } = await a.read(); | ||
if (u) { | ||
i.close(); | ||
return; | ||
} | ||
if (e) { | ||
n += l.byteLength; | ||
const h = r === 0 ? 0 : n / r; | ||
e({ percent: h, transferredBytes: n, totalBytes: r }, l); | ||
} | ||
i.enqueue(l), await c(); | ||
} | ||
await c(); | ||
} | ||
}), { | ||
status: t.status, | ||
statusText: t.statusText, | ||
headers: t.headers | ||
}); | ||
} | ||
} | ||
/*! 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({ | ||
headers: { | ||
referrer: "https://sk.thorswap.net", | ||
referer: "https://sk.thorswap.net", | ||
"Content-Type": "application/json" | ||
} | ||
}), zt = { | ||
get: (s, t) => X.get(s, t).json(), | ||
post: (s, t) => X.post(s, t).json() | ||
}, Z = Object.values(o), Jt = (s = "") => { | ||
const t = s.toUpperCase(), [e] = t.split("."); | ||
if (Z.includes(e)) | ||
return !0; | ||
const [r] = t.split("/"); | ||
if (G.includes(r)) | ||
if (Z.includes(r)) | ||
return !0; | ||
throw new Error( | ||
`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>` | ||
`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>` | ||
); | ||
}, T = 8, S = (n) => 10n ** BigInt(n), v = (n) => Math.log10(parseFloat(n.toString())); | ||
function U({ | ||
value: n, | ||
bigIntDecimal: t = T, | ||
decimal: e = T | ||
}, $ = 8, R = (s) => 10n ** BigInt(s), S = (s) => Math.log10(parseFloat(s.toString())); | ||
function tt({ | ||
value: s, | ||
bigIntDecimal: t = $, | ||
decimal: e = $ | ||
}) { | ||
const r = n < 0n; | ||
let s = n.toString().substring(r ? 1 : 0); | ||
const a = e - (s.length - 1); | ||
a > 0 && (s = "0".repeat(a) + s); | ||
const c = s.length - e; | ||
let o = s.slice(-e); | ||
return parseInt(o[t]) >= 5 ? o = `${o.substring(0, t - 1)}${(parseInt(o[t - 1]) + 1).toString()}` : o = o.substring(0, t), `${r ? "-" : ""}${s.slice(0, c)}.${o}`.replace( | ||
const r = s < 0n; | ||
let n = s.toString().substring(r ? 1 : 0); | ||
const i = e - (n.length - 1); | ||
i > 0 && (n = "0".repeat(i) + n); | ||
const a = n.length - e; | ||
let c = n.slice(-e); | ||
return parseInt(c[t]) >= 5 ? c = `${c.substring(0, t - 1)}${(parseInt(c[t - 1]) + 1).toString()}` : c = c.substring(0, t), `${r ? "-" : ""}${n.slice(0, a)}.${c}`.replace( | ||
/\.?0*$/, | ||
@@ -311,23 +642,23 @@ "" | ||
} | ||
var w, C, M, z, N, J, E, D, b, V, O, L; | ||
const B = class B { | ||
var w, v, M, ut, x, lt, O, F, A, C, k, W; | ||
const I = class I { | ||
constructor(t) { | ||
$(this, w); | ||
$(this, M); | ||
$(this, N); | ||
$(this, E); | ||
$(this, b); | ||
$(this, O); | ||
_(this, "decimalMultiplier", 10n ** 8n); | ||
_(this, "bigIntValue", 0n); | ||
_(this, "decimal"); | ||
const e = P(t); | ||
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = S( | ||
Math.max(g(this, O, L).call(this, g(this, b, V).call(this, e)), this.decimal || 0) | ||
), g(this, M, z).call(this, e); | ||
y(this, w); | ||
y(this, M); | ||
y(this, x); | ||
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); | ||
} | ||
static fromBigInt(t, e) { | ||
return new B({ | ||
return new I({ | ||
decimal: e, | ||
value: U({ value: t, bigIntDecimal: e, decimal: e }) | ||
value: tt({ value: t, bigIntDecimal: e, decimal: e }) | ||
}); | ||
@@ -340,4 +671,4 @@ } | ||
}) { | ||
return B.fromBigInt( | ||
new B(t).bigIntValue * S(r) / S(e), | ||
return I.fromBigInt( | ||
new I(t).bigIntValue * R(r) / R(e), | ||
r | ||
@@ -368,12 +699,12 @@ ); | ||
add(...t) { | ||
return g(this, w, C).call(this, "add", ...t); | ||
return f(this, w, v).call(this, "add", ...t); | ||
} | ||
sub(...t) { | ||
return g(this, w, C).call(this, "sub", ...t); | ||
return f(this, w, v).call(this, "sub", ...t); | ||
} | ||
mul(...t) { | ||
return g(this, w, C).call(this, "mul", ...t); | ||
return f(this, w, v).call(this, "mul", ...t); | ||
} | ||
div(...t) { | ||
return g(this, w, C).call(this, "div", ...t); | ||
return f(this, w, v).call(this, "div", ...t); | ||
} | ||
@@ -398,3 +729,3 @@ gt(t) { | ||
this.bigIntValue, | ||
this.decimal || v(this.decimalMultiplier) | ||
this.decimal || S(this.decimalMultiplier) | ||
); | ||
@@ -411,3 +742,3 @@ switch (t) { | ||
getBaseValue(t) { | ||
const e = this.decimalMultiplier / S(this.decimal || m.THOR), r = this.bigIntValue / e; | ||
const e = this.decimalMultiplier / R(this.decimal || m.THOR), r = this.bigIntValue / e; | ||
switch (t) { | ||
@@ -425,30 +756,30 @@ case "number": | ||
return t.bigIntValue; | ||
const r = P(t), s = g(this, b, V).call(this, r); | ||
return s === "0" || s === "undefined" ? 0n : g(this, E, D).call(this, s, e); | ||
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); | ||
} | ||
formatBigIntToSafeValue(t, e) { | ||
const r = e || this.decimal || T, s = Math.max( | ||
const r = e || this.decimal || $, n = Math.max( | ||
r, | ||
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( | ||
S(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; | ||
let h = u.slice(-n); | ||
return parseInt(h[r]) >= 5 ? h = `${h.substring(0, r - 1)}${(parseInt(h[r - 1]) + 1).toString()}` : h = h.substring(0, r), `${i ? "-" : ""}${u.slice( | ||
0, | ||
l | ||
)}.${d}`.replace(/\.?0*$/, ""); | ||
)}.${h}`.replace(/\.?0*$/, ""); | ||
} | ||
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) | ||
const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "", a = parseInt(n) ? n.length + i.length : i.length; | ||
if (a <= 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, | ||
if (n.length >= t) | ||
return n.slice(0, t).padEnd(n.length, "0"); | ||
if (parseInt(n)) | ||
return `${n}.${i.slice(0, t - n.length)}`.padEnd( | ||
a - t, | ||
"0" | ||
); | ||
const o = parseInt(a), u = `${o}`.slice(0, t); | ||
const c = parseInt(i), u = `${c}`.slice(0, t); | ||
return `0.${u.padStart( | ||
a.length - `${o}`.length + u.length, | ||
i.length - `${c}`.length + u.length, | ||
"0" | ||
@@ -458,80 +789,80 @@ )}`; | ||
}; | ||
w = new WeakSet(), C = function(t, ...e) { | ||
const r = g(this, N, J).call(this, this, ...e), s = S(r), a = e.reduce( | ||
(o, u) => { | ||
w = new WeakSet(), v = function(t, ...e) { | ||
const r = f(this, x, lt).call(this, this, ...e), n = R(r), i = e.reduce( | ||
(c, u) => { | ||
const l = this.getBigIntValue(u, r); | ||
switch (t) { | ||
case "add": | ||
return o + l; | ||
return c + l; | ||
case "sub": | ||
return o - l; | ||
return c - l; | ||
case "mul": | ||
return o * l / s; | ||
return c * l / n; | ||
case "div": { | ||
if (l === 0n) | ||
throw new RangeError("Division by zero"); | ||
return o * s / l; | ||
return c * n / l; | ||
} | ||
default: | ||
return o; | ||
return c; | ||
} | ||
}, | ||
//normalize is to precision multiplier base | ||
this.bigIntValue * s / this.decimalMultiplier | ||
), c = U({ | ||
this.bigIntValue * n / this.decimalMultiplier | ||
), a = tt({ | ||
bigIntDecimal: r, | ||
decimal: Math.max(r, v(this.decimalMultiplier)), | ||
value: a | ||
decimal: Math.max(r, S(this.decimalMultiplier)), | ||
value: i | ||
}); | ||
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() }); | ||
}, M = new WeakSet(), z = function(t) { | ||
const e = g(this, b, V).call(this, t) || "0"; | ||
this.bigIntValue = g(this, E, D).call(this, e); | ||
}, N = new WeakSet(), J = function(...t) { | ||
return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() }); | ||
}, M = new WeakSet(), ut = 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) { | ||
const e = t.map( | ||
(r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : g(this, O, L).call(this, g(this, b, V).call(this, r)) | ||
(r) => typeof r == "object" ? r.decimal || S(r.decimalMultiplier) : f(this, k, W).call(this, f(this, A, C).call(this, r)) | ||
).filter(Boolean); | ||
return Math.max(...e, T); | ||
}, E = new WeakSet(), D = function(t, e) { | ||
const r = e ? S(e) : this.decimalMultiplier, s = v(r), [a = "", c = ""] = t.split("."); | ||
return BigInt(`${a}${c.padEnd(s, "0")}`); | ||
}, b = new WeakSet(), V = function(t) { | ||
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("."); | ||
return BigInt(`${i}${a.padEnd(n, "0")}`); | ||
}, A = new WeakSet(), C = function(t) { | ||
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", { | ||
useGrouping: !1, | ||
maximumFractionDigits: 20 | ||
}) : P(t)}`.replaceAll(",", ".").split("."); | ||
}) : L(t)}`.replaceAll(",", ".").split("."); | ||
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0]; | ||
}, O = new WeakSet(), L = function(t) { | ||
}, k = new WeakSet(), W = function(t) { | ||
var r; | ||
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0; | ||
return Math.max(e, T); | ||
return Math.max(e, $); | ||
}; | ||
let y = B; | ||
function P(n) { | ||
return typeof n == "object" ? "getValue" in n ? n.getValue("string") : n.value : n; | ||
let E = I; | ||
function L(s) { | ||
return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s; | ||
} | ||
let j; | ||
const x = (n) => { | ||
if (!j) | ||
let G; | ||
const D = (s) => { | ||
if (!G) | ||
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first"); | ||
return j.get(n.toUpperCase()) || { decimal: m.THOR, identifier: "" }; | ||
}, W = async (n, t = 0) => { | ||
$t(n); | ||
const e = await K(q(n)); | ||
return new f({ decimal: e, value: t, identifier: n }); | ||
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 }); | ||
}; | ||
class f extends y { | ||
class b extends E { | ||
constructor(e) { | ||
super( | ||
e.value instanceof y ? e.value : { decimal: e.decimal, value: e.value } | ||
e.value instanceof E ? 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 = 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; | ||
p(this, "address"); | ||
p(this, "chain"); | ||
p(this, "isSynthetic", !1); | ||
p(this, "isGasAsset", !1); | ||
p(this, "symbol"); | ||
p(this, "ticker"); | ||
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; | ||
} | ||
@@ -552,32 +883,32 @@ get assetValue() { | ||
static async fromString(e, r = 0) { | ||
return W(e, r); | ||
return et(e, r); | ||
} | ||
static fromStringSync(e, r = 0) { | ||
const { decimal: s, identifier: a } = x( | ||
const { decimal: n, identifier: i } = D( | ||
e | ||
); | ||
return a ? new f({ decimal: s, identifier: a, value: r }) : void 0; | ||
return i ? new b({ decimal: n, identifier: i, value: r }) : void 0; | ||
} | ||
static async fromIdentifier(e, r = 0) { | ||
return W(e, r); | ||
return et(e, r); | ||
} | ||
static fromIdentifierSync(e, r = 0) { | ||
const { decimal: s, identifier: a } = x(e); | ||
return new f({ decimal: s, identifier: a, value: r }); | ||
const { decimal: n, identifier: i } = D(e); | ||
return new b({ decimal: n, identifier: i, value: r }); | ||
} | ||
static fromChainOrSignature(e, r = 0) { | ||
const { decimal: s, identifier: a } = ht(e); | ||
return new f({ value: r, decimal: s, identifier: a }); | ||
const { decimal: n, identifier: i } = vt(e); | ||
return new b({ value: r, decimal: n, identifier: i }); | ||
} | ||
static async fromTCQuote(e, r = 0) { | ||
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 }); | ||
const n = await st(Y(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 s = x(e), a = this.shiftDecimals({ | ||
const n = D(e), i = this.shiftDecimals({ | ||
value: r, | ||
from: m.THOR, | ||
to: s.decimal | ||
to: n.decimal | ||
}); | ||
return new f({ ...s, value: a }); | ||
return new b({ ...n, value: i }); | ||
} | ||
@@ -591,17 +922,17 @@ static async loadStaticAssets() { | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
ThorchainList: s, | ||
NativeList: a, | ||
...c | ||
ThorchainList: n, | ||
NativeList: i, | ||
...a | ||
} = await import("@swapkit/tokens"); | ||
j = [a, ...Object.values(c)].reduce( | ||
(u, { tokens: l }) => (l.forEach(({ identifier: d, chain: A, ...I }) => { | ||
const R = "decimals" in I ? I.decimals : m[A]; | ||
u.set(d, { identifier: d, decimal: R }); | ||
G = [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 }); | ||
}), u), | ||
/* @__PURE__ */ new Map() | ||
), e({ ok: !0 }); | ||
} catch (s) { | ||
console.error(s), r({ | ||
} catch (n) { | ||
console.error(n), r({ | ||
ok: !1, | ||
error: s, | ||
error: n, | ||
message: "Couldn't load static assets. Ensure you have installed @swapkit/tokens package" | ||
@@ -614,16 +945,16 @@ }); | ||
} | ||
const Pt = (n) => { | ||
const t = f.fromChainOrSignature(n); | ||
switch (n) { | ||
case i.Bitcoin: | ||
case i.Litecoin: | ||
case i.BitcoinCash: | ||
const de = (s) => { | ||
const t = b.fromChainOrSignature(s); | ||
switch (s) { | ||
case o.Bitcoin: | ||
case o.Litecoin: | ||
case o.BitcoinCash: | ||
return t.add(10001); | ||
case i.Dogecoin: | ||
case o.Dogecoin: | ||
return t.add(100000001); | ||
case i.Avalanche: | ||
case i.Ethereum: | ||
case o.Avalanche: | ||
case o.Ethereum: | ||
return t.add(10 * 10 ** 9); | ||
case i.THORChain: | ||
case i.Maya: | ||
case o.THORChain: | ||
case o.Maya: | ||
return t.add(0); | ||
@@ -633,13 +964,13 @@ default: | ||
} | ||
}, q = (n) => { | ||
const t = n.slice(0, 14).includes("/"), e = n.includes(".") ? n : `${i.THORChain}.${n}`, [r, s] = e.split("."), [a, c] = s.split("-"); | ||
}, Y = (s) => { | ||
const t = s.slice(0, 14).includes("/"), e = s.includes(".") ? s : `${o.THORChain}.${s}`, [r, n] = e.split("."), [i, a] = n.split("-"); | ||
return { | ||
address: c == null ? void 0 : c.toLowerCase(), | ||
address: a == null ? void 0 : a.toLowerCase(), | ||
chain: r, | ||
isGasAsset: dt({ chain: r, symbol: s }), | ||
isGasAsset: St({ chain: r, symbol: n }), | ||
isSynthetic: t, | ||
symbol: c ? `${a}-${(c == null ? void 0 : c.toLowerCase()) ?? ""}` : s, | ||
ticker: t ? s : a | ||
symbol: a ? `${i}-${(a == null ? void 0 : a.toLowerCase()) ?? ""}` : n, | ||
ticker: t ? n : i | ||
}; | ||
}, wt = { | ||
}, Kt = { | ||
/** | ||
@@ -701,8 +1032,8 @@ * Core | ||
}; | ||
class Q extends Error { | ||
class ht 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: Kt[t], message: t } }), Object.setPrototypeOf(this, ht.prototype); | ||
} | ||
} | ||
class bt extends y { | ||
class Qt extends E { | ||
eq(t) { | ||
@@ -713,29 +1044,28 @@ return this.eqValue(t); | ||
export { | ||
f as AssetValue, | ||
y as BigIntArithmetics, | ||
Q as SwapKitError, | ||
bt as SwapKitNumber, | ||
yt as assetFromString, | ||
Vt as derivationPathToString, | ||
Et as filterAssets, | ||
U as formatBigIntToSafeValue, | ||
Bt as gasFeeMultiplier, | ||
mt as getAssetType, | ||
pt as getAsymmetricAssetShare, | ||
Mt as getAsymmetricAssetWithdrawAmount, | ||
_t as getAsymmetricRuneShare, | ||
Ot as getAsymmetricRuneWithdrawAmount, | ||
ht as getCommonAssetInfo, | ||
K as getDecimal, | ||
Rt as getEstimatedPoolShare, | ||
kt as getLiquiditySlippage, | ||
Ht as getMemoFor, | ||
Pt as getMinAmountByChain, | ||
Tt as getRequest, | ||
ft as getSymmetricPoolShare, | ||
Nt as getSymmetricWithdraw, | ||
vt as getTHORNameCost, | ||
dt as isGasAsset, | ||
at as postRequest, | ||
Ct as validateTHORName | ||
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 | ||
}; |
{ | ||
"author": "swapkit-oss-team", | ||
"description": "SwapKit Lib swapkit-helpers", | ||
"dependencies": { | ||
"ky": "1.1.2" | ||
}, | ||
"devDependencies": { | ||
@@ -9,4 +12,4 @@ "@vitest/coverage-istanbul": "0.34.4", | ||
"@internal/config": "0.0.0-internal.0", | ||
"@swapkit/tokens": "1.0.0-rc.5", | ||
"@swapkit/types": "1.0.0-rc.5" | ||
"@swapkit/tokens": "1.0.0-rc.6", | ||
"@swapkit/types": "1.0.0-rc.6" | ||
}, | ||
@@ -17,4 +20,4 @@ "eslintConfig": { | ||
"peerDependencies": { | ||
"@swapkit/tokens": "1.0.0-rc.5", | ||
"@swapkit/types": "1.0.0-rc.5" | ||
"@swapkit/tokens": "1.0.0-rc.6", | ||
"@swapkit/types": "1.0.0-rc.6" | ||
}, | ||
@@ -44,3 +47,3 @@ "exports": { | ||
"types": "./dist/index.d.ts", | ||
"version": "1.0.0-rc.8", | ||
"version": "1.0.0-rc.9", | ||
"scripts": { | ||
@@ -47,0 +50,0 @@ "build": "vite build", |
import type { EVMChain } from '@swapkit/types'; | ||
import { BaseDecimal, Chain, ChainToRPC, FeeOption } from '@swapkit/types'; | ||
import type { AssetValue } from '../index.ts'; | ||
import { type AssetValue, RequestClient } from '../index.ts'; | ||
import { postRequest } from './others.ts'; | ||
const getDecimalMethodHex = '0x313ce567'; | ||
@@ -14,16 +12,12 @@ | ||
try { | ||
const response = await postRequest<string>( | ||
ChainToRPC[chain], | ||
JSON.stringify({ | ||
const { result } = await RequestClient.post<{ result: string }>(ChainToRPC[chain], { | ||
headers: { accept: '*/*', 'cache-control': 'no-cache' }, | ||
body: JSON.stringify({ | ||
id: 44, | ||
jsonrpc: '2.0', | ||
method: 'eth_call', | ||
params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, 'latest'], | ||
id: 44, | ||
jsonrpc: '2.0', | ||
}), | ||
{ accept: '*/*', 'cache-control': 'no-cache', 'content-type': 'application/json' }, | ||
true, | ||
); | ||
}); | ||
const { result } = JSON.parse(response) as { result: string }; | ||
return parseInt(BigInt(result).toString()); | ||
@@ -30,0 +24,0 @@ } catch (error) { |
@@ -21,49 +21,1 @@ // 10 rune for register, 1 rune per year | ||
}; | ||
export const getRequest = async <T>( | ||
url: string, | ||
params?: { [key in string]?: any }, | ||
): Promise<T> => { | ||
try { | ||
const queryParams = Object.entries(params || {}).reduce( | ||
(acc, [key, value]) => { | ||
if (value) { | ||
acc[key] = value; | ||
} | ||
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' }, | ||
); | ||
return response.json(); | ||
} catch (error) { | ||
console.error(error); | ||
return {} as T; | ||
} | ||
}; | ||
export const postRequest = async <T>( | ||
url: string, | ||
body: string, | ||
headers?: Record<string, string>, | ||
parseAsString = false, | ||
): Promise<T> => { | ||
try { | ||
const response = await fetch(`${url}`, { | ||
body, | ||
headers, | ||
method: 'POST', | ||
referrer: 'https://sk.thorswap.net', | ||
}); | ||
return parseAsString ? response.text() : response.json(); | ||
} catch (error) { | ||
return {} as T; | ||
} | ||
}; |
@@ -8,2 +8,3 @@ /** | ||
export * from './helpers/others.ts'; | ||
export * from './helpers/request.ts'; | ||
@@ -10,0 +11,0 @@ /** |
@@ -82,3 +82,3 @@ import { BaseDecimal, Chain } from '@swapkit/types'; | ||
test('returns asset value string/identifier', async () => { | ||
const fakeAvaxUSDCAsset = new AssetValue({ | ||
const avaxUSDCAsset = new AssetValue({ | ||
decimal: 6, | ||
@@ -89,5 +89,3 @@ value: 1234567890, | ||
}); | ||
expect(fakeAvaxUSDCAsset.toString()).toBe( | ||
'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
); | ||
expect(avaxUSDCAsset.toString()).toBe('AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e'); | ||
@@ -104,6 +102,7 @@ const thor = AssetValue.fromChainOrSignature('ETH.THOR'); | ||
test('creates AssetValue from string', async () => { | ||
const fakeAvaxUSDCAssetString = 'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e'; | ||
const fakeAvaxUSDCAsset = await AssetValue.fromIdentifier(fakeAvaxUSDCAssetString); | ||
const avaxUSDCAsset = await AssetValue.fromIdentifier( | ||
'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
); | ||
expect(fakeAvaxUSDCAsset).toEqual( | ||
expect(avaxUSDCAsset).toEqual( | ||
expect.objectContaining({ | ||
@@ -110,0 +109,0 @@ address: '0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
186735
22
3446
0
3
+ Addedky@1.1.2
+ Added@swapkit/tokens@1.0.0-rc.6(transitive)
+ Added@swapkit/types@1.0.0-rc.6(transitive)
+ Addedky@1.1.2(transitive)
- Removed@swapkit/tokens@1.0.0-rc.5(transitive)
- Removed@swapkit/types@1.0.0-rc.5(transitive)