diff --git a/CHANGELOG.md b/CHANGELOG.md index 3215413..83d779d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +### [0.8.2](https://github.com/juliancwirko/elven.js/releases/tag/v0.8.2) (2023-03-05) +- fix browser extension signing states + ### [0.8.1](https://github.com/juliancwirko/elven.js/releases/tag/v0.8.1) (2023-03-02) - minor improvements in the code and demo diff --git a/build/elven.js b/build/elven.js index 39598ff..ac4520c 100644 --- a/build/elven.js +++ b/build/elven.js @@ -33,7 +33,7 @@ Make sure your charset is UTF-8`);t=(t>>>8&255)*192+(t&255),r.put(t,13)}};L6.exp The chosen QR Code version cannot contain this amount of data. Minimum version required to store current data is: `+s+`. `);let o=CK(e,t,n),a=Gp.getSymbolSize(e),u=new pK(a);return EK(u,e),AK(u),IK(u,e),lE(u,t,0),e>=7&&_K(u,e),bK(u,o),isNaN(i)&&(i=fE.getBestMask(u,lE.bind(null,u,t))),fE.applyMask(i,u),lE(u,t,i),{modules:u,version:e,errorCorrectionLevel:t,maskPattern:i,segments:n}}k6.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let i=uE.M,n,s;return typeof t<"u"&&(i=uE.from(t.errorCorrectionLevel,uE.M),n=jp.from(t.version),s=fE.from(t.maskPattern),t.toSJISFunc&&Gp.setToSJISFunction(t.toSJISFunc)),xK(e,n,i,s)}});var dE=B(Io=>{f();function $6(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let e=r.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+r);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(i){return[i,i]}))),e.length===6&&e.push("F","F");let t=parseInt(e.join(""),16);return{r:t>>24&255,g:t>>16&255,b:t>>8&255,a:t&255,hex:"#"+e.slice(0,6).join("")}}Io.getOptions=function(e){e||(e={}),e.color||(e.color={});let t=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,i=e.width&&e.width>=21?e.width:void 0,n=e.scale||4;return{width:i,scale:i?4:n,margin:t,color:{dark:$6(e.color.dark||"#000000ff"),light:$6(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Io.getScale=function(e,t){return t.width&&t.width>=e+t.margin*2?t.width/(e+t.margin*2):t.scale};Io.getImageWidth=function(e,t){let i=Io.getScale(e,t);return Math.floor((e+t.margin*2)*i)};Io.qrToImageData=function(e,t,i){let n=t.modules.size,s=t.modules.data,o=Io.getScale(n,i),a=Math.floor((n+i.margin*2)*o),u=i.margin*o,h=[i.color.light,i.color.dark];for(let p=0;p=u&&w>=u&&p{f();var pE=dE();function TK(r,e,t){r.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=t,e.width=t,e.style.height=t+"px",e.style.width=t+"px"}function NK(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Kp.render=function(e,t,i){let n=i,s=t;typeof n>"u"&&(!t||!t.getContext)&&(n=t,t=void 0),t||(s=NK()),n=pE.getOptions(n);let o=pE.getImageWidth(e.modules.size,n),a=s.getContext("2d"),u=a.createImageData(o,o);return pE.qrToImageData(u.data,e,n),TK(a,s,o),a.putImageData(u,0,0),s};Kp.renderToDataURL=function(e,t,i){let n=i;typeof n>"u"&&(!t||!t.getContext)&&(n=t,t=void 0),n||(n={});let s=Kp.render(e,t,n),o=n.type||"image/png",a=n.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Z6=B(X6=>{f();var DK=dE();function J6(r,e){let t=r.a/255,i=e+'="'+r.hex+'"';return t<1?i+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':i}function gE(r,e,t){let i=r+e;return typeof t<"u"&&(i+=" "+t),i}function OK(r,e,t){let i="",n=0,s=!1,o=0;for(let a=0;a0&&u>0&&r[a-1]||(i+=s?gE("M",u+t,.5+h+t):gE("m",n,0),n=0,s=!1),u+1':"",h="',p='viewBox="0 0 '+a+" "+a+'"',N=''+u+h+` -`;return typeof i=="function"&&i(null,N),N}});var t8=B(Bl=>{f();var PK=t6(),yE=W6(),e8=Y6(),BK=Z6();function mE(r,e,t,i,n){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!PK())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(n=t,t=e,e=i=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=i,i=void 0):(n=i,i=t,t=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(t=e,e=i=void 0):o===2&&!e.getContext&&(i=t,t=e,e=void 0),new Promise(function(u,h){try{let p=yE.create(t,i);u(r(p,e,i))}catch(p){h(p)}})}try{let u=yE.create(t,i);n(null,r(u,e,i))}catch(u){n(u)}}Bl.create=yE.create;Bl.toCanvas=mE.bind(null,e8.render);Bl.toDataURL=mE.bind(null,e8.renderToDataURL);Bl.toString=mE.bind(null,function(r,e,t){return BK.render(r,t)})});var d8=B(as=>{"use strict";f();var KK=as&&as.__createBinding||(Object.create?function(r,e,t,i){i===void 0&&(i=t),Object.defineProperty(r,i,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}),h8=as&&as.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&KK(e,r,t)};Object.defineProperty(as,"__esModule",{value:!0});h8(vl(),as);h8(Uv(),as)});f();var zK=_e(og()),v8=_e($I()),kK=_e(Gr()),WK=_e(zf()),$K=_e(jy()),YK=_e(sc()),JK=_e(Wy()),XK=_e(wn()),E8=_e(ic()),ZK=_e(ec()),ez=_e(cy()),tz=_e(Yb()),rz=_e(Ko());f();f();var nC=_e(Zy());f();f();var nh="elvenjs_state",tC="https://devnet-api.multiversx.com";var sh="/dapp/init",oh="devnet",rC="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",iC=["wss://relay.walletconnect.com"],xi={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var Ne={get(r){let e=localStorage.getItem(nh);if(!e)return{};let t=JSON.parse(e);return r?t[r]:t},set(r,e){let t=this.get();t[r]=e,localStorage.setItem(nh,JSON.stringify(t))},clear(){localStorage.removeItem(nh)}};var ah=()=>Te(void 0,null,function*(){let r=nC.ExtensionProvider.getInstance();try{let e=yield r.init(),t=Ne.get();if(t!=null&&t.address&&r.setAddress(t.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return r}catch(e){console.warn("Can't initialize the Dapp Provider!")}});var y8=_e(Zy()),m8=_e(dl()),w8=_e(vl());f();var bO=_e(dl());f();f();var De=class{static set(e,t){if(!e)return;let i=OE(bo({},this.events),{[e]:t});this.events=i}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...t){var i,n;!e||!this.events||(n=(i=this.events)[e])==null||n.call(i,...t)}static clear(){this.events=void 0}};f();var mo=(n=>(n.ledger="ledger",n.mobile="mobile",n.webWallet="web-wallet",n.browserExtension="browser-extension",n))(mo||{});var Pu=r=>Te(void 0,null,function*(){if(!r.dappProvider)throw new Error("Error: Logout failed: There is no active session!");De.run("onLoginPending");let e=yield r.dappProvider.logout();return e&&(Ne.clear(),De.run("onLogout")),e});f();var IO=_e(Gr()),_O=_e(zf());f();var Xt=r=>typeof r=="string"?r.toUpperCase():r instanceof Error?r.message:`Error: ${JSON.stringify(r)}`;f();var Bu=()=>new Date().setHours(new Date().getHours()+24),bp=r=>Date.now()>r;var ts=r=>Te(void 0,null,function*(){let e=Ne.get("address"),t=Ne.get("expires");if(!(t&&bp(t))&&e&&r.networkProvider){let n=new IO.Address(e),s=new _O.Account(n);try{let o=yield r.networkProvider.getAccount(n);Ne.set("address",e),Ne.set("nonce",o.nonce.valueOf()),Ne.set("balance",o.balance.toString()),s.update(o)}catch(o){let a=Xt(o);console.warn(`Something went wrong trying to synchronize the user account: ${a}`)}}});f();function Cp(r){return r[Math.floor(Math.random()*r.length)]}var CO=r=>Te(void 0,null,function*(){if(!r.initOptions.walletConnectV2ProjectId||!r.initOptions.chainType)return;let e={onClientLogin:()=>{ts(r),De.run("onLoggedIn")},onClientLogout:()=>Pu(r),onClientEvent:n=>{console.log("wc2 session event: ",n)}},t=Cp(r.initOptions.walletConnectV2RelayAddresses),i=new bO.WalletConnectV2Provider(e,xi[r.initOptions.chainType].shortId,t,r.initOptions.walletConnectV2ProjectId);try{return yield i.init(),i}catch(n){console.warn("Can't initialize the Dapp Provider!")}});f();var KO=_e(TO()),Bp=_e(Gr()),zO=_e(NO()),kO=_e(MO()),WO=_e(zv()),$O=_e(VO()),YO=_e(QO()),JO=_e(jO()),XO=_e(GO());var Mp=class{constructor({apiUrl:e,chainType:t,apiTimeout:i}){var n,s;this.chainType=t||oh,this.apiUrl=e||((n=xi[this.chainType])==null?void 0:n.apiAddress),this.apiTimeout=i||((s=xi[this.chainType])==null?void 0:s.apiTimeout)}apiGet(e,t){return Te(this,null,function*(){if(typeof fetch!="undefined"){let i=new AbortController,n=setTimeout(()=>i.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:i.signal};try{let o=yield fetch(this.apiUrl+"/"+e,Object.assign(s,t||{})),a=yield o.json();if(!o.ok){let u=(a==null?void 0:a.error)||o.status;return clearTimeout(n),Promise.reject(u)}return clearTimeout(n),a}catch(o){this.handleApiError(o,e)}}})}apiPost(e,t,i){return Te(this,null,function*(){if(typeof fetch!="undefined"){let n=new AbortController,s=setTimeout(()=>n.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t||{}),signal:n.signal};try{let a=yield fetch(this.apiUrl+"/"+e,Object.assign(o,i||{})),u=yield a.json();if(!a.ok){let h=(u==null?void 0:u.error)||a.status;return clearTimeout(s),Promise.reject(h)}return clearTimeout(s),u}catch(a){this.handleApiError(a,e)}}})}handleApiError(e,t){if(!e.response)throw new Error(`Request error on url [${t}]: [${e.toString()}]`);let i=e.response.data,n=i.error||i.message||JSON.stringify(i);throw new Error(n)}sendTransaction(e){return Te(this,null,function*(){return(yield this.apiPost("transactions",e.toSendable())).txHash})}getAccount(e){return Te(this,null,function*(){let t=yield this.apiGet(`accounts/${e.bech32()}`);return{address:new Bp.Address((t==null?void 0:t.address)||""),nonce:Number((t==null?void 0:t.nonce)||0),balance:new KO.default((t==null?void 0:t.balance)||0),code:(t==null?void 0:t.code)||"",userName:(t==null?void 0:t.username)||""}})}getTransaction(e){return Te(this,null,function*(){let t=yield this.apiGet(`transactions/${e}`),i=new zO.TransactionStatus(t.status);return{hash:e,type:t.type||"",nonce:t.nonce||0,round:t.round,epoch:t.epoch||0,value:(t.value||0).toString(),sender:new Bp.Address(t.sender),receiver:new Bp.Address(t.receiver),gasPrice:t.gasPrice||0,gasLimit:t.gasLimit||0,data:y.Buffer.from(t.data||"","base64"),status:i,timestamp:t.timestamp||0,blockNonce:t.blockNonce||0,hyperblockNonce:t.hyperblockNonce||0,hyperblockHash:t.hyperblockHash||"",receipt:kO.TransactionReceipt.fromHttpResponse(t.receipt||{}),logs:WO.TransactionLogs.fromHttpResponse(t.logs||{}),contractResults:$O.ContractResults.fromApiHttpResponse(t.results||[]),isCompleted:!i.isPending()}})}queryContract(o){return Te(this,arguments,function*({address:e,func:t,args:i,value:n,caller:s}){try{let a=new XO.Query({address:e,func:t,args:i,value:n,caller:s}),u=new JO.ContractQueryRequest(a).toHttpRequest(),h=yield this.apiPost("query",u);return YO.ContractQueryResponse.fromHttpResponse(h)}catch(a){this.handleApiError(a,"query")}})}};f();var ZO=(r,e)=>Te(void 0,null,function*(){let t=yield ah();try{t&&(yield t.login()),De.run("onLoginPending")}catch(n){let s=Xt(n);console.warn(`Something went wrong trying to login the user: ${s}`)}if(!t)throw new Error("Error: There were problems with auth provider initialization!");let{signature:i}=t.account;if(e&&Ne.set("loginToken",e),i&&Ne.set("signature",i),r.networkProvider)try{let n=yield t.getAddress();if(!n)throw new Error("Canceled!");return Ne.set("address",n),Ne.set("loginMethod","browser-extension"),Ne.set("expires",Bu()),yield ts(r),t}catch(n){console.warn(`Something went wrong trying to synchronize the user account: ${n==null?void 0:n.message}`)}finally{De.run("onLoggedIn")}});f();f();var r8=_e(t8()),i8=_e(dl());var RK=r=>{var t;let e=document.createElement("template");return e.innerHTML=r.trim(),(t=e.content.firstChild)==null?void 0:t.cloneNode(!0)},LK=r=>{let e=`${rC}?wallet-connect=${encodeURIComponent(r)}`,t=document.createElement("a");return t.setAttribute("href",e),t.setAttribute("rel","noopener noreferrer nofollow"),t.setAttribute("target","_blank"),t.textContent="xPortal login",t.classList.add("elven-qr-code-deep-link"),t},FK=()=>{let r=document.createElement("div");return r.classList.add("elven-wc-pairings"),r},UK=()=>{let r=document.createElement("div");return r.textContent="Existing WalletConnect pairings:",r.classList.add("elven-wc-pairings-header"),r},wE={},qK=(r,e)=>{let t=document.createElement("button");return t.classList.add("elven-wc-pairings-remove-btn"),t.textContent="\u2716",wE[r.topic]=new AbortController,t.addEventListener("click",i=>{i.stopImmediatePropagation(),e(r.topic)},{signal:wE[r.topic].signal}),t},zp={},VK=(r,e,t)=>{var o,a;let i=document.createElement("div"),n=document.createElement("div");i.classList.add("elven-wc-pairing-item"),i.setAttribute("id",r.topic),n.classList.add("elven-wc-pairing-item-description"),n.textContent=`${(o=r.peerMetadata)==null?void 0:o.description} (${(a=r.peerMetadata)==null?void 0:a.url})`,i.appendChild(n);let s=qK(r,e);return i.appendChild(s),zp[r.topic]=new AbortController,i.addEventListener("click",()=>t(r.topic),{signal:zp[r.topic].signal}),i},HK=()=>{let r=document.createElement("div");return r.classList.add("elven-wc-pairing-item-confirm-msessage"),r.innerText="Confirm on xPortal app!",r},QK=r=>{if(!r)return;let e=document.getElementById(r);e==null||e.remove()},jK=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),GK=r=>Te(void 0,null,function*(){return r?yield r8.default.toString(r,{type:"svg"}):void 0}),n8=(r,e,t,i)=>Te(void 0,null,function*(){if(!r)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let n=null;typeof r=="string"?n=document.getElementById(r):r instanceof HTMLElement&&(n=r);let s=yield GK(e),o;if(s&&(o=RK(s)),n&&o&&(n.replaceChildren(),n.appendChild(o),jK()&&n.appendChild(LK(e))),n&&t instanceof i8.WalletConnectV2Provider){let a=t.pairings,u=p=>Te(void 0,null,function*(){try{p&&(yield t.logout({topic:p}),QK(p))}catch(w){let N=Xt(w);console.warn(`Something went wrong trying to remove the existing pairing: ${N}`)}finally{zp[p].abort()}}),h=p=>Te(void 0,null,function*(){try{let{approval:w}=yield t.connect({topic:p,methods:["erd_cancelAction"]}),N=document.getElementById(p);N==null||N.after(HK()),yield t.login({approval:w,token:i})}catch(w){let N=Xt(w);console.warn(`Something went wrong trying to login the user: ${N}`)}finally{for(let w of Object.values(zp))w==null||w.abort();for(let w of Object.values(wE))w==null||w.abort()}});if(a&&a.length>0){let p=FK();n.appendChild(p);let w=UK();p.appendChild(w);for(let N of a){let O=VK(N,u,h);p.appendChild(O)}}}return n});var kp=_e(dl());var s8=(r,e,t)=>Te(void 0,null,function*(){if(!e)throw new Error("You haven't provided the QR code container DOM element id");let i=Cp(r.initOptions.walletConnectV2RelayAddresses);if(!i||!r.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!r.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!r.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let n,s={onClientLogin:()=>Te(void 0,null,function*(){if(r.dappProvider instanceof kp.WalletConnectV2Provider){De.run("onLoginPending");let a=yield r.dappProvider.getAddress(),u=yield r.dappProvider.getSignature();Ne.set("address",a),Ne.set("loginMethod","mobile"),Ne.set("expires",Bu()),yield ts(r),u&&Ne.set("signature",u),t&&Ne.set("loginToken",t),De.run("onLoggedIn"),n==null||n.replaceChildren()}}),onClientLogout:()=>Te(void 0,null,function*(){r.dappProvider instanceof kp.WalletConnectV2Provider&&(yield Pu(r),De.run("onLogout"))}),onClientEvent:a=>{console.log("wc2 session event: ",a)}},o=new kp.WalletConnectV2Provider(s,xi[r.initOptions.chainType].shortId,i,r.initOptions.walletConnectV2ProjectId);try{if(o){r.dappProvider=o,De.run("onQrPending");let{uri:a,approval:u}=yield o.connect({methods:["erd_cancelAction"]}),h=t?`${a}&token=${t}`:a;return e&&h&&(n=yield n8(e,h,o,t),De.run("onQrLoaded")),yield o.login({approval:u,token:t}),o}}catch(a){let u=Xt(a);console.warn(`Something went wrong trying to login the user: ${u}`)}});f();var o8=_e(vl());var a8=(r,e,t)=>Te(void 0,null,function*(){let i=new o8.WalletProvider(`${r}${sh}`),n=typeof window!="undefined"?encodeURIComponent(`${window.location.origin}${e||"/"}`):"/",s=bo({callbackUrl:n},t?{token:t}:{});try{return De.run("onLoginPending"),Ne.set("loginMethod","web-wallet"),yield i.login(s),Ne.set("expires",Bu()),t&&Ne.set("loginToken",t),i}catch(o){let a=Xt(o);console.warn(`Something went wrong trying to login the user: ${a}`),Ne.set("loginMethod","")}});f();var _o=r=>{if(typeof window!="undefined"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(r)}};f();var u8=_e(vl());var c8=r=>Te(void 0,null,function*(){let e=_o("signature"),t=_o("address"),i=Ne.get("address");if(e&&Ne.set("signature",e),t||i)return t&&(Ne.set("address",t),window.history.replaceState(null,"",window.location.pathname)),new u8.WalletProvider(`${r}${sh}`)});f();var l8=_e(zf()),f8=_e(Wy());var Wp=(r,e)=>Te(void 0,null,function*(){De.run("onTxSent",r),yield new f8.TransactionWatcher(e).awaitCompleted(r);let i=r.getSender(),n=new l8.Account(i),s=yield e.getAccount(i);n.update(s),Ne.set("address",n.address.bech32()),Ne.set("nonce",n.getNonceThenIncrement().valueOf()),Ne.set("balance",n.balance.toString()),De.run("onTxFinalized",r)});f();var $p=_e(d8()),p8=_e(jy());var g8=(r,e,t)=>Te(void 0,null,function*(){if(_o($p.WALLET_PROVIDER_CALLBACK_PARAM)===$p.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&r&&e&&"getTransactionsFromWalletUrl"in r){let n=r.getTransactionsFromWalletUrl();window.history.replaceState(null,"",window.location.pathname);let s=n==null?void 0:n[0];if(s){s.data=y.Buffer.from(s.data).toString("base64");let o=p8.Transaction.fromPlainObject(s);o.setNonce(t);try{De.run("onTxStarted",o),yield e.sendTransaction(o),yield Wp(o,e)}catch(a){let u=Xt(a);throw De.run("onTxError",o,u),new Error(`Error: Transaction signing failed! ${u}`)}}}});var Rl=class{static init(e){return Te(this,null,function*(){let t=Ne.get();if(t.expires&&bp(t.expires)){Ne.clear(),this.dappProvider=void 0;return}this.initOptions=bo({chainType:oh,apiUrl:tC,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:iC},e),this.networkProvider=new Mp(this.initOptions),this.initOptions.onLoginPending&&De.set("onLoginPending",this.initOptions.onLoginPending),this.initOptions.onLoggedIn&&De.set("onLoggedIn",this.initOptions.onLoggedIn),this.initOptions.onQrPending&&De.set("onQrPending",this.initOptions.onQrPending),this.initOptions.onQrLoaded&&De.set("onQrLoaded",this.initOptions.onQrLoaded),this.initOptions.onLogout&&De.set("onLogout",this.initOptions.onLogout),this.initOptions.onTxStarted&&De.set("onTxStarted",this.initOptions.onTxStarted),this.initOptions.onTxSent&&De.set("onTxSent",this.initOptions.onTxSent),this.initOptions.onTxFinalized&&De.set("onTxFinalized",this.initOptions.onTxFinalized),this.initOptions.onTxError&&De.set("onTxError",this.initOptions.onTxError),((t==null?void 0:t.address)||t.loginMethod==="web-wallet"&&_o("address"))&&(t!=null&&t.loginMethod)&&(De.run("onLoginPending"),t.loginMethod==="browser-extension"&&(this.dappProvider=yield ah()),t.loginMethod==="mobile"&&(this.dappProvider=yield CO(this)),t.loginMethod==="web-wallet"&&this.initOptions.chainType&&(this.dappProvider=yield c8(xi[this.initOptions.chainType].walletAddress)),yield ts(this),De.run("onLoggedIn"),t.loginMethod==="web-wallet"&&(yield g8(this.dappProvider,this.networkProvider,t.nonce)))})}static login(e,t){return Te(this,null,function*(){var n;if(!Object.values(mo).includes(e))throw new Error("Error: Wrong login method!");if(!this.networkProvider)throw new Error("Error: Login failed: Use ElvenJs.init() first!");try{if(e==="browser-extension"){let s=yield ZO(this,t==null?void 0:t.token);this.dappProvider=s}if(e==="mobile"){let s=yield s8(this,t==null?void 0:t.qrCodeContainer,t==null?void 0:t.token);this.dappProvider=s}if(e==="web-wallet"&&((n=this.initOptions)!=null&&n.chainType)){let s=yield a8(xi[this.initOptions.chainType].walletAddress,t==null?void 0:t.callbackRoute,t==null?void 0:t.token);this.dappProvider=s}}catch(s){let o=Xt(s);throw new Error(`Error: ${o}`)}})}static logout(){return Te(this,null,function*(){try{let e=yield Pu(this);return this.dappProvider=void 0,e}catch(e){let t=Xt(e);console.warn("Something went wrong when logging out: ",t)}})}static signAndSendTransaction(e){return Te(this,null,function*(){if(!this.dappProvider)throw new Error("Error: Transaction signing failed: There is no active session!");if(!this.networkProvider)throw new Error("Error: Transaction signing failed: There is no active network provider!");try{De.run("onTxStarted",e);let t=Ne.get();e.setNonce(t.nonce),this.dappProvider instanceof y8.ExtensionProvider&&(yield this.dappProvider.signTransaction(e)),this.dappProvider instanceof m8.WalletConnectV2Provider&&(yield this.dappProvider.signTransaction(e)),this.dappProvider instanceof w8.WalletProvider&&(yield this.dappProvider.signTransaction(e)),t.loginMethod!=="web-wallet"&&(yield this.networkProvider.sendTransaction(e),yield Wp(e,this.networkProvider))}catch(t){let i=Xt(t);throw De.run("onTxError",e,i),new Error(`Error: Transaction signing failed! ${i}`)}return e})}static queryContract(o){return Te(this,arguments,function*({address:e,func:t,args:i=[],value:n=0,caller:s}){if(!this.networkProvider)throw new Error("Error: Query failed: There is no active network provider!");if(!e||!t)throw new Error("Error: Query failed: The Query arguments are not valid! Address and func required");try{return yield this.networkProvider.queryContract({address:e,func:t,args:i,value:n,caller:s})}catch(a){let u=Xt(a);throw new Error(`Error: Smart contract query failed! ${u}`)}})}},Ml=Rl;Ml.storage=Ne,Ml.destroy=()=>{Rl.networkProvider=void 0,Rl.dappProvider=void 0,Rl.initOptions=void 0,De.clear()};var export_Account=WK.Account;var export_Address=kK.Address;var export_AddressValue=rz.AddressValue;var export_BigUIntValue=E8.BigUIntValue;var export_BooleanValue=ZK.BooleanValue;var export_BytesValue=XK.BytesValue;var export_ContractCallPayloadBuilder=ez.ContractCallPayloadBuilder;var export_ContractFunction=tz.ContractFunction;var export_ESDTNFTTransferPayloadBuilder=v8.ESDTNFTTransferPayloadBuilder;var export_ESDTTransferPayloadBuilder=v8.ESDTTransferPayloadBuilder;var export_TokenPayment=zK.TokenPayment;var export_Transaction=$K.Transaction;var export_TransactionPayload=YK.TransactionPayload;var export_TransactionWatcher=JK.TransactionWatcher;var export_U32Value=E8.U32Value;export{export_Account as Account,export_Address as Address,export_AddressValue as AddressValue,export_BigUIntValue as BigUIntValue,export_BooleanValue as BooleanValue,export_BytesValue as BytesValue,export_ContractCallPayloadBuilder as ContractCallPayloadBuilder,export_ContractFunction as ContractFunction,export_ESDTNFTTransferPayloadBuilder as ESDTNFTTransferPayloadBuilder,export_ESDTTransferPayloadBuilder as ESDTTransferPayloadBuilder,Ml as ElvenJS,mo as LoginMethodsEnum,export_TokenPayment as TokenPayment,export_Transaction as Transaction,export_TransactionPayload as TransactionPayload,export_TransactionWatcher as TransactionWatcher,export_U32Value as U32Value}; +`;return typeof i=="function"&&i(null,N),N}});var t8=B(Bl=>{f();var PK=t6(),yE=W6(),e8=Y6(),BK=Z6();function mE(r,e,t,i,n){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!PK())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(n=t,t=e,e=i=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=i,i=void 0):(n=i,i=t,t=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(t=e,e=i=void 0):o===2&&!e.getContext&&(i=t,t=e,e=void 0),new Promise(function(u,h){try{let p=yE.create(t,i);u(r(p,e,i))}catch(p){h(p)}})}try{let u=yE.create(t,i);n(null,r(u,e,i))}catch(u){n(u)}}Bl.create=yE.create;Bl.toCanvas=mE.bind(null,e8.render);Bl.toDataURL=mE.bind(null,e8.renderToDataURL);Bl.toString=mE.bind(null,function(r,e,t){return BK.render(r,t)})});var d8=B(as=>{"use strict";f();var KK=as&&as.__createBinding||(Object.create?function(r,e,t,i){i===void 0&&(i=t),Object.defineProperty(r,i,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}),h8=as&&as.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&KK(e,r,t)};Object.defineProperty(as,"__esModule",{value:!0});h8(vl(),as);h8(Uv(),as)});f();var zK=_e(og()),v8=_e($I()),kK=_e(Gr()),WK=_e(zf()),$K=_e(jy()),YK=_e(sc()),JK=_e(Wy()),XK=_e(wn()),E8=_e(ic()),ZK=_e(ec()),ez=_e(cy()),tz=_e(Yb()),rz=_e(Ko());f();f();var nC=_e(Zy());f();f();var nh="elvenjs_state",tC="https://devnet-api.multiversx.com";var sh="/dapp/init",oh="devnet",rC="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",iC=["wss://relay.walletconnect.com"],xi={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var Ne={get(r){let e=localStorage.getItem(nh);if(!e)return{};let t=JSON.parse(e);return r?t[r]:t},set(r,e){let t=this.get();t[r]=e,localStorage.setItem(nh,JSON.stringify(t))},clear(){localStorage.removeItem(nh)}};var ah=()=>Te(void 0,null,function*(){let r=nC.ExtensionProvider.getInstance();try{let e=yield r.init(),t=Ne.get();if(t!=null&&t.address&&r.setAddress(t.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return r}catch(e){console.warn("Can't initialize the Dapp Provider!")}});var y8=_e(Zy()),m8=_e(dl()),w8=_e(vl());f();var bO=_e(dl());f();f();var De=class{static set(e,t){if(!e)return;let i=OE(bo({},this.events),{[e]:t});this.events=i}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...t){var i,n;!e||!this.events||(n=(i=this.events)[e])==null||n.call(i,...t)}static clear(){this.events=void 0}};f();var mo=(n=>(n.ledger="ledger",n.mobile="mobile",n.webWallet="web-wallet",n.browserExtension="browser-extension",n))(mo||{});var Pu=r=>Te(void 0,null,function*(){if(!r.dappProvider)throw new Error("Error: Logout failed: There is no active session!");De.run("onLoginPending");let e=yield r.dappProvider.logout();return e&&(Ne.clear(),De.run("onLogout")),e});f();var IO=_e(Gr()),_O=_e(zf());f();var Xt=r=>typeof r=="string"?r.toUpperCase():r instanceof Error?r.message:`Error: ${JSON.stringify(r)}`;f();var Bu=()=>new Date().setHours(new Date().getHours()+24),bp=r=>Date.now()>r;var ts=r=>Te(void 0,null,function*(){let e=Ne.get("address"),t=Ne.get("expires");if(!(t&&bp(t))&&e&&r.networkProvider){let n=new IO.Address(e),s=new _O.Account(n);try{let o=yield r.networkProvider.getAccount(n);Ne.set("address",e),Ne.set("nonce",o.nonce.valueOf()),Ne.set("balance",o.balance.toString()),s.update(o)}catch(o){let a=Xt(o);console.warn(`Something went wrong trying to synchronize the user account: ${a}`)}}});f();function Cp(r){return r[Math.floor(Math.random()*r.length)]}var CO=r=>Te(void 0,null,function*(){if(!r.initOptions.walletConnectV2ProjectId||!r.initOptions.chainType)return;let e={onClientLogin:()=>{ts(r),De.run("onLoggedIn")},onClientLogout:()=>Pu(r),onClientEvent:n=>{console.log("wc2 session event: ",n)}},t=Cp(r.initOptions.walletConnectV2RelayAddresses),i=new bO.WalletConnectV2Provider(e,xi[r.initOptions.chainType].shortId,t,r.initOptions.walletConnectV2ProjectId);try{return yield i.init(),i}catch(n){console.warn("Can't initialize the Dapp Provider!")}});f();var KO=_e(TO()),Bp=_e(Gr()),zO=_e(NO()),kO=_e(MO()),WO=_e(zv()),$O=_e(VO()),YO=_e(QO()),JO=_e(jO()),XO=_e(GO());var Mp=class{constructor({apiUrl:e,chainType:t,apiTimeout:i}){var n,s;this.chainType=t||oh,this.apiUrl=e||((n=xi[this.chainType])==null?void 0:n.apiAddress),this.apiTimeout=i||((s=xi[this.chainType])==null?void 0:s.apiTimeout)}apiGet(e,t){return Te(this,null,function*(){if(typeof fetch!="undefined"){let i=new AbortController,n=setTimeout(()=>i.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:i.signal};try{let o=yield fetch(this.apiUrl+"/"+e,Object.assign(s,t||{})),a=yield o.json();if(!o.ok){let u=(a==null?void 0:a.error)||o.status;return clearTimeout(n),Promise.reject(u)}return clearTimeout(n),a}catch(o){this.handleApiError(o,e)}}})}apiPost(e,t,i){return Te(this,null,function*(){if(typeof fetch!="undefined"){let n=new AbortController,s=setTimeout(()=>n.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t||{}),signal:n.signal};try{let a=yield fetch(this.apiUrl+"/"+e,Object.assign(o,i||{})),u=yield a.json();if(!a.ok){let h=(u==null?void 0:u.error)||a.status;return clearTimeout(s),Promise.reject(h)}return clearTimeout(s),u}catch(a){this.handleApiError(a,e)}}})}handleApiError(e,t){if(!e.response)throw new Error(`Request error on url [${t}]: [${e.toString()}]`);let i=e.response.data,n=i.error||i.message||JSON.stringify(i);throw new Error(n)}sendTransaction(e){return Te(this,null,function*(){return(yield this.apiPost("transactions",e.toSendable())).txHash})}getAccount(e){return Te(this,null,function*(){let t=yield this.apiGet(`accounts/${e.bech32()}`);return{address:new Bp.Address((t==null?void 0:t.address)||""),nonce:Number((t==null?void 0:t.nonce)||0),balance:new KO.default((t==null?void 0:t.balance)||0),code:(t==null?void 0:t.code)||"",userName:(t==null?void 0:t.username)||""}})}getTransaction(e){return Te(this,null,function*(){let t=yield this.apiGet(`transactions/${e}`),i=new zO.TransactionStatus(t.status);return{hash:e,type:t.type||"",nonce:t.nonce||0,round:t.round,epoch:t.epoch||0,value:(t.value||0).toString(),sender:new Bp.Address(t.sender),receiver:new Bp.Address(t.receiver),gasPrice:t.gasPrice||0,gasLimit:t.gasLimit||0,data:y.Buffer.from(t.data||"","base64"),status:i,timestamp:t.timestamp||0,blockNonce:t.blockNonce||0,hyperblockNonce:t.hyperblockNonce||0,hyperblockHash:t.hyperblockHash||"",receipt:kO.TransactionReceipt.fromHttpResponse(t.receipt||{}),logs:WO.TransactionLogs.fromHttpResponse(t.logs||{}),contractResults:$O.ContractResults.fromApiHttpResponse(t.results||[]),isCompleted:!i.isPending()}})}queryContract(o){return Te(this,arguments,function*({address:e,func:t,args:i,value:n,caller:s}){try{let a=new XO.Query({address:e,func:t,args:i,value:n,caller:s}),u=new JO.ContractQueryRequest(a).toHttpRequest(),h=yield this.apiPost("query",u);return YO.ContractQueryResponse.fromHttpResponse(h)}catch(a){this.handleApiError(a,"query")}})}};f();var ZO=(r,e)=>Te(void 0,null,function*(){let t=yield ah();try{t&&(yield t.login()),De.run("onLoginPending")}catch(n){let s=Xt(n);console.warn(`Something went wrong trying to login the user: ${s}`)}if(!t)throw new Error("Error: There were problems with auth provider initialization!");let{signature:i}=t.account;if(e&&Ne.set("loginToken",e),i&&Ne.set("signature",i),r.networkProvider)try{let n=yield t.getAddress();if(!n)throw new Error("Canceled!");return Ne.set("address",n),Ne.set("loginMethod","browser-extension"),Ne.set("expires",Bu()),yield ts(r),De.run("onLoggedIn"),t}catch(n){console.warn(`Something went wrong trying to synchronize the user account: ${n==null?void 0:n.message}`),De.run("onLogout")}});f();f();var r8=_e(t8()),i8=_e(dl());var RK=r=>{var t;let e=document.createElement("template");return e.innerHTML=r.trim(),(t=e.content.firstChild)==null?void 0:t.cloneNode(!0)},LK=r=>{let e=`${rC}?wallet-connect=${encodeURIComponent(r)}`,t=document.createElement("a");return t.setAttribute("href",e),t.setAttribute("rel","noopener noreferrer nofollow"),t.setAttribute("target","_blank"),t.textContent="xPortal login",t.classList.add("elven-qr-code-deep-link"),t},FK=()=>{let r=document.createElement("div");return r.classList.add("elven-wc-pairings"),r},UK=()=>{let r=document.createElement("div");return r.textContent="Existing WalletConnect pairings:",r.classList.add("elven-wc-pairings-header"),r},wE={},qK=(r,e)=>{let t=document.createElement("button");return t.classList.add("elven-wc-pairings-remove-btn"),t.textContent="\u2716",wE[r.topic]=new AbortController,t.addEventListener("click",i=>{i.stopImmediatePropagation(),e(r.topic)},{signal:wE[r.topic].signal}),t},zp={},VK=(r,e,t)=>{var o,a;let i=document.createElement("div"),n=document.createElement("div");i.classList.add("elven-wc-pairing-item"),i.setAttribute("id",r.topic),n.classList.add("elven-wc-pairing-item-description"),n.textContent=`${(o=r.peerMetadata)==null?void 0:o.description} (${(a=r.peerMetadata)==null?void 0:a.url})`,i.appendChild(n);let s=qK(r,e);return i.appendChild(s),zp[r.topic]=new AbortController,i.addEventListener("click",()=>t(r.topic),{signal:zp[r.topic].signal}),i},HK=()=>{let r=document.createElement("div");return r.classList.add("elven-wc-pairing-item-confirm-msessage"),r.innerText="Confirm on xPortal app!",r},QK=r=>{if(!r)return;let e=document.getElementById(r);e==null||e.remove()},jK=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),GK=r=>Te(void 0,null,function*(){return r?yield r8.default.toString(r,{type:"svg"}):void 0}),n8=(r,e,t,i)=>Te(void 0,null,function*(){if(!r)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let n=null;typeof r=="string"?n=document.getElementById(r):r instanceof HTMLElement&&(n=r);let s=yield GK(e),o;if(s&&(o=RK(s)),n&&o&&(n.replaceChildren(),n.appendChild(o),jK()&&n.appendChild(LK(e))),n&&t instanceof i8.WalletConnectV2Provider){let a=t.pairings,u=p=>Te(void 0,null,function*(){try{p&&(yield t.logout({topic:p}),QK(p))}catch(w){let N=Xt(w);console.warn(`Something went wrong trying to remove the existing pairing: ${N}`)}finally{zp[p].abort()}}),h=p=>Te(void 0,null,function*(){try{let{approval:w}=yield t.connect({topic:p,methods:["erd_cancelAction"]}),N=document.getElementById(p);N==null||N.after(HK()),yield t.login({approval:w,token:i})}catch(w){let N=Xt(w);console.warn(`Something went wrong trying to login the user: ${N}`)}finally{for(let w of Object.values(zp))w==null||w.abort();for(let w of Object.values(wE))w==null||w.abort()}});if(a&&a.length>0){let p=FK();n.appendChild(p);let w=UK();p.appendChild(w);for(let N of a){let O=VK(N,u,h);p.appendChild(O)}}}return n});var kp=_e(dl());var s8=(r,e,t)=>Te(void 0,null,function*(){if(!e)throw new Error("You haven't provided the QR code container DOM element id");let i=Cp(r.initOptions.walletConnectV2RelayAddresses);if(!i||!r.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!r.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!r.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let n,s={onClientLogin:()=>Te(void 0,null,function*(){if(r.dappProvider instanceof kp.WalletConnectV2Provider){De.run("onLoginPending");let a=yield r.dappProvider.getAddress(),u=yield r.dappProvider.getSignature();Ne.set("address",a),Ne.set("loginMethod","mobile"),Ne.set("expires",Bu()),yield ts(r),u&&Ne.set("signature",u),t&&Ne.set("loginToken",t),De.run("onLoggedIn"),n==null||n.replaceChildren()}}),onClientLogout:()=>Te(void 0,null,function*(){r.dappProvider instanceof kp.WalletConnectV2Provider&&(yield Pu(r),De.run("onLogout"))}),onClientEvent:a=>{console.log("wc2 session event: ",a)}},o=new kp.WalletConnectV2Provider(s,xi[r.initOptions.chainType].shortId,i,r.initOptions.walletConnectV2ProjectId);try{if(o){r.dappProvider=o,De.run("onQrPending");let{uri:a,approval:u}=yield o.connect({methods:["erd_cancelAction"]}),h=t?`${a}&token=${t}`:a;return e&&h&&(n=yield n8(e,h,o,t),De.run("onQrLoaded")),yield o.login({approval:u,token:t}),o}}catch(a){let u=Xt(a);console.warn(`Something went wrong trying to login the user: ${u}`)}});f();var o8=_e(vl());var a8=(r,e,t)=>Te(void 0,null,function*(){let i=new o8.WalletProvider(`${r}${sh}`),n=typeof window!="undefined"?encodeURIComponent(`${window.location.origin}${e||"/"}`):"/",s=bo({callbackUrl:n},t?{token:t}:{});try{return De.run("onLoginPending"),Ne.set("loginMethod","web-wallet"),yield i.login(s),Ne.set("expires",Bu()),t&&Ne.set("loginToken",t),i}catch(o){let a=Xt(o);console.warn(`Something went wrong trying to login the user: ${a}`),Ne.set("loginMethod","")}});f();var _o=r=>{if(typeof window!="undefined"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(r)}};f();var u8=_e(vl());var c8=r=>Te(void 0,null,function*(){let e=_o("signature"),t=_o("address"),i=Ne.get("address");if(e&&Ne.set("signature",e),t||i)return t&&(Ne.set("address",t),window.history.replaceState(null,"",window.location.pathname)),new u8.WalletProvider(`${r}${sh}`)});f();var l8=_e(zf()),f8=_e(Wy());var Wp=(r,e)=>Te(void 0,null,function*(){De.run("onTxSent",r),yield new f8.TransactionWatcher(e).awaitCompleted(r);let i=r.getSender(),n=new l8.Account(i),s=yield e.getAccount(i);n.update(s),Ne.set("address",n.address.bech32()),Ne.set("nonce",n.getNonceThenIncrement().valueOf()),Ne.set("balance",n.balance.toString()),De.run("onTxFinalized",r)});f();var $p=_e(d8()),p8=_e(jy());var g8=(r,e,t)=>Te(void 0,null,function*(){if(_o($p.WALLET_PROVIDER_CALLBACK_PARAM)===$p.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&r&&e&&"getTransactionsFromWalletUrl"in r){let n=r.getTransactionsFromWalletUrl();window.history.replaceState(null,"",window.location.pathname);let s=n==null?void 0:n[0];if(s){s.data=y.Buffer.from(s.data).toString("base64");let o=p8.Transaction.fromPlainObject(s);o.setNonce(t);try{De.run("onTxStarted",o),yield e.sendTransaction(o),yield Wp(o,e)}catch(a){let u=Xt(a);throw De.run("onTxError",o,u),new Error(`Error: Transaction signing failed! ${u}`)}}}});var Rl=class{static init(e){return Te(this,null,function*(){let t=Ne.get();if(t.expires&&bp(t.expires)){Ne.clear(),this.dappProvider=void 0;return}this.initOptions=bo({chainType:oh,apiUrl:tC,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:iC},e),this.networkProvider=new Mp(this.initOptions),this.initOptions.onLoginPending&&De.set("onLoginPending",this.initOptions.onLoginPending),this.initOptions.onLoggedIn&&De.set("onLoggedIn",this.initOptions.onLoggedIn),this.initOptions.onQrPending&&De.set("onQrPending",this.initOptions.onQrPending),this.initOptions.onQrLoaded&&De.set("onQrLoaded",this.initOptions.onQrLoaded),this.initOptions.onLogout&&De.set("onLogout",this.initOptions.onLogout),this.initOptions.onTxStarted&&De.set("onTxStarted",this.initOptions.onTxStarted),this.initOptions.onTxSent&&De.set("onTxSent",this.initOptions.onTxSent),this.initOptions.onTxFinalized&&De.set("onTxFinalized",this.initOptions.onTxFinalized),this.initOptions.onTxError&&De.set("onTxError",this.initOptions.onTxError),((t==null?void 0:t.address)||t.loginMethod==="web-wallet"&&_o("address"))&&(t!=null&&t.loginMethod)&&(De.run("onLoginPending"),t.loginMethod==="browser-extension"&&(this.dappProvider=yield ah()),t.loginMethod==="mobile"&&(this.dappProvider=yield CO(this)),t.loginMethod==="web-wallet"&&this.initOptions.chainType&&(this.dappProvider=yield c8(xi[this.initOptions.chainType].walletAddress)),yield ts(this),De.run("onLoggedIn"),t.loginMethod==="web-wallet"&&(yield g8(this.dappProvider,this.networkProvider,t.nonce)))})}static login(e,t){return Te(this,null,function*(){var n;if(!Object.values(mo).includes(e))throw new Error("Error: Wrong login method!");if(!this.networkProvider)throw new Error("Error: Login failed: Use ElvenJs.init() first!");try{if(e==="browser-extension"){let s=yield ZO(this,t==null?void 0:t.token);this.dappProvider=s}if(e==="mobile"){let s=yield s8(this,t==null?void 0:t.qrCodeContainer,t==null?void 0:t.token);this.dappProvider=s}if(e==="web-wallet"&&((n=this.initOptions)!=null&&n.chainType)){let s=yield a8(xi[this.initOptions.chainType].walletAddress,t==null?void 0:t.callbackRoute,t==null?void 0:t.token);this.dappProvider=s}}catch(s){let o=Xt(s);throw new Error(`Error: ${o}`)}})}static logout(){return Te(this,null,function*(){try{let e=yield Pu(this);return this.dappProvider=void 0,e}catch(e){let t=Xt(e);console.warn("Something went wrong when logging out: ",t)}})}static signAndSendTransaction(e){return Te(this,null,function*(){if(!this.dappProvider)throw new Error("Error: Transaction signing failed: There is no active session!");if(!this.networkProvider)throw new Error("Error: Transaction signing failed: There is no active network provider!");try{De.run("onTxStarted",e);let t=Ne.get();e.setNonce(t.nonce),this.dappProvider instanceof y8.ExtensionProvider&&(yield this.dappProvider.signTransaction(e)),this.dappProvider instanceof m8.WalletConnectV2Provider&&(yield this.dappProvider.signTransaction(e)),this.dappProvider instanceof w8.WalletProvider&&(yield this.dappProvider.signTransaction(e)),t.loginMethod!=="web-wallet"&&(yield this.networkProvider.sendTransaction(e),yield Wp(e,this.networkProvider))}catch(t){let i=Xt(t);throw De.run("onTxError",e,i),new Error(`Error: Transaction signing failed! ${i}`)}return e})}static queryContract(o){return Te(this,arguments,function*({address:e,func:t,args:i=[],value:n=0,caller:s}){if(!this.networkProvider)throw new Error("Error: Query failed: There is no active network provider!");if(!e||!t)throw new Error("Error: Query failed: The Query arguments are not valid! Address and func required");try{return yield this.networkProvider.queryContract({address:e,func:t,args:i,value:n,caller:s})}catch(a){let u=Xt(a);throw new Error(`Error: Smart contract query failed! ${u}`)}})}},Ml=Rl;Ml.storage=Ne,Ml.destroy=()=>{Rl.networkProvider=void 0,Rl.dappProvider=void 0,Rl.initOptions=void 0,De.clear()};var export_Account=WK.Account;var export_Address=kK.Address;var export_AddressValue=rz.AddressValue;var export_BigUIntValue=E8.BigUIntValue;var export_BooleanValue=ZK.BooleanValue;var export_BytesValue=XK.BytesValue;var export_ContractCallPayloadBuilder=ez.ContractCallPayloadBuilder;var export_ContractFunction=tz.ContractFunction;var export_ESDTNFTTransferPayloadBuilder=v8.ESDTNFTTransferPayloadBuilder;var export_ESDTTransferPayloadBuilder=v8.ESDTTransferPayloadBuilder;var export_TokenPayment=zK.TokenPayment;var export_Transaction=$K.Transaction;var export_TransactionPayload=YK.TransactionPayload;var export_TransactionWatcher=JK.TransactionWatcher;var export_U32Value=E8.U32Value;export{export_Account as Account,export_Address as Address,export_AddressValue as AddressValue,export_BigUIntValue as BigUIntValue,export_BooleanValue as BooleanValue,export_BytesValue as BytesValue,export_ContractCallPayloadBuilder as ContractCallPayloadBuilder,export_ContractFunction as ContractFunction,export_ESDTNFTTransferPayloadBuilder as ESDTNFTTransferPayloadBuilder,export_ESDTTransferPayloadBuilder as ESDTTransferPayloadBuilder,Ml as ElvenJS,mo as LoginMethodsEnum,export_TokenPayment as TokenPayment,export_Transaction as Transaction,export_TransactionPayload as TransactionPayload,export_TransactionWatcher as TransactionWatcher,export_U32Value as U32Value}; /*! Bundled license information: ieee754/index.js: diff --git a/example/elven.js b/example/elven.js index 39598ff..ac4520c 100644 --- a/example/elven.js +++ b/example/elven.js @@ -33,7 +33,7 @@ Make sure your charset is UTF-8`);t=(t>>>8&255)*192+(t&255),r.put(t,13)}};L6.exp The chosen QR Code version cannot contain this amount of data. Minimum version required to store current data is: `+s+`. `);let o=CK(e,t,n),a=Gp.getSymbolSize(e),u=new pK(a);return EK(u,e),AK(u),IK(u,e),lE(u,t,0),e>=7&&_K(u,e),bK(u,o),isNaN(i)&&(i=fE.getBestMask(u,lE.bind(null,u,t))),fE.applyMask(i,u),lE(u,t,i),{modules:u,version:e,errorCorrectionLevel:t,maskPattern:i,segments:n}}k6.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let i=uE.M,n,s;return typeof t<"u"&&(i=uE.from(t.errorCorrectionLevel,uE.M),n=jp.from(t.version),s=fE.from(t.maskPattern),t.toSJISFunc&&Gp.setToSJISFunction(t.toSJISFunc)),xK(e,n,i,s)}});var dE=B(Io=>{f();function $6(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let e=r.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+r);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(i){return[i,i]}))),e.length===6&&e.push("F","F");let t=parseInt(e.join(""),16);return{r:t>>24&255,g:t>>16&255,b:t>>8&255,a:t&255,hex:"#"+e.slice(0,6).join("")}}Io.getOptions=function(e){e||(e={}),e.color||(e.color={});let t=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,i=e.width&&e.width>=21?e.width:void 0,n=e.scale||4;return{width:i,scale:i?4:n,margin:t,color:{dark:$6(e.color.dark||"#000000ff"),light:$6(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Io.getScale=function(e,t){return t.width&&t.width>=e+t.margin*2?t.width/(e+t.margin*2):t.scale};Io.getImageWidth=function(e,t){let i=Io.getScale(e,t);return Math.floor((e+t.margin*2)*i)};Io.qrToImageData=function(e,t,i){let n=t.modules.size,s=t.modules.data,o=Io.getScale(n,i),a=Math.floor((n+i.margin*2)*o),u=i.margin*o,h=[i.color.light,i.color.dark];for(let p=0;p=u&&w>=u&&p{f();var pE=dE();function TK(r,e,t){r.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=t,e.width=t,e.style.height=t+"px",e.style.width=t+"px"}function NK(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Kp.render=function(e,t,i){let n=i,s=t;typeof n>"u"&&(!t||!t.getContext)&&(n=t,t=void 0),t||(s=NK()),n=pE.getOptions(n);let o=pE.getImageWidth(e.modules.size,n),a=s.getContext("2d"),u=a.createImageData(o,o);return pE.qrToImageData(u.data,e,n),TK(a,s,o),a.putImageData(u,0,0),s};Kp.renderToDataURL=function(e,t,i){let n=i;typeof n>"u"&&(!t||!t.getContext)&&(n=t,t=void 0),n||(n={});let s=Kp.render(e,t,n),o=n.type||"image/png",a=n.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Z6=B(X6=>{f();var DK=dE();function J6(r,e){let t=r.a/255,i=e+'="'+r.hex+'"';return t<1?i+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':i}function gE(r,e,t){let i=r+e;return typeof t<"u"&&(i+=" "+t),i}function OK(r,e,t){let i="",n=0,s=!1,o=0;for(let a=0;a0&&u>0&&r[a-1]||(i+=s?gE("M",u+t,.5+h+t):gE("m",n,0),n=0,s=!1),u+1':"",h="',p='viewBox="0 0 '+a+" "+a+'"',N=''+u+h+` -`;return typeof i=="function"&&i(null,N),N}});var t8=B(Bl=>{f();var PK=t6(),yE=W6(),e8=Y6(),BK=Z6();function mE(r,e,t,i,n){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!PK())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(n=t,t=e,e=i=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=i,i=void 0):(n=i,i=t,t=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(t=e,e=i=void 0):o===2&&!e.getContext&&(i=t,t=e,e=void 0),new Promise(function(u,h){try{let p=yE.create(t,i);u(r(p,e,i))}catch(p){h(p)}})}try{let u=yE.create(t,i);n(null,r(u,e,i))}catch(u){n(u)}}Bl.create=yE.create;Bl.toCanvas=mE.bind(null,e8.render);Bl.toDataURL=mE.bind(null,e8.renderToDataURL);Bl.toString=mE.bind(null,function(r,e,t){return BK.render(r,t)})});var d8=B(as=>{"use strict";f();var KK=as&&as.__createBinding||(Object.create?function(r,e,t,i){i===void 0&&(i=t),Object.defineProperty(r,i,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}),h8=as&&as.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&KK(e,r,t)};Object.defineProperty(as,"__esModule",{value:!0});h8(vl(),as);h8(Uv(),as)});f();var zK=_e(og()),v8=_e($I()),kK=_e(Gr()),WK=_e(zf()),$K=_e(jy()),YK=_e(sc()),JK=_e(Wy()),XK=_e(wn()),E8=_e(ic()),ZK=_e(ec()),ez=_e(cy()),tz=_e(Yb()),rz=_e(Ko());f();f();var nC=_e(Zy());f();f();var nh="elvenjs_state",tC="https://devnet-api.multiversx.com";var sh="/dapp/init",oh="devnet",rC="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",iC=["wss://relay.walletconnect.com"],xi={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var Ne={get(r){let e=localStorage.getItem(nh);if(!e)return{};let t=JSON.parse(e);return r?t[r]:t},set(r,e){let t=this.get();t[r]=e,localStorage.setItem(nh,JSON.stringify(t))},clear(){localStorage.removeItem(nh)}};var ah=()=>Te(void 0,null,function*(){let r=nC.ExtensionProvider.getInstance();try{let e=yield r.init(),t=Ne.get();if(t!=null&&t.address&&r.setAddress(t.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return r}catch(e){console.warn("Can't initialize the Dapp Provider!")}});var y8=_e(Zy()),m8=_e(dl()),w8=_e(vl());f();var bO=_e(dl());f();f();var De=class{static set(e,t){if(!e)return;let i=OE(bo({},this.events),{[e]:t});this.events=i}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...t){var i,n;!e||!this.events||(n=(i=this.events)[e])==null||n.call(i,...t)}static clear(){this.events=void 0}};f();var mo=(n=>(n.ledger="ledger",n.mobile="mobile",n.webWallet="web-wallet",n.browserExtension="browser-extension",n))(mo||{});var Pu=r=>Te(void 0,null,function*(){if(!r.dappProvider)throw new Error("Error: Logout failed: There is no active session!");De.run("onLoginPending");let e=yield r.dappProvider.logout();return e&&(Ne.clear(),De.run("onLogout")),e});f();var IO=_e(Gr()),_O=_e(zf());f();var Xt=r=>typeof r=="string"?r.toUpperCase():r instanceof Error?r.message:`Error: ${JSON.stringify(r)}`;f();var Bu=()=>new Date().setHours(new Date().getHours()+24),bp=r=>Date.now()>r;var ts=r=>Te(void 0,null,function*(){let e=Ne.get("address"),t=Ne.get("expires");if(!(t&&bp(t))&&e&&r.networkProvider){let n=new IO.Address(e),s=new _O.Account(n);try{let o=yield r.networkProvider.getAccount(n);Ne.set("address",e),Ne.set("nonce",o.nonce.valueOf()),Ne.set("balance",o.balance.toString()),s.update(o)}catch(o){let a=Xt(o);console.warn(`Something went wrong trying to synchronize the user account: ${a}`)}}});f();function Cp(r){return r[Math.floor(Math.random()*r.length)]}var CO=r=>Te(void 0,null,function*(){if(!r.initOptions.walletConnectV2ProjectId||!r.initOptions.chainType)return;let e={onClientLogin:()=>{ts(r),De.run("onLoggedIn")},onClientLogout:()=>Pu(r),onClientEvent:n=>{console.log("wc2 session event: ",n)}},t=Cp(r.initOptions.walletConnectV2RelayAddresses),i=new bO.WalletConnectV2Provider(e,xi[r.initOptions.chainType].shortId,t,r.initOptions.walletConnectV2ProjectId);try{return yield i.init(),i}catch(n){console.warn("Can't initialize the Dapp Provider!")}});f();var KO=_e(TO()),Bp=_e(Gr()),zO=_e(NO()),kO=_e(MO()),WO=_e(zv()),$O=_e(VO()),YO=_e(QO()),JO=_e(jO()),XO=_e(GO());var Mp=class{constructor({apiUrl:e,chainType:t,apiTimeout:i}){var n,s;this.chainType=t||oh,this.apiUrl=e||((n=xi[this.chainType])==null?void 0:n.apiAddress),this.apiTimeout=i||((s=xi[this.chainType])==null?void 0:s.apiTimeout)}apiGet(e,t){return Te(this,null,function*(){if(typeof fetch!="undefined"){let i=new AbortController,n=setTimeout(()=>i.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:i.signal};try{let o=yield fetch(this.apiUrl+"/"+e,Object.assign(s,t||{})),a=yield o.json();if(!o.ok){let u=(a==null?void 0:a.error)||o.status;return clearTimeout(n),Promise.reject(u)}return clearTimeout(n),a}catch(o){this.handleApiError(o,e)}}})}apiPost(e,t,i){return Te(this,null,function*(){if(typeof fetch!="undefined"){let n=new AbortController,s=setTimeout(()=>n.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t||{}),signal:n.signal};try{let a=yield fetch(this.apiUrl+"/"+e,Object.assign(o,i||{})),u=yield a.json();if(!a.ok){let h=(u==null?void 0:u.error)||a.status;return clearTimeout(s),Promise.reject(h)}return clearTimeout(s),u}catch(a){this.handleApiError(a,e)}}})}handleApiError(e,t){if(!e.response)throw new Error(`Request error on url [${t}]: [${e.toString()}]`);let i=e.response.data,n=i.error||i.message||JSON.stringify(i);throw new Error(n)}sendTransaction(e){return Te(this,null,function*(){return(yield this.apiPost("transactions",e.toSendable())).txHash})}getAccount(e){return Te(this,null,function*(){let t=yield this.apiGet(`accounts/${e.bech32()}`);return{address:new Bp.Address((t==null?void 0:t.address)||""),nonce:Number((t==null?void 0:t.nonce)||0),balance:new KO.default((t==null?void 0:t.balance)||0),code:(t==null?void 0:t.code)||"",userName:(t==null?void 0:t.username)||""}})}getTransaction(e){return Te(this,null,function*(){let t=yield this.apiGet(`transactions/${e}`),i=new zO.TransactionStatus(t.status);return{hash:e,type:t.type||"",nonce:t.nonce||0,round:t.round,epoch:t.epoch||0,value:(t.value||0).toString(),sender:new Bp.Address(t.sender),receiver:new Bp.Address(t.receiver),gasPrice:t.gasPrice||0,gasLimit:t.gasLimit||0,data:y.Buffer.from(t.data||"","base64"),status:i,timestamp:t.timestamp||0,blockNonce:t.blockNonce||0,hyperblockNonce:t.hyperblockNonce||0,hyperblockHash:t.hyperblockHash||"",receipt:kO.TransactionReceipt.fromHttpResponse(t.receipt||{}),logs:WO.TransactionLogs.fromHttpResponse(t.logs||{}),contractResults:$O.ContractResults.fromApiHttpResponse(t.results||[]),isCompleted:!i.isPending()}})}queryContract(o){return Te(this,arguments,function*({address:e,func:t,args:i,value:n,caller:s}){try{let a=new XO.Query({address:e,func:t,args:i,value:n,caller:s}),u=new JO.ContractQueryRequest(a).toHttpRequest(),h=yield this.apiPost("query",u);return YO.ContractQueryResponse.fromHttpResponse(h)}catch(a){this.handleApiError(a,"query")}})}};f();var ZO=(r,e)=>Te(void 0,null,function*(){let t=yield ah();try{t&&(yield t.login()),De.run("onLoginPending")}catch(n){let s=Xt(n);console.warn(`Something went wrong trying to login the user: ${s}`)}if(!t)throw new Error("Error: There were problems with auth provider initialization!");let{signature:i}=t.account;if(e&&Ne.set("loginToken",e),i&&Ne.set("signature",i),r.networkProvider)try{let n=yield t.getAddress();if(!n)throw new Error("Canceled!");return Ne.set("address",n),Ne.set("loginMethod","browser-extension"),Ne.set("expires",Bu()),yield ts(r),t}catch(n){console.warn(`Something went wrong trying to synchronize the user account: ${n==null?void 0:n.message}`)}finally{De.run("onLoggedIn")}});f();f();var r8=_e(t8()),i8=_e(dl());var RK=r=>{var t;let e=document.createElement("template");return e.innerHTML=r.trim(),(t=e.content.firstChild)==null?void 0:t.cloneNode(!0)},LK=r=>{let e=`${rC}?wallet-connect=${encodeURIComponent(r)}`,t=document.createElement("a");return t.setAttribute("href",e),t.setAttribute("rel","noopener noreferrer nofollow"),t.setAttribute("target","_blank"),t.textContent="xPortal login",t.classList.add("elven-qr-code-deep-link"),t},FK=()=>{let r=document.createElement("div");return r.classList.add("elven-wc-pairings"),r},UK=()=>{let r=document.createElement("div");return r.textContent="Existing WalletConnect pairings:",r.classList.add("elven-wc-pairings-header"),r},wE={},qK=(r,e)=>{let t=document.createElement("button");return t.classList.add("elven-wc-pairings-remove-btn"),t.textContent="\u2716",wE[r.topic]=new AbortController,t.addEventListener("click",i=>{i.stopImmediatePropagation(),e(r.topic)},{signal:wE[r.topic].signal}),t},zp={},VK=(r,e,t)=>{var o,a;let i=document.createElement("div"),n=document.createElement("div");i.classList.add("elven-wc-pairing-item"),i.setAttribute("id",r.topic),n.classList.add("elven-wc-pairing-item-description"),n.textContent=`${(o=r.peerMetadata)==null?void 0:o.description} (${(a=r.peerMetadata)==null?void 0:a.url})`,i.appendChild(n);let s=qK(r,e);return i.appendChild(s),zp[r.topic]=new AbortController,i.addEventListener("click",()=>t(r.topic),{signal:zp[r.topic].signal}),i},HK=()=>{let r=document.createElement("div");return r.classList.add("elven-wc-pairing-item-confirm-msessage"),r.innerText="Confirm on xPortal app!",r},QK=r=>{if(!r)return;let e=document.getElementById(r);e==null||e.remove()},jK=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),GK=r=>Te(void 0,null,function*(){return r?yield r8.default.toString(r,{type:"svg"}):void 0}),n8=(r,e,t,i)=>Te(void 0,null,function*(){if(!r)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let n=null;typeof r=="string"?n=document.getElementById(r):r instanceof HTMLElement&&(n=r);let s=yield GK(e),o;if(s&&(o=RK(s)),n&&o&&(n.replaceChildren(),n.appendChild(o),jK()&&n.appendChild(LK(e))),n&&t instanceof i8.WalletConnectV2Provider){let a=t.pairings,u=p=>Te(void 0,null,function*(){try{p&&(yield t.logout({topic:p}),QK(p))}catch(w){let N=Xt(w);console.warn(`Something went wrong trying to remove the existing pairing: ${N}`)}finally{zp[p].abort()}}),h=p=>Te(void 0,null,function*(){try{let{approval:w}=yield t.connect({topic:p,methods:["erd_cancelAction"]}),N=document.getElementById(p);N==null||N.after(HK()),yield t.login({approval:w,token:i})}catch(w){let N=Xt(w);console.warn(`Something went wrong trying to login the user: ${N}`)}finally{for(let w of Object.values(zp))w==null||w.abort();for(let w of Object.values(wE))w==null||w.abort()}});if(a&&a.length>0){let p=FK();n.appendChild(p);let w=UK();p.appendChild(w);for(let N of a){let O=VK(N,u,h);p.appendChild(O)}}}return n});var kp=_e(dl());var s8=(r,e,t)=>Te(void 0,null,function*(){if(!e)throw new Error("You haven't provided the QR code container DOM element id");let i=Cp(r.initOptions.walletConnectV2RelayAddresses);if(!i||!r.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!r.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!r.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let n,s={onClientLogin:()=>Te(void 0,null,function*(){if(r.dappProvider instanceof kp.WalletConnectV2Provider){De.run("onLoginPending");let a=yield r.dappProvider.getAddress(),u=yield r.dappProvider.getSignature();Ne.set("address",a),Ne.set("loginMethod","mobile"),Ne.set("expires",Bu()),yield ts(r),u&&Ne.set("signature",u),t&&Ne.set("loginToken",t),De.run("onLoggedIn"),n==null||n.replaceChildren()}}),onClientLogout:()=>Te(void 0,null,function*(){r.dappProvider instanceof kp.WalletConnectV2Provider&&(yield Pu(r),De.run("onLogout"))}),onClientEvent:a=>{console.log("wc2 session event: ",a)}},o=new kp.WalletConnectV2Provider(s,xi[r.initOptions.chainType].shortId,i,r.initOptions.walletConnectV2ProjectId);try{if(o){r.dappProvider=o,De.run("onQrPending");let{uri:a,approval:u}=yield o.connect({methods:["erd_cancelAction"]}),h=t?`${a}&token=${t}`:a;return e&&h&&(n=yield n8(e,h,o,t),De.run("onQrLoaded")),yield o.login({approval:u,token:t}),o}}catch(a){let u=Xt(a);console.warn(`Something went wrong trying to login the user: ${u}`)}});f();var o8=_e(vl());var a8=(r,e,t)=>Te(void 0,null,function*(){let i=new o8.WalletProvider(`${r}${sh}`),n=typeof window!="undefined"?encodeURIComponent(`${window.location.origin}${e||"/"}`):"/",s=bo({callbackUrl:n},t?{token:t}:{});try{return De.run("onLoginPending"),Ne.set("loginMethod","web-wallet"),yield i.login(s),Ne.set("expires",Bu()),t&&Ne.set("loginToken",t),i}catch(o){let a=Xt(o);console.warn(`Something went wrong trying to login the user: ${a}`),Ne.set("loginMethod","")}});f();var _o=r=>{if(typeof window!="undefined"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(r)}};f();var u8=_e(vl());var c8=r=>Te(void 0,null,function*(){let e=_o("signature"),t=_o("address"),i=Ne.get("address");if(e&&Ne.set("signature",e),t||i)return t&&(Ne.set("address",t),window.history.replaceState(null,"",window.location.pathname)),new u8.WalletProvider(`${r}${sh}`)});f();var l8=_e(zf()),f8=_e(Wy());var Wp=(r,e)=>Te(void 0,null,function*(){De.run("onTxSent",r),yield new f8.TransactionWatcher(e).awaitCompleted(r);let i=r.getSender(),n=new l8.Account(i),s=yield e.getAccount(i);n.update(s),Ne.set("address",n.address.bech32()),Ne.set("nonce",n.getNonceThenIncrement().valueOf()),Ne.set("balance",n.balance.toString()),De.run("onTxFinalized",r)});f();var $p=_e(d8()),p8=_e(jy());var g8=(r,e,t)=>Te(void 0,null,function*(){if(_o($p.WALLET_PROVIDER_CALLBACK_PARAM)===$p.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&r&&e&&"getTransactionsFromWalletUrl"in r){let n=r.getTransactionsFromWalletUrl();window.history.replaceState(null,"",window.location.pathname);let s=n==null?void 0:n[0];if(s){s.data=y.Buffer.from(s.data).toString("base64");let o=p8.Transaction.fromPlainObject(s);o.setNonce(t);try{De.run("onTxStarted",o),yield e.sendTransaction(o),yield Wp(o,e)}catch(a){let u=Xt(a);throw De.run("onTxError",o,u),new Error(`Error: Transaction signing failed! ${u}`)}}}});var Rl=class{static init(e){return Te(this,null,function*(){let t=Ne.get();if(t.expires&&bp(t.expires)){Ne.clear(),this.dappProvider=void 0;return}this.initOptions=bo({chainType:oh,apiUrl:tC,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:iC},e),this.networkProvider=new Mp(this.initOptions),this.initOptions.onLoginPending&&De.set("onLoginPending",this.initOptions.onLoginPending),this.initOptions.onLoggedIn&&De.set("onLoggedIn",this.initOptions.onLoggedIn),this.initOptions.onQrPending&&De.set("onQrPending",this.initOptions.onQrPending),this.initOptions.onQrLoaded&&De.set("onQrLoaded",this.initOptions.onQrLoaded),this.initOptions.onLogout&&De.set("onLogout",this.initOptions.onLogout),this.initOptions.onTxStarted&&De.set("onTxStarted",this.initOptions.onTxStarted),this.initOptions.onTxSent&&De.set("onTxSent",this.initOptions.onTxSent),this.initOptions.onTxFinalized&&De.set("onTxFinalized",this.initOptions.onTxFinalized),this.initOptions.onTxError&&De.set("onTxError",this.initOptions.onTxError),((t==null?void 0:t.address)||t.loginMethod==="web-wallet"&&_o("address"))&&(t!=null&&t.loginMethod)&&(De.run("onLoginPending"),t.loginMethod==="browser-extension"&&(this.dappProvider=yield ah()),t.loginMethod==="mobile"&&(this.dappProvider=yield CO(this)),t.loginMethod==="web-wallet"&&this.initOptions.chainType&&(this.dappProvider=yield c8(xi[this.initOptions.chainType].walletAddress)),yield ts(this),De.run("onLoggedIn"),t.loginMethod==="web-wallet"&&(yield g8(this.dappProvider,this.networkProvider,t.nonce)))})}static login(e,t){return Te(this,null,function*(){var n;if(!Object.values(mo).includes(e))throw new Error("Error: Wrong login method!");if(!this.networkProvider)throw new Error("Error: Login failed: Use ElvenJs.init() first!");try{if(e==="browser-extension"){let s=yield ZO(this,t==null?void 0:t.token);this.dappProvider=s}if(e==="mobile"){let s=yield s8(this,t==null?void 0:t.qrCodeContainer,t==null?void 0:t.token);this.dappProvider=s}if(e==="web-wallet"&&((n=this.initOptions)!=null&&n.chainType)){let s=yield a8(xi[this.initOptions.chainType].walletAddress,t==null?void 0:t.callbackRoute,t==null?void 0:t.token);this.dappProvider=s}}catch(s){let o=Xt(s);throw new Error(`Error: ${o}`)}})}static logout(){return Te(this,null,function*(){try{let e=yield Pu(this);return this.dappProvider=void 0,e}catch(e){let t=Xt(e);console.warn("Something went wrong when logging out: ",t)}})}static signAndSendTransaction(e){return Te(this,null,function*(){if(!this.dappProvider)throw new Error("Error: Transaction signing failed: There is no active session!");if(!this.networkProvider)throw new Error("Error: Transaction signing failed: There is no active network provider!");try{De.run("onTxStarted",e);let t=Ne.get();e.setNonce(t.nonce),this.dappProvider instanceof y8.ExtensionProvider&&(yield this.dappProvider.signTransaction(e)),this.dappProvider instanceof m8.WalletConnectV2Provider&&(yield this.dappProvider.signTransaction(e)),this.dappProvider instanceof w8.WalletProvider&&(yield this.dappProvider.signTransaction(e)),t.loginMethod!=="web-wallet"&&(yield this.networkProvider.sendTransaction(e),yield Wp(e,this.networkProvider))}catch(t){let i=Xt(t);throw De.run("onTxError",e,i),new Error(`Error: Transaction signing failed! ${i}`)}return e})}static queryContract(o){return Te(this,arguments,function*({address:e,func:t,args:i=[],value:n=0,caller:s}){if(!this.networkProvider)throw new Error("Error: Query failed: There is no active network provider!");if(!e||!t)throw new Error("Error: Query failed: The Query arguments are not valid! Address and func required");try{return yield this.networkProvider.queryContract({address:e,func:t,args:i,value:n,caller:s})}catch(a){let u=Xt(a);throw new Error(`Error: Smart contract query failed! ${u}`)}})}},Ml=Rl;Ml.storage=Ne,Ml.destroy=()=>{Rl.networkProvider=void 0,Rl.dappProvider=void 0,Rl.initOptions=void 0,De.clear()};var export_Account=WK.Account;var export_Address=kK.Address;var export_AddressValue=rz.AddressValue;var export_BigUIntValue=E8.BigUIntValue;var export_BooleanValue=ZK.BooleanValue;var export_BytesValue=XK.BytesValue;var export_ContractCallPayloadBuilder=ez.ContractCallPayloadBuilder;var export_ContractFunction=tz.ContractFunction;var export_ESDTNFTTransferPayloadBuilder=v8.ESDTNFTTransferPayloadBuilder;var export_ESDTTransferPayloadBuilder=v8.ESDTTransferPayloadBuilder;var export_TokenPayment=zK.TokenPayment;var export_Transaction=$K.Transaction;var export_TransactionPayload=YK.TransactionPayload;var export_TransactionWatcher=JK.TransactionWatcher;var export_U32Value=E8.U32Value;export{export_Account as Account,export_Address as Address,export_AddressValue as AddressValue,export_BigUIntValue as BigUIntValue,export_BooleanValue as BooleanValue,export_BytesValue as BytesValue,export_ContractCallPayloadBuilder as ContractCallPayloadBuilder,export_ContractFunction as ContractFunction,export_ESDTNFTTransferPayloadBuilder as ESDTNFTTransferPayloadBuilder,export_ESDTTransferPayloadBuilder as ESDTTransferPayloadBuilder,Ml as ElvenJS,mo as LoginMethodsEnum,export_TokenPayment as TokenPayment,export_Transaction as Transaction,export_TransactionPayload as TransactionPayload,export_TransactionWatcher as TransactionWatcher,export_U32Value as U32Value}; +`;return typeof i=="function"&&i(null,N),N}});var t8=B(Bl=>{f();var PK=t6(),yE=W6(),e8=Y6(),BK=Z6();function mE(r,e,t,i,n){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!PK())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(n=t,t=e,e=i=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=i,i=void 0):(n=i,i=t,t=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(t=e,e=i=void 0):o===2&&!e.getContext&&(i=t,t=e,e=void 0),new Promise(function(u,h){try{let p=yE.create(t,i);u(r(p,e,i))}catch(p){h(p)}})}try{let u=yE.create(t,i);n(null,r(u,e,i))}catch(u){n(u)}}Bl.create=yE.create;Bl.toCanvas=mE.bind(null,e8.render);Bl.toDataURL=mE.bind(null,e8.renderToDataURL);Bl.toString=mE.bind(null,function(r,e,t){return BK.render(r,t)})});var d8=B(as=>{"use strict";f();var KK=as&&as.__createBinding||(Object.create?function(r,e,t,i){i===void 0&&(i=t),Object.defineProperty(r,i,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}),h8=as&&as.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&KK(e,r,t)};Object.defineProperty(as,"__esModule",{value:!0});h8(vl(),as);h8(Uv(),as)});f();var zK=_e(og()),v8=_e($I()),kK=_e(Gr()),WK=_e(zf()),$K=_e(jy()),YK=_e(sc()),JK=_e(Wy()),XK=_e(wn()),E8=_e(ic()),ZK=_e(ec()),ez=_e(cy()),tz=_e(Yb()),rz=_e(Ko());f();f();var nC=_e(Zy());f();f();var nh="elvenjs_state",tC="https://devnet-api.multiversx.com";var sh="/dapp/init",oh="devnet",rC="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",iC=["wss://relay.walletconnect.com"],xi={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var Ne={get(r){let e=localStorage.getItem(nh);if(!e)return{};let t=JSON.parse(e);return r?t[r]:t},set(r,e){let t=this.get();t[r]=e,localStorage.setItem(nh,JSON.stringify(t))},clear(){localStorage.removeItem(nh)}};var ah=()=>Te(void 0,null,function*(){let r=nC.ExtensionProvider.getInstance();try{let e=yield r.init(),t=Ne.get();if(t!=null&&t.address&&r.setAddress(t.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return r}catch(e){console.warn("Can't initialize the Dapp Provider!")}});var y8=_e(Zy()),m8=_e(dl()),w8=_e(vl());f();var bO=_e(dl());f();f();var De=class{static set(e,t){if(!e)return;let i=OE(bo({},this.events),{[e]:t});this.events=i}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...t){var i,n;!e||!this.events||(n=(i=this.events)[e])==null||n.call(i,...t)}static clear(){this.events=void 0}};f();var mo=(n=>(n.ledger="ledger",n.mobile="mobile",n.webWallet="web-wallet",n.browserExtension="browser-extension",n))(mo||{});var Pu=r=>Te(void 0,null,function*(){if(!r.dappProvider)throw new Error("Error: Logout failed: There is no active session!");De.run("onLoginPending");let e=yield r.dappProvider.logout();return e&&(Ne.clear(),De.run("onLogout")),e});f();var IO=_e(Gr()),_O=_e(zf());f();var Xt=r=>typeof r=="string"?r.toUpperCase():r instanceof Error?r.message:`Error: ${JSON.stringify(r)}`;f();var Bu=()=>new Date().setHours(new Date().getHours()+24),bp=r=>Date.now()>r;var ts=r=>Te(void 0,null,function*(){let e=Ne.get("address"),t=Ne.get("expires");if(!(t&&bp(t))&&e&&r.networkProvider){let n=new IO.Address(e),s=new _O.Account(n);try{let o=yield r.networkProvider.getAccount(n);Ne.set("address",e),Ne.set("nonce",o.nonce.valueOf()),Ne.set("balance",o.balance.toString()),s.update(o)}catch(o){let a=Xt(o);console.warn(`Something went wrong trying to synchronize the user account: ${a}`)}}});f();function Cp(r){return r[Math.floor(Math.random()*r.length)]}var CO=r=>Te(void 0,null,function*(){if(!r.initOptions.walletConnectV2ProjectId||!r.initOptions.chainType)return;let e={onClientLogin:()=>{ts(r),De.run("onLoggedIn")},onClientLogout:()=>Pu(r),onClientEvent:n=>{console.log("wc2 session event: ",n)}},t=Cp(r.initOptions.walletConnectV2RelayAddresses),i=new bO.WalletConnectV2Provider(e,xi[r.initOptions.chainType].shortId,t,r.initOptions.walletConnectV2ProjectId);try{return yield i.init(),i}catch(n){console.warn("Can't initialize the Dapp Provider!")}});f();var KO=_e(TO()),Bp=_e(Gr()),zO=_e(NO()),kO=_e(MO()),WO=_e(zv()),$O=_e(VO()),YO=_e(QO()),JO=_e(jO()),XO=_e(GO());var Mp=class{constructor({apiUrl:e,chainType:t,apiTimeout:i}){var n,s;this.chainType=t||oh,this.apiUrl=e||((n=xi[this.chainType])==null?void 0:n.apiAddress),this.apiTimeout=i||((s=xi[this.chainType])==null?void 0:s.apiTimeout)}apiGet(e,t){return Te(this,null,function*(){if(typeof fetch!="undefined"){let i=new AbortController,n=setTimeout(()=>i.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:i.signal};try{let o=yield fetch(this.apiUrl+"/"+e,Object.assign(s,t||{})),a=yield o.json();if(!o.ok){let u=(a==null?void 0:a.error)||o.status;return clearTimeout(n),Promise.reject(u)}return clearTimeout(n),a}catch(o){this.handleApiError(o,e)}}})}apiPost(e,t,i){return Te(this,null,function*(){if(typeof fetch!="undefined"){let n=new AbortController,s=setTimeout(()=>n.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t||{}),signal:n.signal};try{let a=yield fetch(this.apiUrl+"/"+e,Object.assign(o,i||{})),u=yield a.json();if(!a.ok){let h=(u==null?void 0:u.error)||a.status;return clearTimeout(s),Promise.reject(h)}return clearTimeout(s),u}catch(a){this.handleApiError(a,e)}}})}handleApiError(e,t){if(!e.response)throw new Error(`Request error on url [${t}]: [${e.toString()}]`);let i=e.response.data,n=i.error||i.message||JSON.stringify(i);throw new Error(n)}sendTransaction(e){return Te(this,null,function*(){return(yield this.apiPost("transactions",e.toSendable())).txHash})}getAccount(e){return Te(this,null,function*(){let t=yield this.apiGet(`accounts/${e.bech32()}`);return{address:new Bp.Address((t==null?void 0:t.address)||""),nonce:Number((t==null?void 0:t.nonce)||0),balance:new KO.default((t==null?void 0:t.balance)||0),code:(t==null?void 0:t.code)||"",userName:(t==null?void 0:t.username)||""}})}getTransaction(e){return Te(this,null,function*(){let t=yield this.apiGet(`transactions/${e}`),i=new zO.TransactionStatus(t.status);return{hash:e,type:t.type||"",nonce:t.nonce||0,round:t.round,epoch:t.epoch||0,value:(t.value||0).toString(),sender:new Bp.Address(t.sender),receiver:new Bp.Address(t.receiver),gasPrice:t.gasPrice||0,gasLimit:t.gasLimit||0,data:y.Buffer.from(t.data||"","base64"),status:i,timestamp:t.timestamp||0,blockNonce:t.blockNonce||0,hyperblockNonce:t.hyperblockNonce||0,hyperblockHash:t.hyperblockHash||"",receipt:kO.TransactionReceipt.fromHttpResponse(t.receipt||{}),logs:WO.TransactionLogs.fromHttpResponse(t.logs||{}),contractResults:$O.ContractResults.fromApiHttpResponse(t.results||[]),isCompleted:!i.isPending()}})}queryContract(o){return Te(this,arguments,function*({address:e,func:t,args:i,value:n,caller:s}){try{let a=new XO.Query({address:e,func:t,args:i,value:n,caller:s}),u=new JO.ContractQueryRequest(a).toHttpRequest(),h=yield this.apiPost("query",u);return YO.ContractQueryResponse.fromHttpResponse(h)}catch(a){this.handleApiError(a,"query")}})}};f();var ZO=(r,e)=>Te(void 0,null,function*(){let t=yield ah();try{t&&(yield t.login()),De.run("onLoginPending")}catch(n){let s=Xt(n);console.warn(`Something went wrong trying to login the user: ${s}`)}if(!t)throw new Error("Error: There were problems with auth provider initialization!");let{signature:i}=t.account;if(e&&Ne.set("loginToken",e),i&&Ne.set("signature",i),r.networkProvider)try{let n=yield t.getAddress();if(!n)throw new Error("Canceled!");return Ne.set("address",n),Ne.set("loginMethod","browser-extension"),Ne.set("expires",Bu()),yield ts(r),De.run("onLoggedIn"),t}catch(n){console.warn(`Something went wrong trying to synchronize the user account: ${n==null?void 0:n.message}`),De.run("onLogout")}});f();f();var r8=_e(t8()),i8=_e(dl());var RK=r=>{var t;let e=document.createElement("template");return e.innerHTML=r.trim(),(t=e.content.firstChild)==null?void 0:t.cloneNode(!0)},LK=r=>{let e=`${rC}?wallet-connect=${encodeURIComponent(r)}`,t=document.createElement("a");return t.setAttribute("href",e),t.setAttribute("rel","noopener noreferrer nofollow"),t.setAttribute("target","_blank"),t.textContent="xPortal login",t.classList.add("elven-qr-code-deep-link"),t},FK=()=>{let r=document.createElement("div");return r.classList.add("elven-wc-pairings"),r},UK=()=>{let r=document.createElement("div");return r.textContent="Existing WalletConnect pairings:",r.classList.add("elven-wc-pairings-header"),r},wE={},qK=(r,e)=>{let t=document.createElement("button");return t.classList.add("elven-wc-pairings-remove-btn"),t.textContent="\u2716",wE[r.topic]=new AbortController,t.addEventListener("click",i=>{i.stopImmediatePropagation(),e(r.topic)},{signal:wE[r.topic].signal}),t},zp={},VK=(r,e,t)=>{var o,a;let i=document.createElement("div"),n=document.createElement("div");i.classList.add("elven-wc-pairing-item"),i.setAttribute("id",r.topic),n.classList.add("elven-wc-pairing-item-description"),n.textContent=`${(o=r.peerMetadata)==null?void 0:o.description} (${(a=r.peerMetadata)==null?void 0:a.url})`,i.appendChild(n);let s=qK(r,e);return i.appendChild(s),zp[r.topic]=new AbortController,i.addEventListener("click",()=>t(r.topic),{signal:zp[r.topic].signal}),i},HK=()=>{let r=document.createElement("div");return r.classList.add("elven-wc-pairing-item-confirm-msessage"),r.innerText="Confirm on xPortal app!",r},QK=r=>{if(!r)return;let e=document.getElementById(r);e==null||e.remove()},jK=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),GK=r=>Te(void 0,null,function*(){return r?yield r8.default.toString(r,{type:"svg"}):void 0}),n8=(r,e,t,i)=>Te(void 0,null,function*(){if(!r)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let n=null;typeof r=="string"?n=document.getElementById(r):r instanceof HTMLElement&&(n=r);let s=yield GK(e),o;if(s&&(o=RK(s)),n&&o&&(n.replaceChildren(),n.appendChild(o),jK()&&n.appendChild(LK(e))),n&&t instanceof i8.WalletConnectV2Provider){let a=t.pairings,u=p=>Te(void 0,null,function*(){try{p&&(yield t.logout({topic:p}),QK(p))}catch(w){let N=Xt(w);console.warn(`Something went wrong trying to remove the existing pairing: ${N}`)}finally{zp[p].abort()}}),h=p=>Te(void 0,null,function*(){try{let{approval:w}=yield t.connect({topic:p,methods:["erd_cancelAction"]}),N=document.getElementById(p);N==null||N.after(HK()),yield t.login({approval:w,token:i})}catch(w){let N=Xt(w);console.warn(`Something went wrong trying to login the user: ${N}`)}finally{for(let w of Object.values(zp))w==null||w.abort();for(let w of Object.values(wE))w==null||w.abort()}});if(a&&a.length>0){let p=FK();n.appendChild(p);let w=UK();p.appendChild(w);for(let N of a){let O=VK(N,u,h);p.appendChild(O)}}}return n});var kp=_e(dl());var s8=(r,e,t)=>Te(void 0,null,function*(){if(!e)throw new Error("You haven't provided the QR code container DOM element id");let i=Cp(r.initOptions.walletConnectV2RelayAddresses);if(!i||!r.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!r.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!r.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let n,s={onClientLogin:()=>Te(void 0,null,function*(){if(r.dappProvider instanceof kp.WalletConnectV2Provider){De.run("onLoginPending");let a=yield r.dappProvider.getAddress(),u=yield r.dappProvider.getSignature();Ne.set("address",a),Ne.set("loginMethod","mobile"),Ne.set("expires",Bu()),yield ts(r),u&&Ne.set("signature",u),t&&Ne.set("loginToken",t),De.run("onLoggedIn"),n==null||n.replaceChildren()}}),onClientLogout:()=>Te(void 0,null,function*(){r.dappProvider instanceof kp.WalletConnectV2Provider&&(yield Pu(r),De.run("onLogout"))}),onClientEvent:a=>{console.log("wc2 session event: ",a)}},o=new kp.WalletConnectV2Provider(s,xi[r.initOptions.chainType].shortId,i,r.initOptions.walletConnectV2ProjectId);try{if(o){r.dappProvider=o,De.run("onQrPending");let{uri:a,approval:u}=yield o.connect({methods:["erd_cancelAction"]}),h=t?`${a}&token=${t}`:a;return e&&h&&(n=yield n8(e,h,o,t),De.run("onQrLoaded")),yield o.login({approval:u,token:t}),o}}catch(a){let u=Xt(a);console.warn(`Something went wrong trying to login the user: ${u}`)}});f();var o8=_e(vl());var a8=(r,e,t)=>Te(void 0,null,function*(){let i=new o8.WalletProvider(`${r}${sh}`),n=typeof window!="undefined"?encodeURIComponent(`${window.location.origin}${e||"/"}`):"/",s=bo({callbackUrl:n},t?{token:t}:{});try{return De.run("onLoginPending"),Ne.set("loginMethod","web-wallet"),yield i.login(s),Ne.set("expires",Bu()),t&&Ne.set("loginToken",t),i}catch(o){let a=Xt(o);console.warn(`Something went wrong trying to login the user: ${a}`),Ne.set("loginMethod","")}});f();var _o=r=>{if(typeof window!="undefined"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(r)}};f();var u8=_e(vl());var c8=r=>Te(void 0,null,function*(){let e=_o("signature"),t=_o("address"),i=Ne.get("address");if(e&&Ne.set("signature",e),t||i)return t&&(Ne.set("address",t),window.history.replaceState(null,"",window.location.pathname)),new u8.WalletProvider(`${r}${sh}`)});f();var l8=_e(zf()),f8=_e(Wy());var Wp=(r,e)=>Te(void 0,null,function*(){De.run("onTxSent",r),yield new f8.TransactionWatcher(e).awaitCompleted(r);let i=r.getSender(),n=new l8.Account(i),s=yield e.getAccount(i);n.update(s),Ne.set("address",n.address.bech32()),Ne.set("nonce",n.getNonceThenIncrement().valueOf()),Ne.set("balance",n.balance.toString()),De.run("onTxFinalized",r)});f();var $p=_e(d8()),p8=_e(jy());var g8=(r,e,t)=>Te(void 0,null,function*(){if(_o($p.WALLET_PROVIDER_CALLBACK_PARAM)===$p.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&r&&e&&"getTransactionsFromWalletUrl"in r){let n=r.getTransactionsFromWalletUrl();window.history.replaceState(null,"",window.location.pathname);let s=n==null?void 0:n[0];if(s){s.data=y.Buffer.from(s.data).toString("base64");let o=p8.Transaction.fromPlainObject(s);o.setNonce(t);try{De.run("onTxStarted",o),yield e.sendTransaction(o),yield Wp(o,e)}catch(a){let u=Xt(a);throw De.run("onTxError",o,u),new Error(`Error: Transaction signing failed! ${u}`)}}}});var Rl=class{static init(e){return Te(this,null,function*(){let t=Ne.get();if(t.expires&&bp(t.expires)){Ne.clear(),this.dappProvider=void 0;return}this.initOptions=bo({chainType:oh,apiUrl:tC,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:iC},e),this.networkProvider=new Mp(this.initOptions),this.initOptions.onLoginPending&&De.set("onLoginPending",this.initOptions.onLoginPending),this.initOptions.onLoggedIn&&De.set("onLoggedIn",this.initOptions.onLoggedIn),this.initOptions.onQrPending&&De.set("onQrPending",this.initOptions.onQrPending),this.initOptions.onQrLoaded&&De.set("onQrLoaded",this.initOptions.onQrLoaded),this.initOptions.onLogout&&De.set("onLogout",this.initOptions.onLogout),this.initOptions.onTxStarted&&De.set("onTxStarted",this.initOptions.onTxStarted),this.initOptions.onTxSent&&De.set("onTxSent",this.initOptions.onTxSent),this.initOptions.onTxFinalized&&De.set("onTxFinalized",this.initOptions.onTxFinalized),this.initOptions.onTxError&&De.set("onTxError",this.initOptions.onTxError),((t==null?void 0:t.address)||t.loginMethod==="web-wallet"&&_o("address"))&&(t!=null&&t.loginMethod)&&(De.run("onLoginPending"),t.loginMethod==="browser-extension"&&(this.dappProvider=yield ah()),t.loginMethod==="mobile"&&(this.dappProvider=yield CO(this)),t.loginMethod==="web-wallet"&&this.initOptions.chainType&&(this.dappProvider=yield c8(xi[this.initOptions.chainType].walletAddress)),yield ts(this),De.run("onLoggedIn"),t.loginMethod==="web-wallet"&&(yield g8(this.dappProvider,this.networkProvider,t.nonce)))})}static login(e,t){return Te(this,null,function*(){var n;if(!Object.values(mo).includes(e))throw new Error("Error: Wrong login method!");if(!this.networkProvider)throw new Error("Error: Login failed: Use ElvenJs.init() first!");try{if(e==="browser-extension"){let s=yield ZO(this,t==null?void 0:t.token);this.dappProvider=s}if(e==="mobile"){let s=yield s8(this,t==null?void 0:t.qrCodeContainer,t==null?void 0:t.token);this.dappProvider=s}if(e==="web-wallet"&&((n=this.initOptions)!=null&&n.chainType)){let s=yield a8(xi[this.initOptions.chainType].walletAddress,t==null?void 0:t.callbackRoute,t==null?void 0:t.token);this.dappProvider=s}}catch(s){let o=Xt(s);throw new Error(`Error: ${o}`)}})}static logout(){return Te(this,null,function*(){try{let e=yield Pu(this);return this.dappProvider=void 0,e}catch(e){let t=Xt(e);console.warn("Something went wrong when logging out: ",t)}})}static signAndSendTransaction(e){return Te(this,null,function*(){if(!this.dappProvider)throw new Error("Error: Transaction signing failed: There is no active session!");if(!this.networkProvider)throw new Error("Error: Transaction signing failed: There is no active network provider!");try{De.run("onTxStarted",e);let t=Ne.get();e.setNonce(t.nonce),this.dappProvider instanceof y8.ExtensionProvider&&(yield this.dappProvider.signTransaction(e)),this.dappProvider instanceof m8.WalletConnectV2Provider&&(yield this.dappProvider.signTransaction(e)),this.dappProvider instanceof w8.WalletProvider&&(yield this.dappProvider.signTransaction(e)),t.loginMethod!=="web-wallet"&&(yield this.networkProvider.sendTransaction(e),yield Wp(e,this.networkProvider))}catch(t){let i=Xt(t);throw De.run("onTxError",e,i),new Error(`Error: Transaction signing failed! ${i}`)}return e})}static queryContract(o){return Te(this,arguments,function*({address:e,func:t,args:i=[],value:n=0,caller:s}){if(!this.networkProvider)throw new Error("Error: Query failed: There is no active network provider!");if(!e||!t)throw new Error("Error: Query failed: The Query arguments are not valid! Address and func required");try{return yield this.networkProvider.queryContract({address:e,func:t,args:i,value:n,caller:s})}catch(a){let u=Xt(a);throw new Error(`Error: Smart contract query failed! ${u}`)}})}},Ml=Rl;Ml.storage=Ne,Ml.destroy=()=>{Rl.networkProvider=void 0,Rl.dappProvider=void 0,Rl.initOptions=void 0,De.clear()};var export_Account=WK.Account;var export_Address=kK.Address;var export_AddressValue=rz.AddressValue;var export_BigUIntValue=E8.BigUIntValue;var export_BooleanValue=ZK.BooleanValue;var export_BytesValue=XK.BytesValue;var export_ContractCallPayloadBuilder=ez.ContractCallPayloadBuilder;var export_ContractFunction=tz.ContractFunction;var export_ESDTNFTTransferPayloadBuilder=v8.ESDTNFTTransferPayloadBuilder;var export_ESDTTransferPayloadBuilder=v8.ESDTTransferPayloadBuilder;var export_TokenPayment=zK.TokenPayment;var export_Transaction=$K.Transaction;var export_TransactionPayload=YK.TransactionPayload;var export_TransactionWatcher=JK.TransactionWatcher;var export_U32Value=E8.U32Value;export{export_Account as Account,export_Address as Address,export_AddressValue as AddressValue,export_BigUIntValue as BigUIntValue,export_BooleanValue as BooleanValue,export_BytesValue as BytesValue,export_ContractCallPayloadBuilder as ContractCallPayloadBuilder,export_ContractFunction as ContractFunction,export_ESDTNFTTransferPayloadBuilder as ESDTNFTTransferPayloadBuilder,export_ESDTTransferPayloadBuilder as ESDTTransferPayloadBuilder,Ml as ElvenJS,mo as LoginMethodsEnum,export_TokenPayment as TokenPayment,export_Transaction as Transaction,export_TransactionPayload as TransactionPayload,export_TransactionWatcher as TransactionWatcher,export_U32Value as U32Value}; /*! Bundled license information: ieee754/index.js: diff --git a/package.json b/package.json index 7a08df7..5b086bb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "elven.js", - "version": "0.8.1", + "version": "0.8.2", "description": "Authenticate, sign and send transactions on the MultiversX blockchain in the browser.", "browser": { ".": "./build/elven.js" diff --git a/src/auth/login-with-extension.ts b/src/auth/login-with-extension.ts index 2e906e9..8f3f827 100644 --- a/src/auth/login-with-extension.ts +++ b/src/auth/login-with-extension.ts @@ -47,13 +47,14 @@ export const loginWithExtension = async (elven: any, token?: string) => { await accountSync(elven); + EventsStore.run(EventStoreEvents.onLoggedIn); + return dappProvider; } catch (e: any) { console.warn( `Something went wrong trying to synchronize the user account: ${e?.message}` ); - } finally { - EventsStore.run(EventStoreEvents.onLoggedIn); + EventsStore.run(EventStoreEvents.onLogout); } } };