UNPKG

@dogeuni-org/wallet-connect-react

Version:

dogeuni wallet js sdk rom react provider、swap pools base action, base use for React

376 lines (375 loc) 14.6 kB
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 g from "bignumber.js"; import { useState as D, useCallback as B, useEffect as N, createContext as x, useRef as G, useReducer as M, useContext as K } from "react"; import { jsx as H } from "react/jsx-runtime"; class J { 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 u = await this.getToken({ client: "pump", ...n }); this.token = u, t && t(u), this.eventSource = new EventSource(`${this.BRIDGE_URL}/connect?token=${this.token}`); const w = setTimeout(() => { this.eventSource && this.eventSource.close(); }, 1e3 * 60); this.eventSource.onmessage = (i) => { console.log("event.data::", i); try { if (i.data && typeof i.data == "string") { const l = JSON.parse(i.data); console.log("event.data::", l), l != null && l.data && (l == null ? void 0 : l.code) === 200 && (console.log("event.data::", l.data), d(l == null ? void 0 : l.data)); } } catch { r && r({ code: 500, message: "Error parsing event data", data: null }); } }, this.eventSource.onerror = () => { var i; clearTimeout(w), r && r({ code: 500, message: "Error connecting to the server", data: null }), (i = this.eventSource) == null || i.close(); }, this.eventSource.onopen = (i) => { s && s(i), console.log("connect open::", i); }; } } const te = new J(), oe = (e, n, t) => e ? new g(e).dividedBy(Math.pow(10, t || 8)).decimalPlaces(t || 8, g.ROUND_DOWN).toFormat(n || 0) : "", se = (e, n, t) => e ? new g(e).dividedBy(Math.pow(10, t || 8)).decimalPlaces(t || 8, g.ROUND_DOWN).toFormat(n || 4) : "", re = (e, n, t) => { if (!e) return "0.0000"; const s = new g(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`; }, ae = (e, n = 8) => e ? new g(e).multipliedBy(Math.pow(10, n)).integerValue(g.ROUND_DOWN).toString() : "", ce = (e, n = 8) => e ? new g(e).dividedBy(Math.pow(10, n)).toString() : "0", ie = (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; }, le = (e, n, t, s) => +e == 0 || +n == 0 || !e || !n ? "0.0000" : (s = s || 4, t = t || 8, new g(e).multipliedBy(n).div(Math.pow(10, t)).decimalPlaces(s, g.ROUND_DOWN).toFormat()), Y = (e, n) => { let t = "unconfirmed"; const { tx_hash: s, block_number: r } = e, d = e[`${n}_tx_hash`], u = e[`${n}_tx_block`], w = e[`${n}_tx_block_number`]; return (s || d) && (t = "pending"), u && (w || r) && (t = "completed"), { status: t }; }, ue = (e, n) => e.map((t) => ({ ...t, ...Y(t, n) })), de = (e) => e ? e.slice(0, 6) + "..." + e.slice(-6) : "", me = (e, n, t) => e ? new g(new g(e).dividedBy(Math.pow(10, t || 8)).toFixed(n || 8)).toFormat() : "0", we = (e, n, t) => { if (!e) return ""; t = t ?? 1; const s = new g(e).dividedBy(Math.pow(10, n ?? 8)), r = (d) => s.div(d).decimalPlaces(t, g.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, g.ROUND_DOWN).toFormat(); }; function j() { const [e, n] = D(0), [t, s] = D(0), r = "https://api.dogeuni.com", d = B(async () => { try { const w = await (await fetch(`${r}/v4/info/blocknumber`, { method: "POST", body: JSON.stringify({}), headers: { "Content-Type": "application/json" } })).json(), { index_height: i, chain_height: l } = (w == null ? void 0 : w.data) || {}; return n(i), s(l), { index_height: i, chain_height: l }; } catch { return { index_height: null, chain_height: null }; } }, []); return { uniBlock: e, dogeBlock: t, getBlockNumber: d }; } function q() { const [e, n] = D({ low: 0, hight: 0, medium: 0 }), [t, s] = D(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}`, u = "https://api.dogeuni.com/v4/info/dogeprice", w = "https://api.dogeuni.com/v4/info/dogegas", i = async (a, o) => { try { return await fetch(a, o || {}).then((y) => y.json()); } catch (c) { return c; } }, l = async () => { try { const o = new AbortController().signal, c = await i(u, { signal: o, method: "POST" }), { last: y } = c || {}; return s(+y), c; } catch (a) { return a; } }, b = async (a) => { try { const o = await i(d(a)), c = o == null ? void 0 : o[a]; return s(c), c; } catch (o) { console.log(o); } }, h = async (a) => { a = a || "usd", a = a.toUpperCase(); try { const o = await i(r(a)), { dogecoin: c } = o || {}, y = c == null ? void 0 : c[a.toLowerCase()]; return y ? (s(y), y) : await b(a); } catch { return l(); } }, m = B(async () => { try { const o = new AbortController().signal, c = await i(w, { signal: o, method: "POST" }), { high_fee_per_kb: y, low_fee_per_kb: _, medium_fee_per_kb: p } = c || {}, S = { low: _, hight: y, medium: p }; return n(S), S; } catch (a) { console.warn(a); } }, []); return { getInfoPrice: l, initPriceFee: () => { m(); }, price: t, getFee: m, fee: e, getPrice: h }; } function L() { return typeof window < "u" && typeof window.localStorage < "u"; } function V(e, n) { return L() ? k(e, n, window.localStorage) : [n, () => { }, () => { }]; } function ye(e, n) { return L() ? k(e, n, window.sessionStorage) : [n, () => { }, () => { }]; } function k(e, n, t) { const [s, r] = D(() => { const u = t.getItem(e); return u != null ? JSON.parse(u) : 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 = B(() => { r(void 0); }, []); return [s, r, d]; } function fe() { const e = "https://ipfs.dogeuni.com", n = "https://api.dogeuni.com/v4/info/ipfs/upload", t = (u) => `${e}/ipfs/${u}`, [s, r] = D(!1); return { upload: async (u = {}) => { const { file: w } = u; if (!w || s) return; const i = new FormData(); return i.append("file", w), new Promise(async (l, b) => { try { r(!0); const h = await fetch(n, { method: "POST", body: i }).then((f) => f.json()), { hash: m } = h || {}; l(t(m)); } catch (h) { alert("upload files size max is 1mb"), b(h); } finally { r(!1); } }); }, getUrl: t, loading: s }; } const U = [ { 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$" } ], E = { 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: U, userInfo: {} }, Z = (e, n) => { switch (n.type) { case "SET_STATE": return { ...e, ...n.payload }; default: return e; } }, C = async () => { const e = typeof window < "u" && (window.dogeuni || window.unielon); 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 = G(typeof window < "u" && ((window == null ? void 0 : window.dogeuni) || (window == null ? void 0 : window.unielon))).current, { sendBox: t, createSwap: s, sendDogecoin: r, sendTrade: d, sendNft: u, createLp: w, createPump: i, sendDoge: l, signPsbt: b, createInvite: h } = n || {}; function m(o) { e({ type: "SET_STATE", payload: o }); } async function f(o, c, y) { if (!(typeof window < "u" && (window.dogeuni || window.unielon)) || !o) return null; try { m({ sendLoading: !0, sendError: null }); const p = await o(c, y), { code: S, msg: O, data: T } = p || {}; return S !== 200 && (T != null && T.tx_hash) && m({ sendError: O || "send transaction failed" }), p; } catch (p) { return m({ sendError: p.message }), p || null; } finally { m({ sendLoading: !1 }); } } async function a() { const o = typeof window < "u" && (window == null ? void 0 : window.unielon); if (o) return await o.getBalance(); } return { setState: m, getBalance: a, sendTransaction: f, networkChange: async (o) => { const c = await C(); m({ ...c, network: o }); }, accountChange: async () => { const o = await C(); m(o != null && o.address ? o : E); }, connect: async () => { try { m({ connectLoading: !0 }); const o = await n.requestAccounts(), [c] = o, y = await C(); return m(y), c; } finally { m({ connectLoading: !1 }); } }, disconnect: async () => { m(E); }, currencyChange: async (o, c) => { o = o.toLowerCase(), m({ currency: o, currentCurrency: U.find((y) => y.name === o.toUpperCase()) }), c(o); }, signMessage: async (o) => await n.signMessage(o), sendInscribe: async (o) => await f(r, o), sendTransfer: async (o) => await f(r, o), sendExchange: async (o) => await f(d, o), sendSwap: async (o) => await f(s, o), sendBox: async (o) => await f(t, o), sendNft: async (o) => await f(u, o), sendStake: async (o) => await f(w, o), sendDoge: async (o) => await f(l, o), sendPump: async (o) => await f(i, o), signPsbt: async (o, c) => await b(o, c), createInvite: async (o) => await f(h, o) }; }, I = x(E), ge = ({ children: e, blockRefresh: n }) => { const [t, s] = M(Z, E), r = z(s), { uniBlock: d, dogeBlock: u, getBlockNumber: w } = j(), { price: i, fee: l, getPrice: b, initPriceFee: h, getFee: m, getInfoPrice: f } = q(), [a, o] = V("currency", { currency: "usd", time: typeof window < "u" ? (/* @__PURE__ */ new Date()).getTime() : 1119109377 }), { setState: c, accountChange: y, networkChange: _ } = r, { connected: p } = t, S = B(async () => { w(), h(); const v = !!(typeof window < "u" && (window != null && window.unielon || window != null && window.dogeuni)); if (c({ installed: v }), v) { const P = (window == null ? void 0 : window.dogeuni) || (window == null ? void 0 : window.unielon), $ = await C(), { address: F } = $; c(F ? { connected: !0, ...$ } : { connected: !1 }), P.on("accountsChanged", y), P.on("networkChanged", _); } }, []); N(() => { S(); const v = setInterval(() => w(), n || 1e3 * 60); return () => { if (typeof window < "u") { const P = (window == null ? void 0 : window.unielon) || (window == null ? void 0 : window.dogeuni); p && P && P.removeListener("accountsChanged", y), p && P && P.removeListener("networkChanged", _); } v && clearInterval(v); }; }, []), N(() => { t.currency && t.currency !== (a == null ? void 0 : a.currency) && (b(t.currency), typeof window < "u" && o({ currency: t.currency, time: (/* @__PURE__ */ new Date()).getTime() })); }, [t.currency]); const O = B(() => { f(); }, [u]); N(() => { u && O(); }, [u]); const T = { ...t, ...r, setState: c, getBlockNumber: w, uniBlock: d, dogeBlock: u, price: i, fee: l, getFee: m, getPrice: b, getInfoPrice: f, initPriceFee: h }; return /* @__PURE__ */ H(I.Provider, { value: T, children: e }); }, he = () => { const e = K(I); if (!e) throw new Error("useWallet must be used within a WalletProvider"); return e; }; export { J as Bridge, I as UnielonWalletContext, ge as WalletProvider, me as amtToFormat, re as amtToView, te as bridge, U as currencyList, le as currencyValue, ae as decToDrc, oe as drcToDec, se as drcToView, de as formatAddress, we as formatAmount, Y as getOrderItemStatus, ue as getOrderListStatus, ie as getTickName, C as getWalletInfo, E as initialState, j as useBlocknumber, q as useDogePrice, V as useLocalStorage, ye as useSessionStorage, fe as useUpload, he as useWallet, ce as valueFormat, z as walletAction };