@privy-io/react-auth 1.88.3 → 1.88.4-beta-20241004182123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -2256,7 +2256,7 @@
2256
2256
  && > input::placeholder {
2257
2257
  color: var(--privy-color-foreground-3);
2258
2258
  }
2259
- `;const gp=({isEditable:t,setIsEditable:r,defaultValue:n})=>{let a=i.useRef(null),{authenticated:s}=o.usePrivy(),{navigate:l,setModalData:d,currentScreen:c,data:u}=g.usePrivyModal(),{initLoginWithSms:h}=o.usePrivyInternal(),{enabled:p,token:y}=ba();return e.jsxs(e.Fragment,{children:[e.jsx(ns,{$if:!t,children:e.jsx(yp,{ref:a,onSubmit:async function({qualifiedPhoneNumber:e}){if(!p||y||s)try{await h(e,y,u?.login?.disableSignup),l(g.ModalScreen.AWAITING_PASSWORDLESS_CODE)}catch(e){d({errorModalData:{error:e,previousScreen:c||g.ModalScreen.LANDING}}),l(g.ModalScreen.ERROR_SCREEN)}else d({captchaModalData:{callback:t=>h(e,t,u?.login?.disableSignup),userIntentRequired:!1,onSuccessNavigateTo:g.ModalScreen.AWAITING_PASSWORDLESS_CODE,onErrorNavigateTo:g.ModalScreen.ERROR_SCREEN}}),l(g.ModalScreen.CAPTCHA_SCREEN)},defaultValue:n})}),e.jsx(ns,{$if:t,children:e.jsxs(ts,{onClick:()=>{r(),setTimeout((()=>{a.current?.focus()}),0)},children:[e.jsx(Ye.default,{})," Continue with SMS"]})})]})};let vp={apple:{logo:e.jsx(ea,{}),displayName:"Apple"},discord:{logo:e.jsx(ta,{}),displayName:"Discord"},github:{logo:e.jsx(ra,{}),displayName:"GitHub"},google:{logo:e.jsx(ia,{}),displayName:"Google"},linkedin:{logo:e.jsx(oa,{}),displayName:"LinkedIn"},spotify:{logo:e.jsx(sa,{}),displayName:"Spotify"},instagram:{logo:e.jsx(aa,{}),displayName:"Instagram"},twitter:{logo:e.jsx(da,{}),displayName:"Twitter"},tiktok:{logo:e.jsx(la,{}),displayName:"TikTok"}};const wp=({provider:t})=>{let{enabled:r,token:n}=ba(),{navigate:a,setModalData:s,data:l}=g.usePrivyModal(),[c,u]=i.useState(!1),{initLoginWithOAuth:h}=o.usePrivyInternal(),{accountType:p}=d.useRecentlyUsedLogin(),y=p?np(p):null,{displayName:m,logo:f}=vp[t];return e.jsxs(ts,{onClick:()=>{u(!0),r&&!n?(s({captchaModalData:{callback:e=>h(t,e,l?.login?.disableSignup),userIntentRequired:!0,onSuccessNavigateTo:null,onErrorNavigateTo:g.ModalScreen.ERROR_SCREEN}}),a(g.ModalScreen.CAPTCHA_SCREEN)):h(t,void 0,l?.login?.disableSignup)},disabled:c,children:[f," ",m,y?.loginMethod===t&&e.jsx(xp,{color:"gray",children:"Recent"})]})};let xp=C.styled(d.Chip)`
2259
+ `;const gp=({isEditable:t,setIsEditable:r,defaultValue:n})=>{let a=i.useRef(null),{authenticated:s}=o.usePrivy(),{navigate:l,setModalData:d,currentScreen:c,data:u}=g.usePrivyModal(),{initLoginWithSms:h}=o.usePrivyInternal(),{enabled:p,token:y}=ba();return e.jsxs(e.Fragment,{children:[e.jsx(ns,{$if:!t,children:e.jsx(yp,{ref:a,onSubmit:async function({qualifiedPhoneNumber:e}){if(!p||y||s)try{await h(e,y,u?.login?.disableSignup),l(g.ModalScreen.AWAITING_PASSWORDLESS_CODE)}catch(e){d({errorModalData:{error:e,previousScreen:c||g.ModalScreen.LANDING}}),l(g.ModalScreen.ERROR_SCREEN)}else d({captchaModalData:{callback:t=>h(e,t,u?.login?.disableSignup),userIntentRequired:!1,onSuccessNavigateTo:g.ModalScreen.AWAITING_PASSWORDLESS_CODE,onErrorNavigateTo:g.ModalScreen.ERROR_SCREEN}}),l(g.ModalScreen.CAPTCHA_SCREEN)},defaultValue:n})}),e.jsx(ns,{$if:t,children:e.jsxs(ts,{onClick:()=>{r(),setTimeout((()=>{a.current?.focus()}),0)},children:[e.jsx(Ye.default,{})," Continue with SMS"]})})]})};let vp={apple:{logo:e.jsx(ea,{}),displayName:"Apple"},discord:{logo:e.jsx(ta,{}),displayName:"Discord"},github:{logo:e.jsx(ra,{}),displayName:"GitHub"},google:{logo:e.jsx(ia,{}),displayName:"Google"},linkedin:{logo:e.jsx(oa,{}),displayName:"LinkedIn"},spotify:{logo:e.jsx(sa,{}),displayName:"Spotify"},instagram:{logo:e.jsx(aa,{}),displayName:"Instagram"},twitter:{logo:e.jsx(da,{}),displayName:"X (Twitter)"},tiktok:{logo:e.jsx(la,{}),displayName:"TikTok"}};const wp=({provider:t})=>{let{enabled:r,token:n}=ba(),{navigate:a,setModalData:s,data:l}=g.usePrivyModal(),[c,u]=i.useState(!1),{initLoginWithOAuth:h}=o.usePrivyInternal(),{accountType:p}=d.useRecentlyUsedLogin(),y=p?np(p):null,{displayName:m,logo:f}=vp[t];return e.jsxs(ts,{onClick:()=>{u(!0),r&&!n?(s({captchaModalData:{callback:e=>h(t,e,l?.login?.disableSignup),userIntentRequired:!0,onSuccessNavigateTo:null,onErrorNavigateTo:g.ModalScreen.ERROR_SCREEN}}),a(g.ModalScreen.CAPTCHA_SCREEN)):h(t,void 0,l?.login?.disableSignup)},disabled:c,children:[f," ",m,y?.loginMethod===t&&e.jsx(xp,{color:"gray",children:"Recent"})]})};let xp=C.styled(d.Chip)`
2260
2260
  margin-left: auto;
2261
2261
  `;function Cp(t){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",viewBox:"0 0 240 240",...t,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{x1:"120",y1:"240",x2:"120",gradientUnits:"userSpaceOnUse",id:"telegram-linear-gradient",children:[e.jsx("stop",{offset:"0",stopColor:"#1d93d2"}),e.jsx("stop",{offset:"1",stopColor:"#38b0e3"})]})}),e.jsx("title",{children:"Telegram_logo"}),e.jsx("circle",{cx:"120",cy:"120",r:"120",fill:"url(#telegram-linear-gradient)"}),e.jsx("path",{d:"M81.229,128.772l14.237,39.406s1.78,3.687,3.686,3.687,30.255-29.492,30.255-29.492l31.525-60.89L81.737,118.6Z",fill:"#c8daea"}),e.jsx("path",{d:"M100.106,138.878l-2.733,29.046s-1.144,8.9,7.754,0,17.415-15.763,17.415-15.763",fill:"#a9c6d8"}),e.jsx("path",{d:"M81.486,130.178,52.2,120.636s-3.5-1.42-2.373-4.64c.232-.664.7-1.229,2.1-2.2,6.489-4.523,120.106-45.36,120.106-45.36s3.208-1.081,5.1-.362a2.766,2.766,0,0,1,1.885,2.055,9.357,9.357,0,0,1,.254,2.585c-.009.752-.1,1.449-.169,2.542-.692,11.165-21.4,94.493-21.4,94.493s-1.239,4.876-5.678,5.043A8.13,8.13,0,0,1,146.1,172.5c-8.711-7.493-38.819-27.727-45.472-32.177a1.27,1.27,0,0,1-.546-.9c-.093-.469.417-1.05.417-1.05s52.426-46.6,53.821-51.492c.108-.379-.3-.566-.848-.4-3.482,1.281-63.844,39.4-70.506,43.607A3.21,3.21,0,0,1,81.486,130.178Z",fill:"#fff"})]})}const Ep=()=>{let{enabled:t,token:r}=ba(),{navigate:n,setModalData:a,data:s}=g.usePrivyModal(),[l,c]=i.useState(!1),{initLoginWithTelegram:u}=o.usePrivyInternal(),{accountType:h}=d.useRecentlyUsedLogin();async function p(e){try{await u(e,s?.login?.disableSignup),a({telegramAuthModalData:{seamlessAuth:!1}}),n(g.ModalScreen.TELEGRAM_AUTH_SCREEN)}catch(e){console.error(e),c(!1)}}return e.jsxs(ts,{onClick:async function(){if(c(!0),t&&!r)return a({captchaModalData:{callback:p,userIntentRequired:!0,onSuccessNavigateTo:null,onErrorNavigateTo:g.ModalScreen.ERROR_SCREEN}}),void n(g.ModalScreen.CAPTCHA_SCREEN);await p(r)},disabled:l,children:[e.jsx(Cp,{}),"Telegram","telegram"===h&&e.jsx(bp,{color:"gray",children:"Recent"})]})};let bp=C.styled(d.Chip)`
2262
2262
  margin-left: auto;
@@ -3115,4 +3115,4 @@
3115
3115
  box-shadow: 0px 8px 36px rgba(55, 65, 81, 0.15);
3116
3116
  border-radius: var(--privy-border-radius-lg);
3117
3117
  }
