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