@unielon/wallet-connect-react
Version:
unielon wallet js sdk rom react provider、swap pools base action, base use for React
2 lines (1 loc) • 10.9 kB
JavaScript
(function(a,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("bignumber.js"),require("react"),require("react/jsx-runtime")):typeof define=="function"&&define.amd?define(["exports","bignumber.js","react","react/jsx-runtime"],i):(a=typeof globalThis<"u"?globalThis:a||self,i(a["@unielon/wallet-connect-react"]={},a.BigNumber,a.React,a.jsxRuntime))})(this,function(a,i,l,L){"use strict";var ae=Object.defineProperty;var re=(a,i,l)=>i in a?ae(a,i,{enumerable:!0,configurable:!0,writable:!0,value:l}):a[i]=l;var C=(a,i,l)=>(re(a,typeof i!="symbol"?i+"":i,l),l);class ${constructor(){C(this,"token",null);C(this,"eventSource",null);C(this,"BRIDGE_URL","https://bridge.dogeuni.com")}async getToken(o={}){const n=await fetch(`${this.BRIDGE_URL}/message`,{method:"POST",body:JSON.stringify({data:{...o}})}).then(r=>r.json()),{data:{token:s}}=n;return s}async connect({data:o,onConnect:n,onOpen:s,onError:r,onMessage:f}){const w=await this.getToken({client:"pump",...o});this.token=w,n&&n(w),this.eventSource=new EventSource(`${this.BRIDGE_URL}/connect?token=${this.token}`);const h=setTimeout(()=>{this.eventSource&&this.eventSource.close()},1e3*60);this.eventSource.onmessage=u=>{console.log("event.data::",u);try{if(u.data&&typeof u.data=="string"){const d=JSON.parse(u.data);console.log("event.data::",d),d!=null&&d.data&&(d==null?void 0:d.code)===200&&(console.log("event.data::",d.data),f(d==null?void 0:d.data))}}catch{r&&r({code:500,message:"Error parsing event data",data:null})}},this.eventSource.onerror=()=>{var u;clearTimeout(h),r&&r({code:500,message:"Error connecting to the server",data:null}),(u=this.eventSource)==null||u.close()},this.eventSource.onopen=u=>{s&&s(u),console.log("connect open::",u)}}}const M=new $,G=(e,o,n)=>e?new i(e).dividedBy(Math.pow(10,n||8)).decimalPlaces(n||8,i.ROUND_DOWN).toFormat(o||0):"",K=(e,o,n)=>e?new i(e).dividedBy(Math.pow(10,n||8)).decimalPlaces(n||8,i.ROUND_DOWN).toFormat(o||4):"",j=(e,o,n)=>{if(!e)return"0.0000";const s=new i(e).dividedBy(Math.pow(10,n||8)),r=o||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`},V=(e,o=8)=>e?new i(e).multipliedBy(Math.pow(10,o)).integerValue(i.ROUND_DOWN).toString():"",H=(e,o=8)=>e?new i(e).dividedBy(Math.pow(10,o)).toString():"0",q=(e,o=1)=>{if(!e)return"";const n=e&&e.toUpperCase().includes("(WRAPPED-")?e.split("(WRAPPED-")[0]:e;return n==="WDOGE"?o===1?"DOGE":"WDOGE":n},J=(e,o,n,s)=>+e==0||+o==0||!e||!o?"0.0000":(s=s||4,n=n||8,new i(e).multipliedBy(o).div(Math.pow(10,n)).decimalPlaces(s,i.ROUND_DOWN).toFormat()),U=(e,o)=>{let n="unconfirmed";const{tx_hash:s,block_number:r}=e,f=e[`${o}_tx_hash`],w=e[`${o}_tx_block`],h=e[`${o}_tx_block_number`];return(s||f)&&(n="pending"),w&&(h||r)&&(n="completed"),{status:n}},Y=(e,o)=>e.map(n=>({...n,...U(n,o)})),Z=e=>e?e.slice(0,6)+"..."+e.slice(-6):"",z=(e,o,n)=>e?new i(new i(e).dividedBy(Math.pow(10,n||8)).toFixed(o||8)).toFormat():"0",Q=(e,o,n)=>{if(!e)return"";n=n??1;const s=new i(e).dividedBy(Math.pow(10,o??8)),r=f=>s.div(f).decimalPlaces(n,i.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,i.ROUND_DOWN).toFormat()};function F(){const[e,o]=l.useState(0),[n,s]=l.useState(0),r="https://api.dogeuni.com",f=l.useCallback(async()=>{try{const h=await(await fetch(`${r}/v4/info/blocknumber`,{method:"POST",body:JSON.stringify({}),headers:{"Content-Type":"application/json"}})).json(),{unielon_height:u,chain_height:d}=(h==null?void 0:h.data)||{};return o(u),s(d),{unielon_height:u,chain_height:d}}catch(w){return console.error("Failed to fetch block numbers:",w),{unielon_height:null,chain_height:null}}},[]);return{uniBlock:e,dogeBlock:n,getBlockNumber:f}}function B(){const[e,o]=l.useState({low:0,hight:0,medium:0}),[n,s]=l.useState(0),r=c=>`https://api.coingecko.com/api/v3/simple/price?ids=dogecoin&vs_currencies=${c}`,f=c=>`https://min-api.cryptocompare.com/data/price?fsym=DOGE&tsyms=${c}`,w="https://api.blockcypher.com/v1/doge/main",h=async(c,m)=>{try{return await fetch(c,m||{}).then(y=>y.json())}catch(t){return t}},u=async c=>{try{const m=await h(f(c)),t=m==null?void 0:m[c];return s(t),t}catch(m){console.log(m)}},d=async c=>{c=c||"usd",c=c.toUpperCase();try{const m=await h(r(c)),{dogecoin:t}=m||{},y=t==null?void 0:t[c.toLowerCase()];return y?(s(y),y):await u(c)}catch{return u(c)}},S=async()=>{try{const m=new AbortController().signal,t=await h(w,{signal:m}),{high_fee_per_kb:y,low_fee_per_kb:b,medium_fee_per_kb:R}=t||{},p={low:b,hight:y,medium:R};return o(p),p}catch(c){console.warn(c)}};return{initPriceFee:()=>{S()},price:n,getFee:S,fee:e,getPrice:d}}function A(e,o){return I(e,o,window.localStorage)}function X(e,o){return I(e,o,window.sessionStorage)}function I(e,o,n){const[s,r]=l.useState(()=>{const w=n.getItem(e);return w!=null?JSON.parse(w):typeof o=="function"?o():o});l.useEffect(()=>{if(s===void 0)return n.removeItem(e);n.setItem(e,JSON.stringify(s))},[e,s,n]);const f=l.useCallback(()=>{r(void 0)},[]);return[s,r,f]}function x(){const e="https://ipfs.dogeuni.com",o="https://api.dogeuni.com/v4/info/ipfs/upload",n=w=>`${e}/ipfs/${w}`,[s,r]=l.useState(!1);return{upload:async(w={})=>{const{file:h}=w;if(!h||s)return;const u=new FormData;return u.append("file",h),new Promise(async(d,S)=>{try{r(!0);const g=await fetch(o,{method:"POST",body:u}).then(m=>m.json()),{hash:c}=g||{};d(n(c))}catch(g){alert("upload files size max is 1mb"),S(g)}finally{r(!1)}})},getUrl:n,loading:s}}const O=[{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$"}],P={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:O,userInfo:{}},ee=(e,o)=>{switch(o.type){case"SET_STATE":return{...e,...o.payload};default:return e}},_=async()=>{const e=typeof window<"u"&&window.unielon?window.unielon:null;if(e){const o=await e.getAccounts(),n=await e.getPublicKey(),s=await e.getBalance(),r=await e.getNetwork(),[f]=o;return console.log("💰 Wallet Account Info::Result ===",{account:o,address:f,publicKey:n,balance:s,network:r}),{account:o,address:f,publicKey:n,balance:s,network:r,dogecoinBalance:s==null?void 0:s.confirmed,connected:!!f}}else throw new Error("🐶 Unielon wallet not installed...")},N=e=>{const o=l.useRef(window==null?void 0:window.unielon).current,{sendBox:n,createSwap:s,sendDogecoin:r,sendTrade:f,sendNft:w,createLp:h,createPump:u,sendDoge:d,signPsbt:S}=o||{};function g(t){e({type:"SET_STATE",payload:t})}async function c(t,y,b){if(!(window==null?void 0:window.unielon)||!t)return null;try{g({sendLoading:!0,sendError:null});const p=await t(y,b),{code:E,msg:D,data:v}=p||{};return E!==200&&(v!=null&&v.tx_hash)&&g({sendError:D||"send transaction failed"}),p}catch(p){return g({sendError:p.message}),null}finally{g({sendLoading:!1})}}async function m(){const t=window==null?void 0:window.unielon;if(t)return await t.getBalance()}return{setState:g,getBalance:m,sendTransaction:c,networkChange:async t=>{const y=await _();g({...y,network:t})},accountChange:async()=>{const t=await _();g(t!=null&&t.address?t:P)},connect:async()=>{try{g({connectLoading:!0});const t=await o.requestAccounts(),[y]=t,b=await _();return g(b),y}finally{g({connectLoading:!1})}},disconnect:async()=>{g(P)},currencyChange:async(t,y)=>{t=t.toLowerCase(),g({currency:t,currentCurrency:O.find(b=>b.name===t.toUpperCase())}),y(t)},signMessage:async t=>await o.signMessage(t),sendInscribe:async t=>await c(r,t),sendTransfer:async t=>await c(r,t),sendExchange:async t=>await c(f,t),sendSwap:async t=>await c(s,t),sendBox:async t=>await c(n,t),sendNft:async t=>await c(w,t),sendStake:async t=>await c(h,t),sendDoge:async t=>await c(d,t),sendPump:async t=>await c(u,t),signPsbt:async(t,y)=>await S(t,y)}},k=l.createContext(P),ne=({children:e,blockRefresh:o})=>{const[n,s]=l.useReducer(ee,P),r=N(s),{uniBlock:f,dogeBlock:w,getBlockNumber:h}=F(),{price:u,fee:d,getPrice:S,initPriceFee:g,getFee:c}=B(),[m,t]=A("currency",{currency:"usd",time:new Date().getTime()}),y=l.useRef(void 0),{setState:b,accountChange:R,networkChange:p}=r,{connected:E}=n;if(typeof window>"u"||!(window!=null&&window.unielon))return L.jsx(l.Fragment,{children:e});const D=window==null?void 0:window.unielon,v=async()=>{h(),g();const T=!(typeof window>"u"||!(window!=null&&window.unielon));if(b({installed:T}),T){const W=await _(),{address:se}=W;b(se?{connected:!0,...W}:{connected:!1}),D&&D.on("accountsChanged",R),D&&D.on("networkChanged",p)}};l.useEffect(()=>{let T=null;return y.current||(y.current=!0,v(),S(m==null?void 0:m.currency),T=setInterval(()=>h(),o||1e3*60)),()=>{E&&D&&D.removeListener("accountsChanged",R),E&&D&&D.removeListener("networkChanged",p),T&&clearInterval(T)}},[]),l.useEffect(()=>{y.current&&n.currency&&n.currency!==(m==null?void 0:m.currency)&&(S(n.currency),t({currency:n.currency,time:new Date().getTime()}))},[n.currency]);const oe={...n,...r,setState:b,getBlockNumber:h,uniBlock:f,dogeBlock:w,price:u,fee:d,getFee:c,getPrice:S,initPriceFee:g};return L.jsx(k.Provider,{value:oe,children:e})},te=()=>{const e=l.useContext(k);if(!e)throw new Error("useWallet must be used within a WalletProvider");return e};a.Bridge=$,a.UnielonWalletContext=k,a.WalletProvider=ne,a.amtToFormat=z,a.amtToView=j,a.bridge=M,a.currencyList=O,a.currencyValue=J,a.decToDrc=V,a.drcToDec=G,a.drcToView=K,a.formatAddress=Z,a.formatAmount=Q,a.getOrderItemStatus=U,a.getOrderListStatus=Y,a.getTickName=q,a.getWalletInfo=_,a.initialState=P,a.useBlocknumber=F,a.useDogePrice=B,a.useLocalStorage=A,a.useSessionStorage=X,a.useUpload=x,a.useWallet=te,a.valueFormat=H,a.walletAction=N,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});