3118
- `;function rg(t){let r=i.useRef(null),n=i.useRef();return i.useEffect((()=>{n.current?.remove(),n.current=function({botUsername:e,scriptHost:t}){let r=document.createElement("script"),{origin:n}=new URL(t);return r.async=!0,r.src=`${n}/js/telegram-login.js`,r.setAttribute("data-telegram-login",e),r.setAttribute("data-request-access","write"),r.setAttribute("data-lang","en"),r}(t),r.current?.after(n.current)}),[t]),e.jsx("div",{ref:r,hidden:!0})}async function ng(e,t,r,n,i,a=!1){let o=a,s=async s=>{if(o&&t&&t.length>0){s===(a?0:1)?i("configureMfa","onMfaRequired",t):n.current?.reject(new Ql("missing_or_invalid_mfa","MFA verification failed, retry."));let o=await new Promise(((e,t)=>{r.current={resolve:e,reject:t},setTimeout((()=>{let e=new Ql("mfa_timeout","Timed out waiting for MFA code");n.current?.reject(e),t(e)}),3e5)}));return await e(o)}return await e()},l=null;for(let e=0;e<4;e++)try{l=await s(e),n.current?.resolve(void 0);break}catch(e){if("missing_or_invalid_mfa"!==e.type)throw n.current?.resolve(void 0),e;o=!0}if(null===l){let e=new Ql("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return l}var ig;let ag=(ig=0,()=>"id-"+ig++);function og(e){return void 0!==e.error}let sg=new class{enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let r=this.callbacks[t];if(!r)throw Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:wallet:create":case"privy:wallet:create-additional":case"privy:wallet:import":case"privy:wallet:connect":case"privy:wallet:recover":case"privy:wallet:rpc":case"privy:wallet:set-recovery":case"privy:mfa:verify":case"privy:mfa:init-enrollment":case"privy:mfa:submit-enrollment":case"privy:mfa:unenroll":case"privy:mfa:clear":case"privy:farcaster:init-signer":case"privy:farcaster:sign":case"privy:solana-wallet:create":case"privy:solana-wallet:connect":case"privy:solana-wallet:recover":case"privy:solana-wallet:rpc":case"privy:delegated-actions:consent":return r;default:throw Error(`invalid wallet event type ${e}`)}}constructor(){this.callbacks={}}},lg=new Map,dg=(e,t)=>"bigint"==typeof t?t.toString():t,cg=(e,t)=>`${e}${JSON.stringify(t,dg)}`;function ug(e,t,r,n){let i=r.contentWindow;if(!i)throw Error("iframe not initialized");let a=cg(e,t);if("privy:wallet:create"===e){let e=lg.get(a);if(e)return e}let o=new Promise(((r,a)=>{let o=ag();sg.enqueue(o,{resolve:r,reject:a}),i.postMessage({id:o,event:e,data:t},n)})).finally((()=>{lg.delete(a)}));return lg.set(a,o),o}function hg(t){let r=i.useRef(null),n=i.useRef(t.mfaMethods),a=d.useEmitPrivyEvent(),[o,s]=i.useState(!1);return i.useEffect((()=>{n.current=t.mfaMethods}),[t.mfaMethods]),i.useEffect((()=>{if(!o)return;let e=r.current;if(!e)return;function i(e){var r;e&&e.origin===t.origin&&"string"==typeof(r=e.data).event&&/^privy:.+/.test(r.event)&&function(e){switch(e.event){case"privy:iframe:ready":let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":let r=sg.dequeue(e.event,e.id);return og(e)?r.reject(new Ql(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallet:create-additional":let n=sg.dequeue(e.event,e.id);return og(e)?n.reject(new Ql(e.error.type,e.error.message)):n.resolve(e.data);case"privy:wallet:import":let i=sg.dequeue(e.event,e.id);return og(e)?i.reject(new Ql(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:connect":let a=sg.dequeue(e.event,e.id);return og(e)?a.reject(new Ql(e.error.type,e.error.message)):a.resolve(e.data);case"privy:wallet:recover":let o=sg.dequeue(e.event,e.id);return og(e)?o.reject(new Ql(e.error.type,e.error.message)):o.resolve(e.data);case"privy:wallet:rpc":let s=sg.dequeue(e.event,e.id);return og(e)?s.reject(new Ql(e.error.type,e.error.message)):s.resolve(e.data);case"privy:wallet:set-recovery":let l=sg.dequeue(e.event,e.id);return og(e)?l.reject(new Ql(e.error.type,e.error.message)):l.resolve(e.data);case"privy:mfa:verify":let d=sg.dequeue(e.event,e.id);return og(e)?d.reject(new Ql(e.error.type,e.error.message)):d.resolve(e.data);case"privy:mfa:init-enrollment":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:init-signer":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let c=sg.dequeue(e.event,e.id);return og(e)?c.reject(new Ql(e.error.type,e.error.message)):c.resolve(e.data);case"privy:solana-wallet:connect":let u=sg.dequeue(e.event,e.id);return og(e)?u.reject(new Ql(e.error.type,e.error.message)):u.resolve(e.data);case"privy:solana-wallet:recover":let h=sg.dequeue(e.event,e.id);return og(e)?h.reject(new Ql(e.error.type,e.error.message)):h.resolve(e.data);case"privy:solana-wallet:rpc":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(e.data)}let s={create:r=>ug("privy:wallet:create",r,e,t.origin),createAdditional:r=>ug("privy:wallet:create-additional",r,e,t.origin),import:r=>ug("privy:wallet:import",r,e,t.origin),connect:r=>ug("privy:wallet:connect",r,e,t.origin),recover:r=>ng((n=>ug("privy:wallet:recover",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a,!r.recoveryMethod||"privy"===r.recoveryMethod),rpc:r=>ng((n=>ug("privy:wallet:rpc",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a),createSolana:r=>ug("privy:solana-wallet:create",r,e,t.origin),connectSolana:r=>ug("privy:solana-wallet:connect",r,e,t.origin),recoverSolana:r=>ug("privy:solana-wallet:recover",r,e,t.origin),rpcSolana:r=>ug("privy:solana-wallet:rpc",r,e,t.origin),createDelegatedAction:r=>ug("privy:delegated-actions:consent",r,e,t.origin),setRecovery:r=>ng((n=>ug("privy:wallet:set-recovery",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a),verifyMfa:r=>ng((n=>ug("privy:mfa:verify",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a,!0),initEnrollMfa:r=>ng((n=>ug("privy:mfa:init-enrollment",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a),submitEnrollMfa:r=>ng((n=>ug("privy:mfa:submit-enrollment",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a),unenrollMfa:r=>ng((n=>ug("privy:mfa:unenroll",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a,!0),clearMfa:r=>ug("privy:mfa:clear",r,e,t.origin),initFarcasterSigner:r=>ug("privy:farcaster:init-signer",r,e,t.origin),signFarcasterMessage:r=>ug("privy:farcaster:sign",r,e,t.origin)};window.addEventListener("message",i);let l=new AbortController;return d.invokeUntilSettled((()=>ug("privy:iframe:ready",{},e,t.origin)),{abortSignal:l.signal}).then((()=>t.onLoad(s)),((...e)=>{console.warn("Privy iframe failed to load: ",...e),t.onLoadFailed()})),()=>{window.removeEventListener("message",i),l.abort()}}),[o]),e.jsx("iframe",{ref:r,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>s(!0),src:d.constructURL(t.origin,`/apps/${t.appId}/embedded-wallets`,{caid:t.clientAnalyticsId,client_id:t.appClientId})})}class pg{async handleSignMessage(e){if(!e.params||"string"!=typeof e.params.message)throw Error("Message must be provided as a string for Solana signMessage RPC");return await _g({message:e.params.message})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await Sg())throw Error("User must be authenticated to use embedded Solana wallet");if(!await Pg())throw new o.PrivyClientError("Unable to connect to Solana embedded wallet");if("signMessage"===e.method)return await this.handleSignMessage(e);throw Error("Embedded Solana provider does not yet support this RPC method.")}constructor(e,t){this.walletProxy=e,this.address=t}}const yg="popup-privy-oauth",mg="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";async function fg({url:e,popup:t,provider:r}){return t.location=e,new Promise(((e,r)=>{function n(){t?.close(),window.removeEventListener("message",i)}function i(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(e(t.data),n()),"https://cdn.apple-cloudkit.com"===t.origin&&t.data.ckSession&&(e({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:t.data.ckSession}),n()),"PRIVY_OAUTH_ERROR"===t.data.type&&(r(t.data.error),n()))}window.addEventListener("message",i)}))}let gg,vg,wg,xg,Cg,Eg,bg;function Sg(){return gg?gg.getAccessToken():Promise.resolve(d.e5.get(l.TOKEN_STORAGE_KEY)||null)}const Ag=(e,t,r)=>vg(e,t,r),jg=(e,t,r)=>wg(e,t,r),$g=(e,t,r,n)=>xg(e,t,r,n),Tg=()=>Cg(),Pg=()=>Eg(),_g=({message:e})=>bg({message:e});let kg=s=>{let c=s.client,[h,p]=i.useState(!1),[y,f]=i.useState(!1),[v,w]=i.useState(!1),[x,C]=i.useState(null),[E,b]=i.useState([]),[S,A]=i.useState([]),[j,$]=i.useState(null),T=i.useRef(E),[P,_]=i.useState(!1),[k,N]=i.useState(null),[I,M]=i.useState(!1),[O,R]=i.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:o.notImplemented}),[F,L]=i.useState({status:"initial"}),[U,D]=i.useState({status:"initial"}),[W,B]=i.useState({status:"initial"}),[H,G]=i.useState({status:"initial"}),[q,z]=i.useState({status:"initial"}),[V,K]=i.useState(null),Y=l.useAppConfig(),Z=l.useIsServerConfigLoaded(),[X,J]=i.useState(!0),[Q,ee]=i.useState({}),[te,re]=i.useState(null),[ne,ie]=i.useState(null),[ae,oe]=i.useState(!1),[se,le]=i.useState(!1),[de,ce]=i.useState(Y.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),ue=i.useRef(null),he=i.useRef(null),pe=i.useRef(d.privyEventsDefault),[ye,me]=i.useState(!1);c.onStoreToken=e=>{e&&d.emitPrivyEvent(pe,"accessToken","onAccessTokenGranted",e)},c.onDeleteToken=()=>{C(null),w(!1),d.emitPrivyEvent(pe,"accessToken","onAccessTokenRemoved")};let fe=i.useRef(null),ge=i.useRef(null),ve=i.useRef(!1),we=e=>{N(e),setTimeout((()=>{p(!0)}),15),c.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:e}})},xe=e=>{"off"!==Y.embeddedWallets.createOnLogin&&J(!0),we(e)};i.useEffect((()=>{let e=u.getPrivySolanaWallet(x);if(!e||!V)return void $(null);let t={type:"solana",imported:!1,address:e.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",meta:{name:"Privy Wallet",icon:void 0,id:"io.privy.solana.wallet"},linked:!0,fund:()=>{throw new o.PrivyClientError("Funding is not supported for Solana embedded wallets.")},unlink:()=>{throw new o.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new pg(V,e.address),signMessage:async e=>{let r=await Sg();if(!r||!V)throw new o.PrivyClientError("Must have valid access token and Privy wallet to send transaction",o.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Be.recoverEmbeddedSolanaWallet().catch((()=>!1)))throw new o.PrivyClientError("Wallet couldn't be connected",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let{response:n}=await V.rpcSolana({accessToken:r,publicKey:t.address,request:{method:"signMessage",params:{message:Buffer.from(e).toString("base64")}}});return Buffer.from(n.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:n}=await Oe({transaction:e,connection:t,transactionOptions:r,wallet:this});return n},async signTransaction(e){let t=await Sg();if(!t||!V)throw new o.PrivyClientError("Must have valid access token and Privy wallet to send transaction",o.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Be.recoverEmbeddedSolanaWallet().catch((()=>!1)))throw new o.PrivyClientError("Wallet couldn't be connected",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);return await xm({tx:e,accessToken:t,walletProxy:V,transactingWalletAddress:this.address}),e},loginOrLink:async()=>{throw new o.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{$(null)},isConnected:async()=>!0};$(t)}),[V,x]),i.useEffect((()=>{if(!x)return void c.connectors?.removeEmbeddedWalletConnectors();let e=u.getPrivyEthereumWallet(x),t=u.getPrivyEthereumHDWallets(x),r=u.getImportedPrivyEthereumWallet(x);e&&t.length||c.connectors?.removeEmbeddedWalletConnectors(),r||c.connectors?.removeImportedWalletConnector(),c.connectors?V?(e&&c.connectors.addEmbeddedWalletConnectors({walletProxy:V,rootWallet:e,embeddedWallets:t,defaultChain:Y.defaultChain,appId:s.appId}),r&&c.connectors.addImportedWalletConnector(V,r.address,Y.defaultChain,s.appId)):console.debug("Failed to add embedded wallet connector: Wallet proxy not initialized"):console.debug("Failed to add embedded wallet connector: Client connectors not initialized")}),[V,x]),i.useEffect((()=>{V&&ne?.(V)}),[V]),i.useEffect((()=>{(async()=>{if(!Y.customAuth?.enabled)return void ce({status:"not-enabled"});J(!0),ce({status:"loading"});let{getCustomAccessToken:e,isLoading:t}=Y.customAuth;if(y&&!t)try{let t=await e();if(!t&&v)return await We.logout(),ce({status:"done"}),void d.emitPrivyEvent(pe,"customAuth","onUnauthenticated");if(!t||v)return void ce({status:"done"});c.startAuthFlow(new Ii(t));let{user:r,isNewUser:n}=await c.authenticate();if(!r)return await We.logout(),ce({status:"error",error:new o.PrivyClientError("Failed to sync with custom auth provider")}),void d.emitPrivyEvent(pe,"customAuth","onUnauthenticated");void 0!==n&&d.emitPrivyEvent(pe,"login","onComplete",r,n,!1,"custom",null),d.emitPrivyEvent(pe,"customAuth","onAuthenticated",{user:r}),ce({status:"done"}),C(r||null),_(n||!1),w(!0),le(!0)}catch(e){console.warn(e),v&&(await We.logout(),d.emitPrivyEvent(pe,"customAuth","onUnauthenticated")),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),ce({status:"error",error:e})}})()}),[Y.customAuth?.enabled,Y.customAuth?.getCustomAccessToken,Y.customAuth?.isLoading,y,v]),i.useEffect((()=>{se&&V&&x&&u.shouldProceedtoEmbeddedWalletCreationFlow(x,Y.embeddedWallets.createOnLogin)&&(le(!1),Ie(x,l.WALLET_PROXY_TIMEOUT).catch(console.error))}),[se&&V&&x]),i.useEffect((()=>{if(Y.externalWallets.solana.connectors)return Y.externalWallets.solana.connectors.onMount(),()=>Y.externalWallets.solana.connectors?.onUnmount()}),[Y.externalWallets.solana.connectors]),i.useEffect((()=>{!y&&Z&&async function(){let e,t=Ce(),r=Ee();(()=>{let e=new URLSearchParams(window.location.search).get("privy_token");if(!e)return;d.e5.put(l.FORKED_TOKEN_STORAGE_KEY,e);let t=new URL(window.location.href);t.searchParams.delete("privy_token"),window.history.pushState({},"",t)})();let i=n.createStore();c.initializeConnectorManager({walletConnectCloudProjectId:Y.walletConnectCloudProjectId,rpcConfig:Y.rpcConfig,chains:Y.chains,defaultChain:Y.defaultChain,store:i,walletList:Y.appearance.walletList,shouldEnforceDefaultChainOnConnect:Y.shouldEnforceDefaultChainOnConnect,externalWalletConfig:Y.externalWallets,appName:Y.name??"Privy"}),c.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=c.connectors.walletConnectors.length,r=c.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?me(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),me(!0)}),1500)})),c.connectors?.initialize().then((()=>{$e()}));let a=await c.getAuthenticatedUser(),o=!!a;if(Y.customAuth?.enabled||(w(!!a),a&&d.emitPrivyEvent(pe,"login","onComplete",a,!1,!0,null,null),C(a)),!t)return r&&!o?(ge.current="login",ee({telegramAuthModalData:{seamlessAuth:!0}}),void xe(g.ModalScreen.TELEGRAM_AUTH_SCREEN)):void Be.setReadyToTrue(!!a);ge.current=o?"link":"login"}()}),[c,te,y,Z]),i.useEffect((()=>{if(y){if(!x||!x.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void oe(!0);oe(!!E.find((e=>"privy"===e.walletClientType)))}}),[y,x,E]);let Ce=()=>{let e=ha();return e.inProgress&&e.popupFlow?window.opener.location.origin!==window.location.origin?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Origins between parent and child windows do not match."}):"error"===e.authorizationCode?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Something went wrong. Try again."}):void window.opener.postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}):(e.inProgress&&function(e){return e.startsWith("privy:")}(e.provider)&&!e.popupFlow&&(new BroadcastChannel(yg).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!e.headless&&(c.startAuthFlow(new Ji(e)),xe(g.ModalScreen.AWAITING_OAUTH_SCREEN),!0))},Ee=()=>{let e=function(){let e;return(e=function(){let e=new URLSearchParams(window.location.search),t=Number(e.get("id")||""),r=e.get("hash"),n=Number(e.get("auth_date")||""),i=e.get("first_name"),a=e.get("last_name")||void 0,o=e.get("username")||void 0,s=e.get("photo_url")||void 0;if(t&&i&&n&&r)return{id:t,first_name:i,last_name:a,username:o,photo_url:s,auth_date:n,hash:r}}())?(ja(),{...e,flowType:"login-url"}):(e=function(){let e=window.location.hash;if(!e||!e.startsWith("#tgWebAppData"))return;let t=new URLSearchParams(decodeURIComponent(e.replace("#tgWebAppData=",""))),r=t.get("query_id")||void 0,n=t.get("user"),i=Number(t.get("auth_date")||""),a=t.get("hash"),o=t.get("chat_instance")||void 0,s=t.get("chat_type")||void 0,l=t.get("start_param")||void 0;return n&&i&&a?{query_id:r,user:n,auth_date:i,hash:a,chat_instance:o,chat_type:s,start_param:l}:void 0}())?(ja(),{...e,flowType:"web-app"}):void 0}();if(!e||!Y.loginMethods.telegram||!Y.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new Sa;return c.startAuthFlow(t),"login-url"===e.flowType&&(t.meta.telegramWebAppData=void 0,t.meta.telegramAuthResult={id:e.id,first_name:e.first_name,last_name:e.last_name,auth_date:e.auth_date,username:e.username,photo_url:e.photo_url,hash:e.hash}),"web-app"===e.flowType&&(t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData={query_id:e.query_id,user:e.user,auth_date:e.auth_date,hash:e.hash,chat_instance:e.chat_instance,chat_type:e.chat_type,start_param:e.start_param}),!0},be=async(e,t,r,n)=>{Se(await(c.connectors?.createEthereumWalletConnector(e,t))||null,t,r,n)};async function Se(e,t,r,n){if(!e)return R({status:"disconnected",connectedWallet:null,connectError:new o.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:o.notImplemented}),n?.(null,r);R({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:o.notImplemented}),e instanceof to&&t&&await e.resetConnection(t),R({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Se(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||Ra(t))&&Y.shouldEnforceDefaultChainOnConnect&&!Y.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){R((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:o.notImplemented})));try{await(t?.switchChain(Y.defaultChain.id)),t&&(t.chainId=d.formatChainIdToCAIP2(d.toHex(Y.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${Y.defaultChain.id}`)}}return R((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:o.notImplemented}))),t&&d.emitPrivyEvent(pe,"connectWallet","onSuccess",t),n?.(t,r)}catch(e){return e instanceof o.PrivyError?(console.warn(e.cause?e.cause:e.message),d.emitPrivyEvent(pe,"connectWallet","onError",e.privyErrorCode||o.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),d.emitPrivyEvent(pe,"connectWallet","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),R((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Ae=async(e,t,r)=>{if(null===e||!Ra(e))return;let n=new fa(e,c,t,r);c.startAuthFlow(n)},je=async(e,t)=>{if(null===e||!m.isBaseConnectedSolanaWallet(e))return;let r=new ga(e,c,t);c.startAuthFlow(r)},$e=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client");if(!t||!r)return;if("phantom"!==r||d.isPhantomInstalled()||xe(g.ModalScreen.LOGIN_FAILED_SCREEN),!c.connectors)throw new o.PrivyClientError("Connector not initialized");we(g.ModalScreen.AWAITING_CONNECTION);let n=new URL(window.location.href);n.searchParams.delete("privy_connector"),n.searchParams.delete("privy_wallet_client"),window.history.pushState({},"",n),be(t,r,void 0,Ae)};i.useEffect((()=>{y&&v&&null===x&&c.getAuthenticatedUser().then(C)}),[y,v,x,c]);let Te=e=>{if(!v)throw d.emitPrivyEvent(pe,"linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new o.PrivyClientError("User must be authenticated before linking an account.")},Pe=()=>{Te("siwe"),fe.current="siwe",ge.current="link",we(g.ModalScreen.LINK_WALLET_SCREEN)},_e=e=>{if(!v||!x)return!1;if("privy"===e.walletClientType)return!0;for(let t of x.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},ke=async e=>{let t;if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");t="ethereum"===e.type?c.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:c.connectors.findSolanaWalletConnector(e.connectorType,e.walletClientType)||null,R((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:o.notImplemented}))),Y.captchaEnabled&&!v?(ee({captchaModalData:{callback:t=>Ra(e)?Ae(e,t):je(e,t),userIntentRequired:!1,onSuccessNavigateTo:g.ModalScreen.AWAITING_CONNECTION,onErrorNavigateTo:g.ModalScreen.ERROR_SCREEN}}),xe(g.ModalScreen.CAPTCHA_SCREEN)):(Ra(e)?await Ae(e):await je(e),xe(g.ModalScreen.AWAITING_CONNECTION))},Ne=()=>{b((e=>{let t=c.connectors?.wallets.filter(Ra).map((e=>({...e,linked:_e(e),loginOrLink:async()=>{if(!await e.isConnected())throw new o.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot link or login with embedded wallet");ke(e)},fund:async t=>{await Be.fundWallet(e.address,t)},unlink:async()=>{if(!v)throw new o.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot unlink an embedded wallet");C(await c.unlinkEthereumWallet(e.address))}})))||[];return ao(e,t)?e:t})),A((e=>{let t=c.connectors?.wallets.filter(m.isBaseConnectedSolanaWallet).map((e=>({...e,linked:_e(e),loginOrLink:async()=>{if(!await e.isConnected())throw new o.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot link or login with embedded wallet");ke(e)},fund:async e=>{throw new o.PrivyClientError("Funding not supported for Solana wallets")},unlink:async()=>{if(!v)throw new o.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot unlink an embedded wallet");C(await c.unlinkSolanaWallet(e.address))}})))||[];return ao(e,t)?e:t}))};i.useEffect((()=>{Ne()}),[x?.linkedAccounts,v,y]),i.useEffect((()=>{if(y){if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");Ne(),c.connectors.on("walletsUpdated",Ne)}}),[y]),i.useEffect((()=>{let e;if(!E[0])return;let t=E[0],r=T.current.find((e=>e.address===t.address));if(e="privy"===t.walletClientType?x?.linkedAccounts.find((e=>"wallet"===e.type&&e.address===t.address&&"privy"===e.walletClientType)):x?.linkedAccounts.find((e=>"wallet"===e.type&&e.address===t.address&&"privy"!==e.walletClientType)),!r&&e){let t=Object.assign({},x);t.wallet=e&&{address:e.address,chainType:e.chainType,chainId:e.chainId,walletClient:e.walletClient,walletClientType:e.walletClientType,connectorType:e.connectorType,imported:e.imported,walletIndex:e.walletIndex},C(t)}T.current=E}),[E]);let Ie=async(e,t,r)=>{let n=u.getPrivyEthereumWallet(e),i=u.getPrivySolanaWallet(e);if(n&&!r?.createAdditional)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[a,s]=await Promise.all([Be.initializeWalletProxy(t),Sg()]);if(!a&&Y.customAuth?.enabled)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!a||!s||Y.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return new Promise(((e,t)=>{J(!0),ee({createWallet:{onSuccess:t=>{d.emitPrivyEvent(pe,"createWallet","onSuccess",t),e(t)},onFailure:e=>{d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),we(g.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}));{if(n){let t=u.getPrivyEthereumHDWallets(e),r=t?.length?Math.max(...t.map((e=>e.walletIndex))):n.walletIndex;await Be.recoverEmbeddedEthereumWallet(),await a.createAdditional({accessToken:s,primaryWalletAddress:n?.address,hdWalletIndex:r+1})}else console.log("solanaWallet",i),await a.create({accessToken:s,solanaAddress:i?.address});let t=u.getPrivyEthereumWallet(await Be.refreshUser());if(!t)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return d.emitPrivyEvent(pe,"createWallet","onSuccess",t),t}},Me=(e,r,n,i)=>new Promise((async(a,l)=>{let{requesterAppId:c}=r||{};if(!v||!x)return d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void l(Error("User must be authenticated before signing with a Privy wallet"));let h=i??u.getPrivyEthereumWallet(x)?.address;if(!h)throw new o.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:p,rootWallet:y}=u.getSigningAndRootWallet(x,h);if(!y||!p)return d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void l(Error("Must have a Privy wallet before signing"));J(!0);let f=He.wallets.find((e=>"privy"===e.walletClientType&&t.getAddress(e.address)===t.getAddress(p.address))),w=await(f?.getEthereumProvider());if(!f||!w)throw new o.PrivyClientError(`Cannot sendTransaction before embedded wallet ${p.address} is connected`);let C=e.chainId?Number(e.chainId):sf(f.chainId);(e=>{if(!Y.chains.map((e=>e.id)).includes(e))throw new o.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,o.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(C);let E=Object.assign({},e,{chainId:C});if(Y.embeddedWallets.noPromptOnSignature||ve.current)r&&Y.embeddedWallets.noPromptOnSignature&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config"),(async()=>{let e=await Sg();if(!e||!V)return d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void l(Error("Must have valid access token and Privy wallet to send transaction"));try{if(!await Be.recoverEmbeddedEthereumWallet())return d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void l(Error("Unable to connect to wallet"));let t=d.getJsonRpcProvider(E.chainId,Y.chains,Y.rpcConfig,{appId:s.appId}),r=await dr(p.address,E,t);if(Y.embeddedWallets.noPromptOnSignature||ve.current){let{totalGasEstimate:e}=await sr(r,t),{hasSufficientFunds:n}=await af(p.address,r,e,t);if(!n)throw new m.PrivyProviderRpcError(new m.ProviderRpcError("Wallet has insufficient funds for this transaction.",m.E.E32603_DEFAULT_INTERNAL_ERROR.eipCode))}let n=await nf({accessToken:e,rootWallet:y,transactingWallet:p,walletProxy:V,transactionRequest:r,provider:t,requesterAppId:c});d.emitPrivyEvent(pe,"sendTransaction","onSuccess",n),a(n)}catch(e){d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.TRANSACTION_FAILURE),l(e)}})();else{let e={address:y.address,onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),l(e)}},t=df({address:p.address,appConfig:Y,fundWalletConfig:n,chainIdOverride:E.chainId,comingFromSendTransactionScreen:!0});ee({connectWallet:e,sendTransaction:{transactionRequest:E,transactingWallet:p,rootWallet:y,onSuccess:e=>{d.emitPrivyEvent(pe,"sendTransaction","onSuccess",e),a(e)},onFailure:e=>{d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.TRANSACTION_FAILURE),l(e)},uiOptions:r||{},fundWalletConfig:n,requesterAppId:c},funding:t}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),Oe=({transaction:e,connection:t,transactionOptions:r,uiOptions:n,wallet:i})=>new Promise((async(a,s)=>{let{requesterAppId:l}=n||{};if(!v||!x)return d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void s(new o.PrivyClientError("User must be authenticated before signing with a Privy wallet",o.PrivyErrorCode.MUST_BE_AUTHENTICATED));let c=i?x.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):u.getPrivySolanaWallet(x);if(!c)return d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(new o.PrivyClientError("Must have a Privy wallet before signing",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));J(!0);let h=i??j,p=await(h?.isConnected());if(!h||!p)throw d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new o.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${c.address} is connected`,o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);Y.embeddedWallets.noPromptOnSignature?(n&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config"),(async()=>{let n=await Sg();if(!n||!V)return d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(new o.PrivyClientError("Must have valid access token and Privy wallet to send transaction",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{if(!await Be.recoverEmbeddedSolanaWallet())return d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void s(new o.PrivyClientError("Unable to connect to wallet",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(Y.embeddedWallets.noPromptOnSignature){let{instructions:r}=await vy(e,t);r.every((e=>e.hasFunds))||(d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.INSUFFICIENT_BALANCE),s(new o.PrivyClientError("Solana wallet has insufficient funds for this transaction.",o.PrivyErrorCode.INSUFFICIENT_BALANCE)))}let{signature:i,receipt:l}=await Cm({accessToken:n,tx:e,connection:t,walletProxy:V,transactionOptions:r,transactingWalletAddress:c.address}),u=gy(i,l);d.emitPrivyEvent(pe,"sendSolanaTransaction","onSuccess",u),a(u)}catch(e){d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.TRANSACTION_FAILURE),s(e)}})()):(ee({connectWallet:{address:c.address,onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:c,onSuccess:e=>{d.emitPrivyEvent(pe,"sendSolanaTransaction","onSuccess",e),a(e)},onFailure:e=>{d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.TRANSACTION_FAILURE),s(e)},uiOptions:n||{},requesterAppId:l},funding:void 0}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN))}));function Re(){return new Promise((async(e,t)=>{let r=await Sg();if(!r||!V)throw Error("Must have valid access token to enroll in MFA");try{await V.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let Fe=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],Le=e=>{let t=x?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=np(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw d.emitPrivyEvent(pe,"linkAccount","onError",o.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new o.PrivyClientError(`User already has an account of type ${r} linked.`)};async function Ue({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){N(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!v||!x)throw d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=u.getPrivyEthereumWallet(x);if(!n||!V)throw d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");if(u.getPrivySolanaWallet(x))throw Error("Cannot set user-controlled recovery for user with Solana.");try{await Re()}catch(e){throw d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((i,a)=>{J(!0);let s={onSuccess:e=>{d.emitPrivyEvent(pe,r,"onSuccess","user-passcode",e),i(e)},onFailure:e=>{d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),a(e)},callAuthOnSuccessOnClose:!1},l="user-passcode"===n.recoveryMethod;ee({setWalletPassword:s,createWallet:s,connectWallet:{onCompleteNavigateTo:ld({walletAction:"update",availableRecoveryMethods:Y.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:l,showAutomaticRecovery:e}),shouldForceMFA:!1,onFailure:e=>{d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:l}}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function De({appId:e,action:t}){let r=await Sg();if("link"===t&&!r)throw d.emitPrivyEvent(pe,"linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new o.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw d.emitPrivyEvent(pe,"login","onError",o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new o.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");fe.current=`privy:${e}`,ge.current=t;let n=window.open(void 0,void 0,Ju({w:440,h:680}));return c.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,i)=>{let{name:a,logoUrl:o}=await Yu({api:c.api,providerAppId:e,requesterAppId:Y.id});ee({crossAppAuth:{appId:e,name:a,logoUrl:o,action:t,popup:n,onSuccess:r,onError:i}}),xe(g.ModalScreen.CROSS_APP_AUTH_SCREEN)}))}let We={ready:y,authenticated:v,user:x,walletConnectors:c.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),ee({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress}}),we(v?g.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN:g.ModalScreen.CONNECT_ONLY_LANDING_SCREEN)},importWallet:async({privateKey:e})=>{Te("siwe");let[t,r]=await Promise.all([Be.initializeWalletProxy(15e3),Sg()]);if(t&&r){await t.import({privateKey:e,accessToken:r});let n=u.getImportedPrivyEthereumWallet(await Be.refreshUser());if(!n)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to import wallet");return d.emitPrivyEvent(pe,"createWallet","onSuccess",n),n}throw new o.PrivyClientError("User is not authenticated")},linkWallet:Pe,startCrossAppAuthFlow:De,linkEmail:()=>{Te("email"),Le("email"),fe.current="email",ge.current="link",we(g.ModalScreen.LINK_EMAIL_SCREEN)},linkPhone:()=>{Te("sms"),Le("phone"),fe.current="sms",ge.current="link",we(g.ModalScreen.LINK_PHONE_SCREEN)},linkGoogle:async()=>{Te("google"),Le("google_oauth"),ge.current="link",await Be.initLoginWithOAuth("google")},linkTwitter:async()=>{Te("twitter"),Le("twitter_oauth"),ge.current="link",await Be.initLoginWithOAuth("twitter")},linkDiscord:async()=>{Te("discord"),Le("discord_oauth"),ge.current="link",await Be.initLoginWithOAuth("discord")},linkGithub:async()=>{Te("github"),Le("github_oauth"),ge.current="link",await Be.initLoginWithOAuth("github")},linkSpotify:async()=>{Te("spotify"),Le("spotify_oauth"),ge.current="link",await Be.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Te("instagram"),Le("instagram_oauth"),ge.current="link",await Be.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Te("tiktok"),Le("tiktok_oauth"),ge.current="link",await Be.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{Te("linkedin"),Le("linkedin_oauth"),ge.current="link",await Be.initLoginWithOAuth("linkedin")},linkApple:async()=>{Te("apple"),Le("apple_oauth"),ge.current="link",await Be.initLoginWithOAuth("apple")},linkPasskey:async()=>{Te("passkey"),Le("passkey"),await Be.initLinkWithPasskey(),we(g.ModalScreen.LINK_PASSKEY_SCREEN)},linkTelegram:async()=>{Te("telegram"),Le("telegram"),ge.current="link",fe.current="telegram",await Be.initLoginWithTelegram(),we(g.ModalScreen.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{Te("farcaster"),Le("farcaster"),await Be.initLoginWithFarcaster(),ge.current="link",fe.current="farcaster",we(g.ModalScreen.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(Te("email"),!x?.email)throw new o.PrivyClientError("User does not have an email linked to their account.");ge.current="link",fe.current="email",we(g.ModalScreen.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(Te("sms"),!x?.phone)throw new o.PrivyClientError("User does not have a phone number linked to their account.");ge.current="link",fe.current="sms",we(g.ModalScreen.UPDATE_PHONE_SCREEN)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!y){let e=await new Promise((e=>{re((t=>e.bind(t)))}));if(re(null),e)return void console.warn(t)}!x||x.isGuest?(ge.current="login",ee({login:e}),xe(g.ModalScreen.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{y||(await new Promise((e=>{re((()=>e))})),re(null)),v?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):xe(g.ModalScreen.CONNECT_OR_CREATE)},logout:async()=>{if(x&&c.clearProviderAcccessTokens(x),N(null),await c.logout(),x&&V)try{await V.clearMfa({userId:x.id})}catch(e){}C(null),w(!1),d.emitPrivyEvent(pe,"logout","onSuccess"),ge.current=null,fe.current=null,p(!1),d.e5.del(l.CLIENT_ANALYTICS_ID_KEY),d.e5.del(l.getGuestCredentialStorageKey(Y.id))},getAccessToken:()=>c.getAccessToken(),getEthereumProvider:()=>{if(!x||!x.wallet)return new Pa;let e=E.find((e=>x.wallet&&e.address===x.wallet.address)),t=c.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new Pa},getEthersProvider:()=>{if(!x||!x.wallet)return new r.Web3Provider(new Na(new Pa));let e=E.find((e=>x.wallet&&e.address===x.wallet.address)),t=c.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return new r.Web3Provider(new Na(e&&t?t.proxyProvider:new Pa))},getWeb3jsProvider:()=>{if(!x||!x.wallet)return new Ia(new Pa);let e=E.find((e=>x.wallet&&e.address===x.wallet.address)),t=c.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return new Ia(e&&t?t.proxyProvider:new Pa)},unlinkWallet:async e=>{let t;return C(t=e.startsWith("0x")?await c.unlinkEthereumWallet(e):await c.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await c.unlinkEmail(e);return C(t),t},unlinkPhone:async e=>{let t=await c.unlinkPhone(e);return C(t),t},unlinkGoogle:async e=>{let t=await c.unlinkOAuth("google",e);return C(t),t},unlinkTwitter:async e=>{let t=await c.unlinkOAuth("twitter",e);return C(t),t},unlinkDiscord:async e=>{let t=await c.unlinkOAuth("discord",e);return C(t),t},unlinkGithub:async e=>{let t=await c.unlinkOAuth("github",e);return C(t),t},unlinkSpotify:async e=>{let t=await c.unlinkOAuth("spotify",e);return C(t),t},unlinkInstagram:async e=>{let t=await c.unlinkOAuth("instagram",e);return C(t),t},unlinkTiktok:async e=>{let t=await c.unlinkOAuth("tiktok",e);return C(t),t},unlinkLinkedIn:async e=>{let t=await c.unlinkOAuth("linkedin",e);return C(t),t},unlinkApple:async e=>{let t=await c.unlinkOAuth("apple",e);return C(t),t},unlinkFarcaster:async e=>{let t=await c.unlinkFarcaster(e);return C(t),t},unlinkTelegram:async e=>{let t=await c.unlinkTelegram(e);return C(t),t},unlinkPasskey:async e=>{let t=await c.unlinkPasskey(e);return C(t),t},unlinkCrossAppAccount:async({subject:e})=>{let t=x?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new o.PrivyClientError("Invalid subject");c.storeProviderAccessToken(t.id,null);let r=await c.unlinkOAuth(`privy:${t.id}`,e);return C(r),r},setActiveWallet:async e=>{let r=E.find((r=>t.getAddress(r.address)===t.getAddress(e))),n=x?.linkedAccounts.find((r=>"wallet"===r.type&&t.getAddress(r.address)===t.getAddress(e)));if(r&&await r.isConnected())if(r.linked){let e=Object.assign({},x);e.wallet=n&&{address:n.address,chainType:n.chainType,chainId:n.chainId,walletClient:n.walletClient,walletClientType:n.walletClientType,connectorType:n.connectorType,imported:n.imported,walletIndex:n.walletIndex},C(e)}else r.loginOrLink();else ee({externalConnectWallet:{suggestedAddress:e}}),Pe()},forkSession:()=>c.forkSession(),createWallet:async e=>{if(e&&"target"in e&&e&&(e=void 0),!v||!x)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return Ie(x,15e3,e)},setWalletRecovery:async e=>Ue({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>Ue({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t,r)=>new Promise((async(n,i)=>{let{requesterAppId:a}=t||{};if(!v||!x)return d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void i(Error("User must be authenticated before signing with a Privy wallet"));let s=r??u.getPrivyEthereumWallet(x)?.address;if(!s)throw new o.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:h}=u.getSigningAndRootWallet(x,s);if(!l||!h)return d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void i(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.INVALID_MESSAGE),void i(Error("Message must be a non-empty string"));J(!0);let p=async()=>{if(!v)throw Error("User must be authenticated before signing with a Privy wallet");let t=await Sg();if(!V||!t||!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");c.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:l.address,requesterAppId:a}});let{response:r}=await V.rpc({accessToken:t,address:h.address,hdWalletIndex:l.walletIndex??void 0,requesterAppId:a,request:{method:"personal_sign",params:[e,l.address]}}),n=r.data;return c.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:l.address,requesterAppId:a}}),n};if(Y.embeddedWallets.noPromptOnSignature||ve.current){t&&Y.embeddedWallets.noPromptOnSignature&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config");try{let e=await p();d.emitPrivyEvent(pe,"signMessage","onSuccess",e),n(e)}catch(e){d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),i(e??new m.PrivyProviderRpcError("Unable to sign message"))}}else ee({signMessage:{method:"personal_sign",data:e,confirmAndSign:p,onSuccess:e=>{d.emitPrivyEvent(pe,"signMessage","onSuccess",e),n(e)},onFailure:e=>{d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),i(e)},uiOptions:t||{}},connectWallet:{onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),i(e)},address:h.address}}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),signTypedData:(e,t,r)=>new Promise((async(n,i)=>{let{requesterAppId:a}=t||{};if(!v||!x)return d.emitPrivyEvent(pe,"signTypedData","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void i(Error("User must be authenticated before signing with a Privy wallet"));let s=r??u.getPrivyEthereumWallet(x)?.address;if(!s)throw new o.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:h}=u.getSigningAndRootWallet(x,s);if(!h||!l)return d.emitPrivyEvent(pe,"signTypedData","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void i(Error("Must have a Privy wallet before signing"));J(!0);let p=d.generateTypedDataWithDomainType(e),y=async()=>{if(!v)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Sg();if(!V||!e||!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");c.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:l.address,requesterAppId:a}});let{response:t}=await V.rpc({accessToken:e,address:h.address,hdWalletIndex:l.walletIndex??void 0,requesterAppId:a,request:{method:"eth_signTypedData_v4",params:[l.address,p]}}),r=t.data;return c.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:l.address,requesterAppId:a}}),r};if(ve.current||Y.embeddedWallets.noPromptOnSignature||Y.legacyWalletUiConfig){t&&Y.embeddedWallets.noPromptOnSignature&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config");try{let e=await y();d.emitPrivyEvent(pe,"signTypedData","onSuccess",e),n(e)}catch(e){d.emitPrivyEvent(pe,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),i(e??new m.PrivyProviderRpcError("Unable to sign message"))}}else ee({signMessage:{method:"eth_signTypedData_v4",data:p,confirmAndSign:y,onSuccess:e=>{d.emitPrivyEvent(pe,"signTypedData","onSuccess",e),n(e)},onFailure:e=>{d.emitPrivyEvent(pe,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),i(e)},uiOptions:t||{}},connectWallet:{address:h.address,onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}}}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),sendTransaction:async(e,t,r,n)=>{let i=await Me(e,t,r,n);return of(await i.wait())},sendSolanaTransaction:async(e,t,r,n)=>await Oe({transaction:e,connection:t,transactionOptions:n,uiOptions:r,wallet:j??void 0}),exportWallet:e=>new Promise((async(r,n)=>{if(!v||!x)return void n(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let i=e?.address,a=x.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&"ethereum"===e.chainType)),o=i?a.find((e=>e.address===t.getAddress(i))):a.find((e=>!e.imported))||a[0];if(!o)return void n(Error("Must have a Privy wallet before exporting"));J(!0);let l={onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:n,address:o.address,shouldForceMFA:!0};ee(Q),await Sg()&&V?V?(ee({keyExport:{appId:s.appId,appClientId:s.clientId,origin:c.apiUrl,wallet:o,onSuccess:r,onFailure:n},connectWallet:l}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)):n(Error("Must have a Privy wallet before exporting")):n(Error("Must have valid access token to enroll in MFA"))})),promptMfa:Re,async init(e){switch(e){case"sms":return void await c.initMfaSmsVerification();case"passkey":return await c.initMfaPasskeyVerification();case"totp":return;default:throw Error(`Unsupported MFA method: ${e}`)}},async submit(e,t){switch(e){case"totp":case"sms":if("string"!=typeof t)throw new o.PrivyClientError("Invalid MFA code");ue.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{he.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new o.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=(e=>({id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}))(await r.startAuthentication(t));ue.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{he.current={resolve:e,reject:t}}));break;default:throw ue.current?.reject(new o.PrivyClientError("Unsupported MFA method")),new o.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){ue.current?.reject(new o.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to enroll in MFA");await V.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return Be.closePrivyModal(),void t();Y.mfa.noPromptOnMfaRequired&&console.warn("[Privy Warning] Triggering the 'showMfaEnrollmentModal' function when 'noPromptOnMfaRequired' is set to true is unexpected. If this is intentional, ensure that you are building custom UIs for MFA verification."),ee({mfaEnrollmentFlow:{mfaMethods:Y.mfa.methods,onSuccess:t,onFailure:r}}),we(g.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await Sg();if(!e||!V)throw Error("Must have valid access token to enroll in MFA");let t=await V.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to enroll in MFA");await V.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),C(await c.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to enroll in MFA");await V.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),C(await c.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e}){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to enroll in MFA");await V.submitEnrollMfa({method:"passkey",accessToken:t,credentialIds:e}),C(await c.getAuthenticatedUser())},async unenroll(e){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to remove MFA");"passkey"===e?await V.submitEnrollMfa({method:"passkey",accessToken:t,credentialIds:[]}):await V.unenrollMfa({method:e,accessToken:t}),C(await c.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Sg(),t=x?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!V||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!x?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");let r=await V.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&C(await c.getAuthenticatedUser()||x||null),ee({farcasterSigner:r}),we(g.ModalScreen.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await Sg(),r=x?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!V||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!x?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");if(!x.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=x.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Sg(),r=x?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!V||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!x?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");if(!x.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),i=await V.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(x.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(i.signature))},createGuestAccount:async()=>{if(x&&!x.isGuest)throw Error("User cannot already be authenticated to create a guest account");return x?.isGuest?x:Be.loginWithGuestAccountFlow()},isHeadlessOAuthLoading:I,async loginWithCode(e){await Be.loginWithCode(e)},initLoginWithEmail:e=>Be.initLoginWithEmail(e),initLoginWithSms:e=>Be.initLoginWithSms(e),otpState:W,fundWallet:(e,t)=>Be.fundWallet(e,t),initLoginWithHeadlessOAuth:(e,t)=>Be.initLoginWithHeadlessOAuth(e,t),loginWithHeadlessOAuth:e=>Be.loginWithHeadlessOAuth(e),generateSiweMessage:({address:e,chainId:t})=>Be.generateSiweMessage({address:e,chainId:t}),async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}){Te("siwe"),await Be.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})},signMessageWithCrossAppWallet:(e,{address:t})=>Zu({user:x,client:c,address:t,requesterAppId:Y.id,request:{method:"personal_sign",params:[e,t]},reconnect:De}),signTypedDataWithCrossAppWallet(e,{address:t}){let r=d.generateTypedDataWithDomainType(e);return Zu({user:x,client:c,address:t,requesterAppId:Y.id,request:{method:"eth_signTypedData_v4",params:[t,r]},reconnect:De})},sendTransactionWithCrossAppWallet:(e,{address:t})=>Zu({user:x,client:c,address:t,requesterAppId:Y.id,request:{method:"eth_sendTransaction",params:[e]},reconnect:De}),isModalOpen:h,mfaMethods:Y.mfa.methods};vg=We.signMessage,wg=We.signTypedData,xg=async(...e)=>{let t=await Me(...e);return Y.embeddedWallets.waitForTransactionConfirmation&&await t.wait(),t};let Be={isNewUserThisSession:P,pendingTransaction:null,walletConnectionStatus:O,connectors:c.connectors?.walletConnectors??[],solanaWallets:S,rpcConfig:Y.rpcConfig,chains:Y.chains,appId:s.appId,showFiatPrices:"native-token"!==Y.embeddedWallets.priceDisplay.primary,clientAnalyticsId:c.clientAnalyticsId,customAuthStatus:de,noPromptOnSignature:ve,emailOtpState:U,setEmailOtpState:D,smsOtpState:W,setSmsOtpState:B,oAuthState:q,setOAuthState:z,siweState:H,setSiweState:G,nativeTokenSymbolForChainId:e=>Y.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(V)return V;let t=new Promise((e=>{ie((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return ie(null),n},getAuthFlow:()=>c.authFlow,getAuthMeta:()=>c.authFlow?.meta,client:c,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=y&&v&&x;r&&fe.current&&(t=Fe(x)),"login"===ge.current?e.shouldCallAuthOnSuccess&&r&&fe.current?(d.emitPrivyEvent(pe,"login","onComplete",x,P,!1,fe.current,t??null),s.onSuccess?.(x,P)):d.emitPrivyEvent(pe,"login","onError",o.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===ge.current&&t&&(e.isSuccess&&r&&fe.current?d.emitPrivyEvent(pe,"linkAccount","onSuccess",x,fe.current,t):fe.current&&d.emitPrivyEvent(pe,"linkAccount","onError",o.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:fe.current}));let n=k&&cf.includes(k),i=k===g.ModalScreen.ERROR_SCREEN&&Q.errorModalData&&cf.includes(Q.errorModalData.previousScreen);if((n||i)&&Q.funding){let e,t=uf[k]??null,r=d.getJsonRpcProvider(Q.funding.chain.id,Y.chains,Y.rpcConfig,{appId:s.appId});try{e=(await r.getBalance(Q.funding.address)).toBigInt()}catch{console.error("Unable to pull wallet balance")}d.emitPrivyEvent(pe,"fundWallet","onUserExited",{address:Q.funding.address,chain:Q.funding.chain,fundingMethod:t,balance:e})}ee({...Q,externalConnectWallet:{suggestedAddress:void 0}}),ge.current=null,fe.current=null,_(!1),p(!1),setTimeout((()=>{c.authFlow=void 0}),200),c.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:async({message:e})=>new Promise((async(t,r)=>{let n=async()=>{let t=await c.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");if(!j)throw Error("User must have an embedded Solana wallet to sign messages for Solana.");let r=Be.walletProxy??await Be.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");let{response:n}=await r.rpcSolana({accessToken:t,publicKey:j.address,request:{method:"signMessage",params:{message:e}}});return n.data.signature};if(Y.embeddedWallets.noPromptOnSignature||ve.current)try{let e=await n();t({signature:e})}catch(e){r(e)}else ee({signMessage:{method:"solana_signMessage",data:e,confirmAndSign:n,onSuccess:e=>{t({signature:e})},onFailure:e=>{r(e)},uiOptions:{}}}),xe(g.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN)})),openPrivyModal:we,connectWallet:Se,initLoginWithWallet:async(e,t,r)=>{Ra(e)?(fe.current="siwe",Ae(e,t,r)):(fe.current="siws",je(e,t))},loginWithWallet:async()=>{let e,t,r;if(!y)throw new o.PrivyNotReadyError;if(c.authFlow instanceof fa?e="siwe":c.authFlow instanceof ga&&(e="siws"),!e)throw new o.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await c.getAccessToken())try{({user:t}=await c.link()),fe.current=e}catch(t){throw d.emitPrivyEvent(pe,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await c.authenticate()),fe.current=e}catch(e){throw d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}C(t||x||null),_(r||!1),w(!0)},initDelegateAction:async({address:e})=>new Promise((async(t,r)=>{let n=await Sg();if(!v||!x||!n)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");let i=Be.walletProxy??await Be.initializeWalletProxy(15e3);if(!i)throw new o.PrivyClientError("Wallet proxy not initialized.");let a=(({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new o.PrivyClientError("Address to delegate is not associated with current user.");return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}})({address:e,user:x}),s=(({address:e,user:t})=>{let r,n=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!n)throw new o.PrivyClientError("Address to delegate is not associated with current user.");if(!(r="ethereum"===n.chainType?n.imported?u.getImportedPrivyEthereumWallet(t):u.getPrivyEthereumWallet(t):n))throw new o.PrivyClientError("Unable to determine root address for delegated address.");return{address:r.address,chainType:r.chainType,imported:r.imported}})({address:e,user:x});"ethereum"===a.chainType?await Be.recoverEmbeddedEthereumWallet():await Be.recoverEmbeddedSolanaWallet(),ee({delegatedActions:{address:e,onDelegate:async()=>{await i.createDelegatedAction({accessToken:n,rootWallet:s,delegatedWallets:[a]})},onSuccess:async()=>{t()},onError:async e=>{r(e)}}}),we(g.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN)})),initLoginWithFarcaster:async(e,t)=>{let r=new qi(e,t);c.startAuthFlow(r);try{fe.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===ge.current?d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ge.current&&d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!y)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof qi))throw new o.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await c.getAccessToken())try{({user:e}=await c.link()),fe.current="farcaster"}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await c.authenticate()),fe.current="farcaster"}catch(e){throw d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}C(e||null),_(t||!1),w(!0)},async loginWithGuestAccountFlow(){let e=new Vi(this.appId);c.startAuthFlow(e);try{ge.current="login",fe.current="guest";let{user:e,isNewUser:t}=await c.authenticate();if(t=t||!1,!e)throw new o.PrivyClientError("Unable to authenticate guest account");if(u.shouldProceedtoEmbeddedWalletCreationFlow(e,Y.embeddedWallets.createOnLogin))try{await Ie(e,15e3),e=await Be.refreshUser()}catch(t){C(e),console.warn("Unable to create embedded wallet for guest account")}else C(e);return _(t),w(!0),d.emitPrivyEvent(pe,"login","onComplete",e,t,!1,"guest",null),e}catch(e){throw d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let n=`privy:${e}`;fe.current=n;let{url:i,stateCode:a,codeVerifier:s}=await async function({api:e,appId:t}){let r=Ki(),n=Yi(),i=await Zi(r);try{let{url:a}=await e.post(Pi,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:i,state_code:n});return{url:a,stateCode:n,codeVerifier:r}}catch(e){throw o.formatApiError(e)}}({api:c.api,appId:e});if(!i)throw c.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new o.PrivyClientError("No authorization URL returned for cross-app auth.");try{let l=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,i=setTimeout((()=>{r(new o.PrivyClientError("Authorization request timed out after 2 minutes.")),a()}),12e4);function a(){t?.close(),window.removeEventListener("message",l)}let s=setInterval((()=>{t?.closed&&!n&&(a(),clearInterval(s),clearTimeout(i),r(new o.PrivyClientError("User rejected request")))}),300);function l(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(clearTimeout(i),e(t.data),a()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(i),r(new o.PrivyClientError(t.data.error)),a()),t.data.type===mg&&((n=new BroadcastChannel(yg)).onmessage=l))}window.addEventListener("message",l)}))}({url:i,popup:t,provider:n}),d=l.stateCode,u=l.authorizationCode;if(d!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:n,storedStateCode:a??"",returnedStateCode:d??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:i,client:a}){if(!n||!t)throw new o.PrivyClientError("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new o.PrivyClientError("User denied confirmation during cross-app auth flow");try{let o=new Ku({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`});a.startAuthFlow(o);let s="link"===i?await a.link():await a.authenticate(),l=s.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=o.formatApiError(e);if(t.privyErrorCode)throw new o.PrivyClientError(t.message||"Invalid code during cross-app auth flow.",void 0,t.privyErrorCode);if("User denied confirmation during cross-app auth flow"===t.message)throw new o.PrivyClientError("Invalid code during cross-app auth flow.",void 0,o.PrivyErrorCode.OAUTH_USER_DENIED);throw new o.PrivyClientError("Invalid code during cross-app auth flow.",void 0,o.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:s,stateCode:d,authorizationCode:u,action:r,client:c});h&&c.storeProviderAccessToken(e,h);let p=await Be.refreshUser();if(!p)throw new o.PrivyClientError("Unable to update user");return c.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),p}catch(e){throw c.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:n}}),e}},async initLoginWithOAuth(e,t,r){if(fe.current=e,!d.e())return void xe(g.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&jl(window.navigator.userAgent))return void xe(g.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:mg},"*"),d.e5.del(l.HEADLESS_OAUTH_KEY),d.e5.del(l.OAUTH_DISABLE_SIGNUP_KEY);let n=new Ji({provider:e,disableSignup:!!r});t&&n.addCaptchaToken(t),c.startAuthFlow(n);let i=await c.authFlow.getAuthorizationUrl();i&&i.url&&("twitter"===e&&a.isAndroid&&(i.url=i.url.replace("x.com","twitter.com")),window.location.assign(i.url))},async initLoginWithTelegram(e,t){if(!y)throw new o.PrivyNotReadyError;fe.current="telegram";let r=new Sa(e,t);c.startAuthFlow(r),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>Y.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:Y.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new o.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new o.PrivyClientError("Telegram was not initialized")):t(new o.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(c.authFlow instanceof Sa))throw new o.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");if(c.authFlow.meta.captchaToken||=e,"login"===ge.current)try{let e=await c.authenticate();t=e.user,r=e.isNewUser,fe.current="telegram"}catch(e){throw d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==ge.current)throw new o.PrivyClientError("Unknown auth intent");try{t=(await c.link()).user,fe.current="telegram"}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}C(t),_(r||!1),w(!0)},async recoveryOAuthFlow(e,t,r){let n,i;function a(t){if(!t)throw c.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new o.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,s,{url:l,codeVerifier:d,stateCode:u}=await cd({api:gg.api,provider:e});a(l);try{let n=await fg({url:l,popup:r,provider:e});if(t=n.stateCode,s=n.authorizationCode,t!==u)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:u??"",returnedStateCode:t??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw c.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new o.PrivyClientError("Recovery OAuth failed")}[n,i]=await Promise.all([Sg(),ud({api:gg.api,provider:e,codeVerifier:d,stateCode:t,authorizationCode:s})]);break}case"icloud":{let{url:t}=await cd({api:gg.api,provider:e});a(t);let{ckWebAuthToken:o}=await fg({url:t,popup:r,provider:e});i=o,n=await Sg()}}if(!V)throw new o.PrivyClientError("Cannot connect to wallet proxy");if(!n)throw new o.PrivyClientError("Unable to authorize user");switch(t){case"recover":let t=Q.recoverWallet?.privyWallet?.address;if(!t)throw new o.PrivyClientError("Recovery OAuth failed");c.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await V.recover({address:t,accessToken:n,recoveryAccessToken:i,recoveryMethod:e}),c.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break;case"create-wallet":c.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"});let r=u.getPrivySolanaWallet(x);await V.create({accessToken:n,recoveryAccessToken:i,recoveryMethod:e,solanaAddress:r?.address});let a=u.getPrivyEthereumWallet(await Be.refreshUser());if(!a)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");c.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:a.address}}),d.emitPrivyEvent(pe,"createWallet","onSuccess",a);break;case"set-recovery":let s=u.getPrivyEthereumWallet(x);if(!s)throw d.emitPrivyEvent(pe,"setWalletRecovery","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");c.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:s.address,existingRecoveryMethod:s.recoveryMethod,targetRecoveryMethod:e}}),await V.setRecovery({address:s.address,accessToken:n,recoveryAccessToken:i,recoveryMethod:e});let l=u.getPrivyEthereumWallet(await Be.refreshUser());if(!l)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");c.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:s.address,existingRecoveryMethod:s.recoveryMethod,targetRecoveryMethod:e}}),d.emitPrivyEvent(pe,"setWalletRecovery","onSuccess",e,l);break;default:throw new o.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,n;if(!(c.authFlow instanceof Ji))throw new o.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let i=d.e5.get(l.STATE_CODE_KEY),a=c.authFlow.meta.stateCode;if(i!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:i??"",returnedStateCode:a??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await c.getAccessToken())try{let r=await c.link();t=r.user,n=r.oAuthTokens,fe.current=e}catch(t){throw d.emitPrivyEvent(pe,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let i=await c.authenticate();t=i.user,r=i.isNewUser,n=i.oAuthTokens,fe.current=e}catch(t){throw"login"===ge.current?d.emitPrivyEvent(pe,"login","onError",t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ge.current&&d.emitPrivyEvent(pe,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return C(t),_(r||!1),w(!0),n&&t&&d.emitPrivyEvent(pe,"oAuthAuthorization","onOAuthTokenGrant",n,{user:t}),n},passkeyAuthState:F,setPasskeyAuthState:L,async initLoginWithPasskey(e){let t=new ya(e,L);c.startAuthFlow(t),ge.current="login";try{fe.current="passkey",L({status:"generating-challenge"}),await t.initAuthenticationFlow(),L({status:"awaiting-passkey"})}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(){let e,t;if(!y)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof ya))throw new o.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==fe.current){let e=new o.PrivyClientError("Must init login with Passkey flow first.");throw L({status:"error",error:e}),e}let r=await Sg();try{fe.current="passkey",L({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await c.authenticate())}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}C(e),_(t||!1),w(!0),L({status:"done"});let n=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:n}},async initLinkWithPasskey(e){let t=new ya(e);c.startAuthFlow(t),ge.current="link",fe.current="passkey";try{await t.initLinkFlow()}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),e}},async linkWithPasskey(){let e;if(!y)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof ya))throw new o.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==fe.current)throw new o.PrivyClientError("Must init login with Passkey flow first.");try{fe.current="passkey",({user:e}=await c.link())}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return C(e||x||null),e},async initLoginWithHeadlessOAuth(e,t){if(!d.e())throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");if("google"===e&&jl(window.navigator.userAgent))throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");let r=new Ji({provider:e,headless:!0,disableSignup:!1});t&&r.addCaptchaToken(t),z({status:"loading"});let n=await c.startAuthFlow(r).getAuthorizationUrl();n?.url&&window.location.assign(n.url)},async loginWithHeadlessOAuth(e){let t,r,n;M(!0),z({status:"loading"}),c.startAuthFlow(new Ji(e));let i=d.e5.get(l.STATE_CODE_KEY),a=e.stateCode;if(i!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:i??"",returnedStateCode:a??""}}),M(!1),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await c.getAccessToken())try{({user:t,oAuthTokens:n}=await c.link()),fe.current=e.provider;let r=Fe(t);t&&r&&d.emitPrivyEvent(pe,"linkAccount","onSuccess",t,fe.current,r)}catch(t){throw M(!1),d.emitPrivyEvent(pe,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:n}=await c.authenticate()),fe.current=e.provider;let i=Fe(t);t&&i&&void 0!==r&&"login"===ge.current&&d.emitPrivyEvent(pe,"login","onComplete",t,r,!1,fe.current,i)}catch(e){throw M(!1),z({status:"error",error:e}),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return C(t),_(r||!1),w(!0),M(!1),z({status:"done"}),n&&t&&d.emitPrivyEvent(pe,"oAuthAuthorization","onOAuthTokenGrant",n,{user:t}),t??void 0},initLoginWithEmail:async(e,t,r)=>{let n=new Mi(e,t,r);c.startAuthFlow(n);try{fe.current="email",D({status:"sending-code"}),await n.sendCodeEmail(),D({status:"awaiting-code-input"})}catch(e){throw D({status:"error",error:e}),"login"===ge.current?d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ge.current&&d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let n=new Oi(e,t,r);c.startAuthFlow(n),await n.sendCodeEmail()},initUpdatePhone:async(e,t,r)=>{let n=new wa(e,t,r);c.startAuthFlow(n),await n.sendSmsCode()},initLoginWithSms:async(e,t,r)=>{B({status:"sending-code"});let n=new va(e,t,r);c.startAuthFlow(n);try{fe.current="sms",await n.sendSmsCode(),B({status:"awaiting-code-input"})}catch(e){throw B({status:"error",error:e}),"login"===ge.current?d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ge.current&&d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(c.authFlow?.sendCodeEmail())},resendSmsCode:async()=>{await(c.authFlow?.sendSmsCode())},loginWithCode:async e=>{let t,r;function n(e){c.authFlow instanceof Mi?D(e):c.authFlow instanceof va&&B(e)}if(n({status:"submitting-code"}),!y){let e=new o.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(c.authFlow instanceof Mi)c.authFlow.meta.emailCode=e.trim();else{if(!(c.authFlow instanceof va)){let e=new o.PrivyClientError("Must initialize a passwordless code flow first");throw n({status:"error",error:e}),e}c.authFlow.meta.smsCode=e.trim()}let i=await Sg();if("link"===ge.current)try{({user:t}=await c.link())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:fe.current}),e}else try{({user:t,isNewUser:r}=await c.authenticate())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let a=t||x;C(a||null),_(r||!1),w(!0),n({status:"done"});let s=null;return c.authFlow instanceof Mi?s=a?.linkedAccounts.find((({type:e})=>"email"===e))||null:c.authFlow instanceof va&&(s=a?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:a,isNewUser:r||!1,wasAlreadyAuthenticated:!!i,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{ge.current="link",fe.current="siwe",G({status:"generating-message"});let n=await c.generateSiweNonce({address:e,captchaToken:r});return G({status:"awaiting-signature"}),ma({address:e,chainId:t.replace("eip155:",""),nonce:n})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let n;ge.current=null,fe.current=null;try{n=await c.linkSmartWallet({message:e,signature:t,smartWalletType:r}),n=await Be.refreshUser()??n}catch(e){throw e}C(n||x||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})=>{let a,s=null;try{G({status:"submitting-signature"}),a=await c.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}),a=await Be.refreshUser()??a,G({status:"done"}),(s=Fe(a)||null)&&d.emitPrivyEvent(pe,"linkAccount","onSuccess",a,"siwe",s)}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),ge.current=null,fe.current=null,G({status:"error",error:e}),e}let l=a||x;return C(l||null),ge.current=null,fe.current=null,{user:l,linkedAccount:s}},refreshUser:async()=>{let e=await c.getAuthenticatedUser();return w(!!e),C(e),e},walletProxy:V,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>c.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await c.acceptTerms();return C(e),e},getUsdTokenPrice:e=>c.getUsdTokenPrice(e),getUsdPriceForSol:()=>c.getUsdPriceForSol(),recoverEmbeddedEthereumWallet:async e=>new Promise((async(t,r)=>{let n=u.getPrivyEthereumWallet(e?.user??x)||u.getImportedPrivyEthereumWallet(e?.user??x),i=await Sg();if(i&&V&&n){J(!0);try{await V.connect({accessToken:i,address:n.address}),t(!0)}catch(e){td(e)&&"privy"===n.recoveryMethod?(c.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:n.address}}),(await V.recover({address:n.address,accessToken:i,recoveryMethod:n.recoveryMethod})).address||r(Error("Unable to recover wallet")),c.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:n.address}}),t(!0)):td(e)&&"privy"!==n.recoveryMethod?(ee({recoverWallet:{privyWallet:n,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover"}}),we(dd(n.recoveryMethod))):r(e)}}else r(Error("Must have valid access token and Privy wallet to recover wallet"))})),embeddedSolanaWallet:j,createEmbeddedSolanaWallet:async()=>{J(!0);let e=await Sg(),t=await Be.refreshUser(),r=u.getPrivySolanaWallet(t),n=u.getPrivyEthereumWallet(t);if(!t||!e)throw new o.PrivyClientError("User must be logged in to create a Solana wallet");if(r)throw new o.PrivyClientError("User already has an embedded Solana wallet.");if(n){if("privy"!==n.recoveryMethod)throw new o.PrivyClientError("Cannot create an embedded Solana wallet for a user with an existing Ethereum wallet with user-controlled recovery.");await Be.recoverEmbeddedEthereumWallet({user:t})}let i=await Be.initializeWalletProxy(15e3);if(!i)throw new o.PrivyClientError("Unable to initialize wallet proxy");c.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_started"});try{await i.createSolana({accessToken:e,ethereumAddress:n?.address});let t=await Be.refreshUser(),r=u.getPrivySolanaWallet(t);if(!r)throw new o.PrivyClientError("Could not get Solana wallet for user");return c.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_completed",payload:{walletAddress:r.address}}),r}catch(e){throw c.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_failed"}),new o.PrivyClientError("Failed to create Solana embedded wallet with error ",e)}},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!v||!x)return void r(Error("User must be authenticated before exporting their Privy wallet"));let n=e?.address,i=x.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&"solana"===e.chainType)),a=n?i.find((e=>e.address.toLowerCase()===n.toLowerCase())):i.find((e=>!e.imported))||i[0];a?(J(!0),await Sg()&&V?V?(await Be.recoverEmbeddedSolanaWallet(),ee({keyExport:{appId:s.appId,appClientId:s.clientId,origin:c.apiUrl,wallet:a,onSuccess:t,onFailure:r}}),we(g.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))):r(Error("Must have a Privy wallet before exporting"))})),recoverEmbeddedSolanaWallet:async()=>new Promise((async(e,t)=>{let r=u.getPrivySolanaWallet(x),n=await Sg();if(n&&V&&r){J(!0);try{await V.connectSolana({accessToken:n,publicKey:r.address}),e(!0)}catch(i){td(i)&&"privy"===r.recoveryMethod?(c.createAnalyticsEvent({eventName:"embedded_solana_wallet_pinless_recovery_started",payload:{walletAddress:r.address}}),(await V.recoverSolana({publicKey:r.address,accessToken:n})).publicKey||t(Error("Unable to recover wallet")),c.createAnalyticsEvent({eventName:"embedded_solana_wallet_recovery_completed",payload:{walletAddress:r.address}}),e(!0)):t(i)}}else t(Error("Must have valid access token and Privy wallet to recover wallet"))})),getMoonpaySignedUrl:async(e,t)=>{let{signedUrl:r,externalTransactionId:n}=await async function(e,t,r,n,i=!1){let a=r.currencyCode?{}:{defaultCurrencyCode:"ETH_ETHEREUM"},o=r.uiConfig||{accentColor:n.accent,theme:n.colorScheme};return e.signMoonpayOnRampUrl({address:t,useSandbox:i,config:{...r,...a,...o}})}(c,e,t??{},Y.appearance.palette,Y.fundingMethodConfig?.moonpay.useSandbox??!1);return{signedUrl:r,externalTransactionId:n}},initCoinbaseOnRamp:c.initCoinbaseOnRamp.bind(c),getCoinbaseOnRampStatus:c.getCoinbaseOnRampStatus.bind(c),setReadyToTrue:e=>{f(!0),te?.(e)},updateWallets:()=>Ne(),fundWallet:async(e,t)=>{if(!Y.fundingConfig||0===Y.fundingConfig.methods.length)throw Error("Wallet funding is not enabled");let r=pf({fundingMethods:Y.fundingConfig.methods});ee({funding:df({address:e,appConfig:Y,fundWalletConfig:t,methodScreen:r})}),we(r)},requestFarcasterSignerStatus:async e=>{let t=await Sg(),r=x?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!V||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!x?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await c.requestFarcasterSignerStatus(e);return"approved"===n.status&&C(await c.getAuthenticatedUser()||x||null),n},connectCoinbaseSmartWallet:async()=>{Y.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=c.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||c.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Se(e);await be("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,farcasterEmbeddedAddress:a,oAuthUserInfo:o})=>{try{let s=await c.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,farcasterEmbeddedAddress:a,oAuthUserInfo:o});return C(s),s}catch(e){throw e}}};Cg=Be.recoverEmbeddedEthereumWallet,Eg=Be.recoverEmbeddedSolanaWallet,bg=Be.solanaSignMessage;let He=i.useMemo((()=>({wallets:E,ready:ae&&ye})),[E,ae,ye]);return e.jsx(o.PrivyContext.Provider,{value:We,children:e.jsx(d.PrivyEventsContext.Provider,{value:pe,children:e.jsx(l.UseWalletsContext.Provider,{value:He,children:e.jsx(Ea,{...Y,children:e.jsxs(o.InternalPrivyContext.Provider,{value:Be,children:[e.jsx(d.RecentlyUsedAccountProvider,{children:e.jsxs(g.ModalProvider,{data:Q,setModalData:ee,setInitialScreen:N,initialScreen:k,authenticated:v,open:h,children:[s.children,!Y.headless&&Y.captchaEnabled&&y&&!v&&e.jsx(vo,{delayedExecution:!1}),e.jsx(Wf,{theme:{...Y.appearance.palette||{}}}),!Y.render.standalone&&e.jsx(Qf,{open:h})]})}),X&&Z?e.jsx(hg,{appId:s.appId,appClientId:s.clientId,clientAnalyticsId:c.clientAnalyticsId,origin:c.apiUrl,mfaMethods:x?.mfaMethods,mfaPromise:ue,mfaSubmitPromise:he,onLoad:K,onLoadFailed:()=>null}):null,Y.loginConfig.telegramAuthConfiguration&&e.jsx(ns,{$if:!0,children:e.jsx(rg,{scriptHost:s.apiUrl||l.DEFAULT_PRIVY_API_URL,botUsername:Y.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};let Ng=async(e,t,r,n,i)=>{if(!e)throw n("linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:i}),new o.PrivyClientError("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(i))))throw new o.PrivyClientError(`OAuth account of type ${i} not linked to the account.`);await r(i)};const Ig=Mg;function Mg(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=o.usePrivy();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}}exports.usePrivy=o.usePrivy,exports.SUPPORTED_CHAINS=l.DEFAULT_SUPPORTED_CHAINS,exports.VERSION=l.VERSION,exports.addRpcUrlOverrideToChain=l.addRpcUrlOverrideToChain,exports.useWallets=l.useWallets,exports.useConnectWallet=d.useConnectWallet,exports.useFundWallet=d.useFundWallet,exports.useLogin=d.useLogin,exports.useLogout=d.useLogout,exports.WalletConnector=m.WalletConnector,exports.useSolanaWallets=m.useSolanaWallets,exports.getEmbeddedConnectedWallet=g.getEmbeddedConnectedWallet,exports.AsExternalProvider=Na,exports.Captcha=vo,exports.ConnectorManager=io,exports.EthereumWalletConnector=Fa,exports.LoginModal=Qf,exports.PrivyClient=fo,exports.PrivyProvider=({config:t,...r})=>{var n;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new o.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(n=r.appId)||25!==n.length)throw new o.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");gg||(gg=new fo({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let i=Object.assign({},t);return void 0!==r.createPrivyWalletOnLogin&&void 0===i.embeddedWallets?.createOnLogin&&(i.embeddedWallets||(i.embeddedWallets={}),i.embeddedWallets.createOnLogin=r.createPrivyWalletOnLogin?"users-without-wallets":"off"),void 0!==r.createPrivyWalletOnLogin&&t?.embeddedWallets?.createOnLogin&&console.warn("Both `createPrivyWalletOnLogin` and `config.embeddedWallets.createOnLogin` are set. `createPrivyWalletOnLogin` is deprecated and should be removed."),e.jsx(l.PrivyAppConfigProvider,{client:gg,clientConfig:i,legacyCreateEmbeddedWalletFlag:r.createPrivyWalletOnLogin,children:e.jsx(kg,{...r,client:gg})})},exports.PrivyProxyProvider=Pa,exports.errorIndicatesMaxMfaRetries=id,exports.errorIndicatesMfaTimeout=rd,exports.errorIndicatesMfaVerificationFailed=nd,exports.getAccessToken=Sg,exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=o.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useCreateWallet=function(e){let{createWallet:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("createWallet",e),{createWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:i}=o.usePrivy();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:n,sendTransaction:i}},exports.useCustomAuth=e=>{let{customAuthStatus:t}=o.usePrivyInternal();return d.usePrivyEventSubscription("customAuth",e),{status:t}},exports.useExperimentalFarcasterSigner=Ig,exports.useFarcasterSigner=Mg,exports.useGuestAccounts=function(){let{createGuestAccount:e}=i.useContext(o.PrivyContext);return{createGuestAccount:e}},exports.useLinkAccount=function(e){let{linkEmail:t,linkPhone:r,linkWallet:n,linkGoogle:a,linkApple:s,linkTwitter:l,linkDiscord:c,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkSpotify:y,linkInstagram:m,linkTelegram:f,linkFarcaster:g}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("linkAccount",e),{linkEmail:t,linkPhone:r,linkWallet:n,linkGoogle:a,linkApple:s,linkTwitter:l,linkDiscord:c,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkSpotify:y,linkInstagram:m,linkFarcaster:g,linkTelegram:f}},exports.useLinkWithSiwe=e=>{let t=ba(),{generateSiweMessage:r}=o.usePrivy(),{siweState:n,setSiweState:a,linkWithSiwe:s}=o.usePrivyInternal();return{generateSiweMessage:i.useCallback((async({address:t,chainId:n})=>{try{if(!t||!n)throw Error("wallet address and chainId required to generate nonce");return await r({address:t,chainId:n}).then((e=>e))}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[r]),linkWithSiwe:i.useCallback((async({signature:r,message:n,chainId:i,walletClientType:l,connectorType:d})=>{try{if(t.enabled&&"success"!==t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:a,linkedAccount:c}=await s({message:n,signature:r,chainId:i,walletClientType:l,connectorType:d});c&&e?.onSuccess?.(a,"siwe",c)}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[s,t.status]),state:n}},exports.useLoginWithEmail=e=>{let t=ba(),{emailOtpState:r,setEmailOtpState:n,initLoginWithEmail:a,loginWithCode:s}=o.usePrivyInternal();return{sendCode:i.useCallback((async({email:r})=>{try{let e;if(!r)throw Error("Email required to send OTP code");if(t.enabled&&"error"===t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a(r,e)}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:i.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:l}=await s(r);e?.onComplete?.(n,i,a,"email",l)}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[s,t.status]),state:r}},exports.useLoginWithOAuth=e=>{d.usePrivyEventSubscription("login",e);let t=ba(),r=l.useIsServerConfigLoaded(),{initLoginWithHeadlessOAuth:n,loginWithHeadlessOAuth:a,isHeadlessOAuthLoading:s,ready:c,user:u}=o.usePrivy(),{oAuthState:h,setOAuthState:p}=o.usePrivyInternal(),y=i.useCallback((async e=>{try{if(t.enabled&&"success"!==t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return await n(e.provider,t.token)}catch(e){throw p({status:"error",error:e}),e}}),[n,t]),m=i.useCallback((async()=>{let e=ha();try{if(u)return console.warn("Cannot login with OAuth when already logged in"),u;if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(e.popupFlow)return}catch(e){throw p({status:"error",error:e}),e}try{return await a(e)}catch(e){throw p({status:"error",error:e}),e}finally{pa()}}),[a]);return i.useEffect((()=>{let e=ha();c&&r&&e.inProgress&&e.headless&&!e.popupFlow&&m()}),[c,r]),{initOAuth:y,loginWithOAuth:m,loading:s,state:h}},exports.useLoginWithPasskey=e=>{let t=ba(),{initLoginWithPasskey:r,loginWithPasskey:n,passkeyAuthState:a,setPasskeyAuthState:s}=o.usePrivyInternal();return{loginWithPasskey:i.useCallback((async()=>{try{let i;if(t.enabled&&"error"===t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult()),await r(i);let{user:a,isNewUser:s,wasAlreadyAuthenticated:l,loginAccount:d}=await n();e?.onComplete?.(a,s,l,"passkey",d)}catch(t){throw s({status:"error",error:t}),e?.onError?.(t),t}}),[n,t.status]),state:a}},exports.useLoginWithSms=e=>{let t=ba(),{smsOtpState:r,setSmsOtpState:n,initLoginWithSms:a,loginWithCode:s}=o.usePrivyInternal();return{sendCode:i.useCallback((async({phoneNumber:r})=>{try{let e;if(!r)throw Error("SMS required to send OTP code");if(t.enabled&&"error"===t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a(r,e)}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:i.useCallback((async({code:r})=>{try{if(t.enabled&&"success"!==t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:l}=await s(r);e?.onComplete?.(n,i,a,"sms",l)}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[s,t.status]),state:r}},exports.useMfa=Rp,exports.useMfaEnrollment=Fp,exports.useModalStatus=()=>{let{isModalOpen:e}=i.useContext(o.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(e){let{authenticated:t,user:r}=o.usePrivy(),{initLoginWithOAuth:n}=o.usePrivyInternal(),i=d.useEmitPrivyEvent();return d.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>Ng(t,r,n,i,e.provider)}},exports.useRegisterMfaListener=wo,exports.useSendSolanaTransaction=function(e){let{sendSolanaTransaction:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("sendSolanaTransaction",e),{sendSolanaTransaction:t}},exports.useSendTransaction=function(e){let{sendTransaction:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:t}},exports.useSetWalletPassword=function(e){let{setWalletPassword:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("setWalletPassword",e),{setWalletPassword:t}},exports.useSetWalletRecovery=function(e){let{setWalletRecovery:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("setWalletRecovery",e),{setWalletRecovery:t}},exports.useSignMessage=function(e){let{signMessage:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("signMessage",e),{signMessage:t}},exports.useSignTypedData=function(e){let{signTypedData:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("signTypedData",e),{signTypedData:t}},exports.useToken=function(e){let{getAccessToken:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("accessToken",e),{getAccessToken:t}};
3118
+ `;function rg(t){let r=i.useRef(null),n=i.useRef();return i.useEffect((()=>{n.current?.remove(),n.current=function({botUsername:e,scriptHost:t}){let r=document.createElement("script"),{origin:n}=new URL(t);return r.async=!0,r.src=`${n}/js/telegram-login.js`,r.setAttribute("data-telegram-login",e),r.setAttribute("data-request-access","write"),r.setAttribute("data-lang","en"),r}(t),r.current?.after(n.current)}),[t]),e.jsx("div",{ref:r,hidden:!0})}async function ng(e,t,r,n,i,a=!1){let o=a,s=async s=>{if(o&&t&&t.length>0){s===(a?0:1)?i("configureMfa","onMfaRequired",t):n.current?.reject(new Ql("missing_or_invalid_mfa","MFA verification failed, retry."));let o=await new Promise(((e,t)=>{r.current={resolve:e,reject:t},setTimeout((()=>{let e=new Ql("mfa_timeout","Timed out waiting for MFA code");n.current?.reject(e),t(e)}),3e5)}));return await e(o)}return await e()},l=null;for(let e=0;e<4;e++)try{l=await s(e),n.current?.resolve(void 0);break}catch(e){if("missing_or_invalid_mfa"!==e.type)throw n.current?.resolve(void 0),e;o=!0}if(null===l){let e=new Ql("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return l}var ig;let ag=(ig=0,()=>"id-"+ig++);function og(e){return void 0!==e.error}let sg=new class{enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let r=this.callbacks[t];if(!r)throw Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:wallet:create":case"privy:wallet:create-additional":case"privy:wallet:import":case"privy:wallet:connect":case"privy:wallet:recover":case"privy:wallet:rpc":case"privy:wallet:set-recovery":case"privy:mfa:verify":case"privy:mfa:init-enrollment":case"privy:mfa:submit-enrollment":case"privy:mfa:unenroll":case"privy:mfa:clear":case"privy:farcaster:init-signer":case"privy:farcaster:sign":case"privy:solana-wallet:create":case"privy:solana-wallet:connect":case"privy:solana-wallet:recover":case"privy:solana-wallet:rpc":case"privy:delegated-actions:consent":return r;default:throw Error(`invalid wallet event type ${e}`)}}constructor(){this.callbacks={}}},lg=new Map,dg=(e,t)=>"bigint"==typeof t?t.toString():t,cg=(e,t)=>`${e}${JSON.stringify(t,dg)}`;function ug(e,t,r,n){let i=r.contentWindow;if(!i)throw Error("iframe not initialized");let a=cg(e,t);if("privy:wallet:create"===e){let e=lg.get(a);if(e)return e}let o=new Promise(((r,a)=>{let o=ag();sg.enqueue(o,{resolve:r,reject:a}),i.postMessage({id:o,event:e,data:t},n)})).finally((()=>{lg.delete(a)}));return lg.set(a,o),o}function hg(t){let r=i.useRef(null),n=i.useRef(t.mfaMethods),a=d.useEmitPrivyEvent(),[o,s]=i.useState(!1);return i.useEffect((()=>{n.current=t.mfaMethods}),[t.mfaMethods]),i.useEffect((()=>{if(!o)return;let e=r.current;if(!e)return;function i(e){var r;e&&e.origin===t.origin&&"string"==typeof(r=e.data).event&&/^privy:.+/.test(r.event)&&function(e){switch(e.event){case"privy:iframe:ready":let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":let r=sg.dequeue(e.event,e.id);return og(e)?r.reject(new Ql(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallet:create-additional":let n=sg.dequeue(e.event,e.id);return og(e)?n.reject(new Ql(e.error.type,e.error.message)):n.resolve(e.data);case"privy:wallet:import":let i=sg.dequeue(e.event,e.id);return og(e)?i.reject(new Ql(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:connect":let a=sg.dequeue(e.event,e.id);return og(e)?a.reject(new Ql(e.error.type,e.error.message)):a.resolve(e.data);case"privy:wallet:recover":let o=sg.dequeue(e.event,e.id);return og(e)?o.reject(new Ql(e.error.type,e.error.message)):o.resolve(e.data);case"privy:wallet:rpc":let s=sg.dequeue(e.event,e.id);return og(e)?s.reject(new Ql(e.error.type,e.error.message)):s.resolve(e.data);case"privy:wallet:set-recovery":let l=sg.dequeue(e.event,e.id);return og(e)?l.reject(new Ql(e.error.type,e.error.message)):l.resolve(e.data);case"privy:mfa:verify":let d=sg.dequeue(e.event,e.id);return og(e)?d.reject(new Ql(e.error.type,e.error.message)):d.resolve(e.data);case"privy:mfa:init-enrollment":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:init-signer":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let c=sg.dequeue(e.event,e.id);return og(e)?c.reject(new Ql(e.error.type,e.error.message)):c.resolve(e.data);case"privy:solana-wallet:connect":let u=sg.dequeue(e.event,e.id);return og(e)?u.reject(new Ql(e.error.type,e.error.message)):u.resolve(e.data);case"privy:solana-wallet:recover":let h=sg.dequeue(e.event,e.id);return og(e)?h.reject(new Ql(e.error.type,e.error.message)):h.resolve(e.data);case"privy:solana-wallet:rpc":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=sg.dequeue(e.event,e.id);return og(e)?t.reject(new Ql(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(e.data)}let s={create:r=>ug("privy:wallet:create",r,e,t.origin),createAdditional:r=>ug("privy:wallet:create-additional",r,e,t.origin),import:r=>ug("privy:wallet:import",r,e,t.origin),connect:r=>ug("privy:wallet:connect",r,e,t.origin),recover:r=>ng((n=>ug("privy:wallet:recover",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a,!r.recoveryMethod||"privy"===r.recoveryMethod),rpc:r=>ng((n=>ug("privy:wallet:rpc",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a),createSolana:r=>ug("privy:solana-wallet:create",r,e,t.origin),connectSolana:r=>ug("privy:solana-wallet:connect",r,e,t.origin),recoverSolana:r=>ug("privy:solana-wallet:recover",r,e,t.origin),rpcSolana:r=>ug("privy:solana-wallet:rpc",r,e,t.origin),createDelegatedAction:r=>ug("privy:delegated-actions:consent",r,e,t.origin),setRecovery:r=>ng((n=>ug("privy:wallet:set-recovery",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a),verifyMfa:r=>ng((n=>ug("privy:mfa:verify",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a,!0),initEnrollMfa:r=>ng((n=>ug("privy:mfa:init-enrollment",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a),submitEnrollMfa:r=>ng((n=>ug("privy:mfa:submit-enrollment",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a),unenrollMfa:r=>ng((n=>ug("privy:mfa:unenroll",{...r,...n},e,t.origin)),n.current,t.mfaPromise,t.mfaSubmitPromise,a,!0),clearMfa:r=>ug("privy:mfa:clear",r,e,t.origin),initFarcasterSigner:r=>ug("privy:farcaster:init-signer",r,e,t.origin),signFarcasterMessage:r=>ug("privy:farcaster:sign",r,e,t.origin)};window.addEventListener("message",i);let l=new AbortController;return d.invokeUntilSettled((()=>ug("privy:iframe:ready",{},e,t.origin)),{abortSignal:l.signal}).then((()=>t.onLoad(s)),((...e)=>{console.warn("Privy iframe failed to load: ",...e),t.onLoadFailed()})),()=>{window.removeEventListener("message",i),l.abort()}}),[o]),e.jsx("iframe",{ref:r,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>s(!0),src:d.constructURL(t.origin,`/apps/${t.appId}/embedded-wallets`,{caid:t.clientAnalyticsId,client_id:t.appClientId})})}class pg{async handleSignMessage(e){if(!e.params||"string"!=typeof e.params.message)throw Error("Message must be provided as a string for Solana signMessage RPC");return await _g({message:e.params.message})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await Sg())throw Error("User must be authenticated to use embedded Solana wallet");if(!await Pg())throw new o.PrivyClientError("Unable to connect to Solana embedded wallet");if("signMessage"===e.method)return await this.handleSignMessage(e);throw Error("Embedded Solana provider does not yet support this RPC method.")}constructor(e,t){this.walletProxy=e,this.address=t}}const yg="popup-privy-oauth",mg="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";async function fg({url:e,popup:t,provider:r}){return t.location=e,new Promise(((e,r)=>{function n(){t?.close(),window.removeEventListener("message",i)}function i(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(e(t.data),n()),"https://cdn.apple-cloudkit.com"===t.origin&&t.data.ckSession&&(e({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:t.data.ckSession}),n()),"PRIVY_OAUTH_ERROR"===t.data.type&&(r(t.data.error),n()))}window.addEventListener("message",i)}))}let gg,vg,wg,xg,Cg,Eg,bg;function Sg(){return gg?gg.getAccessToken():Promise.resolve(d.e5.get(l.TOKEN_STORAGE_KEY)||null)}const Ag=(e,t,r)=>vg(e,t,r),jg=(e,t,r)=>wg(e,t,r),$g=(e,t,r,n)=>xg(e,t,r,n),Tg=()=>Cg(),Pg=()=>Eg(),_g=({message:e})=>bg({message:e});let kg=s=>{let c=s.client,[h,p]=i.useState(!1),[y,f]=i.useState(!1),[v,w]=i.useState(!1),[x,C]=i.useState(null),[E,b]=i.useState([]),[S,A]=i.useState([]),[j,$]=i.useState(null),T=i.useRef(E),[P,_]=i.useState(!1),[k,N]=i.useState(null),[I,M]=i.useState(!1),[O,R]=i.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:o.notImplemented}),[F,L]=i.useState({status:"initial"}),[U,D]=i.useState({status:"initial"}),[W,B]=i.useState({status:"initial"}),[H,G]=i.useState({status:"initial"}),[q,z]=i.useState({status:"initial"}),[V,K]=i.useState(null),Y=l.useAppConfig(),Z=l.useIsServerConfigLoaded(),[X,J]=i.useState(!0),[Q,ee]=i.useState({}),[te,re]=i.useState(null),[ne,ie]=i.useState(null),[ae,oe]=i.useState(!1),[se,le]=i.useState(!1),[de,ce]=i.useState(Y.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),ue=i.useRef(null),he=i.useRef(null),pe=i.useRef(d.privyEventsDefault),[ye,me]=i.useState(!1);c.onStoreToken=e=>{e&&d.emitPrivyEvent(pe,"accessToken","onAccessTokenGranted",e)},c.onDeleteToken=()=>{C(null),w(!1),d.emitPrivyEvent(pe,"accessToken","onAccessTokenRemoved")};let fe=i.useRef(null),ge=i.useRef(null),ve=i.useRef(!1),we=e=>{N(e),setTimeout((()=>{p(!0)}),15),c.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:e}})},xe=e=>{"off"!==Y.embeddedWallets.createOnLogin&&J(!0),we(e)};i.useEffect((()=>{let e=u.getPrivySolanaWallet(x);if(!e||!V)return void $(null);let t={type:"solana",imported:!1,address:e.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",meta:{name:"Privy Wallet",icon:void 0,id:"io.privy.solana.wallet"},linked:!0,fund:()=>{throw new o.PrivyClientError("Funding is not supported for Solana embedded wallets.")},unlink:()=>{throw new o.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new pg(V,e.address),signMessage:async e=>{let r=await Sg();if(!r||!V)throw new o.PrivyClientError("Must have valid access token and Privy wallet to send transaction",o.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Be.recoverEmbeddedSolanaWallet().catch((()=>!1)))throw new o.PrivyClientError("Wallet couldn't be connected",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let{response:n}=await V.rpcSolana({accessToken:r,publicKey:t.address,request:{method:"signMessage",params:{message:Buffer.from(e).toString("base64")}}});return Buffer.from(n.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:n}=await Oe({transaction:e,connection:t,transactionOptions:r,wallet:this});return n},async signTransaction(e){let t=await Sg();if(!t||!V)throw new o.PrivyClientError("Must have valid access token and Privy wallet to send transaction",o.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Be.recoverEmbeddedSolanaWallet().catch((()=>!1)))throw new o.PrivyClientError("Wallet couldn't be connected",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);return await xm({tx:e,accessToken:t,walletProxy:V,transactingWalletAddress:this.address}),e},loginOrLink:async()=>{throw new o.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{$(null)},isConnected:async()=>!0};$(t)}),[V,x]),i.useEffect((()=>{if(!x)return void c.connectors?.removeEmbeddedWalletConnectors();let e=u.getPrivyEthereumWallet(x),t=u.getPrivyEthereumHDWallets(x),r=u.getImportedPrivyEthereumWallet(x);e&&t.length||c.connectors?.removeEmbeddedWalletConnectors(),r||c.connectors?.removeImportedWalletConnector(),c.connectors?V?(e&&c.connectors.addEmbeddedWalletConnectors({walletProxy:V,rootWallet:e,embeddedWallets:t,defaultChain:Y.defaultChain,appId:s.appId}),r&&c.connectors.addImportedWalletConnector(V,r.address,Y.defaultChain,s.appId)):console.debug("Failed to add embedded wallet connector: Wallet proxy not initialized"):console.debug("Failed to add embedded wallet connector: Client connectors not initialized")}),[V,x]),i.useEffect((()=>{V&&ne?.(V)}),[V]),i.useEffect((()=>{(async()=>{if(!Y.customAuth?.enabled)return void ce({status:"not-enabled"});J(!0),ce({status:"loading"});let{getCustomAccessToken:e,isLoading:t}=Y.customAuth;if(y&&!t)try{let t=await e();if(!t&&v)return await We.logout(),ce({status:"done"}),void d.emitPrivyEvent(pe,"customAuth","onUnauthenticated");if(!t||v)return void ce({status:"done"});c.startAuthFlow(new Ii(t));let{user:r,isNewUser:n}=await c.authenticate();if(!r)return await We.logout(),ce({status:"error",error:new o.PrivyClientError("Failed to sync with custom auth provider")}),void d.emitPrivyEvent(pe,"customAuth","onUnauthenticated");void 0!==n&&d.emitPrivyEvent(pe,"login","onComplete",r,n,!1,"custom",null),d.emitPrivyEvent(pe,"customAuth","onAuthenticated",{user:r}),ce({status:"done"}),C(r||null),_(n||!1),w(!0),le(!0)}catch(e){console.warn(e),v&&(await We.logout(),d.emitPrivyEvent(pe,"customAuth","onUnauthenticated")),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),ce({status:"error",error:e})}})()}),[Y.customAuth?.enabled,Y.customAuth?.getCustomAccessToken,Y.customAuth?.isLoading,y,v]),i.useEffect((()=>{se&&V&&x&&u.shouldProceedtoEmbeddedWalletCreationFlow(x,Y.embeddedWallets.createOnLogin)&&(le(!1),Ie(x,l.WALLET_PROXY_TIMEOUT).catch(console.error))}),[se&&V&&x]),i.useEffect((()=>{if(Y.externalWallets.solana.connectors)return Y.externalWallets.solana.connectors.onMount(),()=>Y.externalWallets.solana.connectors?.onUnmount()}),[Y.externalWallets.solana.connectors]),i.useEffect((()=>{!y&&Z&&async function(){let e,t=Ce(),r=Ee();(()=>{let e=new URLSearchParams(window.location.search).get("privy_token");if(!e)return;d.e5.put(l.FORKED_TOKEN_STORAGE_KEY,e);let t=new URL(window.location.href);t.searchParams.delete("privy_token"),window.history.pushState({},"",t)})();let i=n.createStore();c.initializeConnectorManager({walletConnectCloudProjectId:Y.walletConnectCloudProjectId,rpcConfig:Y.rpcConfig,chains:Y.chains,defaultChain:Y.defaultChain,store:i,walletList:Y.appearance.walletList,shouldEnforceDefaultChainOnConnect:Y.shouldEnforceDefaultChainOnConnect,externalWalletConfig:Y.externalWallets,appName:Y.name??"Privy"}),c.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=c.connectors.walletConnectors.length,r=c.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?me(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),me(!0)}),1500)})),c.connectors?.initialize().then((()=>{$e()}));let a=await c.getAuthenticatedUser(),o=!!a;if(Y.customAuth?.enabled||(w(!!a),a&&d.emitPrivyEvent(pe,"login","onComplete",a,!1,!0,null,null),C(a)),!t)return r&&!o?(ge.current="login",ee({telegramAuthModalData:{seamlessAuth:!0}}),void xe(g.ModalScreen.TELEGRAM_AUTH_SCREEN)):void Be.setReadyToTrue(!!a);ge.current=o?"link":"login"}()}),[c,te,y,Z]),i.useEffect((()=>{if(y){if(!x||!x.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void oe(!0);oe(!!E.find((e=>"privy"===e.walletClientType)))}}),[y,x,E]);let Ce=()=>{let e=ha();return e.inProgress&&e.popupFlow?window.opener.location.origin!==window.location.origin?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Origins between parent and child windows do not match."}):"error"===e.authorizationCode?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Something went wrong. Try again."}):void window.opener.postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}):(e.inProgress&&function(e){return e.startsWith("privy:")}(e.provider)&&!e.popupFlow&&(new BroadcastChannel(yg).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!e.headless&&(c.startAuthFlow(new Ji(e)),xe(g.ModalScreen.AWAITING_OAUTH_SCREEN),!0))},Ee=()=>{let e=function(){let e;return(e=function(){let e=new URLSearchParams(window.location.search),t=Number(e.get("id")||""),r=e.get("hash"),n=Number(e.get("auth_date")||""),i=e.get("first_name"),a=e.get("last_name")||void 0,o=e.get("username")||void 0,s=e.get("photo_url")||void 0;if(t&&i&&n&&r)return{id:t,first_name:i,last_name:a,username:o,photo_url:s,auth_date:n,hash:r}}())?(ja(),{...e,flowType:"login-url"}):(e=function(){let e=window.location.hash;if(!e||!e.startsWith("#tgWebAppData"))return;let t=new URLSearchParams(decodeURIComponent(e.replace("#tgWebAppData=",""))),r=t.get("query_id")||void 0,n=t.get("user"),i=Number(t.get("auth_date")||""),a=t.get("hash"),o=t.get("chat_instance")||void 0,s=t.get("chat_type")||void 0,l=t.get("start_param")||void 0;return n&&i&&a?{query_id:r,user:n,auth_date:i,hash:a,chat_instance:o,chat_type:s,start_param:l}:void 0}())?(ja(),{...e,flowType:"web-app"}):void 0}();if(!e||!Y.loginMethods.telegram||!Y.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new Sa;return c.startAuthFlow(t),"login-url"===e.flowType&&(t.meta.telegramWebAppData=void 0,t.meta.telegramAuthResult={id:e.id,first_name:e.first_name,last_name:e.last_name,auth_date:e.auth_date,username:e.username,photo_url:e.photo_url,hash:e.hash}),"web-app"===e.flowType&&(t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData={query_id:e.query_id,user:e.user,auth_date:e.auth_date,hash:e.hash,chat_instance:e.chat_instance,chat_type:e.chat_type,start_param:e.start_param}),!0},be=async(e,t,r,n)=>{Se(await(c.connectors?.createEthereumWalletConnector(e,t))||null,t,r,n)};async function Se(e,t,r,n){if(!e)return R({status:"disconnected",connectedWallet:null,connectError:new o.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:o.notImplemented}),n?.(null,r);R({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:o.notImplemented}),e instanceof to&&t&&await e.resetConnection(t),R({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Se(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||Ra(t))&&Y.shouldEnforceDefaultChainOnConnect&&!Y.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){R((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:o.notImplemented})));try{await(t?.switchChain(Y.defaultChain.id)),t&&(t.chainId=d.formatChainIdToCAIP2(d.toHex(Y.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${Y.defaultChain.id}`)}}return R((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:o.notImplemented}))),t&&d.emitPrivyEvent(pe,"connectWallet","onSuccess",t),n?.(t,r)}catch(e){return e instanceof o.PrivyError?(console.warn(e.cause?e.cause:e.message),d.emitPrivyEvent(pe,"connectWallet","onError",e.privyErrorCode||o.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),d.emitPrivyEvent(pe,"connectWallet","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),R((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Ae=async(e,t,r)=>{if(null===e||!Ra(e))return;let n=new fa(e,c,t,r);c.startAuthFlow(n)},je=async(e,t)=>{if(null===e||!m.isBaseConnectedSolanaWallet(e))return;let r=new ga(e,c,t);c.startAuthFlow(r)},$e=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client");if(!t||!r)return;if("phantom"!==r||d.isPhantomInstalled()||xe(g.ModalScreen.LOGIN_FAILED_SCREEN),!c.connectors)throw new o.PrivyClientError("Connector not initialized");we(g.ModalScreen.AWAITING_CONNECTION);let n=new URL(window.location.href);n.searchParams.delete("privy_connector"),n.searchParams.delete("privy_wallet_client"),window.history.pushState({},"",n),be(t,r,void 0,Ae)};i.useEffect((()=>{y&&v&&null===x&&c.getAuthenticatedUser().then(C)}),[y,v,x,c]);let Te=e=>{if(!v)throw d.emitPrivyEvent(pe,"linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new o.PrivyClientError("User must be authenticated before linking an account.")},Pe=()=>{Te("siwe"),fe.current="siwe",ge.current="link",we(g.ModalScreen.LINK_WALLET_SCREEN)},_e=e=>{if(!v||!x)return!1;if("privy"===e.walletClientType)return!0;for(let t of x.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},ke=async e=>{let t;if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");t="ethereum"===e.type?c.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:c.connectors.findSolanaWalletConnector(e.connectorType,e.walletClientType)||null,R((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:o.notImplemented}))),Y.captchaEnabled&&!v?(ee({captchaModalData:{callback:t=>Ra(e)?Ae(e,t):je(e,t),userIntentRequired:!1,onSuccessNavigateTo:g.ModalScreen.AWAITING_CONNECTION,onErrorNavigateTo:g.ModalScreen.ERROR_SCREEN}}),xe(g.ModalScreen.CAPTCHA_SCREEN)):(Ra(e)?await Ae(e):await je(e),xe(g.ModalScreen.AWAITING_CONNECTION))},Ne=()=>{b((e=>{let t=c.connectors?.wallets.filter(Ra).map((e=>({...e,linked:_e(e),loginOrLink:async()=>{if(!await e.isConnected())throw new o.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot link or login with embedded wallet");ke(e)},fund:async t=>{await Be.fundWallet(e.address,t)},unlink:async()=>{if(!v)throw new o.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot unlink an embedded wallet");C(await c.unlinkEthereumWallet(e.address))}})))||[];return ao(e,t)?e:t})),A((e=>{let t=c.connectors?.wallets.filter(m.isBaseConnectedSolanaWallet).map((e=>({...e,linked:_e(e),loginOrLink:async()=>{if(!await e.isConnected())throw new o.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot link or login with embedded wallet");ke(e)},fund:async e=>{throw new o.PrivyClientError("Funding not supported for Solana wallets")},unlink:async()=>{if(!v)throw new o.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot unlink an embedded wallet");C(await c.unlinkSolanaWallet(e.address))}})))||[];return ao(e,t)?e:t}))};i.useEffect((()=>{Ne()}),[x?.linkedAccounts,v,y]),i.useEffect((()=>{if(y){if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");Ne(),c.connectors.on("walletsUpdated",Ne)}}),[y]),i.useEffect((()=>{let e;if(!E[0])return;let t=E[0],r=T.current.find((e=>e.address===t.address));if(e="privy"===t.walletClientType?x?.linkedAccounts.find((e=>"wallet"===e.type&&e.address===t.address&&"privy"===e.walletClientType)):x?.linkedAccounts.find((e=>"wallet"===e.type&&e.address===t.address&&"privy"!==e.walletClientType)),!r&&e){let t=Object.assign({},x);t.wallet=e&&{address:e.address,chainType:e.chainType,chainId:e.chainId,walletClient:e.walletClient,walletClientType:e.walletClientType,connectorType:e.connectorType,imported:e.imported,walletIndex:e.walletIndex},C(t)}T.current=E}),[E]);let Ie=async(e,t,r)=>{let n=u.getPrivyEthereumWallet(e),i=u.getPrivySolanaWallet(e);if(n&&!r?.createAdditional)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[a,s]=await Promise.all([Be.initializeWalletProxy(t),Sg()]);if(!a&&Y.customAuth?.enabled)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!a||!s||Y.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return new Promise(((e,t)=>{J(!0),ee({createWallet:{onSuccess:t=>{d.emitPrivyEvent(pe,"createWallet","onSuccess",t),e(t)},onFailure:e=>{d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),we(g.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}));{if(n){let t=u.getPrivyEthereumHDWallets(e),r=t?.length?Math.max(...t.map((e=>e.walletIndex))):n.walletIndex;await Be.recoverEmbeddedEthereumWallet(),await a.createAdditional({accessToken:s,primaryWalletAddress:n?.address,hdWalletIndex:r+1})}else console.log("solanaWallet",i),await a.create({accessToken:s,solanaAddress:i?.address});let t=u.getPrivyEthereumWallet(await Be.refreshUser());if(!t)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return d.emitPrivyEvent(pe,"createWallet","onSuccess",t),t}},Me=(e,r,n,i)=>new Promise((async(a,l)=>{let{requesterAppId:c}=r||{};if(!v||!x)return d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void l(Error("User must be authenticated before signing with a Privy wallet"));let h=i??u.getPrivyEthereumWallet(x)?.address;if(!h)throw new o.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:p,rootWallet:y}=u.getSigningAndRootWallet(x,h);if(!y||!p)return d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void l(Error("Must have a Privy wallet before signing"));J(!0);let f=He.wallets.find((e=>"privy"===e.walletClientType&&t.getAddress(e.address)===t.getAddress(p.address))),w=await(f?.getEthereumProvider());if(!f||!w)throw new o.PrivyClientError(`Cannot sendTransaction before embedded wallet ${p.address} is connected`);let C=e.chainId?Number(e.chainId):sf(f.chainId);(e=>{if(!Y.chains.map((e=>e.id)).includes(e))throw new o.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,o.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(C);let E=Object.assign({},e,{chainId:C});if(Y.embeddedWallets.noPromptOnSignature||ve.current)r&&Y.embeddedWallets.noPromptOnSignature&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config"),(async()=>{let e=await Sg();if(!e||!V)return d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void l(Error("Must have valid access token and Privy wallet to send transaction"));try{if(!await Be.recoverEmbeddedEthereumWallet())return d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void l(Error("Unable to connect to wallet"));let t=d.getJsonRpcProvider(E.chainId,Y.chains,Y.rpcConfig,{appId:s.appId}),r=await dr(p.address,E,t);if(Y.embeddedWallets.noPromptOnSignature||ve.current){let{totalGasEstimate:e}=await sr(r,t),{hasSufficientFunds:n}=await af(p.address,r,e,t);if(!n)throw new m.PrivyProviderRpcError(new m.ProviderRpcError("Wallet has insufficient funds for this transaction.",m.E.E32603_DEFAULT_INTERNAL_ERROR.eipCode))}let n=await nf({accessToken:e,rootWallet:y,transactingWallet:p,walletProxy:V,transactionRequest:r,provider:t,requesterAppId:c});d.emitPrivyEvent(pe,"sendTransaction","onSuccess",n),a(n)}catch(e){d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.TRANSACTION_FAILURE),l(e)}})();else{let e={address:y.address,onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),l(e)}},t=df({address:p.address,appConfig:Y,fundWalletConfig:n,chainIdOverride:E.chainId,comingFromSendTransactionScreen:!0});ee({connectWallet:e,sendTransaction:{transactionRequest:E,transactingWallet:p,rootWallet:y,onSuccess:e=>{d.emitPrivyEvent(pe,"sendTransaction","onSuccess",e),a(e)},onFailure:e=>{d.emitPrivyEvent(pe,"sendTransaction","onError",o.PrivyErrorCode.TRANSACTION_FAILURE),l(e)},uiOptions:r||{},fundWalletConfig:n,requesterAppId:c},funding:t}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),Oe=({transaction:e,connection:t,transactionOptions:r,uiOptions:n,wallet:i})=>new Promise((async(a,s)=>{let{requesterAppId:l}=n||{};if(!v||!x)return d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void s(new o.PrivyClientError("User must be authenticated before signing with a Privy wallet",o.PrivyErrorCode.MUST_BE_AUTHENTICATED));let c=i?x.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):u.getPrivySolanaWallet(x);if(!c)return d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(new o.PrivyClientError("Must have a Privy wallet before signing",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));J(!0);let h=i??j,p=await(h?.isConnected());if(!h||!p)throw d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new o.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${c.address} is connected`,o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);Y.embeddedWallets.noPromptOnSignature?(n&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config"),(async()=>{let n=await Sg();if(!n||!V)return d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(new o.PrivyClientError("Must have valid access token and Privy wallet to send transaction",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{if(!await Be.recoverEmbeddedSolanaWallet())return d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void s(new o.PrivyClientError("Unable to connect to wallet",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(Y.embeddedWallets.noPromptOnSignature){let{instructions:r}=await vy(e,t);r.every((e=>e.hasFunds))||(d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.INSUFFICIENT_BALANCE),s(new o.PrivyClientError("Solana wallet has insufficient funds for this transaction.",o.PrivyErrorCode.INSUFFICIENT_BALANCE)))}let{signature:i,receipt:l}=await Cm({accessToken:n,tx:e,connection:t,walletProxy:V,transactionOptions:r,transactingWalletAddress:c.address}),u=gy(i,l);d.emitPrivyEvent(pe,"sendSolanaTransaction","onSuccess",u),a(u)}catch(e){d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.TRANSACTION_FAILURE),s(e)}})()):(ee({connectWallet:{address:c.address,onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:c,onSuccess:e=>{d.emitPrivyEvent(pe,"sendSolanaTransaction","onSuccess",e),a(e)},onFailure:e=>{d.emitPrivyEvent(pe,"sendSolanaTransaction","onError",o.PrivyErrorCode.TRANSACTION_FAILURE),s(e)},uiOptions:n||{},requesterAppId:l},funding:void 0}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN))}));function Re(){return new Promise((async(e,t)=>{let r=await Sg();if(!r||!V)throw Error("Must have valid access token to enroll in MFA");try{await V.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let Fe=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],Le=e=>{let t=x?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=np(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw d.emitPrivyEvent(pe,"linkAccount","onError",o.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new o.PrivyClientError(`User already has an account of type ${r} linked.`)};async function Ue({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){N(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!v||!x)throw d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=u.getPrivyEthereumWallet(x);if(!n||!V)throw d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");if(u.getPrivySolanaWallet(x))throw Error("Cannot set user-controlled recovery for user with Solana.");try{await Re()}catch(e){throw d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((i,a)=>{J(!0);let s={onSuccess:e=>{d.emitPrivyEvent(pe,r,"onSuccess","user-passcode",e),i(e)},onFailure:e=>{d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),a(e)},callAuthOnSuccessOnClose:!1},l="user-passcode"===n.recoveryMethod;ee({setWalletPassword:s,createWallet:s,connectWallet:{onCompleteNavigateTo:ld({walletAction:"update",availableRecoveryMethods:Y.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:l,showAutomaticRecovery:e}),shouldForceMFA:!1,onFailure:e=>{d.emitPrivyEvent(pe,r,"onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:l}}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function De({appId:e,action:t}){let r=await Sg();if("link"===t&&!r)throw d.emitPrivyEvent(pe,"linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new o.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw d.emitPrivyEvent(pe,"login","onError",o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new o.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");fe.current=`privy:${e}`,ge.current=t;let n=window.open(void 0,void 0,Ju({w:440,h:680}));return c.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,i)=>{let{name:a,logoUrl:o}=await Yu({api:c.api,providerAppId:e,requesterAppId:Y.id});ee({crossAppAuth:{appId:e,name:a,logoUrl:o,action:t,popup:n,onSuccess:r,onError:i}}),xe(g.ModalScreen.CROSS_APP_AUTH_SCREEN)}))}let We={ready:y,authenticated:v,user:x,walletConnectors:c.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),ee({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress}}),we(v?g.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN:g.ModalScreen.CONNECT_ONLY_LANDING_SCREEN)},importWallet:async({privateKey:e})=>{Te("siwe");let[t,r]=await Promise.all([Be.initializeWalletProxy(15e3),Sg()]);if(t&&r){await t.import({privateKey:e,accessToken:r});let n=u.getImportedPrivyEthereumWallet(await Be.refreshUser());if(!n)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to import wallet");return d.emitPrivyEvent(pe,"createWallet","onSuccess",n),n}throw new o.PrivyClientError("User is not authenticated")},linkWallet:Pe,startCrossAppAuthFlow:De,linkEmail:()=>{Te("email"),Le("email"),fe.current="email",ge.current="link",we(g.ModalScreen.LINK_EMAIL_SCREEN)},linkPhone:()=>{Te("sms"),Le("phone"),fe.current="sms",ge.current="link",we(g.ModalScreen.LINK_PHONE_SCREEN)},linkGoogle:async()=>{Te("google"),Le("google_oauth"),ge.current="link",await Be.initLoginWithOAuth("google")},linkTwitter:async()=>{Te("twitter"),Le("twitter_oauth"),ge.current="link",await Be.initLoginWithOAuth("twitter")},linkDiscord:async()=>{Te("discord"),Le("discord_oauth"),ge.current="link",await Be.initLoginWithOAuth("discord")},linkGithub:async()=>{Te("github"),Le("github_oauth"),ge.current="link",await Be.initLoginWithOAuth("github")},linkSpotify:async()=>{Te("spotify"),Le("spotify_oauth"),ge.current="link",await Be.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Te("instagram"),Le("instagram_oauth"),ge.current="link",await Be.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Te("tiktok"),Le("tiktok_oauth"),ge.current="link",await Be.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{Te("linkedin"),Le("linkedin_oauth"),ge.current="link",await Be.initLoginWithOAuth("linkedin")},linkApple:async()=>{Te("apple"),Le("apple_oauth"),ge.current="link",await Be.initLoginWithOAuth("apple")},linkPasskey:async()=>{Te("passkey"),Le("passkey"),await Be.initLinkWithPasskey(),we(g.ModalScreen.LINK_PASSKEY_SCREEN)},linkTelegram:async()=>{Te("telegram"),Le("telegram"),ge.current="link",fe.current="telegram",await Be.initLoginWithTelegram(),we(g.ModalScreen.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{Te("farcaster"),Le("farcaster"),await Be.initLoginWithFarcaster(),ge.current="link",fe.current="farcaster",we(g.ModalScreen.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(Te("email"),!x?.email)throw new o.PrivyClientError("User does not have an email linked to their account.");ge.current="link",fe.current="email",we(g.ModalScreen.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(Te("sms"),!x?.phone)throw new o.PrivyClientError("User does not have a phone number linked to their account.");ge.current="link",fe.current="sms",we(g.ModalScreen.UPDATE_PHONE_SCREEN)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!y){let e=await new Promise((e=>{re((t=>e.bind(t)))}));if(re(null),e)return void console.warn(t)}!x||x.isGuest?(ge.current="login",ee({login:e}),xe(g.ModalScreen.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{y||(await new Promise((e=>{re((()=>e))})),re(null)),v?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):xe(g.ModalScreen.CONNECT_OR_CREATE)},logout:async()=>{if(x&&c.clearProviderAcccessTokens(x),N(null),await c.logout(),x&&V)try{await V.clearMfa({userId:x.id})}catch(e){}C(null),w(!1),d.emitPrivyEvent(pe,"logout","onSuccess"),ge.current=null,fe.current=null,p(!1),d.e5.del(l.CLIENT_ANALYTICS_ID_KEY),d.e5.del(l.getGuestCredentialStorageKey(Y.id))},getAccessToken:()=>c.getAccessToken(),getEthereumProvider:()=>{if(!x||!x.wallet)return new Pa;let e=E.find((e=>x.wallet&&e.address===x.wallet.address)),t=c.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new Pa},getEthersProvider:()=>{if(!x||!x.wallet)return new r.Web3Provider(new Na(new Pa));let e=E.find((e=>x.wallet&&e.address===x.wallet.address)),t=c.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return new r.Web3Provider(new Na(e&&t?t.proxyProvider:new Pa))},getWeb3jsProvider:()=>{if(!x||!x.wallet)return new Ia(new Pa);let e=E.find((e=>x.wallet&&e.address===x.wallet.address)),t=c.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return new Ia(e&&t?t.proxyProvider:new Pa)},unlinkWallet:async e=>{let t;return C(t=e.startsWith("0x")?await c.unlinkEthereumWallet(e):await c.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await c.unlinkEmail(e);return C(t),t},unlinkPhone:async e=>{let t=await c.unlinkPhone(e);return C(t),t},unlinkGoogle:async e=>{let t=await c.unlinkOAuth("google",e);return C(t),t},unlinkTwitter:async e=>{let t=await c.unlinkOAuth("twitter",e);return C(t),t},unlinkDiscord:async e=>{let t=await c.unlinkOAuth("discord",e);return C(t),t},unlinkGithub:async e=>{let t=await c.unlinkOAuth("github",e);return C(t),t},unlinkSpotify:async e=>{let t=await c.unlinkOAuth("spotify",e);return C(t),t},unlinkInstagram:async e=>{let t=await c.unlinkOAuth("instagram",e);return C(t),t},unlinkTiktok:async e=>{let t=await c.unlinkOAuth("tiktok",e);return C(t),t},unlinkLinkedIn:async e=>{let t=await c.unlinkOAuth("linkedin",e);return C(t),t},unlinkApple:async e=>{let t=await c.unlinkOAuth("apple",e);return C(t),t},unlinkFarcaster:async e=>{let t=await c.unlinkFarcaster(e);return C(t),t},unlinkTelegram:async e=>{let t=await c.unlinkTelegram(e);return C(t),t},unlinkPasskey:async e=>{let t=await c.unlinkPasskey(e);return C(t),t},unlinkCrossAppAccount:async({subject:e})=>{let t=x?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new o.PrivyClientError("Invalid subject");c.storeProviderAccessToken(t.id,null);let r=await c.unlinkOAuth(`privy:${t.id}`,e);return C(r),r},setActiveWallet:async e=>{let r=E.find((r=>t.getAddress(r.address)===t.getAddress(e))),n=x?.linkedAccounts.find((r=>"wallet"===r.type&&t.getAddress(r.address)===t.getAddress(e)));if(r&&await r.isConnected())if(r.linked){let e=Object.assign({},x);e.wallet=n&&{address:n.address,chainType:n.chainType,chainId:n.chainId,walletClient:n.walletClient,walletClientType:n.walletClientType,connectorType:n.connectorType,imported:n.imported,walletIndex:n.walletIndex},C(e)}else r.loginOrLink();else ee({externalConnectWallet:{suggestedAddress:e}}),Pe()},forkSession:()=>c.forkSession(),createWallet:async e=>{if(e&&"target"in e&&e&&(e=void 0),!v||!x)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return Ie(x,15e3,e)},setWalletRecovery:async e=>Ue({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>Ue({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t,r)=>new Promise((async(n,i)=>{let{requesterAppId:a}=t||{};if(!v||!x)return d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void i(Error("User must be authenticated before signing with a Privy wallet"));let s=r??u.getPrivyEthereumWallet(x)?.address;if(!s)throw new o.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:h}=u.getSigningAndRootWallet(x,s);if(!l||!h)return d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void i(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.INVALID_MESSAGE),void i(Error("Message must be a non-empty string"));J(!0);let p=async()=>{if(!v)throw Error("User must be authenticated before signing with a Privy wallet");let t=await Sg();if(!V||!t||!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");c.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:l.address,requesterAppId:a}});let{response:r}=await V.rpc({accessToken:t,address:h.address,hdWalletIndex:l.walletIndex??void 0,requesterAppId:a,request:{method:"personal_sign",params:[e,l.address]}}),n=r.data;return c.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:l.address,requesterAppId:a}}),n};if(Y.embeddedWallets.noPromptOnSignature||ve.current){t&&Y.embeddedWallets.noPromptOnSignature&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config");try{let e=await p();d.emitPrivyEvent(pe,"signMessage","onSuccess",e),n(e)}catch(e){d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),i(e??new m.PrivyProviderRpcError("Unable to sign message"))}}else ee({signMessage:{method:"personal_sign",data:e,confirmAndSign:p,onSuccess:e=>{d.emitPrivyEvent(pe,"signMessage","onSuccess",e),n(e)},onFailure:e=>{d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),i(e)},uiOptions:t||{}},connectWallet:{onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),i(e)},address:h.address}}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),signTypedData:(e,t,r)=>new Promise((async(n,i)=>{let{requesterAppId:a}=t||{};if(!v||!x)return d.emitPrivyEvent(pe,"signTypedData","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void i(Error("User must be authenticated before signing with a Privy wallet"));let s=r??u.getPrivyEthereumWallet(x)?.address;if(!s)throw new o.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:h}=u.getSigningAndRootWallet(x,s);if(!h||!l)return d.emitPrivyEvent(pe,"signTypedData","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void i(Error("Must have a Privy wallet before signing"));J(!0);let p=d.generateTypedDataWithDomainType(e),y=async()=>{if(!v)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Sg();if(!V||!e||!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");c.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:l.address,requesterAppId:a}});let{response:t}=await V.rpc({accessToken:e,address:h.address,hdWalletIndex:l.walletIndex??void 0,requesterAppId:a,request:{method:"eth_signTypedData_v4",params:[l.address,p]}}),r=t.data;return c.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:l.address,requesterAppId:a}}),r};if(ve.current||Y.embeddedWallets.noPromptOnSignature||Y.legacyWalletUiConfig){t&&Y.embeddedWallets.noPromptOnSignature&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config");try{let e=await y();d.emitPrivyEvent(pe,"signTypedData","onSuccess",e),n(e)}catch(e){d.emitPrivyEvent(pe,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),i(e??new m.PrivyProviderRpcError("Unable to sign message"))}}else ee({signMessage:{method:"eth_signTypedData_v4",data:p,confirmAndSign:y,onSuccess:e=>{d.emitPrivyEvent(pe,"signTypedData","onSuccess",e),n(e)},onFailure:e=>{d.emitPrivyEvent(pe,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),i(e)},uiOptions:t||{}},connectWallet:{address:h.address,onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(pe,"signMessage","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}}}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),sendTransaction:async(e,t,r,n)=>{let i=await Me(e,t,r,n);return of(await i.wait())},sendSolanaTransaction:async(e,t,r,n)=>await Oe({transaction:e,connection:t,transactionOptions:n,uiOptions:r,wallet:j??void 0}),exportWallet:e=>new Promise((async(r,n)=>{if(!v||!x)return void n(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let i=e?.address,a=x.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&"ethereum"===e.chainType)),o=i?a.find((e=>e.address===t.getAddress(i))):a.find((e=>!e.imported))||a[0];if(!o)return void n(Error("Must have a Privy wallet before exporting"));J(!0);let l={onCompleteNavigateTo:g.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:n,address:o.address,shouldForceMFA:!0};ee(Q),await Sg()&&V?V?(ee({keyExport:{appId:s.appId,appClientId:s.clientId,origin:c.apiUrl,wallet:o,onSuccess:r,onFailure:n},connectWallet:l}),we(g.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)):n(Error("Must have a Privy wallet before exporting")):n(Error("Must have valid access token to enroll in MFA"))})),promptMfa:Re,async init(e){switch(e){case"sms":return void await c.initMfaSmsVerification();case"passkey":return await c.initMfaPasskeyVerification();case"totp":return;default:throw Error(`Unsupported MFA method: ${e}`)}},async submit(e,t){switch(e){case"totp":case"sms":if("string"!=typeof t)throw new o.PrivyClientError("Invalid MFA code");ue.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{he.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new o.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=(e=>({id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}))(await r.startAuthentication(t));ue.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{he.current={resolve:e,reject:t}}));break;default:throw ue.current?.reject(new o.PrivyClientError("Unsupported MFA method")),new o.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){ue.current?.reject(new o.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to enroll in MFA");await V.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return Be.closePrivyModal(),void t();Y.mfa.noPromptOnMfaRequired&&console.warn("[Privy Warning] Triggering the 'showMfaEnrollmentModal' function when 'noPromptOnMfaRequired' is set to true is unexpected. If this is intentional, ensure that you are building custom UIs for MFA verification."),ee({mfaEnrollmentFlow:{mfaMethods:Y.mfa.methods,onSuccess:t,onFailure:r}}),we(g.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await Sg();if(!e||!V)throw Error("Must have valid access token to enroll in MFA");let t=await V.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to enroll in MFA");await V.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),C(await c.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to enroll in MFA");await V.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),C(await c.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e}){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to enroll in MFA");await V.submitEnrollMfa({method:"passkey",accessToken:t,credentialIds:e}),C(await c.getAuthenticatedUser())},async unenroll(e){let t=await Sg();if(!t||!V)throw Error("Must have valid access token to remove MFA");"passkey"===e?await V.submitEnrollMfa({method:"passkey",accessToken:t,credentialIds:[]}):await V.unenrollMfa({method:e,accessToken:t}),C(await c.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Sg(),t=x?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!V||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!x?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");let r=await V.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&C(await c.getAuthenticatedUser()||x||null),ee({farcasterSigner:r}),we(g.ModalScreen.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await Sg(),r=x?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!V||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!x?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");if(!x.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=x.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Sg(),r=x?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!V||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!x?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedEthereumWallet())throw Error("Unable to connect to wallet");if(!x.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),i=await V.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(x.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(i.signature))},createGuestAccount:async()=>{if(x&&!x.isGuest)throw Error("User cannot already be authenticated to create a guest account");return x?.isGuest?x:Be.loginWithGuestAccountFlow()},isHeadlessOAuthLoading:I,async loginWithCode(e){await Be.loginWithCode(e)},initLoginWithEmail:e=>Be.initLoginWithEmail(e),initLoginWithSms:e=>Be.initLoginWithSms(e),otpState:W,fundWallet:(e,t)=>Be.fundWallet(e,t),initLoginWithHeadlessOAuth:(e,t)=>Be.initLoginWithHeadlessOAuth(e,t),loginWithHeadlessOAuth:e=>Be.loginWithHeadlessOAuth(e),generateSiweMessage:({address:e,chainId:t})=>Be.generateSiweMessage({address:e,chainId:t}),async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}){Te("siwe"),await Be.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})},signMessageWithCrossAppWallet:(e,{address:t})=>Zu({user:x,client:c,address:t,requesterAppId:Y.id,request:{method:"personal_sign",params:[e,t]},reconnect:De}),signTypedDataWithCrossAppWallet(e,{address:t}){let r=d.generateTypedDataWithDomainType(e);return Zu({user:x,client:c,address:t,requesterAppId:Y.id,request:{method:"eth_signTypedData_v4",params:[t,r]},reconnect:De})},sendTransactionWithCrossAppWallet:(e,{address:t})=>Zu({user:x,client:c,address:t,requesterAppId:Y.id,request:{method:"eth_sendTransaction",params:[e]},reconnect:De}),isModalOpen:h,mfaMethods:Y.mfa.methods};vg=We.signMessage,wg=We.signTypedData,xg=async(...e)=>{let t=await Me(...e);return Y.embeddedWallets.waitForTransactionConfirmation&&await t.wait(),t};let Be={isNewUserThisSession:P,pendingTransaction:null,walletConnectionStatus:O,connectors:c.connectors?.walletConnectors??[],solanaWallets:S,rpcConfig:Y.rpcConfig,chains:Y.chains,appId:s.appId,showFiatPrices:"native-token"!==Y.embeddedWallets.priceDisplay.primary,clientAnalyticsId:c.clientAnalyticsId,customAuthStatus:de,noPromptOnSignature:ve,emailOtpState:U,setEmailOtpState:D,smsOtpState:W,setSmsOtpState:B,oAuthState:q,setOAuthState:z,siweState:H,setSiweState:G,nativeTokenSymbolForChainId:e=>Y.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(V)return V;let t=new Promise((e=>{ie((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return ie(null),n},getAuthFlow:()=>c.authFlow,getAuthMeta:()=>c.authFlow?.meta,client:c,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=y&&v&&x;r&&fe.current&&(t=Fe(x)),"login"===ge.current?e.shouldCallAuthOnSuccess&&r&&fe.current?(d.emitPrivyEvent(pe,"login","onComplete",x,P,!1,fe.current,t??null),s.onSuccess?.(x,P)):d.emitPrivyEvent(pe,"login","onError",o.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===ge.current&&t&&(e.isSuccess&&r&&fe.current?d.emitPrivyEvent(pe,"linkAccount","onSuccess",x,fe.current,t):fe.current&&d.emitPrivyEvent(pe,"linkAccount","onError",o.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:fe.current}));let n=k&&cf.includes(k),i=k===g.ModalScreen.ERROR_SCREEN&&Q.errorModalData&&cf.includes(Q.errorModalData.previousScreen);if((n||i)&&Q.funding){let e,t=uf[k]??null,r=d.getJsonRpcProvider(Q.funding.chain.id,Y.chains,Y.rpcConfig,{appId:s.appId});try{e=(await r.getBalance(Q.funding.address)).toBigInt()}catch{console.error("Unable to pull wallet balance")}d.emitPrivyEvent(pe,"fundWallet","onUserExited",{address:Q.funding.address,chain:Q.funding.chain,fundingMethod:t,balance:e})}ee({...Q,externalConnectWallet:{suggestedAddress:void 0}}),ge.current=null,fe.current=null,_(!1),p(!1),setTimeout((()=>{c.authFlow=void 0}),200),c.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:async({message:e})=>new Promise((async(t,r)=>{let n=async()=>{let t=await c.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");if(!j)throw Error("User must have an embedded Solana wallet to sign messages for Solana.");let r=Be.walletProxy??await Be.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");let{response:n}=await r.rpcSolana({accessToken:t,publicKey:j.address,request:{method:"signMessage",params:{message:e}}});return n.data.signature};if(Y.embeddedWallets.noPromptOnSignature||ve.current)try{let e=await n();t({signature:e})}catch(e){r(e)}else ee({signMessage:{method:"solana_signMessage",data:e,confirmAndSign:n,onSuccess:e=>{t({signature:e})},onFailure:e=>{r(e)},uiOptions:{}}}),xe(g.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN)})),openPrivyModal:we,connectWallet:Se,initLoginWithWallet:async(e,t,r)=>{Ra(e)?(fe.current="siwe",Ae(e,t,r)):(fe.current="siws",je(e,t))},loginWithWallet:async()=>{let e,t,r;if(!y)throw new o.PrivyNotReadyError;if(c.authFlow instanceof fa?e="siwe":c.authFlow instanceof ga&&(e="siws"),!e)throw new o.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await c.getAccessToken())try{({user:t}=await c.link()),fe.current=e}catch(t){throw d.emitPrivyEvent(pe,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await c.authenticate()),fe.current=e}catch(e){throw d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}C(t||x||null),_(r||!1),w(!0)},initDelegateAction:async({address:e})=>new Promise((async(t,r)=>{let n=await Sg();if(!v||!x||!n)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");let i=Be.walletProxy??await Be.initializeWalletProxy(15e3);if(!i)throw new o.PrivyClientError("Wallet proxy not initialized.");let a=(({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new o.PrivyClientError("Address to delegate is not associated with current user.");return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}})({address:e,user:x}),s=(({address:e,user:t})=>{let r,n=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!n)throw new o.PrivyClientError("Address to delegate is not associated with current user.");if(!(r="ethereum"===n.chainType?n.imported?u.getImportedPrivyEthereumWallet(t):u.getPrivyEthereumWallet(t):n))throw new o.PrivyClientError("Unable to determine root address for delegated address.");return{address:r.address,chainType:r.chainType,imported:r.imported}})({address:e,user:x});"ethereum"===a.chainType?await Be.recoverEmbeddedEthereumWallet():await Be.recoverEmbeddedSolanaWallet(),ee({delegatedActions:{address:e,onDelegate:async()=>{await i.createDelegatedAction({accessToken:n,rootWallet:s,delegatedWallets:[a]})},onSuccess:async()=>{t()},onError:async e=>{r(e)}}}),we(g.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN)})),initLoginWithFarcaster:async(e,t)=>{let r=new qi(e,t);c.startAuthFlow(r);try{fe.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===ge.current?d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ge.current&&d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!y)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof qi))throw new o.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await c.getAccessToken())try{({user:e}=await c.link()),fe.current="farcaster"}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await c.authenticate()),fe.current="farcaster"}catch(e){throw d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}C(e||null),_(t||!1),w(!0)},async loginWithGuestAccountFlow(){let e=new Vi(this.appId);c.startAuthFlow(e);try{ge.current="login",fe.current="guest";let{user:e,isNewUser:t}=await c.authenticate();if(t=t||!1,!e)throw new o.PrivyClientError("Unable to authenticate guest account");if(u.shouldProceedtoEmbeddedWalletCreationFlow(e,Y.embeddedWallets.createOnLogin))try{await Ie(e,15e3),e=await Be.refreshUser()}catch(t){C(e),console.warn("Unable to create embedded wallet for guest account")}else C(e);return _(t),w(!0),d.emitPrivyEvent(pe,"login","onComplete",e,t,!1,"guest",null),e}catch(e){throw d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let n=`privy:${e}`;fe.current=n;let{url:i,stateCode:a,codeVerifier:s}=await async function({api:e,appId:t}){let r=Ki(),n=Yi(),i=await Zi(r);try{let{url:a}=await e.post(Pi,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:i,state_code:n});return{url:a,stateCode:n,codeVerifier:r}}catch(e){throw o.formatApiError(e)}}({api:c.api,appId:e});if(!i)throw c.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new o.PrivyClientError("No authorization URL returned for cross-app auth.");try{let l=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,i=setTimeout((()=>{r(new o.PrivyClientError("Authorization request timed out after 2 minutes.")),a()}),12e4);function a(){t?.close(),window.removeEventListener("message",l)}let s=setInterval((()=>{t?.closed&&!n&&(a(),clearInterval(s),clearTimeout(i),r(new o.PrivyClientError("User rejected request")))}),300);function l(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(clearTimeout(i),e(t.data),a()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(i),r(new o.PrivyClientError(t.data.error)),a()),t.data.type===mg&&((n=new BroadcastChannel(yg)).onmessage=l))}window.addEventListener("message",l)}))}({url:i,popup:t,provider:n}),d=l.stateCode,u=l.authorizationCode;if(d!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:n,storedStateCode:a??"",returnedStateCode:d??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:i,client:a}){if(!n||!t)throw new o.PrivyClientError("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new o.PrivyClientError("User denied confirmation during cross-app auth flow");try{let o=new Ku({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`});a.startAuthFlow(o);let s="link"===i?await a.link():await a.authenticate(),l=s.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=o.formatApiError(e);if(t.privyErrorCode)throw new o.PrivyClientError(t.message||"Invalid code during cross-app auth flow.",void 0,t.privyErrorCode);if("User denied confirmation during cross-app auth flow"===t.message)throw new o.PrivyClientError("Invalid code during cross-app auth flow.",void 0,o.PrivyErrorCode.OAUTH_USER_DENIED);throw new o.PrivyClientError("Invalid code during cross-app auth flow.",void 0,o.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:s,stateCode:d,authorizationCode:u,action:r,client:c});h&&c.storeProviderAccessToken(e,h);let p=await Be.refreshUser();if(!p)throw new o.PrivyClientError("Unable to update user");return c.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),p}catch(e){throw c.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:n}}),e}},async initLoginWithOAuth(e,t,r){if(fe.current=e,!d.e())return void xe(g.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&jl(window.navigator.userAgent))return void xe(g.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:mg},"*"),d.e5.del(l.HEADLESS_OAUTH_KEY),d.e5.del(l.OAUTH_DISABLE_SIGNUP_KEY);let n=new Ji({provider:e,disableSignup:!!r});t&&n.addCaptchaToken(t),c.startAuthFlow(n);let i=await c.authFlow.getAuthorizationUrl();i&&i.url&&("twitter"===e&&a.isAndroid&&(i.url=i.url.replace("x.com","twitter.com")),window.location.assign(i.url))},async initLoginWithTelegram(e,t){if(!y)throw new o.PrivyNotReadyError;fe.current="telegram";let r=new Sa(e,t);c.startAuthFlow(r),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>Y.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:Y.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new o.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new o.PrivyClientError("Telegram was not initialized")):t(new o.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(c.authFlow instanceof Sa))throw new o.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");if(c.authFlow.meta.captchaToken||=e,"login"===ge.current)try{let e=await c.authenticate();t=e.user,r=e.isNewUser,fe.current="telegram"}catch(e){throw d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==ge.current)throw new o.PrivyClientError("Unknown auth intent");try{t=(await c.link()).user,fe.current="telegram"}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}C(t),_(r||!1),w(!0)},async recoveryOAuthFlow(e,t,r){let n,i;function a(t){if(!t)throw c.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new o.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,s,{url:l,codeVerifier:d,stateCode:u}=await cd({api:gg.api,provider:e});a(l);try{let n=await fg({url:l,popup:r,provider:e});if(t=n.stateCode,s=n.authorizationCode,t!==u)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:u??"",returnedStateCode:t??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw c.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new o.PrivyClientError("Recovery OAuth failed")}[n,i]=await Promise.all([Sg(),ud({api:gg.api,provider:e,codeVerifier:d,stateCode:t,authorizationCode:s})]);break}case"icloud":{let{url:t}=await cd({api:gg.api,provider:e});a(t);let{ckWebAuthToken:o}=await fg({url:t,popup:r,provider:e});i=o,n=await Sg()}}if(!V)throw new o.PrivyClientError("Cannot connect to wallet proxy");if(!n)throw new o.PrivyClientError("Unable to authorize user");switch(t){case"recover":let t=Q.recoverWallet?.privyWallet?.address;if(!t)throw new o.PrivyClientError("Recovery OAuth failed");c.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await V.recover({address:t,accessToken:n,recoveryAccessToken:i,recoveryMethod:e}),c.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break;case"create-wallet":c.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"});let r=u.getPrivySolanaWallet(x);await V.create({accessToken:n,recoveryAccessToken:i,recoveryMethod:e,solanaAddress:r?.address});let a=u.getPrivyEthereumWallet(await Be.refreshUser());if(!a)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");c.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:a.address}}),d.emitPrivyEvent(pe,"createWallet","onSuccess",a);break;case"set-recovery":let s=u.getPrivyEthereumWallet(x);if(!s)throw d.emitPrivyEvent(pe,"setWalletRecovery","onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");c.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:s.address,existingRecoveryMethod:s.recoveryMethod,targetRecoveryMethod:e}}),await V.setRecovery({address:s.address,accessToken:n,recoveryAccessToken:i,recoveryMethod:e});let l=u.getPrivyEthereumWallet(await Be.refreshUser());if(!l)throw d.emitPrivyEvent(pe,"createWallet","onError",o.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");c.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:s.address,existingRecoveryMethod:s.recoveryMethod,targetRecoveryMethod:e}}),d.emitPrivyEvent(pe,"setWalletRecovery","onSuccess",e,l);break;default:throw new o.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,n;if(!(c.authFlow instanceof Ji))throw new o.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let i=d.e5.get(l.STATE_CODE_KEY),a=c.authFlow.meta.stateCode;if(i!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:i??"",returnedStateCode:a??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await c.getAccessToken())try{let r=await c.link();t=r.user,n=r.oAuthTokens,fe.current=e}catch(t){throw d.emitPrivyEvent(pe,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let i=await c.authenticate();t=i.user,r=i.isNewUser,n=i.oAuthTokens,fe.current=e}catch(t){throw"login"===ge.current?d.emitPrivyEvent(pe,"login","onError",t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ge.current&&d.emitPrivyEvent(pe,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return C(t),_(r||!1),w(!0),n&&t&&d.emitPrivyEvent(pe,"oAuthAuthorization","onOAuthTokenGrant",n,{user:t}),n},passkeyAuthState:F,setPasskeyAuthState:L,async initLoginWithPasskey(e){let t=new ya(e,L);c.startAuthFlow(t),ge.current="login";try{fe.current="passkey",L({status:"generating-challenge"}),await t.initAuthenticationFlow(),L({status:"awaiting-passkey"})}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(){let e,t;if(!y)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof ya))throw new o.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==fe.current){let e=new o.PrivyClientError("Must init login with Passkey flow first.");throw L({status:"error",error:e}),e}let r=await Sg();try{fe.current="passkey",L({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await c.authenticate())}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}C(e),_(t||!1),w(!0),L({status:"done"});let n=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:n}},async initLinkWithPasskey(e){let t=new ya(e);c.startAuthFlow(t),ge.current="link",fe.current="passkey";try{await t.initLinkFlow()}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),e}},async linkWithPasskey(){let e;if(!y)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof ya))throw new o.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==fe.current)throw new o.PrivyClientError("Must init login with Passkey flow first.");try{fe.current="passkey",({user:e}=await c.link())}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return C(e||x||null),e},async initLoginWithHeadlessOAuth(e,t){if(!d.e())throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");if("google"===e&&jl(window.navigator.userAgent))throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");let r=new Ji({provider:e,headless:!0,disableSignup:!1});t&&r.addCaptchaToken(t),z({status:"loading"});let n=await c.startAuthFlow(r).getAuthorizationUrl();n?.url&&window.location.assign(n.url)},async loginWithHeadlessOAuth(e){let t,r,n;M(!0),z({status:"loading"}),c.startAuthFlow(new Ji(e));let i=d.e5.get(l.STATE_CODE_KEY),a=e.stateCode;if(i!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:i??"",returnedStateCode:a??""}}),M(!1),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await c.getAccessToken())try{({user:t,oAuthTokens:n}=await c.link()),fe.current=e.provider;let r=Fe(t);t&&r&&d.emitPrivyEvent(pe,"linkAccount","onSuccess",t,fe.current,r)}catch(t){throw M(!1),d.emitPrivyEvent(pe,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:n}=await c.authenticate()),fe.current=e.provider;let i=Fe(t);t&&i&&void 0!==r&&"login"===ge.current&&d.emitPrivyEvent(pe,"login","onComplete",t,r,!1,fe.current,i)}catch(e){throw M(!1),z({status:"error",error:e}),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return C(t),_(r||!1),w(!0),M(!1),z({status:"done"}),n&&t&&d.emitPrivyEvent(pe,"oAuthAuthorization","onOAuthTokenGrant",n,{user:t}),t??void 0},initLoginWithEmail:async(e,t,r)=>{let n=new Mi(e,t,r);c.startAuthFlow(n);try{fe.current="email",D({status:"sending-code"}),await n.sendCodeEmail(),D({status:"awaiting-code-input"})}catch(e){throw D({status:"error",error:e}),"login"===ge.current?d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ge.current&&d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let n=new Oi(e,t,r);c.startAuthFlow(n),await n.sendCodeEmail()},initUpdatePhone:async(e,t,r)=>{let n=new wa(e,t,r);c.startAuthFlow(n),await n.sendSmsCode()},initLoginWithSms:async(e,t,r)=>{B({status:"sending-code"});let n=new va(e,t,r);c.startAuthFlow(n);try{fe.current="sms",await n.sendSmsCode(),B({status:"awaiting-code-input"})}catch(e){throw B({status:"error",error:e}),"login"===ge.current?d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ge.current&&d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(c.authFlow?.sendCodeEmail())},resendSmsCode:async()=>{await(c.authFlow?.sendSmsCode())},loginWithCode:async e=>{let t,r;function n(e){c.authFlow instanceof Mi?D(e):c.authFlow instanceof va&&B(e)}if(n({status:"submitting-code"}),!y){let e=new o.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(c.authFlow instanceof Mi)c.authFlow.meta.emailCode=e.trim();else{if(!(c.authFlow instanceof va)){let e=new o.PrivyClientError("Must initialize a passwordless code flow first");throw n({status:"error",error:e}),e}c.authFlow.meta.smsCode=e.trim()}let i=await Sg();if("link"===ge.current)try{({user:t}=await c.link())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:fe.current}),e}else try{({user:t,isNewUser:r}=await c.authenticate())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(pe,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let a=t||x;C(a||null),_(r||!1),w(!0),n({status:"done"});let s=null;return c.authFlow instanceof Mi?s=a?.linkedAccounts.find((({type:e})=>"email"===e))||null:c.authFlow instanceof va&&(s=a?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:a,isNewUser:r||!1,wasAlreadyAuthenticated:!!i,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{ge.current="link",fe.current="siwe",G({status:"generating-message"});let n=await c.generateSiweNonce({address:e,captchaToken:r});return G({status:"awaiting-signature"}),ma({address:e,chainId:t.replace("eip155:",""),nonce:n})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await c.generateSiweNonce({address:e});return ma({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let n;try{n=await c.linkSmartWallet({message:e,signature:t,smartWalletType:r}),n=await Be.refreshUser()??n}catch(e){throw e}C(n||x||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})=>{let a,s=null;try{G({status:"submitting-signature"}),a=await c.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}),a=await Be.refreshUser()??a,G({status:"done"}),(s=Fe(a)||null)&&d.emitPrivyEvent(pe,"linkAccount","onSuccess",a,"siwe",s)}catch(e){throw d.emitPrivyEvent(pe,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),ge.current=null,fe.current=null,G({status:"error",error:e}),e}let l=a||x;return C(l||null),ge.current=null,fe.current=null,{user:l,linkedAccount:s}},refreshUser:async()=>{let e=await c.getAuthenticatedUser();return w(!!e),C(e),e},walletProxy:V,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>c.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await c.acceptTerms();return C(e),e},getUsdTokenPrice:e=>c.getUsdTokenPrice(e),getUsdPriceForSol:()=>c.getUsdPriceForSol(),recoverEmbeddedEthereumWallet:async e=>new Promise((async(t,r)=>{let n=u.getPrivyEthereumWallet(e?.user??x)||u.getImportedPrivyEthereumWallet(e?.user??x),i=await Sg();if(i&&V&&n){J(!0);try{await V.connect({accessToken:i,address:n.address}),t(!0)}catch(e){td(e)&&"privy"===n.recoveryMethod?(c.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:n.address}}),(await V.recover({address:n.address,accessToken:i,recoveryMethod:n.recoveryMethod})).address||r(Error("Unable to recover wallet")),c.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:n.address}}),t(!0)):td(e)&&"privy"!==n.recoveryMethod?(ee({recoverWallet:{privyWallet:n,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover"}}),we(dd(n.recoveryMethod))):r(e)}}else r(Error("Must have valid access token and Privy wallet to recover wallet"))})),embeddedSolanaWallet:j,createEmbeddedSolanaWallet:async()=>{J(!0);let e=await Sg(),t=await Be.refreshUser(),r=u.getPrivySolanaWallet(t),n=u.getPrivyEthereumWallet(t);if(!t||!e)throw new o.PrivyClientError("User must be logged in to create a Solana wallet");if(r)throw new o.PrivyClientError("User already has an embedded Solana wallet.");if(n){if("privy"!==n.recoveryMethod)throw new o.PrivyClientError("Cannot create an embedded Solana wallet for a user with an existing Ethereum wallet with user-controlled recovery.");await Be.recoverEmbeddedEthereumWallet({user:t})}let i=await Be.initializeWalletProxy(15e3);if(!i)throw new o.PrivyClientError("Unable to initialize wallet proxy");c.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_started"});try{await i.createSolana({accessToken:e,ethereumAddress:n?.address});let t=await Be.refreshUser(),r=u.getPrivySolanaWallet(t);if(!r)throw new o.PrivyClientError("Could not get Solana wallet for user");return c.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_completed",payload:{walletAddress:r.address}}),r}catch(e){throw c.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_failed"}),new o.PrivyClientError("Failed to create Solana embedded wallet with error ",e)}},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!v||!x)return void r(Error("User must be authenticated before exporting their Privy wallet"));let n=e?.address,i=x.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&"solana"===e.chainType)),a=n?i.find((e=>e.address.toLowerCase()===n.toLowerCase())):i.find((e=>!e.imported))||i[0];a?(J(!0),await Sg()&&V?V?(await Be.recoverEmbeddedSolanaWallet(),ee({keyExport:{appId:s.appId,appClientId:s.clientId,origin:c.apiUrl,wallet:a,onSuccess:t,onFailure:r}}),we(g.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))):r(Error("Must have a Privy wallet before exporting"))})),recoverEmbeddedSolanaWallet:async()=>new Promise((async(e,t)=>{let r=u.getPrivySolanaWallet(x),n=await Sg();if(n&&V&&r){J(!0);try{await V.connectSolana({accessToken:n,publicKey:r.address}),e(!0)}catch(i){td(i)&&"privy"===r.recoveryMethod?(c.createAnalyticsEvent({eventName:"embedded_solana_wallet_pinless_recovery_started",payload:{walletAddress:r.address}}),(await V.recoverSolana({publicKey:r.address,accessToken:n})).publicKey||t(Error("Unable to recover wallet")),c.createAnalyticsEvent({eventName:"embedded_solana_wallet_recovery_completed",payload:{walletAddress:r.address}}),e(!0)):t(i)}}else t(Error("Must have valid access token and Privy wallet to recover wallet"))})),getMoonpaySignedUrl:async(e,t)=>{let{signedUrl:r,externalTransactionId:n}=await async function(e,t,r,n,i=!1){let a=r.currencyCode?{}:{defaultCurrencyCode:"ETH_ETHEREUM"},o=r.uiConfig||{accentColor:n.accent,theme:n.colorScheme};return e.signMoonpayOnRampUrl({address:t,useSandbox:i,config:{...r,...a,...o}})}(c,e,t??{},Y.appearance.palette,Y.fundingMethodConfig?.moonpay.useSandbox??!1);return{signedUrl:r,externalTransactionId:n}},initCoinbaseOnRamp:c.initCoinbaseOnRamp.bind(c),getCoinbaseOnRampStatus:c.getCoinbaseOnRampStatus.bind(c),setReadyToTrue:e=>{f(!0),te?.(e)},updateWallets:()=>Ne(),fundWallet:async(e,t)=>{if(!Y.fundingConfig||0===Y.fundingConfig.methods.length)throw Error("Wallet funding is not enabled");let r=pf({fundingMethods:Y.fundingConfig.methods});ee({funding:df({address:e,appConfig:Y,fundWalletConfig:t,methodScreen:r})}),we(r)},requestFarcasterSignerStatus:async e=>{let t=await Sg(),r=x?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!V||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!x?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await c.requestFarcasterSignerStatus(e);return"approved"===n.status&&C(await c.getAuthenticatedUser()||x||null),n},connectCoinbaseSmartWallet:async()=>{Y.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=c.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||c.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Se(e);await be("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,farcasterEmbeddedAddress:a,oAuthUserInfo:o})=>{try{let s=await c.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,farcasterEmbeddedAddress:a,oAuthUserInfo:o});return C(s),s}catch(e){throw e}}};Cg=Be.recoverEmbeddedEthereumWallet,Eg=Be.recoverEmbeddedSolanaWallet,bg=Be.solanaSignMessage;let He=i.useMemo((()=>({wallets:E,ready:ae&&ye})),[E,ae,ye]),Ge=c.authFlow instanceof Sa,qe=!Y.headless&&Y.captchaEnabled&&!v&&(y||Ge);return e.jsx(o.PrivyContext.Provider,{value:We,children:e.jsx(d.PrivyEventsContext.Provider,{value:pe,children:e.jsx(l.UseWalletsContext.Provider,{value:He,children:e.jsx(Ea,{...Y,children:e.jsxs(o.InternalPrivyContext.Provider,{value:Be,children:[e.jsx(d.RecentlyUsedAccountProvider,{children:e.jsxs(g.ModalProvider,{data:Q,setModalData:ee,setInitialScreen:N,initialScreen:k,authenticated:v,open:h,children:[s.children,qe&&e.jsx(vo,{delayedExecution:!1}),e.jsx(Wf,{theme:{...Y.appearance.palette||{}}}),!Y.render.standalone&&e.jsx(Qf,{open:h})]})}),X&&Z?e.jsx(hg,{appId:s.appId,appClientId:s.clientId,clientAnalyticsId:c.clientAnalyticsId,origin:c.apiUrl,mfaMethods:x?.mfaMethods,mfaPromise:ue,mfaSubmitPromise:he,onLoad:K,onLoadFailed:()=>null}):null,Y.loginConfig.telegramAuthConfiguration&&e.jsx(ns,{$if:!0,children:e.jsx(rg,{scriptHost:s.apiUrl||l.DEFAULT_PRIVY_API_URL,botUsername:Y.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};let Ng=async(e,t,r,n,i)=>{if(!e)throw n("linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:i}),new o.PrivyClientError("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(i))))throw new o.PrivyClientError(`OAuth account of type ${i} not linked to the account.`);await r(i)};const Ig=Mg;function Mg(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=o.usePrivy();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}}exports.usePrivy=o.usePrivy,exports.SUPPORTED_CHAINS=l.DEFAULT_SUPPORTED_CHAINS,exports.VERSION=l.VERSION,exports.addPrivyRpcToChain=l.addPrivyRpcToChain,exports.addRpcUrlOverrideToChain=l.addRpcUrlOverrideToChain,exports.useWallets=l.useWallets,exports.useConnectWallet=d.useConnectWallet,exports.useFundWallet=d.useFundWallet,exports.useLogin=d.useLogin,exports.useLogout=d.useLogout,exports.WalletConnector=m.WalletConnector,exports.useSolanaWallets=m.useSolanaWallets,exports.getEmbeddedConnectedWallet=g.getEmbeddedConnectedWallet,exports.AsExternalProvider=Na,exports.Captcha=vo,exports.ConnectorManager=io,exports.EthereumWalletConnector=Fa,exports.LoginModal=Qf,exports.PrivyClient=fo,exports.PrivyProvider=({config:t,...r})=>{var n;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new o.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(n=r.appId)||25!==n.length)throw new o.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");gg||(gg=new fo({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let i=Object.assign({},t);return void 0!==r.createPrivyWalletOnLogin&&void 0===i.embeddedWallets?.createOnLogin&&(i.embeddedWallets||(i.embeddedWallets={}),i.embeddedWallets.createOnLogin=r.createPrivyWalletOnLogin?"users-without-wallets":"off"),void 0!==r.createPrivyWalletOnLogin&&t?.embeddedWallets?.createOnLogin&&console.warn("Both `createPrivyWalletOnLogin` and `config.embeddedWallets.createOnLogin` are set. `createPrivyWalletOnLogin` is deprecated and should be removed."),e.jsx(l.PrivyAppConfigProvider,{client:gg,clientConfig:i,legacyCreateEmbeddedWalletFlag:r.createPrivyWalletOnLogin,children:e.jsx(kg,{...r,client:gg})})},exports.PrivyProxyProvider=Pa,exports.errorIndicatesMaxMfaRetries=id,exports.errorIndicatesMfaTimeout=rd,exports.errorIndicatesMfaVerificationFailed=nd,exports.getAccessToken=Sg,exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=o.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useCreateWallet=function(e){let{createWallet:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("createWallet",e),{createWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:i}=o.usePrivy();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:n,sendTransaction:i}},exports.useCustomAuth=e=>{let{customAuthStatus:t}=o.usePrivyInternal();return d.usePrivyEventSubscription("customAuth",e),{status:t}},exports.useExperimentalFarcasterSigner=Ig,exports.useFarcasterSigner=Mg,exports.useGuestAccounts=function(){let{createGuestAccount:e}=i.useContext(o.PrivyContext);return{createGuestAccount:e}},exports.useLinkAccount=function(e){let{linkEmail:t,linkPhone:r,linkWallet:n,linkGoogle:a,linkApple:s,linkTwitter:l,linkDiscord:c,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkSpotify:y,linkInstagram:m,linkTelegram:f,linkFarcaster:g}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("linkAccount",e),{linkEmail:t,linkPhone:r,linkWallet:n,linkGoogle:a,linkApple:s,linkTwitter:l,linkDiscord:c,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkSpotify:y,linkInstagram:m,linkFarcaster:g,linkTelegram:f}},exports.useLinkWithSiwe=e=>{let t=ba(),{generateSiweMessage:r}=o.usePrivy(),{siweState:n,setSiweState:a,linkWithSiwe:s}=o.usePrivyInternal();return{generateSiweMessage:i.useCallback((async({address:t,chainId:n})=>{try{if(!t||!n)throw Error("wallet address and chainId required to generate nonce");return await r({address:t,chainId:n}).then((e=>e))}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[r]),linkWithSiwe:i.useCallback((async({signature:r,message:n,chainId:i,walletClientType:l,connectorType:d})=>{try{if(t.enabled&&"success"!==t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:a,linkedAccount:c}=await s({message:n,signature:r,chainId:i,walletClientType:l,connectorType:d});c&&e?.onSuccess?.(a,"siwe",c)}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[s,t.status]),state:n}},exports.useLoginWithEmail=e=>{let t=ba(),{emailOtpState:r,setEmailOtpState:n,initLoginWithEmail:a,loginWithCode:s}=o.usePrivyInternal();return{sendCode:i.useCallback((async({email:r})=>{try{let e;if(!r)throw Error("Email required to send OTP code");if(t.enabled&&"error"===t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a(r,e)}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:i.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:l}=await s(r);e?.onComplete?.(n,i,a,"email",l)}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[s,t.status]),state:r}},exports.useLoginWithOAuth=e=>{d.usePrivyEventSubscription("login",e);let t=ba(),r=l.useIsServerConfigLoaded(),{initLoginWithHeadlessOAuth:n,loginWithHeadlessOAuth:a,isHeadlessOAuthLoading:s,ready:c,user:u}=o.usePrivy(),{oAuthState:h,setOAuthState:p}=o.usePrivyInternal(),y=i.useCallback((async e=>{try{if(t.enabled&&"success"!==t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return await n(e.provider,t.token)}catch(e){throw p({status:"error",error:e}),e}}),[n,t]),m=i.useCallback((async()=>{let e=ha();try{if(u)return console.warn("Cannot login with OAuth when already logged in"),u;if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(e.popupFlow)return}catch(e){throw p({status:"error",error:e}),e}try{return await a(e)}catch(e){throw p({status:"error",error:e}),e}finally{pa()}}),[a]);return i.useEffect((()=>{let e=ha();c&&r&&e.inProgress&&e.headless&&!e.popupFlow&&m()}),[c,r]),{initOAuth:y,loginWithOAuth:m,loading:s,state:h}},exports.useLoginWithPasskey=e=>{let t=ba(),{initLoginWithPasskey:r,loginWithPasskey:n,passkeyAuthState:a,setPasskeyAuthState:s}=o.usePrivyInternal();return{loginWithPasskey:i.useCallback((async()=>{try{let i;if(t.enabled&&"error"===t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult()),await r(i);let{user:a,isNewUser:s,wasAlreadyAuthenticated:l,loginAccount:d}=await n();e?.onComplete?.(a,s,l,"passkey",d)}catch(t){throw s({status:"error",error:t}),e?.onError?.(t),t}}),[n,t.status]),state:a}},exports.useLoginWithSms=e=>{let t=ba(),{smsOtpState:r,setSmsOtpState:n,initLoginWithSms:a,loginWithCode:s}=o.usePrivyInternal();return{sendCode:i.useCallback((async({phoneNumber:r})=>{try{let e;if(!r)throw Error("SMS required to send OTP code");if(t.enabled&&"error"===t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a(r,e)}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:i.useCallback((async({code:r})=>{try{if(t.enabled&&"success"!==t.status)throw new Ca(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:l}=await s(r);e?.onComplete?.(n,i,a,"sms",l)}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[s,t.status]),state:r}},exports.useMfa=Rp,exports.useMfaEnrollment=Fp,exports.useModalStatus=()=>{let{isModalOpen:e}=i.useContext(o.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(e){let{authenticated:t,user:r}=o.usePrivy(),{initLoginWithOAuth:n}=o.usePrivyInternal(),i=d.useEmitPrivyEvent();return d.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>Ng(t,r,n,i,e.provider)}},exports.useRegisterMfaListener=wo,exports.useSendSolanaTransaction=function(e){let{sendSolanaTransaction:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("sendSolanaTransaction",e),{sendSolanaTransaction:t}},exports.useSendTransaction=function(e){let{sendTransaction:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:t}},exports.useSetWalletPassword=function(e){let{setWalletPassword:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("setWalletPassword",e),{setWalletPassword:t}},exports.useSetWalletRecovery=function(e){let{setWalletRecovery:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("setWalletRecovery",e),{setWalletRecovery:t}},exports.useSignMessage=function(e){let{signMessage:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("signMessage",e),{signMessage:t}},exports.useSignTypedData=function(e){let{signTypedData:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("signTypedData",e),{signTypedData:t}},exports.useToken=function(e){let{getAccessToken:t}=i.useContext(o.PrivyContext);return d.usePrivyEventSubscription("accessToken",e),{getAccessToken:t}};
@@ -1 +1 @@
1
- "use strict";var e,t=require("ofetch"),i=require("react");class n extends Error{toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}constructor(e,t,i){super(e),t instanceof Error&&(this.cause=t),this.privyErrorCode=i}}class r extends n{constructor(e,t,i,n,r,s){super(i,n,r),this.type=e,this.status=t,this.data=s}}class s extends n{constructor(e,t,i){super(e,t,i),this.type="client_error"}}const a=e=>e instanceof n?e:e instanceof Error?new s(e.message,e):new s(`Internal error: ${e}`);exports.PrivyErrorCode=void 0,(e=exports.PrivyErrorCode||(exports.PrivyErrorCode={})).OAUTH_ACCOUNT_SUSPENDED="oauth_account_suspended",e.MISSING_OR_INVALID_PRIVY_APP_ID="missing_or_invalid_privy_app_id",e.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID="missing_or_invalid_privy_account_id",e.MISSING_OR_INVALID_TOKEN="missing_or_invalid_token",e.INVALID_DATA="invalid_data",e.INVALID_CAPTCHA="invalid_captcha",e.LINKED_TO_ANOTHER_USER="linked_to_another_user",e.CANNOT_LINK_MORE_OF_TYPE="cannot_link_more_of_type",e.FAILED_TO_LINK_ACCOUNT="failed_to_link_account",e.ALLOWLIST_REJECTED="allowlist_rejected",e.OAUTH_USER_DENIED="oauth_user_denied",e.OAUTH_UNEXPECTED="oauth_unexpected",e.UNKNOWN_AUTH_ERROR="unknown_auth_error",e.USER_EXITED_AUTH_FLOW="exited_auth_flow",e.USER_EXITED_LINK_FLOW="exited_link_flow",e.USER_EXITED_SET_PASSWORD_FLOW="user_exited_set_password_flow",e.MUST_BE_AUTHENTICATED="must_be_authenticated",e.UNKNOWN_CONNECT_WALLET_ERROR="unknown_connect_wallet_error",e.GENERIC_CONNECT_WALLET_ERROR="generic_connect_wallet_error",e.CLIENT_REQUEST_TIMEOUT="client_request_timeout",e.INVALID_CREDENTIALS="invalid_credentials",e.MISSING_MFA_CREDENTIALS="missing_or_invalid_mfa",e.UNKNOWN_MFA_ERROR="unknown_mfa_error",e.EMBEDDED_WALLET_ALREADY_EXISTS="embedded_wallet_already_exists",e.EMBEDDED_WALLET_NOT_FOUND="embedded_wallet_not_found",e.UNKNOWN_EMBEDDED_WALLET_ERROR="unknown_embedded_wallet_error",e.EMBEDDED_WALLET_PASSWORD_UNCONFIRMED="embedded_wallet_password_unconfirmed",e.EMBEDDED_WALLET_PASSWORD_ALREADY_EXISTS="embedded_wallet_password_already_exists",e.EMBEDDED_WALLET_RECOVERY_ALREADY_EXISTS="embedded_wallet_recovery_already_exists",e.TRANSACTION_FAILURE="transaction_failure",e.UNSUPPORTED_CHAIN_ID="unsupported_chain_id",e.NOT_SUPPORTED="not_supported",e.CAPTCHA_TIMEOUT="captcha_timeout",e.INVALID_MESSAGE="invalid_message",e.UNABLE_TO_SIGN="unable_to_sign",e.CAPTCHA_FAILURE="captcha_failure",e.CAPTCHA_DISABLED="captcha_disabled",e.SESSION_STORAGE_UNAVAILABLE="session_storage_unavailable",e.TOO_MANY_REQUESTS="too_many_requests",e.USER_LIMIT_REACHED="max_accounts_reached",e.DISALLOWED_LOGIN_METHOD="disallowed_login_method",e.PASSKEY_NOT_ALLOWED="passkey_not_allowed",e.USER_DOES_NOT_EXIST="user_does_not_exist",e.INSUFFICIENT_BALANCE="insufficient_balance",e.ACCOUNT_TRANSFER_REQUIRED="account_transfer_required";const o=()=>{throw Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")},l=i.createContext({isNewUserThisSession:!1,walletConnectionStatus:null,connectors:[],solanaWallets:[],rpcConfig:{rpcUrls:{}},showFiatPrices:!0,chains:[],clientAnalyticsId:null,pendingTransaction:null,client:null,appId:"notAdded",customAuthStatus:{status:"not-enabled"},noPromptOnSignature:{current:!1},nativeTokenSymbolForChainId:o,initializeWalletProxy:o,getAuthMeta:o,getAuthFlow:o,closePrivyModal:o,openPrivyModal:o,connectWallet:o,initLoginWithWallet:o,loginWithWallet:o,initLoginWithFarcaster:o,loginWithFarcaster:o,loginWithCode:o,initLoginWithEmail:o,initLoginWithSms:o,initUpdateEmail:o,initUpdatePhone:o,resendEmailCode:o,resendSmsCode:o,initLoginWithHeadlessOAuth:o,loginWithHeadlessOAuth:o,crossAppAuthFlow:o,initLoginWithOAuth:o,recoveryOAuthFlow:o,loginWithOAuth:o,passkeyAuthState:{status:"initial"},setPasskeyAuthState:o,initLoginWithPasskey:o,loginWithPasskey:o,initLinkWithPasskey:o,linkWithPasskey:o,refreshUser:o,loginWithGuestAccountFlow:o,walletProxy:null,createAnalyticsEvent:o,acceptTerms:o,getUsdTokenPrice:o,getUsdPriceForSol:o,recoverEmbeddedEthereumWallet:o,getMoonpaySignedUrl:o,initCoinbaseOnRamp:o,getCoinbaseOnRampStatus:o,updateWallets:o,fundWallet:o,setReadyToTrue:o,requestFarcasterSignerStatus:o,initLoginWithTelegram:o,loginWithTelegram:o,generateSiweMessage:o,linkWithSiwe:o,linkSmartWallet:o,initDelegateAction:o,embeddedSolanaWallet:null,createEmbeddedSolanaWallet:o,recoverEmbeddedSolanaWallet:o,exportSolanaWallet:o,solanaSignMessage:o,connectCoinbaseSmartWallet:o,initiateAccountTransfer:o,emailOtpState:{status:"initial"},setEmailOtpState:o,smsOtpState:{status:"initial"},setSmsOtpState:o,siweState:{status:"initial"},setSiweState:o,oAuthState:{status:"initial"},setOAuthState:o}),_=i.createContext({ready:!1,authenticated:!1,user:null,walletConnectors:null,connectWallet:o,login:o,connectOrCreateWallet:o,linkEmail:o,linkPhone:o,linkFarcaster:o,linkWallet:o,startCrossAppAuthFlow:o,linkGoogle:o,linkTwitter:o,linkDiscord:o,linkGithub:o,linkSpotify:o,linkInstagram:o,linkTelegram:o,linkTiktok:o,linkLinkedIn:o,linkApple:o,linkPasskey:o,updateEmail:o,updatePhone:o,logout:o,getAccessToken:o,getEthereumProvider:o,getEthersProvider:o,getWeb3jsProvider:o,unlinkEmail:o,unlinkPhone:o,unlinkWallet:o,unlinkGoogle:o,unlinkTwitter:o,unlinkDiscord:o,unlinkGithub:o,unlinkSpotify:o,unlinkInstagram:o,unlinkTiktok:o,unlinkLinkedIn:o,unlinkApple:o,unlinkCrossAppAccount:o,unlinkFarcaster:o,unlinkTelegram:o,unlinkPasskey:o,setActiveWallet:o,forkSession:o,createWallet:o,importWallet:o,signMessage:o,signTypedData:o,enrollInMfa:o,initEnrollmentWithSms:o,initEnrollmentWithTotp:o,initEnrollmentWithPasskey:o,promptMfa:o,init:o,submitEnrollmentWithSms:o,submitEnrollmentWithTotp:o,submitEnrollmentWithPasskey:o,unenroll:o,submit:o,cancel:o,sendTransaction:o,sendSolanaTransaction:o,exportWallet:o,setWalletPassword:o,setWalletRecovery:o,requestFarcasterSignerFromWarpcast:o,getFarcasterSignerPublicKey:o,signFarcasterMessage:o,createGuestAccount:o,initLoginWithEmail:o,initLoginWithSms:o,otpState:{status:"initial"},loginWithCode:o,fundWallet:o,initLoginWithHeadlessOAuth:o,loginWithHeadlessOAuth:o,generateSiweMessage:o,linkWithSiwe:o,signMessageWithCrossAppWallet:o,signTypedDataWithCrossAppWallet:o,sendTransactionWithCrossAppWallet:o,isHeadlessOAuthLoading:!1,isModalOpen:!1,mfaMethods:[]});exports.InternalPrivyContext=l,exports.PrivyApiError=r,exports.PrivyClientError=s,exports.PrivyConnectorError=class extends n{constructor(e,t,i){super(e,t,i),this.type="connector_error"}},exports.PrivyContext=_,exports.PrivyEmbeddedWalletError=class extends s{constructor(e="Embedded wallet error",t){super(e,t,"unknown_embedded_wallet_error")}},exports.PrivyError=n,exports.PrivyNotReadyError=class extends s{constructor(){super("Method called before `ready`. Ensure you wait until `ready` is true before calling.")}},exports.PrivyTimeoutError=class extends s{constructor(){super("Request timed out",void 0,"client_request_timeout")}},exports.PrivyUnauthenticatedError=class extends s{constructor(e="User must be authenticated"){super(e,void 0,"must_be_authenticated")}},exports.PrivyUserLimitReachedError=class extends s{constructor(e){super("This application is in development mode and must be upgraded to production to log in new users.",e,"max_accounts_reached")}},exports.formatApiError=e=>{if(e instanceof n)return e;if(!(e instanceof t.FetchError))return a(e);if(!e.response)return new r("api_error",null,e.message,e);let{type:i,message:s,error:o,code:l}=e.data;return new r(i||"ApiError",e.response.status,s||o,e,l,e.data)},exports.formatPrivyError=a,exports.notImplemented=o,exports.usePrivy=()=>i.useContext(_),exports.usePrivyInternal=()=>i.useContext(l);
1
+ "use strict";var e,t=require("ofetch"),i=require("react");class n extends Error{toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}constructor(e,t,i){super(e),t instanceof Error&&(this.cause=t),this.privyErrorCode=i}}class r extends n{constructor(e,t,i,n,r,s){super(i,n,r),this.type=e,this.status=t,this.data=s}}class s extends n{constructor(e,t,i){super(e,t,i),this.type="client_error"}}const a=e=>e instanceof n?e:e instanceof Error?new s(e.message,e):new s(`Internal error: ${e}`);exports.PrivyErrorCode=void 0,(e=exports.PrivyErrorCode||(exports.PrivyErrorCode={})).OAUTH_ACCOUNT_SUSPENDED="oauth_account_suspended",e.MISSING_OR_INVALID_PRIVY_APP_ID="missing_or_invalid_privy_app_id",e.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID="missing_or_invalid_privy_account_id",e.MISSING_OR_INVALID_TOKEN="missing_or_invalid_token",e.INVALID_DATA="invalid_data",e.INVALID_CAPTCHA="invalid_captcha",e.LINKED_TO_ANOTHER_USER="linked_to_another_user",e.CANNOT_LINK_MORE_OF_TYPE="cannot_link_more_of_type",e.FAILED_TO_LINK_ACCOUNT="failed_to_link_account",e.ALLOWLIST_REJECTED="allowlist_rejected",e.OAUTH_USER_DENIED="oauth_user_denied",e.OAUTH_UNEXPECTED="oauth_unexpected",e.UNKNOWN_AUTH_ERROR="unknown_auth_error",e.USER_EXITED_AUTH_FLOW="exited_auth_flow",e.USER_EXITED_LINK_FLOW="exited_link_flow",e.USER_EXITED_SET_PASSWORD_FLOW="user_exited_set_password_flow",e.MUST_BE_AUTHENTICATED="must_be_authenticated",e.UNKNOWN_CONNECT_WALLET_ERROR="unknown_connect_wallet_error",e.GENERIC_CONNECT_WALLET_ERROR="generic_connect_wallet_error",e.CLIENT_REQUEST_TIMEOUT="client_request_timeout",e.INVALID_CREDENTIALS="invalid_credentials",e.MISSING_MFA_CREDENTIALS="missing_or_invalid_mfa",e.UNKNOWN_MFA_ERROR="unknown_mfa_error",e.EMBEDDED_WALLET_ALREADY_EXISTS="embedded_wallet_already_exists",e.EMBEDDED_WALLET_NOT_FOUND="embedded_wallet_not_found",e.UNKNOWN_EMBEDDED_WALLET_ERROR="unknown_embedded_wallet_error",e.EMBEDDED_WALLET_PASSWORD_UNCONFIRMED="embedded_wallet_password_unconfirmed",e.EMBEDDED_WALLET_PASSWORD_ALREADY_EXISTS="embedded_wallet_password_already_exists",e.EMBEDDED_WALLET_RECOVERY_ALREADY_EXISTS="embedded_wallet_recovery_already_exists",e.TRANSACTION_FAILURE="transaction_failure",e.UNSUPPORTED_CHAIN_ID="unsupported_chain_id",e.NOT_SUPPORTED="not_supported",e.CAPTCHA_TIMEOUT="captcha_timeout",e.INVALID_MESSAGE="invalid_message",e.UNABLE_TO_SIGN="unable_to_sign",e.CAPTCHA_FAILURE="captcha_failure",e.CAPTCHA_DISABLED="captcha_disabled",e.SESSION_STORAGE_UNAVAILABLE="session_storage_unavailable",e.TOO_MANY_REQUESTS="too_many_requests",e.USER_LIMIT_REACHED="max_accounts_reached",e.DISALLOWED_LOGIN_METHOD="disallowed_login_method",e.PASSKEY_NOT_ALLOWED="passkey_not_allowed",e.USER_DOES_NOT_EXIST="user_does_not_exist",e.INSUFFICIENT_BALANCE="insufficient_balance",e.ACCOUNT_TRANSFER_REQUIRED="account_transfer_required";const o=()=>{throw Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")},l=i.createContext({isNewUserThisSession:!1,walletConnectionStatus:null,connectors:[],solanaWallets:[],rpcConfig:{rpcUrls:{}},showFiatPrices:!0,chains:[],clientAnalyticsId:null,pendingTransaction:null,client:null,appId:"notAdded",customAuthStatus:{status:"not-enabled"},noPromptOnSignature:{current:!1},nativeTokenSymbolForChainId:o,initializeWalletProxy:o,getAuthMeta:o,getAuthFlow:o,closePrivyModal:o,openPrivyModal:o,connectWallet:o,initLoginWithWallet:o,loginWithWallet:o,initLoginWithFarcaster:o,loginWithFarcaster:o,loginWithCode:o,initLoginWithEmail:o,initLoginWithSms:o,initUpdateEmail:o,initUpdatePhone:o,resendEmailCode:o,resendSmsCode:o,initLoginWithHeadlessOAuth:o,loginWithHeadlessOAuth:o,crossAppAuthFlow:o,initLoginWithOAuth:o,recoveryOAuthFlow:o,loginWithOAuth:o,passkeyAuthState:{status:"initial"},setPasskeyAuthState:o,initLoginWithPasskey:o,loginWithPasskey:o,initLinkWithPasskey:o,linkWithPasskey:o,refreshUser:o,loginWithGuestAccountFlow:o,walletProxy:null,createAnalyticsEvent:o,acceptTerms:o,getUsdTokenPrice:o,getUsdPriceForSol:o,recoverEmbeddedEthereumWallet:o,getMoonpaySignedUrl:o,initCoinbaseOnRamp:o,getCoinbaseOnRampStatus:o,updateWallets:o,fundWallet:o,setReadyToTrue:o,requestFarcasterSignerStatus:o,initLoginWithTelegram:o,loginWithTelegram:o,generateSiweMessage:o,generateSiweMessageForSmartWallet:o,linkWithSiwe:o,linkSmartWallet:o,initDelegateAction:o,embeddedSolanaWallet:null,createEmbeddedSolanaWallet:o,recoverEmbeddedSolanaWallet:o,exportSolanaWallet:o,solanaSignMessage:o,connectCoinbaseSmartWallet:o,initiateAccountTransfer:o,emailOtpState:{status:"initial"},setEmailOtpState:o,smsOtpState:{status:"initial"},setSmsOtpState:o,siweState:{status:"initial"},setSiweState:o,oAuthState:{status:"initial"},setOAuthState:o}),_=i.createContext({ready:!1,authenticated:!1,user:null,walletConnectors:null,connectWallet:o,login:o,connectOrCreateWallet:o,linkEmail:o,linkPhone:o,linkFarcaster:o,linkWallet:o,startCrossAppAuthFlow:o,linkGoogle:o,linkTwitter:o,linkDiscord:o,linkGithub:o,linkSpotify:o,linkInstagram:o,linkTelegram:o,linkTiktok:o,linkLinkedIn:o,linkApple:o,linkPasskey:o,updateEmail:o,updatePhone:o,logout:o,getAccessToken:o,getEthereumProvider:o,getEthersProvider:o,getWeb3jsProvider:o,unlinkEmail:o,unlinkPhone:o,unlinkWallet:o,unlinkGoogle:o,unlinkTwitter:o,unlinkDiscord:o,unlinkGithub:o,unlinkSpotify:o,unlinkInstagram:o,unlinkTiktok:o,unlinkLinkedIn:o,unlinkApple:o,unlinkCrossAppAccount:o,unlinkFarcaster:o,unlinkTelegram:o,unlinkPasskey:o,setActiveWallet:o,forkSession:o,createWallet:o,importWallet:o,signMessage:o,signTypedData:o,enrollInMfa:o,initEnrollmentWithSms:o,initEnrollmentWithTotp:o,initEnrollmentWithPasskey:o,promptMfa:o,init:o,submitEnrollmentWithSms:o,submitEnrollmentWithTotp:o,submitEnrollmentWithPasskey:o,unenroll:o,submit:o,cancel:o,sendTransaction:o,sendSolanaTransaction:o,exportWallet:o,setWalletPassword:o,setWalletRecovery:o,requestFarcasterSignerFromWarpcast:o,getFarcasterSignerPublicKey:o,signFarcasterMessage:o,createGuestAccount:o,initLoginWithEmail:o,initLoginWithSms:o,otpState:{status:"initial"},loginWithCode:o,fundWallet:o,initLoginWithHeadlessOAuth:o,loginWithHeadlessOAuth:o,generateSiweMessage:o,linkWithSiwe:o,signMessageWithCrossAppWallet:o,signTypedDataWithCrossAppWallet:o,sendTransactionWithCrossAppWallet:o,isHeadlessOAuthLoading:!1,isModalOpen:!1,mfaMethods:[]});exports.InternalPrivyContext=l,exports.PrivyApiError=r,exports.PrivyClientError=s,exports.PrivyConnectorError=class extends n{constructor(e,t,i){super(e,t,i),this.type="connector_error"}},exports.PrivyContext=_,exports.PrivyEmbeddedWalletError=class extends s{constructor(e="Embedded wallet error",t){super(e,t,"unknown_embedded_wallet_error")}},exports.PrivyError=n,exports.PrivyNotReadyError=class extends s{constructor(){super("Method called before `ready`. Ensure you wait until `ready` is true before calling.")}},exports.PrivyTimeoutError=class extends s{constructor(){super("Request timed out",void 0,"client_request_timeout")}},exports.PrivyUnauthenticatedError=class extends s{constructor(e="User must be authenticated"){super(e,void 0,"must_be_authenticated")}},exports.PrivyUserLimitReachedError=class extends s{constructor(e){super("This application is in development mode and must be upgraded to production to log in new users.",e,"max_accounts_reached")}},exports.formatApiError=e=>{if(e instanceof n)return e;if(!(e instanceof t.FetchError))return a(e);if(!e.response)return new r("api_error",null,e.message,e);let{type:i,message:s,error:o,code:l}=e.data;return new r(i||"ApiError",e.response.status,s||o,e,l,e.data)},exports.formatPrivyError=a,exports.notImplemented=o,exports.usePrivy=()=>i.useContext(_),exports.usePrivyInternal=()=>i.useContext(l);