@dogeuni-org/wallet-connect-react
Version:
dogeuni wallet js sdk rom react provider、swap pools base action, base use for React
361 lines (360 loc) • 14.3 kB
JavaScript
var A = Object.defineProperty;
var W = (e, t, n) => t in e ? A(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
var R = (e, t, n) => (W(e, typeof t != "symbol" ? t + "" : t, n), n);
import f from "bignumber.js";
import { useState as _, useCallback as $, useEffect as E, createContext as x, useRef as L, useReducer as G, useContext as M } from "react";
import { jsx as K } 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(t = {}) {
const n = await fetch(`${this.BRIDGE_URL}/message`, { method: "POST", body: JSON.stringify({ data: { ...t } }) }).then((r) => r.json()), {
data: { token: s }
} = n;
return s;
}
async connect({ data: t, onConnect: n, onOpen: s, onError: r, onMessage: u }) {
const d = await this.getToken({ client: "pump", ...t });
this.token = d, n && n(d), 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), u(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 ne = new H(), te = (e, t, n) => e ? new f(e).dividedBy(Math.pow(10, n || 8)).decimalPlaces(n || 8, f.ROUND_DOWN).toFormat(t || 0) : "", oe = (e, t, n) => e ? new f(e).dividedBy(Math.pow(10, n || 8)).decimalPlaces(n || 8, f.ROUND_DOWN).toFormat(t || 4) : "", se = (e, t, n) => {
if (!e)
return "0.0000";
const s = new f(e).dividedBy(Math.pow(10, n || 8)), r = t || 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, t = 8) => e ? new f(e).multipliedBy(Math.pow(10, t)).integerValue(f.ROUND_DOWN).toString() : "", ae = (e, t = 8) => e ? new f(e).dividedBy(Math.pow(10, t)).toString() : "0", ce = (e, t = 1) => {
if (!e)
return "";
const n = e && e.toUpperCase().includes("(WRAPPED-") ? e.split("(WRAPPED-")[0] : e;
return n === "WDOGE" ? t === 1 ? "DOGE" : "WDOGE" : n;
}, ie = (e, t, n, s) => +e == 0 || +t == 0 || !e || !t ? "0.0000" : (s = s || 4, n = n || 8, new f(e).multipliedBy(t).div(Math.pow(10, n)).decimalPlaces(s, f.ROUND_DOWN).toFormat()), J = (e, t) => {
let n = "unconfirmed";
const { tx_hash: s, block_number: r } = e, u = e[`${t}_tx_hash`], d = e[`${t}_tx_block`], w = e[`${t}_tx_block_number`];
return (s || u) && (n = "pending"), d && (w || r) && (n = "completed"), { status: n };
}, le = (e, t) => e.map((n) => ({ ...n, ...J(n, t) })), ue = (e) => e ? e.slice(0, 6) + "..." + e.slice(-6) : "", de = (e, t, n) => e ? new f(new f(e).dividedBy(Math.pow(10, n || 8)).toFixed(t || 8)).toFormat() : "0", me = (e, t, n) => {
if (!e)
return "";
n = n ?? 1;
const s = new f(e).dividedBy(Math.pow(10, t ?? 8)), r = (u) => s.div(u).decimalPlaces(n, 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(n, f.ROUND_DOWN).toFormat();
};
function V() {
const [e, t] = _(0), [n, s] = _(0), r = "https://api.dogeuni.com", u = $(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 t(i), s(l), { index_height: i, chain_height: l };
} catch {
return { index_height: null, chain_height: null };
}
}, []);
return { uniBlock: e, dogeBlock: n, getBlockNumber: u };
}
function Y() {
const [e, t] = _({ low: 0, hight: 0, medium: 0 }), [n, s] = _(0), r = (a) => `https://api.coingecko.com/api/v3/simple/price?ids=dogecoin&vs_currencies=${a}`, u = (a) => `https://min-api.cryptocompare.com/data/price?fsym=DOGE&tsyms=${a}`, d = "https://api.dogeuni.com/v4/info/dogeprice", w = "https://api.blockcypher.com/v1/doge/main", 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(d, { signal: o, method: "POST" });
console.log("data::", c);
const { last: y } = c || {};
return s(+y), c;
} catch (a) {
console.log(a);
}
}, b = async (a) => {
try {
const o = await i(u(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 = async () => {
try {
const o = new AbortController().signal, c = await i(w, { signal: o }), { high_fee_per_kb: y, low_fee_per_kb: T, medium_fee_per_kb: p } = c || {}, P = { low: T, hight: y, medium: p };
return t(P), P;
} catch (a) {
console.warn(a);
}
};
return { getInfoPrice: l, initPriceFee: () => {
m();
}, price: n, getFee: m, fee: e, getPrice: h };
}
function j(e, t) {
return k(e, t, window.localStorage);
}
function ye(e, t) {
return k(e, t, window.sessionStorage);
}
function k(e, t, n) {
const [s, r] = _(() => {
const d = n.getItem(e);
return d != null ? JSON.parse(d) : typeof t == "function" ? t() : t;
});
E(() => {
if (s === void 0)
return n.removeItem(e);
n.setItem(e, JSON.stringify(s));
}, [e, s, n]);
const u = $(() => {
r(void 0);
}, []);
return [s, r, u];
}
function we() {
const e = "https://ipfs.dogeuni.com", t = "https://api.dogeuni.com/v4/info/ipfs/upload", n = (d) => `${e}/ipfs/${d}`, [s, r] = _(!1);
return { upload: async (d = {}) => {
const { file: w } = d;
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(t, {
method: "POST",
body: i
}).then((g) => g.json()), { hash: m } = h || {};
l(n(m));
} catch (h) {
alert("upload files size max is 1mb"), b(h);
} finally {
r(!1);
}
});
}, getUrl: n, 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$" }
], C = {
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: {}
}, q = (e, t) => {
switch (t.type) {
case "SET_STATE":
return {
...e,
...t.payload
};
default:
return e;
}
}, B = async () => {
const e = typeof window < "u" && (window.dogeuni || window.unielon);
if (e) {
const t = await e.getAccounts(), n = await e.getPublicKey(), s = await e.getBalance(), r = await e.getNetwork(), [u] = t;
return console.log("💰 Wallet Account Info::Result ===", { account: t, address: u, publicKey: n, balance: s, network: r }), { account: t, address: u, publicKey: n, balance: s, network: r, dogecoinBalance: s == null ? void 0 : s.confirmed, connected: !!u };
} else
throw new Error("🐶 Unielon wallet not installed...");
}, Z = (e) => {
const t = L((window == null ? void 0 : window.dogeuni) || (window == null ? void 0 : window.unielon)).current, { sendBox: n, createSwap: s, sendDogecoin: r, sendTrade: u, sendNft: d, createLp: w, createPump: i, sendDoge: l, signPsbt: b, createInvite: h } = t || {};
function m(o) {
e({
type: "SET_STATE",
payload: o
});
}
async function g(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: P, msg: N, data: v } = p || {};
return P !== 200 && (v != null && v.tx_hash) && m({ sendError: N || "send transaction failed" }), p;
} catch (p) {
return m({
sendError: p.message
}), p || null;
} finally {
m({ sendLoading: !1 });
}
}
async function a() {
const o = window == null ? void 0 : window.unielon;
if (o)
return await o.getBalance();
}
return {
setState: m,
getBalance: a,
sendTransaction: g,
networkChange: async (o) => {
const c = await B();
m({ ...c, network: o });
},
accountChange: async () => {
const o = await B();
m(o != null && o.address ? o : C);
},
connect: async () => {
try {
m({ connectLoading: !0 });
const o = await t.requestAccounts(), [c] = o, y = await B();
return m(y), c;
} finally {
m({ connectLoading: !1 });
}
},
disconnect: async () => {
m(C);
},
currencyChange: async (o, c) => {
o = o.toLowerCase(), m({ currency: o, currentCurrency: U.find((y) => y.name === o.toUpperCase()) }), c(o);
},
signMessage: async (o) => await t.signMessage(o),
sendInscribe: async (o) => await g(r, o),
sendTransfer: async (o) => await g(r, o),
sendExchange: async (o) => await g(u, o),
sendSwap: async (o) => await g(s, o),
sendBox: async (o) => await g(n, o),
sendNft: async (o) => await g(d, o),
sendStake: async (o) => await g(w, o),
sendDoge: async (o) => await g(l, o),
sendPump: async (o) => await g(i, o),
signPsbt: async (o, c) => await b(o, c),
createInvite: async (o) => await g(h, o)
};
}, I = x(C), ge = ({ children: e, blockRefresh: t }) => {
const [n, s] = G(q, C), r = Z(s), { uniBlock: u, dogeBlock: d, getBlockNumber: w } = V(), { price: i, fee: l, getPrice: b, initPriceFee: h, getFee: m, getInfoPrice: g } = Y(), [a, o] = j("currency", { currency: "usd", time: (/* @__PURE__ */ new Date()).getTime() }), c = L(void 0), { setState: y, accountChange: T, networkChange: p } = r, { connected: P } = n, N = async () => {
w(), h();
const D = !!(typeof window < "u" && (window != null && window.unielon || window != null && window.dogeuni));
if (y({ installed: D }), D) {
const S = (window == null ? void 0 : window.unielon) || (window == null ? void 0 : window.dogeuni), O = await B(), { address: F } = O;
y(F ? { connected: !0, ...O } : { connected: !1 }), S.on("accountsChanged", T), S.on("networkChanged", p);
}
};
E(() => {
let D = null;
return c.current || (b(n.currency), N(), D = setInterval(() => w(), t || 1e3 * 60), c.current = !0), () => {
const S = (window == null ? void 0 : window.unielon) || (window == null ? void 0 : window.dogeuni);
P && S && S.removeListener("accountsChanged", T), P && S && S.removeListener("networkChanged", p), D && clearInterval(D);
};
}, []), E(() => {
console.log("currency changed::", a), n.currency && n.currency !== (a == null ? void 0 : a.currency) && (b(n.currency), o({ currency: n.currency, time: (/* @__PURE__ */ new Date()).getTime() }));
}, [n.currency]);
const v = { ...n, ...r, setState: y, getBlockNumber: w, uniBlock: u, dogeBlock: d, price: i, fee: l, getFee: m, getPrice: b, getInfoPrice: g, initPriceFee: h };
return /* @__PURE__ */ K(I.Provider, { value: v, children: e });
}, fe = () => {
const e = M(I);
if (!e)
throw new Error("useWallet must be used within a WalletProvider");
return e;
};
export {
H as Bridge,
I as UnielonWalletContext,
ge as WalletProvider,
de as amtToFormat,
se as amtToView,
ne as bridge,
U 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,
C as initialState,
V as useBlocknumber,
Y as useDogePrice,
j as useLocalStorage,
ye as useSessionStorage,
we as useUpload,
fe as useWallet,
ae as valueFormat,
Z as walletAction
};