@unielon/wallet-connect-react
Version:
unielon wallet js sdk rom react provider、swap pools base action, base use for React
353 lines (352 loc) • 13.9 kB
JavaScript
var A = Object.defineProperty;
var W = (e, n, t) => n in e ? A(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
var R = (e, n, t) => (W(e, typeof n != "symbol" ? n + "" : n, t), t);
import f from "bignumber.js";
import { useState as S, useCallback as O, useEffect as N, createContext as x, useRef as $, useReducer as G, Fragment as M, useContext as K } from "react";
import { jsx as C } from "react/jsx-runtime";
class H {
constructor() {
R(this, "token", null);
R(this, "eventSource", null);
R(this, "BRIDGE_URL", "https://bridge.dogeuni.com");
}
async getToken(n = {}) {
const t = await fetch(`${this.BRIDGE_URL}/message`, { method: "POST", body: JSON.stringify({ data: { ...n } }) }).then((r) => r.json()), {
data: { token: s }
} = t;
return s;
}
async connect({ data: n, onConnect: t, onOpen: s, onError: r, onMessage: d }) {
const m = await this.getToken({ client: "pump", ...n });
this.token = m, t && t(m), this.eventSource = new EventSource(`${this.BRIDGE_URL}/connect?token=${this.token}`);
const y = setTimeout(() => {
this.eventSource && this.eventSource.close();
}, 1e3 * 60);
this.eventSource.onmessage = (c) => {
console.log("event.data::", c);
try {
if (c.data && typeof c.data == "string") {
const i = JSON.parse(c.data);
console.log("event.data::", i), i != null && i.data && (i == null ? void 0 : i.code) === 200 && (console.log("event.data::", i.data), d(i == null ? void 0 : i.data));
}
} catch {
r && r({ code: 500, message: "Error parsing event data", data: null });
}
}, this.eventSource.onerror = () => {
var c;
clearTimeout(y), r && r({ code: 500, message: "Error connecting to the server", data: null }), (c = this.eventSource) == null || c.close();
}, this.eventSource.onopen = (c) => {
s && s(c), console.log("connect open::", c);
};
}
}
const ne = new H(), te = (e, n, t) => e ? new f(e).dividedBy(Math.pow(10, t || 8)).decimalPlaces(t || 8, f.ROUND_DOWN).toFormat(n || 0) : "", oe = (e, n, t) => e ? new f(e).dividedBy(Math.pow(10, t || 8)).decimalPlaces(t || 8, f.ROUND_DOWN).toFormat(n || 4) : "", se = (e, n, t) => {
if (!e)
return "0.0000";
const s = new f(e).dividedBy(Math.pow(10, t || 8)), r = n || 4;
return s.isLessThan(1e3) ? s.toFormat() : s.isLessThan(1e6) ? `${s.dividedBy(1e3).toFormat(r)}K` : s.isLessThan(1e9) ? `${s.dividedBy(1e6).toFormat(r)}M` : s.isLessThan(1e12) ? `${s.dividedBy(1e9).toFormat(r)}B` : `${s.dividedBy(1e12).toFormat(r)}T`;
}, re = (e, n = 8) => e ? new f(e).multipliedBy(Math.pow(10, n)).integerValue(f.ROUND_DOWN).toString() : "", ae = (e, n = 8) => e ? new f(e).dividedBy(Math.pow(10, n)).toString() : "0", ce = (e, n = 1) => {
if (!e)
return "";
const t = e && e.toUpperCase().includes("(WRAPPED-") ? e.split("(WRAPPED-")[0] : e;
return t === "WDOGE" ? n === 1 ? "DOGE" : "WDOGE" : t;
}, ie = (e, n, t, s) => +e == 0 || +n == 0 || !e || !n ? "0.0000" : (s = s || 4, t = t || 8, new f(e).multipliedBy(n).div(Math.pow(10, t)).decimalPlaces(s, f.ROUND_DOWN).toFormat()), J = (e, n) => {
let t = "unconfirmed";
const { tx_hash: s, block_number: r } = e, d = e[`${n}_tx_hash`], m = e[`${n}_tx_block`], y = e[`${n}_tx_block_number`];
return (s || d) && (t = "pending"), m && (y || r) && (t = "completed"), { status: t };
}, le = (e, n) => e.map((t) => ({ ...t, ...J(t, n) })), ue = (e) => e ? e.slice(0, 6) + "..." + e.slice(-6) : "", de = (e, n, t) => e ? new f(new f(e).dividedBy(Math.pow(10, t || 8)).toFixed(n || 8)).toFormat() : "0", me = (e, n, t) => {
if (!e)
return "";
t = t ?? 1;
const s = new f(e).dividedBy(Math.pow(10, n ?? 8)), r = (d) => s.div(d).decimalPlaces(t, f.ROUND_DOWN).toFormat();
return s.isGreaterThanOrEqualTo(1e9) ? `${r(1e9)}B` : s.isGreaterThanOrEqualTo(1e6) ? `${r(1e6)}M` : s.isGreaterThanOrEqualTo(1e3) ? `${r(1e3)}K` : s.decimalPlaces(t, f.ROUND_DOWN).toFormat();
};
function V() {
const [e, n] = S(0), [t, s] = S(0), r = "https://api.dogeuni.com", d = O(async () => {
try {
const y = await (await fetch(`${r}/v4/info/blocknumber`, { method: "POST", body: JSON.stringify({}), headers: { "Content-Type": "application/json" } })).json(), { unielon_height: c, chain_height: i } = (y == null ? void 0 : y.data) || {};
return n(c), s(i), { unielon_height: c, chain_height: i };
} catch (m) {
return console.error("Failed to fetch block numbers:", m), { unielon_height: null, chain_height: null };
}
}, []);
return { uniBlock: e, dogeBlock: t, getBlockNumber: d };
}
function Y() {
const [e, n] = S({ low: 0, hight: 0, medium: 0 }), [t, s] = S(0), r = (a) => `https://api.coingecko.com/api/v3/simple/price?ids=dogecoin&vs_currencies=${a}`, d = (a) => `https://min-api.cryptocompare.com/data/price?fsym=DOGE&tsyms=${a}`, m = "https://api.blockcypher.com/v1/doge/main", y = async (a, l) => {
try {
return await fetch(a, l || {}).then((u) => u.json());
} catch (o) {
return o;
}
}, c = async (a) => {
try {
const l = await y(d(a)), o = l == null ? void 0 : l[a];
return s(o), o;
} catch (l) {
console.log(l);
}
}, i = async (a) => {
a = a || "usd", a = a.toUpperCase();
try {
const l = await y(r(a)), { dogecoin: o } = l || {}, u = o == null ? void 0 : o[a.toLowerCase()];
return u ? (s(u), u) : await c(a);
} catch {
return c(a);
}
}, h = async () => {
try {
const l = new AbortController().signal, o = await y(m, { signal: l }), { high_fee_per_kb: u, low_fee_per_kb: g, medium_fee_per_kb: P } = o || {}, p = { low: g, hight: u, medium: P };
return n(p), p;
} catch (a) {
console.warn(a);
}
};
return { initPriceFee: () => {
h();
}, price: t, getFee: h, fee: e, getPrice: i };
}
function j(e, n) {
return k(e, n, window.localStorage);
}
function ye(e, n) {
return k(e, n, window.sessionStorage);
}
function k(e, n, t) {
const [s, r] = S(() => {
const m = t.getItem(e);
return m != null ? JSON.parse(m) : typeof n == "function" ? n() : n;
});
N(() => {
if (s === void 0)
return t.removeItem(e);
t.setItem(e, JSON.stringify(s));
}, [e, s, t]);
const d = O(() => {
r(void 0);
}, []);
return [s, r, d];
}
function we() {
const e = "https://ipfs.dogeuni.com", n = "https://api.dogeuni.com/v4/info/ipfs/upload", t = (m) => `${e}/ipfs/${m}`, [s, r] = S(!1);
return { upload: async (m = {}) => {
const { file: y } = m;
if (!y || s)
return;
const c = new FormData();
return c.append("file", y), new Promise(async (i, h) => {
try {
r(!0);
const w = await fetch(n, {
method: "POST",
body: c
}).then((l) => l.json()), { hash: a } = w || {};
i(t(a));
} catch (w) {
alert("upload files size max is 1mb"), h(w);
} finally {
r(!1);
}
});
}, getUrl: t, loading: s };
}
const L = [
{ name: "USD", symbol: "$" },
{ name: "CNY", symbol: "¥" },
{ name: "JPY", symbol: "¥" },
{ name: "KRW", symbol: "₩" },
{ name: "EUR", symbol: "€" },
{ name: "GBP", symbol: "£" },
{ name: "RUB", symbol: "₽" },
{ name: "TRY", symbol: "₺" },
{ name: "VND", symbol: "₫" },
{ name: "IDR", symbol: "Rp" },
{ name: "PHP", symbol: "₱" },
{ name: "INR", symbol: "₹" },
{ name: "ARS", symbol: "$" },
{ name: "SAR", symbol: "﷼" },
{ name: "AED", symbol: "د.إ" },
{ name: "IQD", symbol: "ع.د" },
{ name: "BND", symbol: "$" },
{ name: "LAK", symbol: "₭" },
{ name: "NPR", symbol: "₨" },
{ name: "PKR", symbol: "₨" },
{ name: "SGD", symbol: "$" },
{ name: "MMK", symbol: "K" },
{ name: "MNT", symbol: "₮" },
{ name: "COP", symbol: "$" },
{ name: "CLP", symbol: "$" },
{ name: "VES", symbol: "Bs." },
{ name: "MXN", symbol: "$" },
{ name: "BRL", symbol: "R$" },
{ name: "PEN", symbol: "S/." },
{ name: "HNL", symbol: "L" },
{ name: "UYU", symbol: "$" },
{ name: "CHF", symbol: "CHF" },
{ name: "UAH", symbol: "₴" },
{ name: "AUD", symbol: "$" },
{ name: "NZD", symbol: "$" },
{ name: "CAD", symbol: "$" },
{ name: "ZAR", symbol: "R" },
{ name: "ILS", symbol: "₪" },
{ name: "TWD", symbol: "NT$" },
{ name: "HKD", symbol: "HK$" }
], v = {
address: null,
balance: {
confirmed: null,
unconfirmed: null,
total: null
},
installed: !1,
network: null,
account: [],
sendLoading: !1,
connectLoading: !1,
sendError: null,
connected: !1,
publicKey: null,
currency: "usd",
currentCurrency: { name: "USD", symbol: "$" },
currencyList: L,
userInfo: {}
}, q = (e, n) => {
switch (n.type) {
case "SET_STATE":
return {
...e,
...n.payload
};
default:
return e;
}
}, B = async () => {
const e = typeof window < "u" && window.unielon ? window.unielon : null;
if (e) {
const n = await e.getAccounts(), t = await e.getPublicKey(), s = await e.getBalance(), r = await e.getNetwork(), [d] = n;
return console.log("💰 Wallet Account Info::Result ===", { account: n, address: d, publicKey: t, balance: s, network: r }), { account: n, address: d, publicKey: t, balance: s, network: r, dogecoinBalance: s == null ? void 0 : s.confirmed, connected: !!d };
} else
throw new Error("🐶 Unielon wallet not installed...");
}, Z = (e) => {
const n = $(window == null ? void 0 : window.unielon).current, { sendBox: t, createSwap: s, sendDogecoin: r, sendTrade: d, sendNft: m, createLp: y, createPump: c, sendDoge: i, signPsbt: h } = n || {};
function w(o) {
e({
type: "SET_STATE",
payload: o
});
}
async function a(o, u, g) {
if (!(window == null ? void 0 : window.unielon) || !o)
return null;
try {
w({ sendLoading: !0, sendError: null });
const p = await o(u, g), { code: T, msg: b, data: _ } = p || {};
return T !== 200 && (_ != null && _.tx_hash) && w({ sendError: b || "send transaction failed" }), p;
} catch (p) {
return w({
sendError: p.message
}), null;
} finally {
w({ sendLoading: !1 });
}
}
async function l() {
const o = window == null ? void 0 : window.unielon;
if (o)
return await o.getBalance();
}
return {
setState: w,
getBalance: l,
sendTransaction: a,
networkChange: async (o) => {
const u = await B();
w({ ...u, network: o });
},
accountChange: async () => {
const o = await B();
w(o != null && o.address ? o : v);
},
connect: async () => {
try {
w({ connectLoading: !0 });
const o = await n.requestAccounts(), [u] = o, g = await B();
return w(g), u;
} finally {
w({ connectLoading: !1 });
}
},
disconnect: async () => {
w(v);
},
currencyChange: async (o, u) => {
o = o.toLowerCase(), w({ currency: o, currentCurrency: L.find((g) => g.name === o.toUpperCase()) }), u(o);
},
signMessage: async (o) => await n.signMessage(o),
sendInscribe: async (o) => await a(r, o),
sendTransfer: async (o) => await a(r, o),
sendExchange: async (o) => await a(d, o),
sendSwap: async (o) => await a(s, o),
sendBox: async (o) => await a(t, o),
sendNft: async (o) => await a(m, o),
sendStake: async (o) => await a(y, o),
sendDoge: async (o) => await a(i, o),
sendPump: async (o) => await a(c, o),
signPsbt: async (o, u) => await h(o, u)
};
}, U = x(v), fe = ({ children: e, blockRefresh: n }) => {
const [t, s] = G(q, v), r = Z(s), { uniBlock: d, dogeBlock: m, getBlockNumber: y } = V(), { price: c, fee: i, getPrice: h, initPriceFee: w, getFee: a } = Y(), [l, o] = j("currency", { currency: "usd", time: (/* @__PURE__ */ new Date()).getTime() }), u = $(void 0), { setState: g, accountChange: P, networkChange: p } = r, { connected: T } = t;
if (typeof window > "u" || !(window != null && window.unielon))
return /* @__PURE__ */ C(M, { children: e });
const b = window == null ? void 0 : window.unielon, _ = async () => {
y(), w();
const D = !(typeof window > "u" || !(window != null && window.unielon));
if (g({ installed: D }), D) {
const E = await B(), { address: I } = E;
g(I ? { connected: !0, ...E } : { connected: !1 }), b && b.on("accountsChanged", P), b && b.on("networkChanged", p);
}
};
N(() => {
let D = null;
return u.current || (u.current = !0, _(), h(l == null ? void 0 : l.currency), D = setInterval(() => y(), n || 1e3 * 60)), () => {
T && b && b.removeListener("accountsChanged", P), T && b && b.removeListener("networkChanged", p), D && clearInterval(D);
};
}, []), N(() => {
u.current && t.currency && t.currency !== (l == null ? void 0 : l.currency) && (h(t.currency), o({ currency: t.currency, time: (/* @__PURE__ */ new Date()).getTime() }));
}, [t.currency]);
const F = { ...t, ...r, setState: g, getBlockNumber: y, uniBlock: d, dogeBlock: m, price: c, fee: i, getFee: a, getPrice: h, initPriceFee: w };
return /* @__PURE__ */ C(U.Provider, { value: F, children: e });
}, ge = () => {
const e = K(U);
if (!e)
throw new Error("useWallet must be used within a WalletProvider");
return e;
};
export {
H as Bridge,
U as UnielonWalletContext,
fe as WalletProvider,
de as amtToFormat,
se as amtToView,
ne as bridge,
L as currencyList,
ie as currencyValue,
re as decToDrc,
te as drcToDec,
oe as drcToView,
ue as formatAddress,
me as formatAmount,
J as getOrderItemStatus,
le as getOrderListStatus,
ce as getTickName,
B as getWalletInfo,
v as initialState,
V as useBlocknumber,
Y as useDogePrice,
j as useLocalStorage,
ye as useSessionStorage,
we as useUpload,
ge as useWallet,
ae as valueFormat,
Z as walletAction
};