starknetkit
Version:
<!-- logo --> <p align="center"> <img width='300' src="https://starknetkit-website-git-blo-1541-argentlabs.vercel.app/starknetKit-logo.svg"> </p>
2 lines (1 loc) • 9.41 kB
JavaScript
"use strict";var P=Object.defineProperty;var A=(a,n,o)=>n in a?P(a,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):a[n]=o;var p=(a,n,o)=>(A(a,typeof n!="symbol"?n+"":n,o),o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("starknet"),l=require("./connector-e4ffe813.cjs"),i=require("./trpc-23773a5d.cjs"),f=require("./lastConnected-2e5632be.cjs");class W extends Error{constructor(o,t){super(o);p(this,"code");this.name="ConnectAndSignSessionError",this.code=t}}class I extends Error{constructor(o,t){super(o);p(this,"code");this.name="WebwalletError",this.code=t}}const k=385,v=775,O=385,N=440,U=420,L=438,m=[],D=(a,n)=>({...a,getLoginStatus:()=>n.getLoginStatus.mutate(),connectWebwallet:(t={})=>{const{theme:e}=t;return n.connectWebwallet.mutate({theme:e})},connectAndSignSession:t=>n.connectAndSignSession.mutate(t),connectWebwalletSSO:(t,e)=>n.connectWebwalletSSO.mutate({token:t,authorizedPartyId:e}),async request(t){switch(t.type){case"wallet_requestAccounts":return n.requestAccounts.mutate(t.params);case"wallet_signTypedData":{const e=t.params,s=e?.primaryType==="Session"&&e?.domain.name==="SessionAccount.session";i.setPopupOptions({width:O,height:N,location:s?"/signSessionKeys":"/signMessage"});const r=Array.isArray(t.params)?t.params:[t.params];return n.signTypedData.mutate(r)}case"wallet_getPermissions":return n.getPermissions.mutate();case"wallet_addInvokeTransaction":{const e=t.params.calls;return i.setPopupOptions({width:k,height:v,location:"/review"}),{transaction_hash:await n.addInvokeTransaction.mutate(e)}}case"wallet_requestChainId":return await n.requestChainId.mutate();case"wallet_addStarknetChain":return n.addStarknetChain.mutate(t.params);case"wallet_switchStarknetChain":return n.switchStarknetChain.mutate(t.params);case"wallet_watchAsset":return n.watchAsset.mutate();case"wallet_deploymentData":return n.deploymentData.mutate();default:throw new Error("not implemented")}},on:(t,e)=>{if(t==="accountsChanged")m.push({type:t,handler:e});else if(t==="networkChanged")m.push({type:t,handler:e});else throw new Error(`Unknwown event: ${t}`)},off:(t,e)=>{if(t!=="accountsChanged"&&t!=="networkChanged")throw new Error(`Unknwown event: ${t}`);const s=m.findIndex(r=>r.type===t&&r.handler===e);s>=0&&m.splice(s,1)}}),R=a=>{a.style.display="none",a.style.borderRadius="40px",a.style.inset="0",a.style.position="fixed",a.style.top="50%",a.style.left="50%",a.style.transform="translate(-50%, -50%)",a.style.backgroundColor="transparent",a.style.zIndex="999999",a.style.height=`${L}px`,a.style.width=`${U}px`},q=(a,n)=>{a.style.display="block",n.style.display="block"},x=(a,n)=>{a.style.display="none",n.style.display="none"},H=(a,n,o)=>{a.style.width=`${n}px`,a.style.height=`${o}px`},b="argent-webwallet-iframe",M=async(a,n)=>{const o="argent-webwallet-backdrop",t=new URL(a);t.pathname="/iframes/comms",a=t.toString();const e=document.createElement("iframe");e.src=a,e.loading="eager",e.sandbox.add("allow-scripts","allow-same-origin","allow-forms","allow-top-navigation","allow-popups"),e.allow="clipboard-write",e.id=b,e.setAttribute("allowtransparency","true"),e.setAttribute("transparent","true"),R(e),e.style.display=n?"block":"none";const s=document.createElement("div");s.id=o,s.style.position="fixed",s.style.inset="0",s.style.backgroundColor="rgba(0,0,0,0.5)",s.style.zIndex="999998",s.style.width="100dvw",s.style.height="100dvh",s.style.backdropFilter="blur(4px)";const r=document.getElementById(b);return r&&(r.remove(),document.getElementById(o)?.remove()),window.document.body.appendChild(e),await new Promise((c,w)=>{const h=setTimeout(()=>w(new Error("Timeout while loading an iframe")),2e4);e.addEventListener("load",async()=>{clearTimeout(h),c()})}),window.document.body.appendChild(s),{iframe:e,backdrop:s}},E=async(a,n,o)=>{const t=typeof window<"u"?window:void 0;if(!t)throw new Error("window is not defined");const e=D({host:t.location.origin,id:"argentWebWallet",icon:"https://www.ready.co/favicon.ico",name:"Web Wallet",version:"1.0.0"},n);if(o){const{iframe:s,backdrop:r}=o;n.updateModal.subscribe(void 0,{onData(c){switch(c.action){case"show":q(s,r);break;case"hide":x(s,r);break;case"updateSize":H(s,c.width,c.height);break}}})}return e},T="allowed-dapps",B=async a=>{const n=a===S.constants.NetworkName.SN_MAIN?i.MAINNET_WHITELIST_URL:i.TESTNET_WHITELIST_URL;try{const t=await(await caches.open(T)).match(n);if(t){const h=parseInt(t.headers.get("X-Cache-Timestamp")??"0",10);if((new Date().getTime()-h)/(1e3*60*60)<24)return t.json()}const e=await fetch(n),s=new Headers(e.headers);s.set("X-Cache-Timestamp",new Date().getTime().toString());const r=await e.json(),c=new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s});return await(await caches.open(T)).put(n,c),r}catch(o){throw new Error(o)}},G=async a=>new Promise(n=>{if(!a)return n(!1);try{navigator.webkitTemporaryStorage.queryUsageAndQuota((t,e)=>{n(Math.round(e/(1024*1024))<Math.round((performance?.memory?.jsHeapSizeLimit??1073741824)/(1024*1024))*2)},()=>n(!1))}catch{n(!1)}}),j=async a=>{const{userAgent:n}=navigator,o=!!(navigator.vendor&&navigator.vendor.indexOf("Google")===0&&navigator.brave===void 0&&!n.match(/Edg/)&&!n.match(/OPR/)),t=await G(o);if(!o||t){const r=i.trpcProxyClient({});return await E(a,r,void 0)}const e=i.mapTargetUrlToNetworkId(a),{allowedDapps:s}=await B(e);if(s.includes(window.location.hostname)){const r="argent-webwallet-backdrop",c="argent-webwallet-iframe",w=document.getElementById(r),h=document.getElementById(c);h&&h&&w&&(h.remove(),w.remove());const{iframe:g,backdrop:y}=await M(a,!1),C=i.trpcProxyClient({iframe:g.contentWindow??void 0});return await E(a,C,{iframe:g,backdrop:y})}else{const r=i.trpcProxyClient({});return await E(a,r,void 0)}},_="webwallet_logout";let d=null,u=null;class F extends l.Connector{constructor(o={}){super();p(this,"_wallet",null);p(this,"_options");this._options=o}available(){return!0}async ready(){if(this._wallet||await this.ensureWallet(),this._wallet)try{return(await this._wallet.request({type:"wallet_getPermissions"})).includes(f.Permission.ACCOUNTS)}catch{return!1}else return this._wallet=null,u=null,!1}get id(){return this._wallet=d,this._wallet?.id||"argentWebWallet"}get name(){return this._wallet=d,this._wallet?.name||"Web Wallet"}get icon(){return{light:i.DEFAULT_WEBWALLET_ICON,dark:i.DEFAULT_WEBWALLET_ICON}}get wallet(){if(!this._wallet)throw new l.ConnectorNotConnectedError;return this._wallet}get title(){return"Email"}get subtitle(){return"Powered by Ready"}async connectAndSignSession({callbackData:o,approvalRequests:t,sessionTypedData:e}){if(this._wallet||await this.ensureWallet(),!this._wallet)throw new l.ConnectorNotFoundError;try{return await this._wallet.connectAndSignSession({callbackData:o,approvalRequests:t,sessionTypedData:e,theme:this._options.theme})}catch(s){if(s instanceof Error&&(s.constructor.name==="TRPCClientError"||s.name==="TRPCClientError")){const r=s,c=r.shape.data.webwalletErrorMessage||r.message,w=r.shape.data.webwalletErrorCode||r.shape.message;throw new W(c,w)}throw new Error(s instanceof Error?s.message:String(s))}}async connect(o={}){if(this._wallet||await this.ensureWallet(),!this._wallet)throw new l.ConnectorNotFoundError;try{let t,e;if(this._options.ssoToken){const r=await this._wallet.connectWebwalletSSO(this._options.ssoToken,this._options.authorizedPartyId);t=r.account,e=r.chainId}else{const r=await this._wallet.connectWebwallet({theme:this._options.theme});t=r.account,e=r.chainId}if(!t||!e)return{};const s=i.getStarknetChainId(e);return u=t[0],{account:t[0],chainId:BigInt(s)}}catch{throw new l.UserRejectedRequestError}}async request(o){if(this._wallet||await this.ensureWallet(),!this._wallet)throw new l.ConnectorNotConnectedError;try{return await this._wallet.request(o)}catch(t){if(t instanceof Error&&(t.constructor.name==="TRPCClientError"||t.name==="TRPCClientError")){const e=t,s=e.shape.data.webwalletErrorMessage||e.message,r=e.shape.data.webwalletErrorCode||e.shape.message;throw r==="USER_LOGGED_OUT"&&(d=null,u=null,this._wallet=null,document.dispatchEvent(new Event(_))),new I(s,r)}throw new l.UserRejectedRequestError}}async disconnect(){if(!this.available()&&!this._wallet)throw new l.ConnectorNotFoundError;d=null,u=null,this._wallet=d,f.removeStarknetLastConnectedWallet()}async account(o){if(this._wallet=d,!this._wallet)throw new l.ConnectorNotConnectedError;if(!u)throw new l.ConnectorNotConnectedError;return new S.WalletAccount({provider:o,walletProvider:this._wallet,address:u})}async chainId(){if(!this._wallet)throw new l.ConnectorNotConnectedError;const o=await this._wallet.request({type:"wallet_requestChainId"}),t=i.getStarknetChainId(o);return BigInt(t)}async initEventListener(o){if(this._wallet=d,!this._wallet)throw new l.ConnectorNotConnectedError;this._wallet.on("accountsChanged",o)}async removeEventListener(o){if(this._wallet=d,!this._wallet)throw new l.ConnectorNotConnectedError;this._wallet.off("accountsChanged",o),d=null,u=null,this._wallet=null}async ensureWallet(){const o=this._options.url||i.DEFAULT_WEBWALLET_URL;i.setPopupOptions({origin:o,location:"/interstitialLogin"}),d=await j(o)??null,this._wallet=d}}const z=a=>{document.addEventListener(_,()=>{a()})};exports.ConnectAndSignSessionError=W;exports.WEBWALLET_LOGOUT_EVENT=_;exports.WebWalletConnector=F;exports.WebwalletError=I;exports.handleWebwalletLogoutEvent=z;