UNPKG

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