@keplr-ewallet/ewallet-sdk-core
Version:
3 lines (2 loc) • 7.55 kB
JavaScript
import"@keplr-ewallet/stdlib-js";const e="keplr_ewallet_attached";function t(e){return new Promise((t,n)=>{if(null===this.iframe.contentWindow)return void n("iframe contentWindow is null");const s=this.iframe.contentWindow,o=new MessageChannel;o.port1.onmessage=e=>{const n=e.data;console.debug("[keplr] reply recv",n),n.hasOwnProperty("payload")?t(n):(console.error("[keplr] unknown msg type"),t({target:"keplr_ewallet_sdk",msg_type:"unknown_msg_type",payload:JSON.stringify(n)}))},s.postMessage(e,this.sdkEndpoint,[o.port2])})}async function n(e){let t=null;const n=new Promise((e,n)=>{t=setTimeout(()=>n(new Error("Show modal timeout")),3e5)});try{this.iframe.style.display="block";const s=await Promise.race([this.sendMsgToIframe(e),n]);if(t&&(clearTimeout(t),t=null),"show_modal_ack"!==s.msg_type)throw new Error("Unreachable");if(!s.payload.success)throw new Error(s.payload.err);return s.payload.data}catch(e){if(t&&(clearTimeout(t),t=null),e instanceof Error&&"Show modal timeout"===e.message)throw await this.hideModal(),new Error("Show modal timeout");throw e}}const s={STATE:"state"};async function o(t){if("google"===t)return await async function(t,n,o){const r=`${new URL(t).origin}/google/callback`;console.debug("[keplr] window host: %s",window.location.host),console.debug("[keplr] redirectUri: %s",r);const i=Array.from(crypto.getRandomValues(new Uint8Array(8))).map(e=>e.toString(16).padStart(2,"0")).join(""),a=o({target:e,msg_type:"set_oauth_nonce",payload:i}),c={apiKey:n,targetOrigin:window.location.origin},l=JSON.stringify(c);console.debug("[keplr] oauthStateString: %s",l);const d=new URL("https://accounts.google.com/o/oauth2/v2/auth");d.searchParams.set("client_id","239646646986-8on7ql1vmbcshbjk12bdtopmto99iipm.apps.googleusercontent.com"),d.searchParams.set("redirect_uri",r),d.searchParams.set("response_type","token id_token"),d.searchParams.set("scope","openid email profile"),d.searchParams.set("prompt","login"),d.searchParams.set("nonce",i),d.searchParams.set(s.STATE,l);const u=window.open(d.toString(),"google_oauth","width=1200,height=800");if(!u)throw new Error("Failed to open new window for google oauth sign in");const h=await a;if("set_oauth_nonce_ack"!==h.msg_type||!h.payload.success)throw u.close(),new Error("Failed to set nonce for google oauth sign in");return new Promise((e,t)=>{let n,s;function o(e){n=window.setTimeout(()=>{u&&u.closed&&(i(),t(new Error("Window closed by user")))},200)}function r(n){const s=n.data;"oauth_sign_in_ack"===s.msg_type&&(i(),s.payload.success?e():t(new Error(s.payload.err)))}function i(){window.clearTimeout(n),window.clearTimeout(s),window.removeEventListener("focus",o),window.removeEventListener("message",r),u&&!u.closed&&u.close()}window.addEventListener("focus",o),window.addEventListener("message",r),s=window.setTimeout(()=>{i(),t(new Error("Timeout: no response within 5 minutes"))},3e5)})}(this.sdkEndpoint,this.apiKey,this.sendMsgToIframe);throw Error(`invalid type: ${t}`)}async function r(){await this.sendMsgToIframe({target:e,msg_type:"sign_out",payload:null})}async function i(){try{const t=await this.sendMsgToIframe({target:e,msg_type:"get_public_key",payload:null});return"get_public_key_ack"===t.msg_type&&t.payload.success?t.payload.data:null}catch(e){return console.error("[core] getPublicKey failed with error:",e),null}}async function a(){try{const t=await this.sendMsgToIframe({target:e,msg_type:"get_email",payload:null});return"get_email_ack"===t.msg_type&&t.payload.success?t.payload.data:null}catch(e){return console.error("[core] getEmail failed with error:",e),null}}async function c(){this.iframe.style.display="none"}async function l(e){const t=await this.sendMsgToIframe(e);if("make_signature_ack"!==t.msg_type)throw new Error("Unreachable");if(!t.payload.success)throw new Error(t.payload.err);return t.payload.data}async function d(e){try{console.debug("[keplr] init core, origin: %s",e);return"init_state_ack"===(await this.sendMsgToIframe({target:"keplr_ewallet_attached",msg_type:"init_state",payload:e})).msg_type?{success:!0,data:!0}:{success:!1,err:"init_state_ack not received"}}catch(e){return console.error("[keplr] initState failed with error:",e),{success:!1,err:e instanceof Error?e.message:String(e)}}}async function u(e,t){this.eventEmitter&&this.eventEmitter.on("accountsChanged",()=>{console.log(123)})}class h{constructor(){this.listeners={},this.listeners={}}on(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(e=>e(...t))}}class w{constructor(e,s,w){this.showModal=n.bind(this),this.hideModal=c.bind(this),this.sendMsgToIframe=t.bind(this),this.signIn=o.bind(this),this.signOut=r.bind(this),this.getPublicKey=i.bind(this),this.getEmail=a.bind(this),this.makeSignature=l.bind(this),this.initState=d.bind(this),this.on=u.bind(this),this.apiKey=e,this.iframe=s,this.sdkEndpoint=w,this.origin=window.location.origin,this.eventEmitter=new h}}const p="keplr-ewallet-attached";const g="https://attached.embed.keplr.app";async function m(e){if(console.debug("[keplr] init"),console.debug("[keplr] sdk endpoint: %s",e.sdk_endpoint),void 0===window)return console.error("[keplr] EWallet can only be initialized in the browser"),{success:!1,err:"Not in the browser context"};if(window.__keplr_ewallet){return null!==document.getElementById("keplr-ewallet")?{success:!1,err:"Some problem occurred during Keplr eWallet initialization"}:(console.debug("[keplr] already initialized"),{success:!0,data:window.__keplr_ewallet})}const t=await async function(e){const t=e??g;try{return(await fetch(t,{mode:"no-cors"})).ok?{success:!1,err:`SDK endpoint, resp contains err, url: ${t}`}:{success:!0,data:t}}catch(e){return console.error("[keplr] check url fail, url: %s",t),{success:!1,err:`check url fail, ${e.toString()}`}}}(e.sdk_endpoint);if(!t.success)return t;const n=function(){if(window.__keplr_ewallet_ev)return Promise.resolve(!1);const e=[],t=new Promise(t=>{e.push(t)});async function n(t){if("init"===t.data.msg_type){if(e.length>1)throw new Error("Callback should exist");(0,e[0])(!0)}}return window.addEventListener("message",n),window.__keplr_ewallet_ev=n,console.debug("[keplr] msg listener registered"),t}(),s=t.data;console.log("[keplr] resolved sdk endpoint: %s",s);const o=function(e){const t=document.getElementsByTagName("body");if(void 0===t[0])return console.error("body element not found"),{success:!1,err:"body element not found"};const n=document.getElementById(p);if(null!==n)return console.warn("[keplr] iframe already exists"),{success:!0,data:n};const s=t[0];console.debug("[keplr] appending iframe");const o=document.createElement("iframe");return o.src=e,o.id=p,o.style.position="fixed",o.style.top="0",o.style.left="0",o.style.width="100vw",o.style.height="100vh",o.style.border="none",o.style.display="none",o.style.backgroundColor="transparent",o.style.overflow="hidden",o.style.zIndex="1000000",s.appendChild(o),{success:!0,data:o}}(s);if(!o.success)return o;const r=o.data;await n;const i=new w(e.api_key,r,s);window.__keplr_ewallet=i;const a=await async function(){try{const e=window.location.toString();return{success:!0,data:new URL(e).origin}}catch(e){return console.error("[keplr] get host origin fail"),{success:!1,err:`get host origin fail, ${e.toString()}`}}}();if(!a.success)return a;const c=a.data,l=await i.initState(c);return l.success?{success:!0,data:i}:l}export{h as EventEmitter2,w as KeplrEWallet,s as RedirectUriSearchParamsKey,m as initKeplrEwalletCore};
//# sourceMappingURL=index.min.js.map