@privy-io/react-auth 2.6.2 → 2.6.3

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.
Files changed (54) hide show
  1. package/dist/cjs/abstract-smart-wallets.js +1 -1
  2. package/dist/cjs/farcaster.js +1 -1
  3. package/dist/cjs/getEmbeddedConnectedWallet-DTU4T9TJ.js +1 -0
  4. package/dist/cjs/index.js +1 -5
  5. package/dist/cjs/internal-context-HesndSYh.js +1 -0
  6. package/dist/cjs/privy-provider-CWADob3g.js +27 -0
  7. package/dist/cjs/smart-wallets-Dsq1trqs.js +1 -0
  8. package/dist/cjs/smart-wallets.js +1 -1
  9. package/dist/cjs/solana.js +1 -1
  10. package/dist/cjs/ui.js +2 -2
  11. package/dist/cjs/useActiveWallet-D5FyaqZJ.js +1 -0
  12. package/dist/cjs/useFundWallet-BsBuslJV.js +1 -0
  13. package/dist/dts/farcaster.d.mts +1 -1
  14. package/dist/dts/farcaster.d.ts +1 -1
  15. package/dist/dts/index.d.mts +12 -8
  16. package/dist/dts/index.d.ts +12 -8
  17. package/dist/dts/smart-wallets.d.mts +1 -1
  18. package/dist/dts/smart-wallets.d.ts +1 -1
  19. package/dist/dts/solana.d.mts +6 -6
  20. package/dist/dts/solana.d.ts +6 -6
  21. package/dist/dts/{types-CcosPsy6.d.mts → types-CsAGoXth.d.mts} +9 -9
  22. package/dist/dts/{types-CcosPsy6.d.ts → types-CsAGoXth.d.ts} +9 -9
  23. package/dist/dts/ui.d.mts +1 -1
  24. package/dist/dts/ui.d.ts +1 -1
  25. package/dist/dts/{useSolanaWallets-BHduxJmW.d.mts → useSolanaWallets-CFgYdjDv.d.mts} +18 -1
  26. package/dist/dts/{useSolanaWallets-BHduxJmW.d.ts → useSolanaWallets-CFgYdjDv.d.ts} +18 -1
  27. package/dist/esm/abstract-smart-wallets.mjs +1 -1
  28. package/dist/esm/farcaster.mjs +1 -1
  29. package/dist/esm/getEmbeddedConnectedWallet-CSSBWE2p.mjs +1 -0
  30. package/dist/esm/index.mjs +1 -5
  31. package/dist/esm/{internal-context-CL_EG4e1.mjs → internal-context-O3TPYUku.mjs} +1 -1
  32. package/dist/esm/privy-provider-u_cmfixS.mjs +27 -0
  33. package/dist/esm/smart-wallets-vK26EMrU.mjs +1 -0
  34. package/dist/esm/smart-wallets.mjs +1 -1
  35. package/dist/esm/solana.mjs +1 -1
  36. package/dist/esm/ui.mjs +2 -2
  37. package/dist/esm/useActiveWallet-Cwj5v4eK.mjs +1 -0
  38. package/dist/esm/useFundWallet-BPk4tVPS.mjs +1 -0
  39. package/package.json +4 -4
  40. package/dist/cjs/AwaitingEvmToSolBridgingScreen-pmGmvR1q.js +0 -22
  41. package/dist/cjs/getEmbeddedConnectedWallet-CGj_I0cc.js +0 -2
  42. package/dist/cjs/importWallet-Du1BO6qb.js +0 -1
  43. package/dist/cjs/internal-context-D5TgeQk8.js +0 -1
  44. package/dist/cjs/prepareFundingModalData-C2_ED32S.js +0 -1
  45. package/dist/cjs/smart-wallets-CoYci1bf.js +0 -1
  46. package/dist/cjs/useActiveWallet-CaLK0Ao4.js +0 -1
  47. package/dist/cjs/useFundWallet-92y-LJjK.js +0 -1
  48. package/dist/esm/AwaitingEvmToSolBridgingScreen-DnBONxHo.mjs +0 -22
  49. package/dist/esm/getEmbeddedConnectedWallet-Cyt02rK3.mjs +0 -2
  50. package/dist/esm/importWallet-Bqr-aqzk.mjs +0 -1
  51. package/dist/esm/prepareFundingModalData-Bkg2jc5P.mjs +0 -1
  52. package/dist/esm/smart-wallets-KrlR2oLu.mjs +0 -1
  53. package/dist/esm/useActiveWallet-SKrFBYMY.mjs +0 -1
  54. package/dist/esm/useFundWallet-BvMwnH48.mjs +0 -1
@@ -1,5 +1 @@
1
- import{jsx as t,jsxs as n,Fragment as r}from"react/jsx-runtime";import{createStore as a}from"mipd";import i,{useMemo as o,useEffect as s,useState as l,useContext as h,useRef as u,useCallback as p,forwardRef as m}from"react";import{isMobile as w,isIOS as y,isSafari as f,isAndroid as v}from"react-device-detect";import{getAddress as k,isAddress as A}from"viem/utils";import{P as C,c as E,f as T,p as _,a as I,b as S,u as W,d as x,e as P,g as N,h as U,i as O,o as R,j as M,k as L,l as D,m as F,n as z,q,r as B,s as V,t as j,v as H,w as $,x as K,y as Y,z as G,A as X,B as J,C as Q,D as Z,E as ee,F as te,G as ne,H as re,I as ae,J as ie,K as oe,L as se,M as le,N as ce,O as de,Q as he,R as ue,S as pe,T as me,U as we,V as ye,W as ge,X as fe,Y as ve,Z as ke,_ as Ae,$ as Ce,a0 as Ee,a1 as be,a2 as Te,a3 as _e,a4 as Ie,a5 as Se,a6 as We,a7 as xe,a8 as Pe,a9 as Ne,aa as Ue,ab as Oe,ac as Re,ad as Me}from"./internal-context-CL_EG4e1.mjs";import{o as Le,R as De,e as Fe,s as ze,r as qe,g as Be,a as Ve,C as je,H as He,O as $e,c as Ke,b as Ye,S as Ge,d as Xe,G as Je,D as Qe,f as Ze,L as et,T as tt,h as nt,I as rt,i as at,A as it,j as ot,E as st,k as lt,l as ct,P as dt,m as ht,t as ut,B as pt,n as mt,p as wt,q as yt,u as gt,v as ft,w as vt,x as kt,y as At,z as Ct,F as Et,J as bt,W as Tt,K as _t,M as It,V as St,N as Wt,Q as xt,U as Pt,X as Nt,Y as Ut,Z as Ot,_ as Rt,$ as Mt,a0 as Lt,a1 as Dt,a2 as Ft,a3 as zt,a4 as qt,a5 as Bt,a6 as Vt,a7 as jt,a8 as Ht,a9 as $t,aa as Kt,ab as Yt,ac as Gt,ad as Xt,ae as Jt,af as Qt,ag as Zt,ah as en,ai as tn,aj as nn,ak as rn,al as an,am as on,an as sn,ao as ln,ap as cn,aq as dn,ar as hn,as as un,at as pn,au as mn,av as wn,aw as yn,ax as gn,ay as fn,az as vn,aA as kn,aB as An,aC as Cn,aD as En,aE as bn,aF as Tn,aG as _n,aH as In,aI as Sn,aJ as Wn,aK as xn,aL as Pn,aM as Nn,aN as Un,aO as On,aP as Rn,aQ as Mn,aR as Ln,aS as Dn,aT as Fn,aU as zn,aV as qn,aW as Bn,aX as Vn,aY as jn,aZ as Hn,a_ as $n,a$ as Kn,b0 as Yn,b1 as Gn,b2 as Xn,b3 as Jn,b4 as Qn,b5 as Zn,b6 as er,b7 as tr,b8 as nr,b9 as rr,ba as ar,bb as ir,bc as or,bd as sr,be as lr,bf as cr,bg as dr,bh as hr,bi as ur,bj as pr,bk as mr,bl as wr,bm as yr,bn as gr,bo as fr,bp as vr,bq as kr,br as Ar,bs as Cr,bt as Er,bu as br,bv as Tr,bw as _r,bx as Ir,by as Sr,bz as Wr,bA as xr,bB as Pr,bC as Nr,bD as Ur,bE as Or,bF as Rr,bG as Mr,bH as Lr,bI as Dr,bJ as Fr,bK as zr,bL as qr,bM as Br,bN as Vr,bO as jr,bP as Hr,bQ as $r,bR as Kr,bS as Yr,bT as Gr,bU as Xr,bV as Jr,bW as Qr,bX as Zr,bY as ea,bZ as ta,b_ as na,b$ as ra,c0 as aa,c1 as ia,c2 as oa,c3 as sa,c4 as la,c5 as ca,c6 as da,c7 as ha,c8 as ua,c9 as pa,ca as ma,cb as wa,cc as ya,cd as ga,ce as fa,cf as va,cg as ka,ch as Aa,ci as Ca,cj as Ea,ck as ba,cl as Ta,cm as _a,cn as Ia,co as Sa,cp as Wa,cq as xa,cr as Pa,cs as Na,ct as Ua,cu as Oa,cv as Ra,cw as Ma,cx as La,cy as Da,cz as Fa,cA as za,cB as qa,cC as Ba,cD as Va,cE as ja,cF as Ha,cG as $a,cH as Ka,cI as Ya,cJ as Ga,cK as Xa,cL as Ja,cM as Qa,cN as Za,cO as ei,cP as ti,cQ as ni,cR as ri,cS as ai,cT as ii,cU as oi,cV as si,cW as li,cX as ci,cY as di}from"./AwaitingEvmToSolBridgingScreen-DnBONxHo.mjs";export{c$ as SUPPORTED_CHAINS,cZ as WalletConnector,d1 as addPrivyRpcToChain,d0 as addRpcUrlOverrideToChain,c_ as useSolanaWallets}from"./AwaitingEvmToSolBridgingScreen-DnBONxHo.mjs";import*as hi from"jose";import{base64url as ui}from"jose";import{v4 as pi}from"uuid";import mi from"eventemitter3";import{CoinbaseWalletSDK as wi}from"@coinbase/wallet-sdk";import{S as yi,i as gi,l as fi,f as vi,p as ki,a as Ai,b as Ci,e as Ei}from"./prepareFundingModalData-Bkg2jc5P.mjs";import{ofetch as bi}from"ofetch";import Ti from"js-cookie";import{create as _i}from"zustand";import{Turnstile as Ii}from"@marsidev/react-turnstile";import{styled as Si,createGlobalStyle as Wi,css as xi}from"styled-components";import{u as Pi,a as Ni}from"./useActiveWallet-SKrFBYMY.mjs";export{e as useActiveWallet,c as useConnectWallet,d as useFundWallet,b as useLogin}from"./useActiveWallet-SKrFBYMY.mjs";import Ui from"@heroicons/react/24/outline/DevicePhoneMobileIcon";import Oi from"@heroicons/react/24/outline/FingerPrintIcon";import Ri from"@heroicons/react/24/outline/PhoneIcon";import Mi from"@heroicons/react/24/outline/ShieldCheckIcon";import{toHex as Li,formatUnits as Di,zeroAddress as Fi,getAddress as zi,createWalletClient as qi,http as Bi,parseSignature as Vi}from"viem";import ji from"@heroicons/react/24/outline/CalendarIcon";import Hi from"@heroicons/react/24/outline/ExclamationTriangleIcon";import{Transition as $i,Dialog as Ki,TransitionChild as Yi,DialogPanel as Gi}from"@headlessui/react";import Xi from"@heroicons/react/24/outline/CheckCircleIcon";import Ji from"@heroicons/react/24/outline/CloudArrowUpIcon";import Qi from"@heroicons/react/24/outline/ExclamationCircleIcon";import Zi from"@heroicons/react/24/outline/NoSymbolIcon";import{S as eo,E as to,a as no}from"./getEmbeddedConnectedWallet-Cyt02rK3.mjs";export{g as getEmbeddedConnectedWallet}from"./getEmbeddedConnectedWallet-Cyt02rK3.mjs";import ro from"@heroicons/react/24/outline/ArrowTopRightOnSquareIcon";import ao from"@heroicons/react/24/outline/EnvelopeIcon";import io from"@heroicons/react/24/outline/ClockIcon";import oo from"@heroicons/react/24/outline/TrashIcon";import so from"@heroicons/react/24/solid/CheckBadgeIcon";import lo from"@heroicons/react/24/solid/LockClosedIcon";import co from"@heroicons/react/24/outline/QuestionMarkCircleIcon";import ho from"@heroicons/react/24/solid/IdentificationIcon";import uo from"@heroicons/react/24/outline/ChevronRightIcon";import po from"@heroicons/react/24/outline/MinusCircleIcon";import mo from"@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon";import{lastFourDigits as wo,SolanaClient as yo}from"@privy-io/js-sdk-core";import go from"@heroicons/react/24/solid/ShieldCheckIcon";import fo from"@heroicons/react/24/outline/GlobeAltIcon";import vo from"@heroicons/react/24/outline/ChevronDownIcon";import{i as ko}from"./importWallet-Bqr-aqzk.mjs";import{eip7702Actions as Ao,hashAuthorization as Co}from"viem/experimental";import"tinycolor2";import"@heroicons/react/24/outline/ArrowLeftIcon";import"@heroicons/react/24/outline/ArrowRightIcon";import"@heroicons/react/24/outline/XMarkIcon";import"@heroicons/react/24/outline/CheckIcon";import"@heroicons/react/24/outline/Square2StackIcon";import"@heroicons/react/24/outline/WalletIcon";import"@walletconnect/ethereum-provider";import"@heroicons/react/24/outline/UserCircleIcon";import"@heroicons/react/20/solid/CheckIcon";import"@heroicons/react/24/solid/DocumentCheckIcon";import"@heroicons/react/24/solid/XCircleIcon";import"fast-password-entropy";import"secure-password-utilities";import"secure-password-utilities/wordlists";import"@heroicons/react/24/outline/LockClosedIcon";import"@heroicons/react/24/outline/PencilSquareIcon";import"@heroicons/react/24/solid/CheckCircleIcon";import"@heroicons/react/24/outline/ArrowPathIcon";import"@heroicons/react/24/outline/EyeIcon";import"@heroicons/react/24/outline/EyeSlashIcon";import"@heroicons/react/24/outline/KeyIcon";import"@heroicons/react/24/outline/ArrowDownTrayIcon";import"@heroicons/react/24/outline/ClipboardDocumentCheckIcon";import"@heroicons/react/24/outline/DocumentDuplicateIcon";import"qrcode";import"@heroicons/react/24/outline/InformationCircleIcon";import"@heroicons/react/24/outline/CreditCardIcon";import"@heroicons/react/24/outline/QrCodeIcon";import"@heroicons/react/24/solid/ArrowsRightLeftIcon";import"@heroicons/react/24/outline";import"@heroicons/react/24/outline/ClipboardDocumentIcon";import"zustand/shallow";import"zustand/traditional";class Eo{async authenticate(){if(!this.api)throw new C("Auth flow has no API instance");try{return await this.api.post(E,{token:this.meta.token})}catch(e){throw T(e)}}async link(){throw Error("Unimplemented")}constructor(e){this.meta={token:e}}}function bo(e){return e?{"privy-ui":"t"}:void 0}class To{async authenticate(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new C("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(_,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw T(e)}}async link(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new C("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(I,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw T(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:n}){if(!this.api)throw new C("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new C("Email must be set when initialzing authentication.");let r=bo(n);try{return await this.api.post(S,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...r}})}catch(e){throw T(e)}}constructor({email:e,captchaToken:t,disableSignup:n}){this.meta={email:e,captchaToken:t,disableSignup:n??!1}}}class _o extends To{async link(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new C("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(W,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw T(e)}}constructor(e,t,n){super({email:t,captchaToken:n}),this.meta={email:t,captchaToken:n,oldAddress:e,disableSignup:!1}}}class Io{get meta(){return this._meta}async authenticate(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.channelToken)throw new C("Auth flow must be initialized first");try{let e=await this.api.post(x,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});if(!e)throw new C("No response from authentication");return e}catch(e){throw T(e)}}async link(){if(!this.api)throw new C("Auth flow has no API instance");try{return await this.api.post(P,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw T(e)}}async _startChannelOnce(){if(!this.api)throw new C("Auth flow has no API instance");let e=await this.api.post(N,{token:this.captchaToken});w&&!y&&e.connect_uri&&Le(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new C("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.channelToken)throw new C("Auth flow must be initialized first");let e=await this.api.get(U,{headers:{"farcaster-channel-token":this.meta.channelToken}});return"completed"===e.state&&(this.message=e.message,this.signature=e.signature,this.fid=e.fid,!0)}constructor(e,t=!1){this._meta={disableSignup:!1},this.captchaToken=e,this.startChannelOnce=new De(this._startChannelOnce.bind(this)),this.pollForReady=new De(this._pollForReady.bind(this)),this._meta.disableSignup=t}}class So{getOrCreateGuestCredential(e){let t=Be(e);if(Fe()){if(ze.get(t))return ze.get(t);{let e=ui.encode(qe(32));return ze.put(t,e),e}}return ui.encode(qe(32))}async authenticate(){if(!this.api)throw new C("Auth flow has no API instance");try{return await this.api.post(O,{guest_credential:this.meta.guestCredential})}catch(e){throw T(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}class Wo{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new C("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new C("User denied confirmation during OAuth flow");let e=Ve();try{let t=await this.api.post(R,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return ze.del(je),ze.del(He),ze.del($e),t}catch(e){let t=T(e);if(t.privyErrorCode)throw new C(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new C("Invalid code during oauth flow.",void 0,M.OAUTH_USER_DENIED);throw new C("Invalid code during OAuth flow.",void 0,M.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new C("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new C("User denied confirmation during OAuth flow");let e=ze.get(je);if(!e)throw new C("Authentication error.");try{let t=await this.api.post(L,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return ze.del(je),t}catch(e){throw T(e)}}async getAuthorizationUrl(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.provider)throw new C("Provider must be set when initializing OAuth authentication.");let e=Ke();ze.put(je,e);let t=Ye();ze.put(Ge,t);let n=await Xe(e);this.meta.withPrivyUi||ze.put(He,!0),this.meta.disableSignup&&ze.put($e,!0);let r=bo(this.meta.withPrivyUi);try{return await this.api.post(D,{provider:this.meta.provider,redirect_to:window.location.href,token:this.meta.captchaToken,code_challenge:n,state_code:t},{headers:{...r}})}catch(e){throw T(e)}}constructor(e){this.meta=e}}const xo=({style:e})=>/*#__PURE__*/t(fo,{style:{color:"var(--privy-color-error)",...e}});let Po={google:{name:"Google",component:Je},discord:{name:"Discord",component:Qe},github:{name:"Github",component:Ze},linkedin:{name:"LinkedIn",component:et},twitter:{name:"Twitter",component:tt},spotify:{name:"Spotify",component:nt},instagram:{name:"Instagram",component:rt},tiktok:{name:"Tiktok",component:at},apple:{name:"Apple",component:it}};const No=e=>e in Po?Po[e]:{name:"Unknown",component:xo};function Uo(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),n=e.get("privy_oauth_state"),r=e.get("privy_oauth_provider");if(!t||!n||!r)return{inProgress:!1};let a=!1;try{a=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:n,provider:r,withPrivyUi:!ze.get(He),popupFlow:null!==window.opener&&a,disableSignup:!!ze.get($e)}}class Oo{async initRegisterFlow(e){if(!this.api)throw new C("Auth flow has no API instance");this.authenticateForRegistration=!0,this.meta.initRegisterResponse=await this.initRegisterOnce.execute(e)}async initAuthenticationFlow(e){if(!this.api)throw new C("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new C("Auth flow has no API instance");this.meta.initLinkResponse=await this.initLinkOnce.execute()}async register(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new C("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new C("WebAuthn is not supported in this browser");this.meta.initRegisterResponse||(this.meta.initRegisterResponse=await this.initRegisterOnce.execute());try{let t=this.meta.initRegisterResponse.options,n=await e.startRegistration(this._transformInitLinkOptionsToCamelCase(t));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(F,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(n)})}catch(e){if("NotAllowedError"===e.name)throw new C("Passkey request timed out or rejected by user.",void 0,M.PASSKEY_NOT_ALLOWED);throw T(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new C("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new C("WebAuthn is not supported in this browser");this.meta.initAuthenticateResponse||(this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute());let t=this.meta.allowedCredentialsIds?.map((e=>({type:"public-key",id:e})))??this.meta.initAuthenticateResponse.options.allow_credentials;try{let n=await e.startAuthentication(this._transformInitAuthenticateOptionsToCamelCase({...this.meta.initAuthenticateResponse.options,allow_credentials:t}));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(z,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(n)})}catch(e){if("NotAllowedError"===e.name)throw new C("Passkey request timed out or rejected by user.",void 0,M.PASSKEY_NOT_ALLOWED);throw T(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new C("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new C("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let t=this.meta.initLinkResponse.options,n=await e.startRegistration(this._transformInitLinkOptionsToCamelCase(t));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(q,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(n)})}catch(e){if("NotAllowedError"===e.name)throw new C("Passkey request timed out or rejected by user.",void 0,M.PASSKEY_NOT_ALLOWED);throw T(e)}}async _initRegisterOnce(e){if(!this.api)throw new C("Auth flow has no API instance");let t=bo(e);return await this.api.post(B,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new C("Auth flow has no API instance");let t=bo(e);return await this.api.post(V,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new C("Auth flow has no API instance");return await this.api.post(j,{})}_transformInitLinkOptionsToCamelCase(e){return{rp:e.rp,user:{id:e.user.id,name:e.user.name,displayName:e.user.display_name},challenge:e.challenge,pubKeyCredParams:e.pub_key_cred_params.map((e=>({type:e.type,alg:e.alg}))),timeout:e.timeout,excludeCredentials:e.exclude_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports}))),authenticatorSelection:{authenticatorAttachment:e.authenticator_selection?.authenticator_attachment,requireResidentKey:e.authenticator_selection?.require_resident_key,residentKey:e.authenticator_selection?.resident_key,userVerification:e.authenticator_selection?.user_verification},attestation:e.attestation,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props?.rk,hmacCreateSecret:e.extensions?.hmac_create_secret}}}_transformRegistrationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData},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}}_transformInitAuthenticateOptionsToCamelCase(e){return{rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}}_transformAuthenticationResponseToSnakeCase(e){return{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}}constructor({captchaToken:e,setPasskeyAuthState:t}){this.authenticateForRegistration=!1,this.initRegisterOnce=new De(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new De(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new De(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t}}}class Ro{async authenticate(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new C("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(H,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw T(e)}}async link(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new C("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post($,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw T(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:n}){if(!this.api)throw new C("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new C("phone nNumber must be set when initialzing authentication.");let r=bo(n);try{return await this.api.post(K,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...r}})}catch(e){throw T(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:n}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:n??!1}}}class Mo extends Ro{async link(){if(!this.api)throw new C("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new C("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(Y,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw T(e)}}constructor(e,t,n){super({phoneNumber:t,captchaToken:n}),this.meta={phoneNumber:t,captchaToken:n,oldPhoneNumber:e,disableSignup:!1}}}class Lo{static parse(e){try{return new Lo(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return hi.decodeJwt(e),e}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=1e3*(this.expiration-e)}constructor(e){this.value=e,this._decoded=hi.decodeJwt(e)}}class Do extends Lo{static parse(e){try{return new Do(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let Fo,zo=[1,11155111,137,10,8453,84532,42161,7777777,43114,56],qo=(e,t)=>e.makeWeb3Provider({options:t});class Bo extends st{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:lt,id:"com.coinbase.wallet"}}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new G("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw ct(e)}}updateConnectionPreference(e){this.connectionOptions=e,this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",this.proxyProvider.setWalletProvider(qo(Fo,this.connectionOptions))}constructor(e,t,n,r,a,i){if(super("coinbase_wallet",e,t,n),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new dt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.connectionOptions=r.coinbaseWallet.connectionOptions??"all",this.walletClientType="smartWalletOnly"===this.connectionOptions?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!Fo){let n=[t.id].concat(e.map((e=>e.id))),r="eoaOnly"!==this.connectionOptions?n.filter((e=>!zo.includes(e))):[];r.length>0&&!r.every((e=>ht.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${r.join(", ")}`),Fo=new wi({appName:a,appLogoUrl:i,appChainIds:n})}this.proxyProvider.setWalletProvider(qo(Fo,this.connectionOptions))}}class Vo extends st{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return await this.isConnected()?(await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[ut(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:pt,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}constructor({provider:e,chains:t,defaultChain:n,rpcConfig:r,imported:a,walletIndex:i}){super("privy",t,n,r),this.connectorType="embedded",this.proxyProvider=e,this.walletIndex=i,a&&(this.connectorType="embedded_imported"),this.subscribeListeners()}}const jo=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];class Ho extends Error{constructor(e,t,n){super(e),this.code=t,this.data=n}}class $o extends mi{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Ho(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await $c()||!this.address)throw new Ho("Disconnected",4900);let{hash:n}=await Xc(t,{address:this.address});return n}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Ho(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await $c()||!this.address)throw new Ho("Disconnected",4900);let{signature:n}=await Gc(t,{address:this.address});return n}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new Ho(`Invalid params for ${e.method}`,4200);if("string"==typeof e.params[0])t=e.params[0];else{if(!("chainId"in e.params[0])||"string"!=typeof e.params[0].chainId)throw new Ho(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=mt(this.chainId,this.chains,this.rpcConfig,{appId:this.appId}),this.emit("chainChanged",t)}async handlePersonalSign(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for personal_sign");let t=e.params[0],n=e.params[1],{signature:r}=await Kc({message:t},{address:n});return r}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],n="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1],{signature:r}=await Yc(wt(n),{address:t});return r}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;let t={...e.params[0],chainId:ut(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...yt(t)})}async request(e){switch(console.debug("Embedded1193Provider.request() called with args",e),e.method){case"eth_accounts":case"eth_requestAccounts":return this.address?[this.address]:[];case"eth_chainId":return ut(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":return this.handleSendTransaction(e);case"eth_signTransaction":return this.handleSignTransaction(e);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"personal_sign":return this.handlePersonalSign(e);case"eth_signTypedData_v4":return this.handleSignedTypedData(e)}if(!(e=>jo.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await $c();if(await Jc(),!t||!this.address)throw new Ho("Disconnected",4900);try{return(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:{method:e.method,params:e.params}})).response.data}catch(e){throw console.error(e),new Ho("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:n,entropyIdVerifier:r,rpcConfig:a,chains:i,appId:o,chainId:s=1,walletIndex:l}){super(),this.walletProxy=e,this.address=t,this.entropyId=n,this.entropyIdVerifier=r,this.chainId=s,this.rpcConfig=a,this.chains=i,this.publicClient=mt(s,this.chains,a,{appId:o}),this.rpcTimeoutDuration=gt(a,"privy"),this.appId=o,this.walletIndex=l}}class Ko extends st{get walletBranding(){return{id:this.id,name:this.name,icon:this.icon}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw Error("connect called for an uninstalled wallet via the EthereumNullConnector")}disconnect(){throw Error("disconnect called for an uninstalled wallet via the EthereumNullConnector")}promptConnection(e){throw Error(`promptConnection called for an uninstalled wallet via the EthereumNullConnector for ${e}`)}constructor({id:e,name:t,icon:n,walletClientType:r,defaultChain:a}){super(r,[],a,{}),this.connectorType="null",this.proxyProvider=new dt(void 0,ft),this.id=e,this.name=t,this.icon=n,this.connectorType=r}}const Yo=({style:e,...r})=>/*#__PURE__*/n("svg",{xmlns:"http://www.w3.org/2000/svg",xmlSpace:"preserve",x:0,y:0,viewBox:"0 0 318.6 318.6",width:"28",height:"28",style:{height:"28px",width:"28px",...e},...r,children:[/*#__PURE__*/t("style",{children:".s1{stroke-linecap:round;stroke-linejoin:round}.s2{fill:#e4761b;stroke:#e4761b}.s3{fill:#f6851b;stroke:#f6851b}"}),/*#__PURE__*/t("path",{fill:"#e2761b",stroke:"#e2761b",className:"s1",d:"m274.1 35.5-99.5 73.9L193 65.8z"}),/*#__PURE__*/t("path",{d:"m44.4 35.5 98.7 74.6-17.5-44.3zm193.9 171.3-26.5 40.6 56.7 15.6 16.3-55.3zm-204.4.9L50.1 263l56.7-15.6-26.5-40.6z",className:"s1 s2"}),/*#__PURE__*/t("path",{d:"m103.6 138.2-15.8 23.9 56.3 2.5-2-60.5zm111.3 0-39-34.8-1.3 61.2 56.2-2.5zM106.8 247.4l33.8-16.5-29.2-22.8zm71.1-16.5 33.9 16.5-4.7-39.3z",className:"s1 s2"}),/*#__PURE__*/t("path",{fill:"#d7c1b3",stroke:"#d7c1b3",className:"s1",d:"m211.8 247.4-33.9-16.5 2.7 22.1-.3 9.3zm-105 0 31.5 14.9-.2-9.3 2.5-22.1z"}),/*#__PURE__*/t("path",{fill:"#233447",stroke:"#233447",className:"s1",d:"m138.8 193.5-28.2-8.3 19.9-9.1zm40.9 0 8.3-17.4 20 9.1z"}),/*#__PURE__*/t("path",{fill:"#cd6116",stroke:"#cd6116",className:"s1",d:"m106.8 247.4 4.8-40.6-31.3.9zM207 206.8l4.8 40.6 26.5-39.7zm23.8-44.7-56.2 2.5 5.2 28.9 8.3-17.4 20 9.1zm-120.2 23.1 20-9.1 8.2 17.4 5.3-28.9-56.3-2.5z"}),/*#__PURE__*/t("path",{fill:"#e4751f",stroke:"#e4751f",className:"s1",d:"m87.8 162.1 23.6 46-.8-22.9zm120.3 23.1-1 22.9 23.7-46zm-64-20.6-5.3 28.9 6.6 34.1 1.5-44.9zm30.5 0-2.7 18 1.2 45 6.7-34.1z"}),/*#__PURE__*/t("path",{d:"m179.8 193.5-6.7 34.1 4.8 3.3 29.2-22.8 1-22.9zm-69.2-8.3.8 22.9 29.2 22.8 4.8-3.3-6.6-34.1z",className:"s3"}),/*#__PURE__*/t("path",{fill:"#c0ad9e",stroke:"#c0ad9e",className:"s1",d:"m180.3 262.3.3-9.3-2.5-2.2h-37.7l-2.3 2.2.2 9.3-31.5-14.9 11 9 22.3 15.5h38.3l22.4-15.5 11-9z"}),/*#__PURE__*/t("path",{fill:"#161616",stroke:"#161616",className:"s1",d:"m177.9 230.9-4.8-3.3h-27.7l-4.8 3.3-2.5 22.1 2.3-2.2h37.7l2.5 2.2z"}),/*#__PURE__*/t("path",{fill:"#763d16",stroke:"#763d16",className:"s1",d:"m278.3 114.2 8.5-40.8-12.7-37.9-96.2 71.4 37 31.3 52.3 15.3 11.6-13.5-5-3.6 8-7.3-6.2-4.8 8-6.1zM31.8 73.4l8.5 40.8-5.4 4 8 6.1-6.1 4.8 8 7.3-5 3.6 11.5 13.5 52.3-15.3 37-31.3-96.2-71.4z"}),/*#__PURE__*/t("path",{d:"m267.2 153.5-52.3-15.3 15.9 23.9-23.7 46 31.2-.4h46.5zm-163.6-15.3-52.3 15.3-17.4 54.2h46.4l31.1.4-23.6-46zm71 26.4 3.3-57.7 15.2-41.1h-67.5l15 41.1 3.5 57.7 1.2 18.2.1 44.8h27.7l.2-44.8z",className:"s3"})]}),Go=({style:e,...r})=>/*#__PURE__*/n("svg",{xmlns:"http://www.w3.org/2000/svg",width:"108",height:"108",viewBox:"0 0 108 108",fill:"none",style:{height:"28px",width:"28px",...e},...r,children:[/*#__PURE__*/t("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),/*#__PURE__*/t("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M46.5267 69.9229C42.0054 76.8509 34.4292 85.6182 24.348 85.6182C19.5824 85.6182 15 83.6563 15 75.1342C15 53.4305 44.6326 19.8327 72.1268 19.8327C87.768 19.8327 94 30.6846 94 43.0079C94 58.8258 83.7355 76.9122 73.5321 76.9122C70.2939 76.9122 68.7053 75.1342 68.7053 72.314C68.7053 71.5783 68.8275 70.7812 69.0719 69.9229C65.5893 75.8699 58.8685 81.3878 52.5754 81.3878C47.993 81.3878 45.6713 78.5063 45.6713 74.4598C45.6713 72.9884 45.9768 71.4556 46.5267 69.9229ZM83.6761 42.5794C83.6761 46.1704 81.5575 47.9658 79.1875 47.9658C76.7816 47.9658 74.6989 46.1704 74.6989 42.5794C74.6989 38.9885 76.7816 37.1931 79.1875 37.1931C81.5575 37.1931 83.6761 38.9885 83.6761 42.5794ZM70.2103 42.5795C70.2103 46.1704 68.0916 47.9658 65.7216 47.9658C63.3157 47.9658 61.233 46.1704 61.233 42.5795C61.233 38.9885 63.3157 37.1931 65.7216 37.1931C68.0916 37.1931 70.2103 38.9885 70.2103 42.5795Z",fill:"#FFFDF8"})]});function Xo(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var Jo=0;class Qo extends st{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return{name:this.providerDetail.info.name,icon:this.providerDetail.info.icon,id:this.providerDetail.info.rdns}}disconnect(){console.warn(`Programmatic disconnect with ${this.providerDetail.info.name} is not yet supported.`)}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new G("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw ct(e)}}constructor(e,t,n,r,a){super(a||"unknown",e,t,n),this.connectorType="injected",this.proxyProvider=new dt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=r;let i=r.provider;this.proxyProvider.setWalletProvider(i)}}var Zo="__private_"+Jo+++"__walletBranding";class es extends st{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return Xo(this,Zo)[Zo]??{name:"Browser Extension",icon:vt,id:"extension"}}disconnect(){console.warn("Programmatic disconnect with browser wallets is not yet supported.")}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new G("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw ct(e)}}constructor(e,t,n,r,a){super(a??"unknown",e,t,n),Object.defineProperty(this,Zo,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new dt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(r),"metamask"===a?Xo(this,Zo)[Zo]={name:"MetaMask",icon:Yo,id:"io.metamask"}:"phantom"===a&&(Xo(this,Zo)[Zo]={name:"Phantom",icon:Go,id:"phantom"})}}class ts extends Qo{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{w||await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new G("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw ct(e)}}}class ns extends yi{get walletBranding(){return{id:this.id,name:this.name,icon:this.icon}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw Error("connect called for an uninstalled wallet via the SolanaNullConnector")}constructor({id:e,name:t,icon:n}){super({name:t},!1),this.connectorType="null",this.proxyProvider=new dt(void 0,ft),this.disconnect=async()=>{throw Error("disconnect called for an uninstalled wallet via the SolanaNullConnector")},this.promptConnection=async()=>{throw Error("promptConnection called for an uninstalled wallet via the SolanaNullConnector")},this.id=e,this.name=t,this.icon=n}}class rs extends mi{get wallets(){let e=new Set,t=this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let n=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(n)&&(e.add(n),!0)})),n=t.findIndex((e=>e.address===(this.activeWallet?this.activeWallet:"unknown")));return n>=0&&t.unshift(t.splice(n,1)[0]),t}async initialize(e){if(this.initialized&&!e)return;e&&this.removeAllConnectors(),ze.get(kt)&&(ze.getKeys().forEach((e=>{e.startsWith("walletconnect")&&ze.del(e)})),ze.del(kt));let t=At({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:n})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:n}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),Object.values(Ct)))!e.isInstalled&&this.walletList.includes(e.client)&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&e.chainTypes.includes("ethereum")&&this.createEthereumWalletConnector({connectorType:"null",walletClientType:e.client,walletConfig:e}),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&e.chainTypes.includes("solana")&&this.addSolanaWalletConnector(new ns({id:e.client,name:e.name})));this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"}),this.externalWalletConfig.solana.connectors?.get().forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{e?.forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(Et).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(Et).find((n=>n.connectorType===e&&n.walletClientType===t))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(gi).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id:t.walletClientType===e.walletClientType)));t&&(e.connectedAt=t.connectedAt)})),this.saveConnectionHistory(),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&(this.saveConnectionHistory(),this.emit("walletsUpdated"))}addEmbeddedWalletConnectors({walletProxy:e,rootWallet:t,embeddedWallets:n,defaultChain:r,appId:a}){for(let i of n){let n=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===i.walletIndex));if(n&&Et(n))n.proxyProvider.walletProxy=e;else{let{entropyId:n,entropyIdVerifier:o}=bt(t),s=new Vo({provider:new $o({walletProxy:e,address:i.address,entropyId:n,entropyIdVerifier:o,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:r.id,walletIndex:i.walletIndex}),chains:this.chains,defaultChain:r,rpcConfig:this.rpcConfig,imported:!1,walletIndex:i.walletIndex});this.addWalletConnector(s)}}}addImportedWalletConnector(e,t,n,r){let a=this.findWalletConnector("embedded_imported","privy");if(a&&Et(a))a.proxyProvider.walletProxy=e;else{let a=new Vo({provider:new $o({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:r,chainId:n.id}),chains:this.chains,walletIndex:0,defaultChain:n,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(a)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=fi(),this.emit("walletsUpdated")}removeImportedWalletConnector(){let e=this.findWalletConnector("embedded_imported","privy");if(e){let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1),this.saveConnectionHistory(),this.storedConnections=fi(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:n,walletConfig:r}){let a=this.findWalletConnector(e,t);if(a&&Et(a))return a instanceof Tt&&a.resetConnection(t),a;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new Bo(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"null"!==e?new Tt(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):r?new Ko({id:r.client,name:r.name,defaultChain:this.defaultChain,walletClientType:r.client}):null:"metamask"===t&&n?.eip6963InjectedProvider?new ts(this.chains,this.defaultChain,this.rpcConfig,n?.eip6963InjectedProvider,"metamask"):"metamask"===t&&n?.legacyInjectedProvider?new es(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider,"metamask"):"phantom"===t&&n?.legacyInjectedProvider?new es(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider,"phantom"):n?.legacyInjectedProvider&&"unknown_browser_extension"===t?new es(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider):n?.eip6963InjectedProvider?new Qo(this.chains,this.defaultChain,this.rpcConfig,n?.eip6963InjectedProvider,t):void 0)();return i&&this.addWalletConnector(i),i||null}addWalletConnector(e){this.walletConnectors.push(e),e.on("initialized",(()=>this.onInitialized(e))),e.on("walletsUpdated",(()=>this.onWalletsUpdated(e))),e.initialize().catch((e=>{console.debug("Failed to initialize connector",e)}))}saveConnectionHistory(){let e=this.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt,id:e.meta.id})));ze.put(_t,e)}async activeWalletSign(e){let t=this.wallets,n=t.length>0?t[0]:null;return n&&It(n)?n.sign(e):null}setActiveWallet(e){this.activeWallet=k(e),this.emit("walletsUpdated")}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,n,r,a,i,o,s,l,c,d,h){super(),this.addSolanaWalletConnector=async e=>{let t=this.findSolanaWalletConnector(e.walletClientType);if(!t||"null"===t.connectorType){if("null"===t?.connectorType){let e=this.walletConnectors.indexOf(t);this.walletConnectors.splice(e,1)}this.addWalletConnector(e)}},this.getEthereumProvider=()=>{let e=this.wallets[0],t=this.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new dt},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=n,this.chains=r,this.defaultChain=a,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=s,this.externalWalletConfig=l,this.privyAppName=c,this.privyAppLogo=d,this.walletChainType=h||"ethereum-only",this.storedConnections=fi()}}let as=[J,Q,Z];class is{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw T(e)}}async post(e,t,n){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...n})}catch(e){throw T(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw T(e)}}constructor({appId:e,appClientId:t,client:n,defaults:r}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=n.clientAnalyticsId,this.sdkVersion=St,this.client=n,this.defaults=r,this.fallbackApiUrl=n.fallbackApiUrl,this.baseFetch=bi.create({baseURL:this.defaults.baseURL,timeout:this.defaults.timeout,retry:3,retryDelay:500,retryStatusCodes:[408,409,425,500,502,503,504],credentials:"include",onRequest:async({request:e,options:t})=>{let n=new Headers(t.headers);n.set("privy-app-id",this.appId),this.appClientId&&n.set("privy-client-id",this.appClientId),n.set("privy-ca-id",this.clientAnalyticsId||""),n.set("privy-client",`react-auth:${this.sdkVersion}`);let r=as.includes(e.toString());if(!n.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:r});null!==e&&n.set("authorization",`Bearer ${e}`)}t.headers=n,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new X}})}}let os=/paymaster\.biconomy\.io\/api/i,ss={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const ls=(e,t)=>e&&os.test(e)?ss:t&&t.policy_id?{policyId:t.policy_id}:void 0;function cs(){return!(f&&window.location.origin.startsWith("http://localhost"))}const ds=_i((()=>({identityToken:null})));function hs(){let{identityToken:e}=ds();return{identityToken:e}}var us,ps=((us={}).PRIVY="privy_access_token",us.CUSTOMER="customer_access_token",us);class ms{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(xt)}get privyAccessToken(){return this._getToken(Pt)}_getToken(e){try{let t=ze.get(e);return"string"==typeof t?Lo.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=ze.get(Nt);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=ze.get(Ut(e));if("string"!=typeof t)return null;{let n=new Lo(t);return n.isExpired()?(ze.del(Ut(e)),null):n.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=Ti.get(Ot);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e="privy_access_token"){let t="string"==typeof this.getToken(e),n="string"==typeof this.refreshToken&&this.refreshToken!==Rt;return this.mightHaveServerCookies||t&&n}hasActiveAccessToken(e){let t=Lo.parse(this.getToken(e));return null!==t&&!t.isExpired(30)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(e,t){"string"==typeof t?ze.put(Ut(e),t):ze.del(Ut(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:n,is_new_user:r,oauth_tokens:a}=t;this.handleTokenResponse(t);let i=a?{provider:a.provider,accessToken:a.access_token,accessTokenExpiresInSeconds:a.access_token_expires_in_seconds,refreshToken:a.refresh_token,refreshTokenExpiresInSeconds:a.refresh_token_expires_in_seconds,scopes:a.scopes}:void 0;return this._trackAuthenticateEvents(e,r),{user:Mt(n),isNewUser:r,oAuthTokens:i}}catch(e){throw console.warn("Error authenticating session"),ee(e)}}_trackAuthenticateEvents(e,t){let n=function(e){return e instanceof To?"email":e instanceof Ro?"sms":e instanceof Wt?"siwe":e instanceof So?"guest":e instanceof Eo?"custom_auth":e instanceof Wo?e.meta.provider:null}(e);n&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:n,isNewUser:t}}),"siwe"===n&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:e.meta.connectorType,walletClientType:e.meta.walletClientType}})}async _link(e){try{let t=await e.link(),n=t.oauth_tokens,r=n?{provider:n.provider,accessToken:n.access_token,accessTokenExpiresInSeconds:n.access_token_expires_in_seconds,refreshToken:n.refresh_token,refreshTokenExpiresInSeconds:n.refresh_token_expires_in_seconds,scopes:n.scopes}:void 0;return{user:Mt(t),oAuthTokens:r}}catch(e){throw console.warn("Error linking account"),ee(e)}}async _refresh(){if(!this.api)throw new C("Session has no API instance");if(!this.client)throw new C("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let e=this.token,t=this.refreshToken;if(this.client.useServerCookies&&!this.mightHaveServerCookies&&this.token&&window.location.origin===this.client.apiUrl)return this.destroyLocalState(),null;try{let n;if(!(e&&t||this.mightHaveServerCookies))return null;{let r={};e&&(r.authorization=`Bearer ${e}`),n=await this.api.post(J,t?{refresh_token:t}:{},{headers:r})}return this.handleTokenResponse(n),Mt(n.user)}catch(e){if(e instanceof te&&e.privyErrorCode===M.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw ee(e)}}handleTokenResponse(e){e.session_update_action&&"set"!==e.session_update_action?"clear"===e.session_update_action?this.destroyLocalState():"ignore"===e.session_update_action&&(e.token&&(this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token)),e.identity_token&&this.storeIdentityToken(e.identity_token)):this._storeAllTokens(e)}_storeAllTokens(e){this.storeRefreshToken(e.refresh_token),this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token),e.identity_token&&this.storeIdentityToken(e.identity_token)}async _destroy(){try{await(this.api?.post(Q,{refresh_token:this.refreshToken}))}catch(e){console.warn("Error destroying session")}this.destroyLocalState()}destroyLocalState(){this.storeRefreshToken(null),this.storeCustomerAccessToken(null),this.storePrivyAccessToken(null),this.clearIdentityToken()}storeCustomerAccessToken(e){if("string"==typeof e){let t=ze.get(xt);if(ze.put(xt,e),!this.client?.useServerCookies){let t=Lo.parse(e)?.expiration;Ti.set(Lt,e,{sameSite:"Strict",secure:cs(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else ze.del(xt),Ti.remove(Lt),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(ze.put(Nt,e),this.client?.useServerCookies||Ti.set(Ot,"t",{sameSite:"Strict",secure:cs(),expires:30})):(ze.del(Nt),Ti.remove(Dt),Ti.remove(Ot))}storePrivyAccessToken(e){"string"==typeof e?ze.put(Pt,e):ze.del(Pt)}storeIdentityToken(e){if(ds.setState({identityToken:e}),this.client?.useServerCookies)return;ze.put(Ft,e);let t=Lo.parse(e)?.expiration;Ti.set(zt,e,{sameSite:"Strict",secure:cs(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){ze.del(Ft),ds.setState({identityToken:null}),Ti.remove(zt)}constructor(){this.authenticateOnce=new De((async e=>this._authenticate(e))),this.linkOnce=new De((async e=>this._link(e))),this.refreshOnce=new De(this._refresh.bind(this)),this.destroyOnce=new De(this._destroy.bind(this))}}let ws;var ys=0,gs="__private_"+ys+++"__getOrGenerateClientAnalyticsId";class fs{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:n,defaultChain:r,store:a,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new rs(this.appId,e,t,n,r,a,i,o,s,l,void 0,c))}generateApi(){let e=new is({appId:this.appId,appClientId:this.appClientId,client:this,defaults:{baseURL:this.apiUrl,timeout:this.timeout}});return this.session.api=e,e}updateApiUrl(e){this.apiUrl=e||this.fallbackApiUrl,this.api=this.generateApi(),e&&(this.useServerCookies=!0)}authenticate(){if(!this.authFlow)throw new C("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new C("No auth flow in progress.");let{oAuthTokens:e}=await this.session.link(this.authFlow);return{user:await this.getAuthenticatedUser(),oAuthTokens:e}}storeProviderAccessToken(e,t){this.session.storeProviderAccessToken(e,t)}getProviderAccessToken(e){return this.session.getProviderAccessToken(e)}async logout(){await this.session.destroy(),this.authFlow=void 0}clearProviderAcccessTokens(e){e.linkedAccounts.filter((e=>"cross_app"===e.type)).forEach((e=>{this.storeProviderAccessToken(e.providerApp.id,null)}))}startAuthFlow(e){return e.api=this.api,this.authFlow=e,this.authFlow}async initMfaSmsVerification(){try{await this.api.post(ne,{action:"verify"})}catch(e){throw T(e)}}async initMfaPasskeyVerification(){try{return(e=>({rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}))((await this.api.post(re,{})).options)}catch(e){throw T(e)}}async getCrossAppProviderDetails(e){try{return this._cachedProviderAppDetails[e]||(this._cachedProviderAppDetails[e]=await this.api.get(`/api/v1/apps/${e}/cross-app/details`)),this._cachedProviderAppDetails[e]}catch(e){console.error("Error fetching cross app provider details",e)}}async acceptTerms(){try{let e=await this.api.post(ae,{});return Mt(e)}catch(e){throw ee(e)}}async unlinkEmail(e){try{let t=await this.api.post(ie,{address:e});return await this.getAuthenticatedUser()??Mt(t)}catch(e){throw ee(e)}}async unlinkPhone(e){try{let t=await this.api.post(oe,{phoneNumber:e});return await this.getAuthenticatedUser()??Mt(t)}catch(e){throw ee(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(se,{address:e});return await this.getAuthenticatedUser()??Mt(t)}catch(e){throw ee(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(le,{address:e});return await this.getAuthenticatedUser()??Mt(t)}catch(e){throw ee(e)}}async unlinkOAuth(e,t){try{let n=await this.api.post(ce,{provider:e,subject:t});return await this.getAuthenticatedUser()??Mt(n)}catch(e){throw ee(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(de,{fid:e});return await this.getAuthenticatedUser()??Mt(t)}catch(e){throw ee(e)}}async unlinkTelegram(e){try{let t=await this.api.post(he,{telegram_user_id:e});return await this.getAuthenticatedUser()??Mt(t)}catch(e){throw ee(e)}}async revokeDelegatedWallet(){try{await this.api.post(ue,{})}catch(e){throw ee(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:n,options:r}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(Z,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:n?n.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:r?.keepAlive??!1})}catch(e){console.log("Unable to submit event. This is not an issue.")}}async signMoonpayOnRampUrl(e){try{return this.api.post(pe,e)}catch(e){throw ee(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(me,e)}catch(e){throw ee(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${we}?partnerUserId=${e}`)}catch(e){throw ee(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(ps.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(ps.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?Do.parse(this.session.getToken(e))?.appId!==this.appId?(await this.logout(),null):this.session.getToken(e):(this.session.destroyLocalState(),null):!t?.disableAutoRefresh&&this.session.hasRefreshCredentials(e)?(await this.session.refresh(),this.session.getToken(e)):null:null}async getSmartWalletsConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let n=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return n.enabled?{enabled:n.enabled,smartWalletType:n.smart_wallet_type,configuredNetworks:n.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:ls(e.paymaster_url,e.paymaster_context)})))}:{enabled:n.enabled}}catch(e){throw ee(e)}}async getServerConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let n=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:e}),r=n.telegram_auth_config?{botId:n.telegram_auth_config.bot_id,botName:n.telegram_auth_config.bot_name,linkEnabled:n.telegram_auth_config.link_enabled,seamlessAuthEnabled:n.telegram_auth_config.seamless_auth_enabled}:void 0,a=n.funding_config?{methods:n.funding_config.methods,options:n.funding_config.options,defaultRecommendedAmount:n.funding_config.default_recommended_amount,defaultRecommendedCurrency:n.funding_config.default_recommended_currency,promptFundingOnWalletCreation:n.funding_config.prompt_funding_on_wallet_creation,crossChainBridgingEnabled:n.funding_config.cross_chain_bridging_enabled}:void 0;return{id:n.id,name:n.name,verificationKey:n.verification_key,logoUrl:n.logo_url||void 0,accentColor:n.accent_color||void 0,showWalletLoginFirst:n.show_wallet_login_first,allowlistConfig:{errorTitle:n.allowlist_config.error_title,errorDetail:n.allowlist_config.error_detail,errorCtaText:n.allowlist_config.cta_text,errorCtaLink:n.allowlist_config.cta_link},walletAuth:n.wallet_auth,solanaWalletAuth:n.solana_wallet_auth,emailAuth:n.email_auth,smsAuth:n.sms_auth,googleOAuth:n.google_oauth,twitterOAuth:n.twitter_oauth,discordOAuth:n.discord_oauth,githubOAuth:n.github_oauth,spotifyOAuth:n.spotify_oauth,instagramOAuth:n.instagram_oauth,tiktokOAuth:n.tiktok_oauth,linkedinOAuth:n.linkedin_oauth,appleOAuth:n.apple_oauth,farcasterAuth:n.farcaster_auth,passkeyAuth:n.passkey_auth,passkeysForSignupEnabled:n.passkeys_for_signup_enabled,telegramAuth:n.telegram_auth,disablePlusEmails:n.disable_plus_emails,termsAndConditionsUrl:n.terms_and_conditions_url,embeddedWalletConfig:{ethereum:{createOnLogin:n.embedded_wallet_config.ethereum?.create_on_login??n.embedded_wallet_config.create_on_login},solana:{createOnLogin:n.embedded_wallet_config.solana?.create_on_login??"off"},userOwnedRecoveryOptions:n.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:n.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:n.privacy_policy_url,requireUsersAcceptTerms:n.require_users_accept_terms,customApiUrl:n.custom_api_url,walletConnectCloudProjectId:n.wallet_connect_cloud_project_id,fiatOnRampEnabled:n.fiat_on_ramp_enabled,captchaEnabled:n.captcha_enabled,captchaSiteKey:n.captcha_site_key,createdAt:new Date(1e3*n.created_at),updatedAt:new Date(1e3*n.updated_at),mfaMethods:n.mfa_methods,enforceWalletUis:n.enforce_wallet_uis,legacyWalletUiConfig:n.legacy_wallet_ui_config,telegramAuthConfiguration:r,fundingConfig:a}}catch(e){throw ee(e)}}async getUsdTokenPrice(e){try{return(await this.api.get(`/api/v1/token_price?chainId=${e.id}&tokenSymbol=${e.nativeCurrency.symbol}`)).usd}catch(t){return void console.error(`Unable to fetch token price for chain with id ${e.id}`)}}async getUsdPriceForSol(){try{return(await this.api.get("/api/v1/token_price?chainId=0&tokenSymbol=SOL")).usd}catch(e){return void console.error("Unable to fetch token price for SOL")}}async getSplTokenMetadata({mintAddress:e,cluster:t}){try{return await this.api.get(`/api/v1/spl_token_info?mint_address=${e}&cluster=${t}`)}catch(n){return void console.error(`Unable to fetch token metadata for ${t}:${e}`)}}async requestFarcasterSignerStatus(e){try{return await this.api.post("/api/v1/farcaster/signer/status",{ed25519_public_key:e})}catch(e){throw console.error("Unable to fetch Farcaster signer status"),e}}async generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(ye,{address:e,token:t})).nonce}catch(e){throw ee(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:n,walletClientType:r,connectorType:a,mode:i}){return await this.api.post(ge,{message:e,signature:t,chainId:n,walletClientType:r,connectorType:a,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:n,walletClientType:r,connectorType:a}){return await this.api.post(fe,{message:e,signature:t,chainId:n,walletClientType:r,connectorType:a})}async linkSmartWallet({message:e,signature:t,smartWalletType:n}){try{let r=await this.api.post(ve,{message:e,signature:t,smart_wallet_type:n});return Mt(r)}catch(e){throw ee(e)}}async linkWithSiwe({message:e,signature:t,chainId:n,walletClientType:r,connectorType:a}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:n,walletClientType:r,connectorType:a});return Mt(i)}catch(e){throw ee(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(ke,{address:e,token:t})).nonce}catch(e){throw ee(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:n,connectorType:r,mode:a}){return await this.api.post(Ae,{message:e,signature:t,walletClientType:n,connectorType:r,mode:a})}async sendAccountTransferRequest({nonce:e,account:t,accountType:n,externalWalletMetadata:r,telegramAuthResult:a,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s}){try{let l,c;switch(n){case"email":l=Ie,c={nonce:e,email:t};break;case"sms":l=_e,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=Te,!r)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...r};break;case"farcaster":l=be,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=Ee,c={nonce:e,telegram_auth_result:a,telegram_web_app_data:i};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:l=Ce,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??Mt(d)}catch(e){throw ee(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:n,connectorType:r}){return await this.api.post(Se,{message:e,signature:t,walletClientType:n,connectorType:r})}async linkWithSiws({message:e,signature:t,walletClientType:n,connectorType:r}){try{let a=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:n,connectorType:r});return Mt(a)}catch(e){throw ee(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(We);return this.session.updateIdentityToken(e.identity_token),Mt(e.user)}catch(e){throw ee(e)}}async scanTransaction(e){try{return await this.api.post(xe,e)}catch(e){throw ee(e)}}constructor({apiUrl:e=qt,appId:t,appClientId:n,timeout:r=Bt}){Object.defineProperty(this,gs,{value:vs}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==qt&&e.startsWith("https://privy."),this.timeout=r,this.appId=t,this.appClientId=n,this.clientAnalyticsId=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}(this,gs)[gs](),ws||(ws=new ms),this.session=ws,this.api=this.generateApi(),this.session.client=this}}function vs(){if("undefined"==typeof window)return null;try{let e=ze.get(Vt);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=pi();try{return ze.put(Vt,e),e}catch(t){return e}}const ks=e=>{let{enabled:n,siteKey:r,appId:a,setError:i,setToken:l,setExecuting:c,ref:d}=jt(),[,h]=o((()=>r?.split("t:")||[]),[r]);if(s((()=>d.current?.remove),[]),!n)return null;if(!h)throw Error("Unsupported captcha site key");/*#__PURE__*/return t("div",{className:"hidden h-0 w-0",children:/*#__PURE__*/t(Ii,{...e,ref:d,siteKey:h,options:{action:a,size:"invisible",...e.delayedExecution?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{e.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:()=>{e.onError?.(),i("Captcha failed"),c(!1)},onSuccess:t=>{e.onSuccess?.(t),l(t),c(!1)},onExpire:()=>{e.onExpire?.();try{d.current?.reset(),i(void 0),l(void 0)}catch(e){i("expired_and_failed_reset")}}})})};function As(e){Ht("configureMfa",e)}let Cs=Array(6).fill("");var Es,bs=((Es=bs||{})[Es.RESET_AFTER_DELAY=0]="RESET_AFTER_DELAY",Es[Es.CLEAR_ON_NEXT_VALID_INPUT=1]="CLEAR_ON_NEXT_VALID_INPUT",Es);function Ts(e){return/^[0-9]{1}$/.test(e)}function _s(e){return 6===e.length&&e.every(Ts)}const Is=({onChange:e,disabled:a,errorReasonOverride:i,success:o})=>{let[s,c]=l(Cs),[d,h]=l(null),[u,p]=l(null),m=async t=>{t.preventDefault();let n=t.currentTarget.value.replace(/\s+/g,"");if(""===n)return;let r=s.reduce(((e,t)=>e+Number(Ts(t))),0),a=n.split(""),i=!a.every(Ts),o=a.length+r>6;if(i)return h("Passcode can only be numbers"),void p(1);if(o)return h("Passcode must be exactly 6 numbers"),void p(1);h(null),p(null);let l=Number(t.currentTarget.name?.charAt(4)),d=[...n||[""]].slice(0,6-l),u=[...s.slice(0,l),...d,...s.slice(l+d.length)];c(u);let m=Math.min(Math.max(l+d.length,0),5),w=document.querySelector(`input[name=pin-${m}]`);if(w?.focus(),_s(u))try{await e(u.join(""));let t=document.querySelector(`input[name=pin-${m}]`);t?.blur()}catch(t){p(1),h(t.message)}else try{await e(null)}catch(t){p(1),h(t.message)}},y=o?"success":!(!i&&!d)?"fail":"";/*#__PURE__*/return t(r,{children:/*#__PURE__*/n(Ss,{children:[/*#__PURE__*/t("div",{children:s.map(((n,r)=>/*#__PURE__*/t("input",{name:`pin-${r}`,type:"text",value:s[r],onChange:m,onKeyUp:t=>{"Backspace"===t.key&&(t=>{1===u&&(h(null),p(null));let n=[...s.slice(0,t),"",...s.slice(t+1)];if(c(n),t>0){let e=document.querySelector(`input[name=pin-${t-1}]`);e?.focus()}_s(n)?e(n.join("")):e(null)})(r)},inputMode:"numeric",autoFocus:0===r,pattern:"[0-9]",className:y,autoComplete:w?"one-time-code":"off",disabled:a},r)))}),/*#__PURE__*/t("div",{children:/*#__PURE__*/t(Ws,{$fail:!!i||!!d,children:i||d})})]})})};let Ss=/*#__PURE__*/Si.div.withConfig({displayName:"PinInputContainer",componentId:"sc-7a171f6-0"})(["display:flex;flex-direction:column;width:100%;gap:8px;@media (max-width:440px){margin-top:8px;margin-bottom:8px;}> div:nth-child(1){display:flex;justify-content:center;gap:0.5rem;width:100%;border-radius:var(--privy-border-radius-md);> input{border:1px solid var(--privy-color-foreground-4);background:var(--privy-color-background);border-radius:var(--privy-border-radius-md);padding:8px 10px;height:58px;width:46px;text-align:center;font-size:18px;}> input:disabled{background:var(--privy-color-background-2);}> input:focus{border:1px solid var(--privy-color-accent);}> input:invalid{border:1px solid var(--privy-color-error);}> input.success{border:1px solid var(--privy-color-success);}> input.fail{border:1px solid var(--privy-color-error);animation:shake 180ms;animation-iteration-count:2;}}@keyframes shake{0%{transform:translate(1px,0px);}33%{transform:translate(-1px,0px);}67%{transform:translate(-1px,0px);}100%{transform:translate(1px,0px);}}"]),Ws=/*#__PURE__*/Si.div.withConfig({displayName:"InputHelp",componentId:"sc-7a171f6-1"})(["line-height:20px;font-size:13px;display:flex;justify-content:flex-start;width:100%;color:",";"],(e=>e.$fail?"var(--privy-color-error)":"var(--privy-color-foreground-3)"));const xs=({pendingTransaction:e})=>{let{getAccessToken:n}=$t(),{wallets:r}=Kt(),{walletProxy:a,rpcConfig:i,chains:c,appId:d,nativeTokenSymbolForChainId:h}=Pe(),[u,p]=l(null),[m,w]=l(e),{tokenPrice:y}=Yt(m.chainId),g=h(e.chainId)||"ETH",f=o((()=>r.find((e=>"privy"===e.walletClientType))),[r]);return s((()=>{(async function(){if(!await n()||!a||!f)return m;let e=mt(m.chainId,c,i,{appId:d}),t=await Gt(m,e,f.address);return p(Li(BigInt(t.gas??0))),t})().then(w).catch(console.error)}),[a]),f?/*#__PURE__*/t(Ps,{children:/*#__PURE__*/t(Xt,{from:f.address,to:m.to,txn:m,gas:u??void 0,tokenPrice:y,tokenSymbol:g})}):null};let Ps=/*#__PURE__*/Si.div.withConfig({displayName:"TransactionInfoWrapper",componentId:"sc-731f1950-0"})(["width:100%;padding:1rem 0;"]);function Ns(){let{promptMfa:e,init:t,submit:n,cancel:r,mfaMethods:a}=h(Jt);return{promptMfa:e,init:t,submit:n,cancel:r,mfaMethods:a}}const Us=({hasBlockingError:e,error:a,onClose:i,onBack:o,handleSubmit:s,account:l,submitSuccess:c})=>{let{pendingTransaction:d}=Pe();/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{onClose:i},"header"),/*#__PURE__*/t(Zt,{children:/*#__PURE__*/n("div",{children:[/*#__PURE__*/t(en,{success:c,fail:!!a}),/*#__PURE__*/t(a?Hi:tn,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/t(nn,{style:{marginTop:"1rem"},children:"Verifying with passkey"}),/*#__PURE__*/n(rn,{children:[/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(Mi,{})}),"Approve this action using your touch, face, PIN, or hardware key."]}),/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(ji,{})}),"You last added a passkey on"," ",l?.firstVerifiedAt?.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),"."]})]}),d&&/*#__PURE__*/t(sn,{children:/*#__PURE__*/t(xs,{pendingTransaction:d})}),a&&/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(ln,{style:{marginTop:"1.25rem"},children:a.message}),/*#__PURE__*/t(cn,{disabled:e,onClick:s,style:{marginTop:"1.25rem"},children:"Try again"})]}),o&&/*#__PURE__*/t(dn,{style:{marginTop:"1rem"},onClick:o,children:"Choose another method"}),/*#__PURE__*/t(hn,{})]})},Os=({open:e,onClose:a})=>{let{user:i}=$t(),[o,c]=l(i?.mfaMethods[0]??null),{init:d,cancel:h,submit:p}=Ns(),[m,w]=l(!1),[y,g]=l(!1),[f,v]=l(null),[k,A]=l(null);s((()=>{c(i?.mfaMethods[0]??null)}),[i?.mfaMethods]);let C=u(!1);s((()=>{!C.current&&o&&e&&(C.current=!0,T(o).finally((()=>{C.current=!1})))}),[e]);let E=e=>fn(e)?(w(!0),Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.")):vn(e)?(w(!1),Error("The code you entered is not valid")):kn(e)?(w(!0),Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.")):(console.error(e),w(!1),Error("Something went wrong."));async function b(e){A(null);try{if(!e||!o)return;await p(o,e),g(!0),w(!1),a()}catch(e){throw E(e)}}async function T(e){if("passkey"!==e)try{c(e),await d(e)}catch(e){console.error(e)}else try{c(e);let t=await d(e);if(!t)throw Error("something went wrong");v(t),await p(e,t),g(!0),w(!1),a()}catch(e){A(E(e))}}let _=()=>{c(null),A(null),h(),a()};return e&&i?"passkey"===o?/*#__PURE__*/t(Us,{account:i.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],selectedMethod:o,submitSuccess:y,hasBlockingError:m,error:k,onClose:_,onBack:()=>{c(null),A(null)},handleSubmit:()=>b(f).catch(A)}):o?/*#__PURE__*/t(Rs,{submitSuccess:y,hasBlockingError:m,handleSubmitCode:b,selectedMethod:o,onClose:_,onBack:i.mfaMethods.length>1?()=>c(null):void 0}):/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Qt,{onClose:_},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Mi,{})}),/*#__PURE__*/t(nn,{children:"Verify your identity"}),/*#__PURE__*/t(pn,{children:"Choose a verification method"}),/*#__PURE__*/n(mn,{children:[i.mfaMethods.includes("totp")&&/*#__PURE__*/n(wn,{onClick:()=>T("totp"),children:[/*#__PURE__*/t(Ui,{}),"Authenticator App"]},"totp"),i.mfaMethods.includes("sms")&&/*#__PURE__*/n(wn,{onClick:()=>T("sms"),children:[/*#__PURE__*/t(Ri,{}),"SMS"]},"sms"),i.mfaMethods.includes("passkey")&&/*#__PURE__*/n(wn,{onClick:()=>T("passkey"),children:[/*#__PURE__*/t(Oi,{}),"Passkey"]},"passkey")]}),/*#__PURE__*/t(hn,{})]}):null};let Rs=({selectedMethod:e,submitSuccess:a,hasBlockingError:i,onClose:o,onBack:s,handleSubmitCode:l})=>{let{app:c}=yn(),{pendingTransaction:d}=Pe();switch(e){case"sms":/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{onClose:o},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ri,{})}),/*#__PURE__*/t(nn,{children:"Enter verification code"}),/*#__PURE__*/n(sn,{children:[/*#__PURE__*/t(Is,{success:a,disabled:i,onChange:l}),/*#__PURE__*/n(pn,{children:["To continue, please enter the 6-digit code sent to your ",/*#__PURE__*/t("strong",{children:"mobile device"})]}),d&&/*#__PURE__*/t(xs,{pendingTransaction:d})]}),s&&/*#__PURE__*/t(dn,{theme:c?.appearance.palette.colorScheme,onClick:s,children:"Choose another method"}),/*#__PURE__*/t(gn,{onClick:o,children:"Not now"}),/*#__PURE__*/t(hn,{})]});case"totp":/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{onClose:o},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ui,{})}),/*#__PURE__*/t(nn,{children:"Enter verification code"}),/*#__PURE__*/n(sn,{children:[/*#__PURE__*/t(Is,{success:a,disabled:i,onChange:l}),/*#__PURE__*/n(pn,{children:["To continue, please enter the 6-digit code generated from your"," ",/*#__PURE__*/t("strong",{children:"authenticator app"})]}),d&&/*#__PURE__*/t(xs,{pendingTransaction:d})]}),s&&/*#__PURE__*/t(dn,{theme:c?.appearance.palette.colorScheme,onClick:s,children:"Choose another method"}),/*#__PURE__*/t(gn,{onClick:o,children:"Not now"}),/*#__PURE__*/t(hn,{})]});default:return null}};const Ms=/*#__PURE__*/Wi([":root{--privy-border-radius-sm:6px;--privy-border-radius-md:12px;--privy-border-radius-mdlg:16px;--privy-border-radius-lg:24px;--privy-border-radius-full:9999px;--privy-color-background:",";--privy-color-background-2:",";--privy-color-background-3:",";--privy-color-foreground:",";--privy-color-foreground-2:",";--privy-color-foreground-3:",";--privy-color-foreground-4:",";--privy-color-foreground-accent:",";--privy-color-accent:",";--privy-color-accent-light:",";--privy-color-accent-lightest:",";--privy-color-accent-dark:",";--privy-color-accent-darkest:",";--privy-color-success:",";--privy-color-success-dark:",";--privy-color-success-light:",";--privy-color-error:",";--privy-color-error-light:",";--privy-color-warn:",";--privy-color-warn-light:",";--privy-height-modal-full:620px;--privy-height-modal-compact:480px;};"],(e=>e.theme.background),(e=>e.theme.background2),(e=>e.theme.background3),(e=>e.theme.foreground),(e=>e.theme.foreground2),(e=>e.theme.foreground3),(e=>e.theme.foreground4),(e=>e.theme.foregroundAccent),(e=>e.theme.accent),(e=>e.theme.accentLight),(e=>e.theme.accentLightest),(e=>e.theme.accentDark),(e=>e.theme.accentDarkest),(e=>e.theme.success),(e=>e.theme.successDark),(e=>e.theme.successLight),(e=>e.theme.error),(e=>e.theme.errorLight),(e=>e.theme.warn),(e=>e.theme.warnLight)),Ls=/*#__PURE__*/Si.div.withConfig({displayName:"StylesWrapper",componentId:"sc-bc1e45b4-0"})([""," color:var(--privy-color-foreground-2);h3{font-size:16px;line-height:24px;font-weight:500;color:var(--privy-color-foreground-2);}h4{font-size:14px;line-height:20px;font-weight:500;color:var(--privy-color-foreground);}p{font-size:13px;line-height:20px;color:var(--privy-color-foreground-2);}button:focus,input:focus,optgroup:focus,select:focus,textarea:focus{outline:none;border-color:var(--privy-color-accent-light);box-shadow:0 0 0 1px var(--privy-color-accent-light);}.mobile-only{@media (min-width:441px){display:none;}}@keyframes fadein{0%{opacity:0;}100%{opacity:1;}}"],"\n *,\n ::before,\n ::after {\n box-sizing: border-box;\n border-width: 0;\n border-style: solid;\n }\n\n line-height: 1.15;\n -webkit-text-size-adjust: 100%;\n -moz-tab-size: 4;\n tab-size: 4;\n font-feature-settings: normal;\n\n margin: 0;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji';\n\n hr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n }\n\n abbr:where([title]) {\n text-decoration: underline dotted;\n }\n\n h1,\n h2,\n h3,\n h4,\n h5,\n h6 {\n font-size: inherit;\n font-weight: inherit;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji';\n display: inline;\n }\n\n a {\n color: inherit;\n text-decoration: inherit;\n }\n\n b,\n strong {\n font-weight: bolder;\n }\n\n code,\n kbd,\n samp,\n pre {\n font-family: ui-monospace, SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 1em;\n }\n\n small {\n font-size: 80%;\n }\n\n sub,\n sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n }\n\n sub {\n bottom: -0.25em;\n }\n\n sup {\n top: -0.5em;\n }\n\n table {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n }\n\n button,\n input,\n optgroup,\n select,\n textarea {\n font-family: inherit;\n font-size: 100%;\n font-weight: inherit;\n line-height: inherit;\n color: inherit;\n margin: 0;\n padding: 0;\n }\n\n button,\n select {\n text-transform: none;\n }\n\n button,\n [type='button'],\n [type='reset'],\n [type='submit'] {\n -webkit-appearance: button;\n background-color: transparent;\n background-image: none;\n }\n\n ::-moz-focus-inner {\n border-style: none;\n padding: 0;\n }\n\n :-moz-focusring {\n outline: 1px dotted ButtonText;\n }\n\n :-moz-ui-invalid {\n box-shadow: none;\n }\n\n legend {\n padding: 0;\n }\n\n progress {\n vertical-align: baseline;\n }\n\n ::-webkit-inner-spin-button,\n ::-webkit-outer-spin-button {\n height: auto;\n }\n\n [type='search'] {\n -webkit-appearance: textfield;\n outline-offset: -2px;\n }\n\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n\n ::-webkit-file-upload-button {\n -webkit-appearance: button;\n font: inherit;\n }\n\n summary {\n display: list-item;\n }\n\n blockquote,\n dl,\n dd,\n h1,\n h2,\n h3,\n h4,\n h5,\n h6,\n hr,\n figure,\n p,\n pre {\n margin: 0;\n }\n\n fieldset {\n margin: 0;\n padding: 0;\n }\n\n legend {\n padding: 0;\n }\n\n ol,\n ul,\n menu {\n list-style: none;\n margin: 0;\n padding: 0;\n }\n\n textarea {\n resize: vertical;\n }\n\n input::placeholder,\n textarea::placeholder {\n opacity: 1;\n color: #9ca3af;\n }\n\n button,\n [role='button'] {\n cursor: pointer;\n }\n\n :disabled {\n cursor: default;\n }\n\n img,\n svg,\n video,\n canvas,\n audio,\n iframe,\n embed,\n object {\n display: block;\n }\n\n img,\n video {\n max-width: 100%;\n height: auto;\n }\n\n [hidden] {\n display: none;\n }\n"),Ds=({children:e,open:r,onClick:a,...o})=>/*#__PURE__*/t($i,{show:r,as:i.Fragment,children:/*#__PURE__*/n(Ki,{onClose:a,...o,as:zs,children:[/*#__PURE__*/t(Yi,{as:i.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/t(Fs,{id:"privy-dialog-backdrop","aria-hidden":"true"})}),/*#__PURE__*/t(qs,{children:/*#__PURE__*/t(Yi,{as:i.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/t(Gi,{as:Bs,children:e})})})]})});let Fs=/*#__PURE__*/Si.div.withConfig({displayName:"Backdrop",componentId:"sc-3cfde0b5-0"})(["position:fixed;inset:0;transition:backdrop-filter 100ms ease;backdrop-filter:blur(3px);-webkit-backdrop-filter:blur(3px);&.entering,&.leaving{backdrop-filter:unset;-webkit-backdrop-filter:unset;}"]),zs=/*#__PURE__*/Si.div.withConfig({displayName:"DialogWrapper",componentId:"sc-3cfde0b5-1"})(["position:relative;z-index:999999;"]),qs=/*#__PURE__*/Si.div.withConfig({displayName:"DialogContainer",componentId:"sc-3cfde0b5-2"})(["position:fixed;inset:0;display:flex;align-items:center;justify-content:center;width:100vw;min-height:100vh;"]);const Bs=/*#__PURE__*/Si.div.withConfig({displayName:"Panel",componentId:"sc-3cfde0b5-3"})(["padding:0;background:transparent;border:none;width:100%;pointer-events:auto;outline:none;display:block;@media (max-width:440px){opacity:1;transform:translate3d(0,0,0);transition:transform 200ms ease-in;position:fixed;bottom:0;&.entering,&.leaving{opacity:0;transform:translate3d(0,100%,0);transition:transform 150ms ease-in 0ms,opacity 0ms ease 150ms;}}@media (min-width:441px){opacity:1;transition:opacity 100ms ease-in;&.entering,&.leaving{opacity:0;transition-delay:5ms;}margin:auto;width:360px;box-shadow:0px 8px 36px rgba(55,65,81,0.15);border-radius:var(--privy-border-radius-lg);}"]),Vs=/*#__PURE__*/Si.div.withConfig({displayName:"CenterItem",componentId:"sc-3cfde0b5-4"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;"]);let js=({isMfaVerifying:e,onMfaVerificationComplete:a})=>{let{ready:i,isModalOpen:o}=$t(),{headless:l}=An(),{currentScreen:c}=yn(),{status:d,execute:h,reset:u,enabled:p}=jt(),m=o&&c&&c.isCaptchaRequired&&!l&&"ready"===d;return s((()=>{m&&h()}),[m]),s((()=>{!o&&p&&u()}),[o,p]),c&&!i&&c.isShownBeforeReady?/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Qt,{}),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/t(Vs,{children:/*#__PURE__*/t(En,{})}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(hn,{})]}):!c&&e?/*#__PURE__*/t(Os,{open:e,onClose:a}):c?/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Tn,{$if:!!e,children:/*#__PURE__*/t(c.component,{})}),/*#__PURE__*/t(Tn,{$if:!e,children:/*#__PURE__*/t(Os,{open:e,onClose:a})})]}):null},Hs=({isMfaVerifying:e,onMfaVerificationComplete:n})=>{let r=u(null);/*#__PURE__*/return t(Ys,{style:{height:Pi(r)},id:"privy-modal-content",children:/*#__PURE__*/t("div",{ref:r,children:/*#__PURE__*/t(js,{isMfaVerifying:e,onMfaVerificationComplete:n})})})};const $s=({open:e})=>{let n=An(),{gracefulClosePrivyModal:r}=(()=>{let{closePrivyModal:e}=Pe(),{onUserCloseViaDialogOrKeybindRef:t}=yn();return{gracefulClosePrivyModal:p((()=>{if(!t?.current)return e({shouldCallAuthOnSuccess:!1});t.current()}),[e])}})(),[a,i]=l(!1);As({onMfaRequired:()=>{n.mfa.noPromptOnMfaRequired||i(!0)}});let o=e||a;return n.render.standalone?/*#__PURE__*/t(Ls,{children:/*#__PURE__*/t(Ks,{id:"privy-modal-content",children:/*#__PURE__*/t(js,{isMfaVerifying:a,onMfaVerificationComplete:()=>i(!1)})})}):/*#__PURE__*/t(Ds,{open:o,id:"privy-dialog","aria-label":"log in or sign up","aria-labelledby":"privy-dialog-title",onClick:()=>r(),children:/*#__PURE__*/t(Ls,{children:/*#__PURE__*/t(Hs,{isMfaVerifying:a,onMfaVerificationComplete:()=>i(!1)})})})};let Ks=/*#__PURE__*/Si.div.withConfig({displayName:"ContentWrapper",componentId:"sc-df48cc55-0"})(["display:flex;flex-direction:column;text-align:center;font-size:14px;line-height:20px;width:100%;background:var(--privy-color-background);padding:0 16px;"]),Ys=/*#__PURE__*/Si(Ks).withConfig({displayName:"BaseModal",componentId:"sc-df48cc55-1"})(["transition:height 150ms ease-out;overflow-x:hidden;overflow-y:auto;scrollbar-width:none;max-height:calc(100svh - 32px);border-radius:var(--privy-border-radius-lg) var(--privy-border-radius-lg) 0 0;box-shadow:0px 0px 36px rgba(55,65,81,0.15);@media (min-width:441px){box-shadow:0px 8px 36px rgba(55,65,81,0.15);border-radius:var(--privy-border-radius-lg);}"]);function Gs(e){let n=u(null),r=u();return s((()=>{r.current?.remove(),r.current=function({botUsername:e,scriptHost:t}){let n=document.createElement("script"),{origin:r}=new URL(t);return n.async=!0,n.src=`${r}/js/telegram-login.js`,n.setAttribute("data-telegram-login",e),n.setAttribute("data-request-access","write"),n.setAttribute("data-lang","en"),n}(e),n.current?.after(r.current)}),[e]),/*#__PURE__*/t("div",{ref:n,hidden:!0})}async function Xs(e,t,n,r,a,i=!1){let o=i,s=async s=>{if(o&&t&&t.length>0){s===(i?0:1)?a("configureMfa","onMfaRequired",{mfaMethods:t}):r.current?.reject(new _n("missing_or_invalid_mfa","MFA verification failed, retry."));let o=await new Promise(((e,t)=>{n.current={resolve:e,reject:t},setTimeout((()=>{let e=new _n("mfa_timeout","Timed out waiting for MFA code");r.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),r.current?.resolve(void 0);break}catch(e){if("missing_or_invalid_mfa"!==e.type)throw r.current?.resolve(void 0),e;o=!0}if(null===l){let e=new _n("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw r.current?.reject(e),e}return l}var Js;let Qs=(Js=0,()=>"id-"+Js++);function Zs(e){return void 0!==e.error}let el=new class{enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let n=this.callbacks[t];if(!n)throw Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:signer:create":case"privy:wallets:add":case"privy:wallets:import":case"privy:wallets:set-recovery":case"privy:wallets:connect":case"privy:wallets:recover":case"privy:wallets:rpc":case"privy:wallet:create":case"privy:mfa:verify":case"privy:mfa:init-enrollment":case"privy:mfa:submit-enrollment":case"privy:mfa:unenroll":case"privy:mfa:clear":case"privy:auth:unlink-passkey":case"privy:farcaster:init-signer":case"privy:farcaster:sign":case"privy:solana-wallet:create":case"privy:delegated-actions:consent":return n;default:throw Error(`invalid wallet event type ${e}`)}}constructor(){this.callbacks={}}},tl=new Map,nl=(e,t)=>"bigint"==typeof t?t.toString():t;function rl(e,t,n,r){let a=n.contentWindow;if(!a)throw Error("iframe not initialized");let i=((e,t)=>`${e}${JSON.stringify(t,nl)}`)(e,t);if("privy:wallet:create"===e){let e=tl.get(i);if(e)return e}let o=new Promise(((n,i)=>{let o=Qs();el.enqueue(o,{resolve:n,reject:i}),a.postMessage({id:o,event:e,data:t},r)})).finally((()=>{tl.delete(i)}));return tl.set(i,o),o}function al(e){let n=In(),r=u(null),a=u(e.mfaMethods),i=Sn(),[o,c]=l(!1);return s((()=>{a.current=e.mfaMethods}),[e.mfaMethods]),s((()=>{if(!o)return;let t=r.current;if(!t)return;function n(t){var n;t&&t.origin===e.origin&&"string"==typeof(n=t.data).event&&/^privy:.+/.test(n.event)&&function(e){switch(e.event){case"privy:iframe:ready":let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data);case"privy:signer:create":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:add":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:set-recovery":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:connect":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:recover":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:rpc":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallet:create":let n=el.dequeue(e.event,e.id);return Zs(e)?n.reject(new _n(e.error.type,e.error.message)):n.resolve(e.data);case"privy:wallets:import":let r=el.dequeue(e.event,e.id);return Zs(e)?r.reject(new _n(e.error.type,e.error.message)):r.resolve(e.data);case"privy:mfa:verify":let a=el.dequeue(e.event,e.id);return Zs(e)?a.reject(new _n(e.error.type,e.error.message)):a.resolve(e.data);case"privy:mfa:init-enrollment":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:auth:unlink-passkey":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let i=el.dequeue(e.event,e.id);return Zs(e)?i.reject(new _n(e.error.type,e.error.message)):i.resolve(e.data);case"privy:farcaster:init-signer":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=el.dequeue(e.event,e.id);return Zs(e)?t.reject(new _n(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(t.data)}let s={createSigner:n=>Xs((r=>rl("privy:signer:create",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),addWallet:n=>Xs((r=>rl("privy:wallets:add",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),setRecovery:n=>Xs((r=>rl("privy:wallets:set-recovery",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),connect:n=>Xs((r=>rl("privy:wallets:connect",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),recover:n=>Xs((r=>rl("privy:wallets:recover",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i,!n.recoveryAccessToken&&!n.recoveryPassword&&!n.recoverySecretOverride),rpc:n=>Xs((r=>rl("privy:wallets:rpc",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),create:n=>rl("privy:wallet:create",n,t,e.origin),importWallet:n=>rl("privy:wallets:import",n,t,e.origin),createSolana:n=>Xs((r=>rl("privy:solana-wallet:create",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),createDelegatedAction:n=>rl("privy:delegated-actions:consent",n,t,e.origin),verifyMfa:n=>Xs((r=>rl("privy:mfa:verify",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i,!0),initEnrollMfa:n=>Xs((r=>rl("privy:mfa:init-enrollment",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),submitEnrollMfa:n=>Xs((r=>rl("privy:mfa:submit-enrollment",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),unenrollMfa:n=>Xs((r=>rl("privy:mfa:unenroll",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),clearMfa:n=>rl("privy:mfa:clear",n,t,e.origin),unlinkPasskeyAccount:n=>Xs((r=>rl("privy:auth:unlink-passkey",{...n,...r},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),initFarcasterSigner:n=>rl("privy:farcaster:init-signer",n,t,e.origin),signFarcasterMessage:n=>rl("privy:farcaster:sign",n,t,e.origin)};window.addEventListener("message",n);let l=new AbortController;return Wn((()=>rl("privy:iframe:ready",{},t,e.origin)),{abortSignal:l.signal}).then((()=>e.onLoad(s)),((...t)=>{console.warn("Privy iframe failed to load: ",...t),e.onLoadFailed()})),()=>{window.removeEventListener("message",n),l.abort()}}),[o]),n?
2
- /*#__PURE__*/t("iframe",{ref:r,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>c(!0),src:xn(e.origin,`/apps/${e.appId}/embedded-wallets`,{caid:e.clientAnalyticsId,client_id:e.appClientId})}):null}const il=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));class ol{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 Zc({message:e.params.message,options:{address:this.address,uiOptions:{}}})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await $c())throw Error("User must be authenticated to use embedded Solana wallet");if(!await Qc())throw new C("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}}async function sl({tx:e,accessToken:t,walletProxy:n,entropyId:r,entropyIdVerifier:a,transactingWalletAddress:i,transactingWalletIndex:o}){let s=Nn(e,i),l=Un(e)?Buffer.from(e.message.serialize()):e.serializeMessage(),{response:c}=await n.rpc({accessToken:t,entropyId:r,entropyIdVerifier:a,chainType:"solana",hdWalletIndex:o,request:{method:"signMessage",params:{message:l.toString("base64")}}}),d=c.data.signature,h=Buffer.from(d,"base64");e.addSignature(s,h)}async function ll({tx:e,connection:t,accessToken:n,walletProxy:r,entropyId:a,entropyIdVerifier:i,transactingWalletAddress:o,transactingWalletIndex:s,transactionOptions:l}){let c;try{await sl({tx:e,accessToken:n,walletProxy:r,entropyId:a,entropyIdVerifier:i,transactingWalletAddress:o,transactingWalletIndex:s});let d=e.serialize();c=await t.sendRawTransaction(d,l);let h=await t.confirmTransaction(c);if(h.value.err||h.value.err){let e=h.value.err||h.value.err;if("string"==typeof e)throw Error(e);throw e}return{signature:c,signedTransaction:e,receipt:await t.getParsedTransaction(c,{maxSupportedTransactionVersion:0})}}catch(e){throw e.txSignature=c,e}}const cl=()=>{let e=An();s((()=>{(async e=>{let t=new URL("v3/wallets","https://explorer-api.walletconnect.com");t.searchParams.append("projectId",e);let n=await fetch(t);return n.ok?Object.values((await n.json()).listings).sort((({slug:e},{slug:t})=>"rainbow"===e&&"metamask"===t?1:"metamask"===e||"rainbow"===e?-1:1)):(console.debug(`Failed to fetch WalletConnect listings: ${await n.text().catch((()=>"No response."))}`),[])})(e.walletConnectCloudProjectId).then((e=>On({listings:e}))).catch(console.error)}),[e.walletConnectCloudProjectId])},dl="popup-privy-oauth",hl="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class ul{async authenticate(){if(!this.api)throw new C("Auth flow has no API instance");try{return await this.api.post(R,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw T(e)}}async link(){if(!this.api)throw new C("Auth flow has no API instance");try{return await this.api.post(L,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw T(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:n,provider:r}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:n,provider:r}}}async function pl({api:e,requesterAppId:t,providerAppId:n}){let r=(await e.get(`/api/v1/apps/${t}/cross-app/connections`)).connections.find((e=>e.provider_app_id===n));if(!r)throw new C("Invalid connected app");return{name:r.provider_app_name,logoUrl:r.provider_app_icon_url||void 0,apiUrl:r.provider_app_custom_api_url,readOnly:r.read_only}}const ml=async({user:e,address:t,client:n,request:r,requesterAppId:a,reconnect:i})=>{n.createAnalyticsEvent({eventName:"cross_app_request_started",payload:{address:t,method:r.method}});let o=e?.linkedAccounts.find((e=>"cross_app"===e.type&&(e.embeddedWallets.some((e=>e.address===t))||e.smartWallets.some((e=>e.address===t)))));if(!e||!o)throw n.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Cannot request a signature with this wallet address",address:t}}),new C("Cannot request a signature with this wallet address");let s=n.getProviderAccessToken(o.providerApp.id),l=await pl({api:n.api,requesterAppId:a,providerAppId:o.providerApp.id});if(!s){if(l.readOnly)throw console.error("cannot transact against a read-only provider app"),new C("Cannot transact against a read-only provider app");await i({appId:o.providerApp.id,action:"link"})&&(s=n.getProviderAccessToken(o.providerApp.id))}if(!s)throw n.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Transactions require a valid token",address:t}}),new C("Transactions require a valid token");let c=Rn();if(!c)throw n.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new C("Failed to initialize signature request");let d=new URL(`${l.apiUrl}/oauth/transact`);return d.searchParams.set("token",s||""),d.searchParams.set("request",wl(r)),c.location=d.href,new Promise(((e,a)=>{let i=setTimeout((()=>{d(),a(new C("Request timeout")),n.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),s=setInterval((()=>{c.closed&&(d(),a(new C("User rejected request")),n.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"User rejected request",address:t}}))}),300),l=i=>{i.data&&("set"===i.data.token?.action&&void 0!==i.data.token?.value?n.storeProviderAccessToken(o.providerApp.id,i.data.token.value):"clear"===i.data.token?.action&&n.storeProviderAccessToken(o.providerApp.id,null),"PRIVY_CROSS_APP_ACTION_RESPONSE"===i.data.type&&i.data.result&&(d(),e(i.data.result),n.createAnalyticsEvent({eventName:"cross_app_request_success",payload:{address:t,method:r.method}})),"PRIVY_CROSS_APP_ACTION_ERROR"===i.data.type&&i.data.error&&(d(),a(i.data.error),n.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:i.data.error,address:t}})))};window.addEventListener("message",l);let d=()=>{c.close(),clearInterval(s),clearTimeout(i),window.removeEventListener("message",l)}}))};let wl=e=>JSON.stringify({content:{request:{request:yl(e,Li)}},timestamp:Date.now(),callbackUrl:window.origin});const yl=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>yl(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,n])=>[e,yl(n,t)]))):e;let gl=({passkeys:e,expanded:r,onUnlink:a,onExpand:i})=>{let[o,s]=l([]),c=r?e.length:2,d=e=>e.authenticatorName?e.createdWithBrowser?`${e.authenticatorName} on ${e.createdWithBrowser}`:e.authenticatorName:e.createdWithBrowser?e.createdWithOs?`${e.createdWithBrowser} on ${e.createdWithOs}`:`${e.createdWithBrowser}`:"Unknown device";/*#__PURE__*/return n("div",{children:[/*#__PURE__*/t(Sl,{children:"Your passkeys"}),/*#__PURE__*/n(bl,{children:[e.slice(0,c).map((e=>/*#__PURE__*/n(Pl,{children:[/*#__PURE__*/n("div",{children:[/*#__PURE__*/t(Wl,{children:d(e)}),/*#__PURE__*/n(xl,{children:["Last used: ",(e.latestVerifiedAt??e.verifiedAt).toLocaleString()]})]}),/*#__PURE__*/t(Ul,{disabled:o.includes(e.credentialId),onClick:()=>(async e=>{s((t=>t.concat([e]))),await a(e),s((t=>t.filter((t=>t!==e))))})(e.credentialId),children:o.includes(e.credentialId)?/*#__PURE__*/t(Fn,{}):/*#__PURE__*/t(oo,{height:"1.6em"})})]},e.credentialId))),e.length>2&&!r&&/*#__PURE__*/t(El,{onClick:i,children:"View all"})]})]})},fl=()=>/*#__PURE__*/n(bl,{children:[/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(so,{})}),"Log in with Touch ID, Face ID, or a security key."]}),/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(lo,{})}),"More secure than a password."]}),/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(io,{})}),"Takes seconds to set up and use."]})]});const vl={component:()=>{let{user:e,unlinkPasskey:a}=$t(),{linkWithPasskey:i,closePrivyModal:o}=Pe(),c=e?.linkedAccounts.filter((e=>"passkey"===e.type)),[d,h]=l(!1),[u,p]=l(""),[m,w]=l(!1),[y,g]=l(!1);s((()=>{0===c.length&&g(!1)}),[c.length]);let f=async e=>(h(!0),await a(e).then((()=>w(!0))).catch((e=>{e instanceof Ne&&e.privyErrorCode===M.MISSING_MFA_CREDENTIALS?p("Cannot unlink a passkey enrolled in MFA"):p("Unknown error occurred.")})).finally((()=>{h(!1)})));/*#__PURE__*/return n(r,m?{children:[/*#__PURE__*/t(Qt,{onClose:()=>o()},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Xi,{})}),/*#__PURE__*/t(Tl,{style:{marginBottom:"1.5rem"},children:"Passkeys updated"}),/*#__PURE__*/t(_l,{children:" "}),/*#__PURE__*/t(Mn,{children:/*#__PURE__*/t(cn,{onClick:()=>o(),children:"Done"})}),/*#__PURE__*/t(hn,{})]}:y?{children:[/*#__PURE__*/t(Qt,{backFn:()=>g(!1),onClose:()=>o()},"header"),/*#__PURE__*/t(gl,{passkeys:c,expanded:y,onUnlink:f,onExpand:()=>g(!0)}),/*#__PURE__*/t(hn,{})]}:{children:[/*#__PURE__*/t(Qt,{onClose:()=>o()},"header"),/*#__PURE__*/t(Ln,{children:/*#__PURE__*/n(kl,{children:[/*#__PURE__*/t(tn,{}),/*#__PURE__*/t(Dn,{})]})}),/*#__PURE__*/t(Tl,{children:"Secure your account with a passkey"}),/*#__PURE__*/t(Il,{}),0===c.length?/*#__PURE__*/t(fl,{}):/*#__PURE__*/t(gl,{passkeys:c,expanded:y,onUnlink:f,onExpand:()=>g(!0)}),/*#__PURE__*/n(Mn,{style:{marginTop:"12px"},children:[u&&/*#__PURE__*/t(Al,{$fail:!0,children:u}),/*#__PURE__*/t(cn,{onClick:()=>{h(!0),i().then((()=>w(!0))).catch((e=>{if(e instanceof Ne){if(e.privyErrorCode===M.CANNOT_LINK_MORE_OF_TYPE)return void p("Cannot link more passkeys to account.");if(e.privyErrorCode===M.PASSKEY_NOT_ALLOWED)return void p("Passkey request timed out or rejected by user.")}p("Unknown error occurred.")})).finally((()=>{h(!1)}))},loading:d,children:"Add new passkey"})]}),/*#__PURE__*/t(hn,{})]})}},kl=/*#__PURE__*/Si.div.withConfig({displayName:"DoubleIconWrapper",componentId:"sc-d6832d36-0"})(["display:flex;align-items:center;justify-content:center;width:180px;height:90px;border-radius:50%;svg + svg{margin-left:12px;}> svg{z-index:2;color:var(--privy-color-accent) !important;stroke:var(--privy-color-accent) !important;fill:var(--privy-color-accent) !important;}"]);let Al=/*#__PURE__*/Si.div.withConfig({displayName:"InputHelp",componentId:"sc-d6832d36-1"})(["line-height:20px;height:20px;font-size:13px;color:",";display:flex;justify-content:flex-beginngin;width:100%;"],(e=>e.$fail?"var(--privy-color-error)":"var(--privy-color-foreground-3)")),Cl=/*#__PURE__*/xi(["&&{width:100%;font-size:0.875rem;line-height:1rem;@media (min-width:440px){font-size:14px;}display:flex;gap:12px;justify-content:center;padding:6px 8px;background-color:var(--privy-color-background);transition:background-color 200ms ease;color:var(--privy-color-accent) !important;:focus{outline:none;box-shadow:none;}}"]);const El=/*#__PURE__*/Si.button.withConfig({displayName:"LinkButton",componentId:"sc-d6832d36-2"})(["",""],Cl);let bl=/*#__PURE__*/Si.div.withConfig({displayName:"List",componentId:"sc-d6832d36-3"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.8rem;padding:0.5rem 0rem 0rem;flex-grow:1;width:100%;"]),Tl=/*#__PURE__*/Si.div.withConfig({displayName:"ModalTitle",componentId:"sc-d6832d36-4"})(["font-size:18px;line-height:18px;text-align:center;font-weight:600;"]),_l=/*#__PURE__*/Si.div.withConfig({displayName:"ModalSubTitle",componentId:"sc-d6832d36-5"})(["font-size:0.875rem;text-align:center;margin-top:10px;"]),Il=/*#__PURE__*/Si.div.withConfig({displayName:"SectionSpacer",componentId:"sc-d6832d36-6"})(["height:32px;"]),Sl=/*#__PURE__*/Si.div.withConfig({displayName:"PasskeyListTitle",componentId:"sc-d6832d36-7"})(["line-height:20px;height:20px;font-size:1em;font-weight:450;display:flex;justify-content:flex-beginning;width:100%;"]),Wl=/*#__PURE__*/Si.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-d6832d36-8"})(["font-size:1em;line-height:1.3em;font-weight:500;color:var(--privy-color-foreground-2);padding:0.2em 0;"]),xl=/*#__PURE__*/Si.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-d6832d36-9"})(["font-size:0.875rem;line-height:1rem;color:#64668b;padding:0.2em 0;"]),Pl=/*#__PURE__*/Si.div.withConfig({displayName:"PasskeyListItem",componentId:"sc-d6832d36-10"})(["display:flex;align-items:center;justify-content:space-between;padding:1em;gap:10px;font-size:0.875rem;line-height:1rem;text-align:left;border-radius:8px;border:1px solid #e2e3f0 !important;width:100%;height:5em;"]),Nl=/*#__PURE__*/xi([":focus,:hover,:active{outline:none;}display:flex;width:2em;height:2em;justify-content:center;align-items:center;svg{color:var(--privy-color-error);}svg:hover{color:var(--privy-color-foreground-3);}"]),Ul=/*#__PURE__*/Si.button.withConfig({displayName:"PasskeyItemUnlinkButton",componentId:"sc-d6832d36-11"})(["",""],Nl);const Ol=new Map([[zn,null],[qn,"external"],[Bn,"external"],[Vn,"external"],[jn,"external"],[Hn,"external"],[$n,"manual"],[Kn,"moonpay"]]),Rl=e=>!!e.fundingConfig&&vi(e.fundingConfig.options).length>=1;async function Ml({url:e,popup:t,provider:n}){return t.location=e,new Promise(((e,n)=>{function r(){t?.close(),window.removeEventListener("message",a)}function a(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(e(t.data),r()),"https://cdn.apple-cloudkit.com"===t.origin&&t.data.ckSession&&(e({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:t.data.ckSession}),r()),"PRIVY_OAUTH_ERROR"===t.data.type&&(n(t.data.error),r()))}window.addEventListener("message",a)}))}const Ll={component:()=>{let{app:e,data:a}=yn(),i=An(),o=a?.externalConnectWallet?.suggestedAddress,s=o?`Connect the wallet with address ${Yn(o)} ${e?.name?`to ${e.name}.`:"."}`:`Connect a wallet to ${e?.name}`,{connectors:l}=Pe(),c=Gn({walletList:a?.externalConnectWallet?.walletList??e.appearance.walletList,walletChainType:a?.externalConnectWallet?.walletChainType??e.appearance.walletChainType,connectors:l,connectOnly:!0,ignore:e.appearance.walletList,walletConnectEnabled:e.externalWallets.walletConnect.enabled});/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{},"header"),c.length>0&&/*#__PURE__*/t(Xn,{title:"Connect your wallet",description:s}),/*#__PURE__*/t(Jn,{$colorScheme:i.appearance.palette.colorScheme,children:/*#__PURE__*/t(Qn,{wallets:c})}),/*#__PURE__*/t(Zn,{})]})}},Dl={component:()=>{let e=An(),{data:a,navigate:i,setModalData:c,onUserCloseViaDialogOrKeybindRef:d}=yn(),{crossAppAuthFlow:h,updateWallets:u,closePrivyModal:p,createAnalyticsEvent:m}=Pe(),{logout:w}=Ni(),[y,g]=l({}),f=a?.crossAppAuth,v={id:f.appId,name:f.name,logoUrl:f.logoUrl},k=new C(`There was an issue connecting your ${v.name} account. Please try again.`),A=new De((async e=>{if(f.popup)try{let t=await h({appId:e,popup:f.popup,action:f.action});g({data:t})}catch(e){e instanceof C?g({error:e}):(e instanceof te&&f.popup&&f.popup.close(),g({error:k}))}else g({error:k})})),E=()=>{y.data&&(u(),f.onSuccess(y.data),p({shouldCallAuthOnSuccess:!0,isSuccess:!0})),f.onError(y.error??new C("User canceled flow")),p({shouldCallAuthOnSuccess:!1,isSuccess:!1})};d.current=E,s((()=>{v.id.length&&A.execute(v.id)}),[v.id]),s((()=>{if(!y.data)return;let t=y.data;if(e.legal.requireUsersAcceptTerms&&!t.hasAcceptedTerms){let e=setTimeout((()=>{i(er)}),tr);return()=>clearTimeout(e)}if(nr(t,e.embeddedWallets)){let e=setTimeout((()=>{c({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),m({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:`privy:${v.id}`,screen:"CrossAppAuthScreen"}}),w()},callAuthOnSuccessOnClose:!0}}),i(rr)}),tr);return()=>clearTimeout(e)}let n=setTimeout(E,tr);return()=>clearTimeout(n)}),[y.data]);let{title:b,subtitle:T}=o((()=>y.data?{title:`Successfully connected with ${v.name}`,subtitle:"You're good to go!"}:y.error?{title:"Authentication failed",subtitle:y.error.message}:{title:`Connecting to ${v.name}`,subtitle:`Please check the pop-up from ${v.name} to continue`}),[y,v.name]);/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{onClose:E}),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/n(Fl,{children:[/*#__PURE__*/t(Zt,{children:/*#__PURE__*/n("div",{children:[/*#__PURE__*/t(en,{success:!!y.data,fail:!!y.error}),/*#__PURE__*/t(ar,{name:v.name,logoUrl:v.logoUrl})]})}),/*#__PURE__*/n(ir,{children:[/*#__PURE__*/t("h3",{children:b}),/*#__PURE__*/t("p",{children:T})]})]}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(hn,{})]})}};let Fl=/*#__PURE__*/Si.div.withConfig({displayName:"ConnectContainer",componentId:"sc-33c02367-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-left:27px;margin-right:27px;gap:24px;"]);const zl={component:()=>{let{app:e,data:a}=yn(),{closePrivyModal:i}=Pe(),[o,c]=l(!1),[d,h]=l(),{address:u,onDelegate:p,onSuccess:m,onError:w}=a.delegatedActions.consent,y=async()=>{o?m():w(d??new C("User declined delegating actions.")),i({shouldCallAuthOnSuccess:!1})};return s((()=>{if(!o&&!d)return;let e=setTimeout(y,or);return()=>clearTimeout(e)}),[o,d]),/*#__PURE__*/n(r,o||d?{children:[/*#__PURE__*/t(Qt,{onClose:y}),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/n(sr,{children:[d?/*#__PURE__*/t(Qi,{stroke:"var(--privy-color-error)",width:"64px",height:"64px"}):/*#__PURE__*/t(Xi,{stroke:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/t(lr,{height:20}),/*#__PURE__*/t(cr,{title:d?"Something went wrong":"Success!",description:d?"Please try again.":`You’ve successfully granted delegated action permissions to ${e.name}.`})]}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]}:{children:[/*#__PURE__*/t(Qt,{closeable:!0,onClose:y}),/*#__PURE__*/t(Ji,{width:56,height:56,style:{margin:"auto"}}),/*#__PURE__*/t(nn,{style:{marginTop:24,color:"var(--privy-color-foreground)"},children:"Enable offline access"}),/*#__PURE__*/n(pn,{style:{marginBottom:24,textWrap:"pretty"},children:["By confirming, ",e.name," will be able to use your wallet for you even when you're not around. You can revoke this later."]}),/*#__PURE__*/t(Bl,{showIcon:!0,address:u,title:"Wallet",isLoading:!1}),/*#__PURE__*/n(ql,{style:{marginTop:24},children:[/*#__PURE__*/t(gn,{onClick:y,children:"Not now"}),/*#__PURE__*/t(cn,{onClick:async()=>{try{await p(),c(!0)}catch(e){h(e)}},children:"Accept"})]}),/*#__PURE__*/t(Zn,{})]})}};let ql=/*#__PURE__*/Si.div.withConfig({displayName:"ButtonsContainer",componentId:"sc-bdb7bc51-0"})(["display:flex;gap:10px;"]),Bl=/*#__PURE__*/Si(dr).withConfig({displayName:"StyledWalletInfoCard",componentId:"sc-bdb7bc51-1"})(["margin-top:1.5rem;"]);const Vl={component:()=>{let{app:e,data:a}=yn(),{closePrivyModal:i}=Pe(),[o,c]=l(!1),[d,h]=l(),{onRevoke:u,onSuccess:p,onError:m}=a.delegatedActions.revoke,w=async()=>{o?p():m(d??new C("User declined revoking access to their delegated wallet.")),i({shouldCallAuthOnSuccess:!1})};return s((()=>{if(!o&&!d)return;let e=setTimeout(w,or);return()=>clearTimeout(e)}),[o,d]),/*#__PURE__*/n(r,o||d?{children:[/*#__PURE__*/t(Qt,{onClose:w}),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/n(sr,{children:[d?/*#__PURE__*/t(Qi,{stroke:"var(--privy-color-error)",width:"64px",height:"64px"}):/*#__PURE__*/t(Xi,{stroke:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/t(lr,{height:20}),/*#__PURE__*/t(cr,{title:d?"Something went wrong":"Success!",description:d?"Please try again.":"You've successfully revoked permissions."})]}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]}:{children:[/*#__PURE__*/t(Qt,{closeable:!0,onClose:w}),/*#__PURE__*/t(Zi,{width:56,height:56,style:{margin:"auto"}}),/*#__PURE__*/t(nn,{style:{marginTop:24},children:"Revoke offline access to wallet"}),/*#__PURE__*/n(pn,{children:["By confirming, ",e.name," will no longer be able to use this wallet on your behalf when you are not online."]}),/*#__PURE__*/n(jl,{style:{marginTop:24},children:[/*#__PURE__*/t(gn,{onClick:w,children:"Deny"}),/*#__PURE__*/t(cn,{onClick:async()=>{try{await u(),c(!0)}catch(e){h(e)}},children:"Confirm"})]}),/*#__PURE__*/t(Zn,{})]})}};let jl=/*#__PURE__*/Si.div.withConfig({displayName:"ButtonsContainer",componentId:"sc-993a839-0"})(["display:flex;gap:10px;"]),Hl="#8a63d2";const $l={component:()=>{let{lastScreen:e,navigateBack:a,data:i,app:o}=yn(),{requestFarcasterSignerStatus:c,closePrivyModal:d}=Pe(),[h,p]=l(void 0),[m,g]=l(!1),[f,v]=l(!1),k=u([]),A=i?.farcasterSigner;s((()=>{let e=Date.now(),t=setInterval((async()=>{if(!A?.public_key)return clearInterval(t),void p({retryable:!0,message:"Connect failed",detail:"Something went wrong. Please try again."});"approved"===A.status&&(clearInterval(t),g(!1),v(!0),k.current.push(setTimeout((()=>d({shouldCallAuthOnSuccess:!1,isSuccess:!0})),tr)));let n=await c(A?.public_key),r=Date.now()-e;"approved"===n.status?(clearInterval(t),g(!1),v(!0),k.current.push(setTimeout((()=>d({shouldCallAuthOnSuccess:!1,isSuccess:!0})),tr))):r>3e5?(clearInterval(t),p({retryable:!0,message:"Connect failed",detail:"The request timed out. Try again."})):"revoked"===n.status&&(clearInterval(t),p({retryable:!0,message:"Request rejected",detail:"The request was rejected. Please try again."}))}),2e3);return()=>{clearInterval(t),k.current.forEach((e=>clearTimeout(e)))}}),[]);let C="pending_approval"===A?.status?A.signer_approval_url:void 0;/*#__PURE__*/return n(r,w||m?{children:[/*#__PURE__*/t(Qt,{backFn:e?a:void 0,onClose:d},"header"),/*#__PURE__*/t(Cn,{}),
3
- /*#__PURE__*/t(r,y?{children:/*#__PURE__*/n(Yl,{children:[/*#__PURE__*/t(Zt,{children:/*#__PURE__*/n("div",{children:[/*#__PURE__*/t(en,{success:f,fail:!!h}),/*#__PURE__*/t(hr,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/n(ir,{children:[/*#__PURE__*/t(nn,{children:h?h.message:"Add a signer to Farcaster"}),/*#__PURE__*/t(pn,{children:h?h.detail:"This will allow "+o.name+" to add casts, likes, follows, and more on your behalf."})]}),C&&/*#__PURE__*/t(cn,{onClick:e=>{e.preventDefault(),window.location.href=C},children:"Open Warpcast app"})]})}:{children:/*#__PURE__*/n(Kl,{children:[/*#__PURE__*/t(Zt,{children:/*#__PURE__*/n("div",{children:[/*#__PURE__*/t(en,{success:f,fail:!!h}),/*#__PURE__*/t(hr,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/n(ir,{children:[/*#__PURE__*/t(nn,{children:h?h.message:"Requesting signer from Farcaster"}),/*#__PURE__*/t(pn,{children:h?h.detail:"This should only take a moment"}),/*#__PURE__*/t(ur,{children:C&&w&&/*#__PURE__*/t(pr,{text:"Take me to Warpcast",url:C,color:Hl})})]})]})}),/*#__PURE__*/t(hn,{})]}:{children:[/*#__PURE__*/t(Qt,{backFn:e?a:void 0,onClose:d},"header"),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/t(Kl,{children:/*#__PURE__*/n("div",{children:[/*#__PURE__*/t(nn,{children:"Add a signer to Farcaster"}),/*#__PURE__*/n(pn,{children:["This will allow ",o.name," to add casts, likes, follows, and more on your behalf."]}),/*#__PURE__*/t(mr,{children:"pending_approval"===A?.status?/*#__PURE__*/t(wr,{url:A.signer_approval_url,size:275,squareLogoElement:hr}):/*#__PURE__*/t(En,{})}),/*#__PURE__*/n(ur,{children:[/*#__PURE__*/t(pn,{children:"Or copy this link and paste it into a phone browser to open the Warpcast app."}),"pending_approval"===A?.status&&/*#__PURE__*/t(yr,{text:A.signer_approval_url,itemName:"link",color:Hl})]})]})}),/*#__PURE__*/t(hn,{})]})}};let Kl=/*#__PURE__*/Si.div.withConfig({displayName:"ConnectContainer",componentId:"sc-6e8f76e5-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-left:27px;margin-right:27px;gap:24px;"]),Yl=/*#__PURE__*/Si.div.withConfig({displayName:"ConnectContainerButton",componentId:"sc-6e8f76e5-1"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;"]);const Gl={component:()=>{let{closePrivyModal:e}=Pe();/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{},"header"),/*#__PURE__*/t(Xl,{children:/*#__PURE__*/t(ro,{style:{width:32,height:32}})}),/*#__PURE__*/t(Xn,{title:"Could not log in with provider",description:"It looks like you're using an in-app browser. To log in, please try again using an external browser.",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",textAlign:"center"}}),/*#__PURE__*/t(gr,{children:/*#__PURE__*/t(cn,{onClick:()=>e(),children:"Close"})}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]})}};let Xl=/*#__PURE__*/Si.div.withConfig({displayName:"StyledCircle",componentId:"sc-7bde5742-0"})(["border-radius:50%;height:68px;width:68px;display:flex;align-items:center;justify-content:center;background-color:var(--privy-color-accent);color:white;margin:0 auto 24px auto;"]);const Jl={component:()=>{let{app:e}=yn();/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{},"header"),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/t(cr,{title:"Connect your email",description:`Add your email to your ${e?.name} account`,icon:/*#__PURE__*/t(ao,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/t(gr,{children:/*#__PURE__*/t(fr,{stacked:!0})}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]})}},Ql={component:()=>{let{app:e,currentScreen:a,data:i,navigate:o,setModalData:s}=yn(),{initLoginWithSms:l}=Pe();/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{},"header"),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/t(cr,{title:"Connect your phone",description:`Add your number to your ${e?.name} account`,icon:/*#__PURE__*/t(Ri,{color:"var(--privy-color-accent)",strokeWidth:2,height:"40px",width:"40px"})}),/*#__PURE__*/t(gr,{children:/*#__PURE__*/t(vr,{stacked:!0,onSubmit:async function({qualifiedPhoneNumber:e}){try{await l({phoneNumber:e,withPrivyUi:!0}),o(kr)}catch(e){s({errorModalData:{error:e,previousScreen:i?.errorModalData?.previousScreen||a||Ql}}),o(Ar)}},hideRecent:!0})}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]})}},Zl={component:()=>{let{app:e,data:a}=yn(),i=a?.externalConnectWallet?.suggestedAddress,o=i?/*#__PURE__*/n("span",{children:["Link the wallet with address ",/*#__PURE__*/t(Cr,{showCopyIcon:!1,address:i})," ",e?.name?`to ${e.name}.`:"."]}):`Link a wallet to your ${e?.name} account`,{connectors:s}=Pe(),l=Gn({walletList:a?.externalConnectWallet?.walletList??e.appearance.walletList,walletChainType:a?.externalConnectWallet?.walletChainType??e.appearance.walletChainType,connectors:s,connectOnly:!1,ignore:e.appearance.walletList,walletConnectEnabled:e.externalWallets.walletConnect.enabled});/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{},"header"),l.length>0&&/*#__PURE__*/t(Xn,{title:"Link your wallet",description:o}),/*#__PURE__*/t(Er,{children:/*#__PURE__*/t(Qn,{wallets:l})}),/*#__PURE__*/t(Zn,{})]})}},ec=({style:e,...r})=>/*#__PURE__*/n("svg",{width:"164",height:"164",viewBox:"0 0 164 164",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"26px",width:"26px",...e},...r,children:[/*#__PURE__*/t("circle",{cx:"82",cy:"82",r:"80",stroke:"#EC6351","stroke-width":"4","stroke-linecap":"round"}),/*#__PURE__*/t("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M81.9999 100.788C93.3288 100.788 102.513 91.6043 102.513 80.2754C102.513 68.9465 93.3288 59.7626 81.9999 59.7626C70.671 59.7626 61.4871 68.9465 61.4871 80.2754C61.4871 91.6043 70.671 100.788 81.9999 100.788ZM88.3236 71.8304C88.9093 71.2446 89.8591 71.2446 90.4449 71.8304C91.0307 72.4161 91.0307 73.3659 90.4449 73.9517L84.121 80.2756L90.445 86.5996C91.0308 87.1854 91.0308 88.1351 90.445 88.7209C89.8592 89.3067 88.9095 89.3067 88.3237 88.7209L81.9997 82.3969L75.6756 88.7209C75.0899 89.3067 74.1401 89.3067 73.5543 88.7209C72.9685 88.1351 72.9685 87.1854 73.5543 86.5996L79.8783 80.2756L73.5544 73.9517C72.9686 73.3659 72.9686 72.4161 73.5544 71.8304C74.1402 71.2446 75.09 71.2446 75.6758 71.8304L81.9997 78.1543L88.3236 71.8304Z",fill:"#EC6351"})]}),tc={component:()=>{let{closePrivyModal:e}=Pe(),{navigate:a}=yn();/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{},"header"),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/t(ec,{style:{width:"160px",height:"160px",margin:"0 auto 20px"}}),/*#__PURE__*/t(Xn,{title:"Could not connect with wallet",description:"Please check that Phantom multichain is enabled and try again.",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",textAlign:"center"}}),/*#__PURE__*/n(gr,{children:[/*#__PURE__*/t(cn,{onClick:()=>a(br),children:"Try again"}),/*#__PURE__*/t(gn,{onClick:()=>e(),children:"Cancel"})]}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]})}};function nc(){let{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:r,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:i,unenroll:o,enrollInMfa:s}=h(Jt);return{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:r,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:i,unenrollWithSms:()=>o("sms"),unenrollWithTotp:()=>o("totp"),unenrollWithPasskey:e=>o("passkey",e),showMfaEnrollmentModal:()=>s(!0),closeMfaEnrollmentModal:()=>s(!1)}}const rc=e=>/*#__PURE__*/n(ac,{xmlns:"http://www.w3.org/2000/svg",fill:"none",width:"88",height:"89",viewBox:"0 0 88 89",...e,children:[/*#__PURE__*/t("rect",{y:"0.666016",width:"88",height:"88",rx:"44"}),/*#__PURE__*/t("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M45.2463 20.9106C44.5473 20.2486 43.4527 20.2486 42.7537 20.9106C37.8798 25.5263 31.3034 28.3546 24.0625 28.3546C23.9473 28.3546 23.8323 28.3539 23.7174 28.3525C22.9263 28.3427 22.2202 28.8471 21.9731 29.5987C20.9761 32.6311 20.4375 35.8693 20.4375 39.2297C20.4375 53.5896 30.259 65.651 43.5482 69.0714C43.8446 69.1477 44.1554 69.1477 44.4518 69.0714C57.741 65.651 67.5625 53.5896 67.5625 39.2297C67.5625 35.8693 67.0239 32.6311 66.0269 29.5987C65.7798 28.8471 65.0737 28.3427 64.2826 28.3525C64.1677 28.3539 64.0527 28.3546 63.9375 28.3546C56.6966 28.3546 50.1202 25.5263 45.2463 20.9106ZM52.7249 40.2829C53.3067 39.4683 53.1181 38.3363 52.3035 37.7545C51.4889 37.1726 50.3569 37.3613 49.7751 38.1759L41.9562 49.1223L38.0316 45.1977C37.3238 44.4899 36.1762 44.4899 35.4684 45.1977C34.7605 45.9056 34.7605 47.0532 35.4684 47.761L40.9059 53.1985C41.2826 53.5752 41.806 53.7671 42.337 53.7232C42.868 53.6792 43.3527 53.4039 43.6624 52.9704L52.7249 40.2829Z"})]});let ac=/*#__PURE__*/Si.svg.withConfig({displayName:"StyledSvg",componentId:"sc-59fa943f-0"})(["height:90px;width:90px;> rect{","}> path{fill:white;}"],(e=>"success"===e.color?"fill: var(--privy-color-success);":"fill: var(--privy-color-accent);"));const ic=({showIntro:e,userMfaMethods:a,appMfaMethods:i,userHasAuthSms:o,isTotpLoading:s,isPasskeyLoading:l,error:c,onClose:d,onBackToIntro:h,handleSelectMethod:u,setRemovingMfaMethod:p})=>{let m=a.reduce(((e,t)=>({...e,[t]:!0})),{}),w=i.reduce(((e,t)=>({...e,[t]:!0})),{});/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{backFn:e?h:void 0,onClose:d},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Mi,{})}),/*#__PURE__*/t(nn,{children:"Choose a verification method"}),a.length>0?/*#__PURE__*/t(pn,{children:"To add or delete verification methods, verification is required."}):/*#__PURE__*/t(pn,{children:"How would you like to verify your identity? You can change this later."}),c&&/*#__PURE__*/t(ln,{style:{marginTop:"1.25rem"},children:c.message}),/*#__PURE__*/n(mn,{children:[(w.totp||m.totp)&&/*#__PURE__*/n(Tr,{children:[/*#__PURE__*/t(wn,{style:{justifyContent:"center"},disabled:m.totp||s,onClick:()=>u("totp"),children:s?/*#__PURE__*/t(En,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/n(_r,{children:[/*#__PURE__*/n(Ir,{children:[/*#__PURE__*/t(Ui,{}),"Authenticator app"]}),m.totp?/*#__PURE__*/t(oc,{color:"green",children:"Enabled"}):/*#__PURE__*/t(Sr,{children:"Recommended"})]})}),m.totp&&/*#__PURE__*/t(Wr,{style:{position:"absolute",right:0},onClick:()=>p("totp"),children:/*#__PURE__*/t(po,{})})]},"totp"),(w.sms||m.sms)&&/*#__PURE__*/n(Tr,{children:[/*#__PURE__*/t(wn,{disabled:m.sms||o,onClick:()=>u("sms"),children:/*#__PURE__*/n(_r,{children:[/*#__PURE__*/n(Ir,{children:[/*#__PURE__*/t(Ri,{}),"SMS"]}),m.sms&&/*#__PURE__*/t(oc,{color:"green",children:"Enabled"}),o&&/*#__PURE__*/t(Sr,{children:"Disabled"})]})}),m.sms&&/*#__PURE__*/t(Wr,{style:{position:"absolute",right:0},onClick:()=>p("sms"),children:/*#__PURE__*/t(po,{})})]},"sms"),(w.passkey||m.passkey)&&/*#__PURE__*/n(Tr,{children:[/*#__PURE__*/t(wn,{style:{justifyContent:"center"},onClick:()=>u("passkey"),disabled:m.passkey||l,children:l?/*#__PURE__*/t(En,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/n(_r,{children:[/*#__PURE__*/n(Ir,{children:[/*#__PURE__*/t(Oi,{}),"Passkey"]}),m.passkey?/*#__PURE__*/t(oc,{color:"green",children:"Enabled"}):/*#__PURE__*/t(Sr,{isAccent:!0,children:/*#__PURE__*/t(uo,{})})]})}),m.passkey&&/*#__PURE__*/t(Wr,{style:{position:"absolute",right:0},onClick:()=>p("passkey"),children:/*#__PURE__*/t(po,{})})]},"passkey")]}),/*#__PURE__*/t(hn,{})]})};let oc=/*#__PURE__*/Si(xr).withConfig({displayName:"StyledChip",componentId:"sc-998ca5bc-0"})(["margin-right:1.5rem;"]);const sc=({appName:e,onComplete:n,onClose:r,onReset:a})=>{let{user:i}=$t(),{data:s}=yn(),{initLinkWithPasskey:c,linkWithPasskey:d}=Pe(),{initEnrollmentWithPasskey:h,submitEnrollmentWithPasskey:u}=nc(),[p,m]=l(!1),[w,y]=l(!1),[g,f]=l(!1),[v,k]=l(null),A=o((()=>i?.linkedAccounts.filter((e=>"passkey"===e.type))??[]),[i]),C=()=>{s?.mfaEnrollmentFlow?.onSuccess(),n()},E=async e=>{m(!0);try{await h(),await u({credentialIds:e},{removeForLogin:s?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa}),f(!0)}catch(e){k(e)}finally{m(!1)}},b=async()=>{y(!0),k(null);try{await c();let e=await d(),t=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];await E(t)}catch(e){k(e)}finally{y(!1)}};return 0===A.length||w?/*#__PURE__*/t(lc,{onReset:a,onClose:r,onClick:b,isCreating:w}):g?/*#__PURE__*/t(dc,{appName:e,onClick:C,onClose:C}):v?/*#__PURE__*/t(Pr,{error:v,backFn:()=>k(null),onClick:()=>k(null)}):/*#__PURE__*/t(cc,{passkeys:A,isSubmitting:p,isCreating:w,onReset:a,onClose:r,onSubmitEnrollment:()=>E(A.map((e=>e.credentialId))),onAddPasskey:b})};let lc=({onReset:e,onClose:a,onClick:i,isCreating:o})=>/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Qt,{backFn:e,onClose:a},"header"),/*#__PURE__*/t(Ln,{children:/*#__PURE__*/n(kl,{children:[/*#__PURE__*/t(tn,{}),/*#__PURE__*/t(Dn,{})]})}),/*#__PURE__*/t(nn,{children:"Set up passkey verification"}),/*#__PURE__*/n(rn,{children:[/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(Mi,{})}),"Verify with Touch ID, Face ID, PIN, or hardware key"]}),/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(io,{})}),"Takes seconds to set up and use"]}),/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(mo,{})}),"Use your passkey to verify transactions and login to your account"]})]}),/*#__PURE__*/t(cn,{style:{marginTop:"2.25rem"},onClick:i,loading:o,children:"Add a new passkey"}),/*#__PURE__*/t(hn,{})]}),cc=({onReset:e,onClose:a,onAddPasskey:i,onSubmitEnrollment:o,passkeys:s,isSubmitting:c,isCreating:d})=>{let[h,u]=l(!1),p=h?s.length:s.length>3?2:3;/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{backFn:h?()=>u(!1):e,onClose:a},"header"),!h&&/*#__PURE__*/t(Ln,{children:/*#__PURE__*/n(kl,{children:[/*#__PURE__*/t(tn,{}),/*#__PURE__*/t(Dn,{})]})}),/*#__PURE__*/t(nn,{children:"Enable your passkeys for verification"}),/*#__PURE__*/n(rn,{children:[s.slice(0,p).map((e=>/*#__PURE__*/n(hc,{children:[/*#__PURE__*/t(uc,{children:mc(e)}),/*#__PURE__*/n(pc,{children:["Last used: ",e.latestVerifiedAt?.toLocaleString()]})]},e.credentialId))),!h&&s.length>3&&/*#__PURE__*/t(wc,{onClick:()=>u(!0),children:"View All"})]}),/*#__PURE__*/t(cn,{style:{marginTop:"1.5rem"},onClick:o,loading:c,children:"Enable passkeys"}),s.length<5&&/*#__PURE__*/t(wc,{style:{marginTop:"0.5rem"},onClick:i,disabled:d,children:d?/*#__PURE__*/t(En,{style:{height:"1rem",width:"1rem",borderWidth:2}}):"Add new passkey"}),/*#__PURE__*/t(hn,{})]})},dc=({appName:e,onClick:a,onClose:i})=>/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Qt,{onClose:i},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Xi,{})}),/*#__PURE__*/t(nn,{children:"Passkey verification added"}),/*#__PURE__*/n(pn,{children:["From now on, you'll use the passkey whenever you use your ",e," wallet."]}),/*#__PURE__*/t(Mn,{children:/*#__PURE__*/t(cn,{onClick:a,children:"Done"})}),/*#__PURE__*/t(hn,{})]}),hc=/*#__PURE__*/Si.div.withConfig({displayName:"PasskeyItem",componentId:"sc-d5b2bf9c-0"})(["&&{padding:0.75rem 1rem;text-align:left;border-radius:0.5rem;border:1px solid var(--privy-color-foreground-4);width:100%;}"]),uc=/*#__PURE__*/Si.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-d5b2bf9c-1"})(["font-size:0.875rem;line-height:1.375rem;font-weight:500;color:var(--privy-color-foreground-1);"]),pc=/*#__PURE__*/Si.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-d5b2bf9c-2"})(["font-size:0.75rem;font-weight:400;line-height:1.125rem;color:var(--privy-color-foreground-2);"]),mc=e=>e.authenticatorName?e.createdWithBrowser?`${e.authenticatorName} on ${e.createdWithBrowser}`:e.authenticatorName:e.createdWithBrowser?e.createdWithOs?`${e.createdWithBrowser} on ${e.createdWithOs}`:`${e.createdWithBrowser}`:"Unknown device";const wc=/*#__PURE__*/Si.button.withConfig({displayName:"StyledLink",componentId:"sc-d5b2bf9c-3"})(["&&{width:100%;font-size:0.875rem;line-height:1rem;@media (min-width:440px){font-size:14px;}display:flex;gap:12px;justify-content:center;padding:0.75rem 1rem;background-color:var(--privy-color-background);transition:background-color 200ms ease;color:var(--privy-color-accent);:focus{outline:none;box-shadow:none;}}"]),yc=({appName:e,onComplete:a,onReset:i,onClose:o})=>{let[s,c]=l(""),[d,h]=l(!1),[u,p]=l(null),[m,w]=l("enroll"),{initEnrollmentWithSms:y,submitEnrollmentWithSms:g}=nc(),{app:f,data:v}=yn();function k(){v?.mfaEnrollmentFlow?.onSuccess(),a()}return u?/*#__PURE__*/t(Pr,{error:u,backFn:()=>p(null),onClick:()=>p(null)}):/*#__PURE__*/n(r,"enroll"===m?{children:[/*#__PURE__*/t(Qt,{backFn:i,onClose:o},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ri,{})}),/*#__PURE__*/t(nn,{children:"Set up SMS verification"}),/*#__PURE__*/n(pn,{children:["We'll text a verification code to this mobile device whenever you use your ",e," ","wallet."]}),/*#__PURE__*/n(sn,{children:[/*#__PURE__*/t(vr,{onSubmit:async function({qualifiedPhoneNumber:e}){try{await y({phoneNumber:e}),c(e),w("verify")}catch(e){p(e)}},hideRecent:!0}),/*#__PURE__*/n(Nr,{children:["By providing your mobile number, you agree to receive text messages from ",f?.name,". Some carrier charges may apply"]})]}),/*#__PURE__*/t(hn,{})]}:d?{children:[/*#__PURE__*/t(Qt,{onClose:k},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Xi,{})}),/*#__PURE__*/t(nn,{children:"SMS verification added"}),/*#__PURE__*/n(pn,{children:["From now on, you'll enter the verification code sent to your mobile device whenever you use your ",e," wallet."]}),/*#__PURE__*/t(Mn,{children:/*#__PURE__*/t(cn,{onClick:k,children:"Done"})}),/*#__PURE__*/t(hn,{})]}:{children:[/*#__PURE__*/t(Qt,{backFn:function(){"verify"===m?w("enroll"):i()},onClose:o},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ri,{})}),/*#__PURE__*/t(nn,{children:"Enter enrollment code"}),/*#__PURE__*/n(sn,{children:[/*#__PURE__*/t(Is,{onChange:async function(e){try{if(!e)return;await g({phoneNumber:s,mfaCode:e}),h(!0)}catch(e){if(Ur(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(vn(e))throw Error("The code you entered is not valid");if(kn(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw Or(e)?Error("Verification canceled"):Error("Unknown error")}}}),/*#__PURE__*/n(pn,{children:["To continue, enter the 6-digit code sent to ",/*#__PURE__*/t("strong",{children:wo(s)})]})]}),/*#__PURE__*/t(hn,{})]})},gc=({size:e,authUrl:n})=>/*#__PURE__*/t(wr,{url:n,squareLogoElement:go,size:e,fgColor:"#1F1F1F"}),fc=({onComplete:e,onClose:a,onReset:i,totpInfo:o})=>{let[s,c]=l("enroll"),[d,h]=l(!1),{submitEnrollmentWithTotp:u}=nc(),{data:p}=yn();function m(){p?.mfaEnrollmentFlow?.onSuccess(),e()}/*#__PURE__*/return n(r,"enroll"===s?{children:[/*#__PURE__*/t(Qt,{backFn:i,onClose:a},"header"),/*#__PURE__*/t(nn,{children:"Scan QR code"}),/*#__PURE__*/t(pn,{children:"Open your authenticator app and scan the QR code to continue."}),/*#__PURE__*/t(mr,{children:/*#__PURE__*/t(gc,{authUrl:o.authUrl,size:200})}),/*#__PURE__*/n(Mn,{children:[/*#__PURE__*/t(ur,{children:/*#__PURE__*/t(yr,{itemName:"setup key",text:o.secret})}),/*#__PURE__*/t(cn,{onClick:function(){c("verify")},children:"Continue"})]}),/*#__PURE__*/t(hn,{})]}:d?{children:[/*#__PURE__*/t(Qt,{onClose:m},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Xi,{})}),/*#__PURE__*/t(nn,{children:"Authenticator app verification added"}),/*#__PURE__*/n(pn,{children:["From now on, you'll enter the verification code generated by your authenticator app whenever you use your ",o.appName," wallet."]}),/*#__PURE__*/t(Mn,{children:/*#__PURE__*/t(cn,{onClick:m,children:"Done"})}),/*#__PURE__*/t(hn,{})]}:{children:[/*#__PURE__*/t(Qt,{backFn:function(){"verify"===s?c("enroll"):i()},onClose:a},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ui,{})}),/*#__PURE__*/t(nn,{children:"Enter enrollment code"}),/*#__PURE__*/t(sn,{children:/*#__PURE__*/t(Is,{onChange:async function(e){try{if(!e)return;await u({mfaCode:e}),h(!0)}catch(e){if(Ur(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(vn(e))throw Error("The code you entered is not valid");if(kn(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw Or(e)?Error("Verification canceled"):Error("Unknown error")}}})}),/*#__PURE__*/n(pn,{children:["To continue, enter the 6-digit code generated from your ",/*#__PURE__*/t("strong",{children:"authenticator app"})]}),/*#__PURE__*/t(hn,{})]})},vc={component:()=>{let{user:e,enrollInMfa:a,ready:i}=$t(),[o,c]=l(null),{unenrollWithSms:d,unenrollWithTotp:h,unenrollWithPasskey:u}=nc(),{app:p,data:m,onUserCloseViaDialogOrKeybindRef:w}=yn(),{closePrivyModal:y}=Pe(),{promptMfa:g}=Ns(),{initEnrollmentWithTotp:f}=nc(),[v,k]=l(!1),[A,C]=l(null),[E,b]=l(null),T=()=>{y({shouldCallAuthOnSuccess:!0}),a(!1),setTimeout((()=>{c(null),C(null)}),500)},{initEnrollmentWithPasskey:_,submitEnrollmentWithPasskey:I}=nc(),[S,W]=l(!1),[x,P]=l(null);w.current=T;let N=e?.mfaMethods.includes("sms"),U=!!e?.phone,O=e?.mfaMethods.includes("totp"),R=e?.mfaMethods.includes("passkey"),M=N||O||R,L=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function D(){c(null),C(null)}if(s((()=>{M&&k(!0)}),[M]),!i||!e||!p/*#__PURE__*/)return n(r,{children:[/*#__PURE__*/t(Qt,{onClose:T},"header"),/*#__PURE__*/t(Ln,{children:/*#__PURE__*/t(rc,{})}),/*#__PURE__*/t(sn,{children:/*#__PURE__*/t(En,{})}),/*#__PURE__*/t(hn,{})]});if("sms"===o)/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{backFn:D,onClose:T},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(co,{})}),/*#__PURE__*/t(nn,{children:"Remove SMS verification?"}),/*#__PURE__*/n(pn,{children:["MFA adds an extra layer of security to your ",p?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/t(Mn,{children:/*#__PURE__*/t(cn,{warn:!0,onClick:async function(){c(null);try{await d()}catch(e){c(null)}},children:"Remove SMS for MFA"})}),/*#__PURE__*/t(hn,{})]});if("totp"===o)/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{backFn:D,onClose:T},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(co,{})}),/*#__PURE__*/t(nn,{children:"Remove Authenticator App verification?"}),/*#__PURE__*/n(pn,{children:["MFA adds an extra layer of security to your ",p?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/t(Mn,{children:/*#__PURE__*/t(cn,{warn:!0,onClick:async function(){c(null);try{await h()}catch(e){c(null)}},children:"Remove Authenticator App for MFA"})}),/*#__PURE__*/t(hn,{})]});if("passkey"===o){let e=m?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{backFn:D,onClose:T},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(co,{})}),/*#__PURE__*/t(nn,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/t(pn,{children:e?"Removing your passkey will remove as both a verification method and a login method.":"Removing your passkey will remove as a verification method."}),/*#__PURE__*/t(Mn,{children:/*#__PURE__*/t(cn,{warn:!0,onClick:async function(){c(null);try{await u({removeForLogin:m?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){c(null)}},children:"Yes, remove"})}),/*#__PURE__*/t(hn,{})]})}if(0===m.mfaEnrollmentFlow.mfaMethods.length&&!M)/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{onClose:T},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Mi,{})}),/*#__PURE__*/t(nn,{children:"Add more security"}),/*#__PURE__*/n(pn,{children:[p?.name," does not have any verification methods enabled."]}),/*#__PURE__*/t(Mn,{children:/*#__PURE__*/t(cn,{onClick:T,children:"Close"})}),/*#__PURE__*/t(hn,{})]});let F=!M&&!v;return F?/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Qt,{onClose:T},"header"),/*#__PURE__*/t(un,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Mi,{})}),/*#__PURE__*/t(nn,{children:"Transaction Protection"}),/*#__PURE__*/t(pn,{children:"Set up transaction protection to add an extra layer of security to your account"}),/*#__PURE__*/n(rn,{children:[/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(so,{})}),"Enable 2-Step verification for your ",p?.name," wallet."]}),/*#__PURE__*/n(an,{children:[/*#__PURE__*/t(on,{children:/*#__PURE__*/t(ho,{})}),"You'll be prompted to authenticate to complete transactions."]})]}),/*#__PURE__*/n(Mn,{children:[/*#__PURE__*/t(cn,{onClick:()=>k(!0),children:"Continue"}),/*#__PURE__*/t(gn,{onClick:T,children:"Not now"})]}),/*#__PURE__*/t(hn,{})]}):"sms"===A?/*#__PURE__*/t(yc,{appName:p?.name||"Privy",onComplete:T,onReset:D,onClose:T}):"totp"===A&&E?/*#__PURE__*/t(fc,{onComplete:T,onClose:T,onReset:D,totpInfo:{...E,appName:p?.name||"Privy"}}):"passkey"===A?/*#__PURE__*/t(sc,{appName:p?.name||"Privy",onComplete:T,onReset:D,onClose:T}):/*#__PURE__*/t(ic,{showIntro:F,userMfaMethods:e.mfaMethods,appMfaMethods:p.mfa.methods,userHasAuthSms:U,onBackToIntro:function(){k(!1)},handleSelectMethod:async function(e){return await g().catch(P),"totp"===e?(C(e),b(null),void f().then((e=>{b(e)})).catch((()=>{b(null),D()}))):"passkey"===e&&1===L.length?await async function(){W(!0);try{await _(),await I({credentialIds:L},{removeForLogin:m?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){P(e)}finally{W(!1)}}():void C(e)},isTotpLoading:"totp"===A&&!E,isPasskeyLoading:S,error:x,onClose:T,setRemovingMfaMethod:async e=>{await g().catch(P),c(e)}})}},kc={component:()=>{let{authenticated:e,logout:a,ready:i,user:o}=$t(),{app:c,setModalData:d,navigate:h,resetNavigation:u}=yn(),{getAuthMeta:p,initLoginWithOAuth:m,loginWithOAuth:w,updateWallets:y,setReadyToTrue:g,closePrivyModal:f,createAnalyticsEvent:v}=Pe(),[k,A]=l(!1),[C,E]=l(void 0),b=p()?.provider||"google",{name:T,component:_}=No(b);s((()=>{w(b).then((()=>{A(!0),g(!0)})).catch((e=>{if(g(!1),e?.privyErrorCode===M.ALLOWLIST_REJECTED)return E(void 0),u(),void h(Rr);if(e?.privyErrorCode===M.USER_LIMIT_REACHED)return console.error(new Ue(e).toString()),E(void 0),u(),void h(Mr);if(e?.privyErrorCode===M.USER_DOES_NOT_EXIST)return E(void 0),u(),void h(Lr);if(e?.privyErrorCode===M.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return E(void 0),u(),d({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:p()?.provider,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void h(Dr);let{retryable:t,detail:n}=function(e,t){let n={detail:"",retryable:!1},r=ot(t);if(e?.privyErrorCode===M.LINKED_TO_ANOTHER_USER&&(n.detail="This account has already been linked to another user."),e?.privyErrorCode===M.INVALID_CREDENTIALS&&(n.retryable=!0,n.detail="Something went wrong. Try again."),e.privyErrorCode===M.OAUTH_USER_DENIED&&(n.detail=`Retry and check ${r} to finish connecting your account.`,n.retryable=!0),e?.privyErrorCode===M.TOO_MANY_REQUESTS&&(n.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===M.TOO_MANY_REQUESTS&&e.message.includes("provider rate limit")){let e=No(t).name;n.detail=`Request limit reached for ${e}. Please wait a moment and try again.`}if(e?.privyErrorCode===M.OAUTH_ACCOUNT_SUSPENDED){let e=No(t).name;n.detail=`Your ${e} account is suspended. Please try another login method.`}return e?.privyErrorCode===M.CANNOT_LINK_MORE_OF_TYPE&&(n.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode===M.OAUTH_UNEXPECTED&&t.startsWith("privy:")&&(n.detail="Something went wrong. Please try again."),n}(e,b);E({retryable:t,detail:n,message:"Authentication failed"})})).finally((()=>{Fr()}))}),[T,b]),s((()=>{if(i&&e&&k&&o){if(c?.legal.requireUsersAcceptTerms&&!o.hasAcceptedTerms){let e=setTimeout((()=>{h(er)}),tr);return()=>clearTimeout(e)}if(nr(o,c.embeddedWallets)){let e=setTimeout((()=>{d({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),v({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:b,screen:"OAuthStatusScreen"}}),a()},callAuthOnSuccessOnClose:!0}}),h(rr)}),tr);return()=>clearTimeout(e)}{let e=setTimeout((()=>f({shouldCallAuthOnSuccess:!0,isSuccess:!0})),tr);return y(),()=>clearTimeout(e)}}}),[i,e,k,o]);let I=k?`Successfully connected with ${T}`:C?C.message:`Verifying connection to ${T}`,S="";return S=k?"You’re good to go!":C?C.detail:"Just a few moments more",/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Qt,{}),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/n(Ac,{children:[/*#__PURE__*/t(Zt,{children:/*#__PURE__*/n("div",{children:[/*#__PURE__*/t(en,{success:k,fail:!!C}),/*#__PURE__*/t(_,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/n(ir,{children:[/*#__PURE__*/t("h3",{children:I}),/*#__PURE__*/t("p",{children:S})]}),C&&C?.retryable?/*#__PURE__*/t(zr,{onClick:()=>{Fr(),m(b),E(void 0)},disabled:!k&&!C?.retryable,children:"Retry"}):null]}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(hn,{})]})}};let Ac=/*#__PURE__*/Si.div.withConfig({displayName:"ConnectContainer",componentId:"sc-89bb91a9-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-left:27px;margin-right:27px;gap:24px;"]);const Cc=({instructions:e,fees:a,transactionInfo:i,solPrice:o,rpcEndpoint:s})=>{let c=e.reduce(((e,{amount:t,token:n})=>t&&"SOL"===n?.symbol?e+t:e),0n),[d,h]=l(0),[u,p]=l(!1),m=e[d];/*#__PURE__*/return n(qr,{children:[/*#__PURE__*/n(Br,{children:[/*#__PURE__*/t(Vr,{children:"Total"}),/*#__PURE__*/t(jr,{children:/*#__PURE__*/t(Hr,{quantities:[c,a],tokenPrice:o})})]}),i&&i.action&&/*#__PURE__*/n(Br,{children:[/*#__PURE__*/t(Vr,{children:"Action"}),/*#__PURE__*/t(jr,{children:i.action})]}),/*#__PURE__*/n(Br,{children:[/*#__PURE__*/t(Vr,{children:"Fees"}),/*#__PURE__*/t(jr,{children:/*#__PURE__*/t(Hr,{quantities:[a||0n],tokenPrice:o})})]}),e.length>1?/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Br,{children:/*#__PURE__*/n($r,{onClick:()=>p((e=>!e)),children:[/*#__PURE__*/t("span",{children:"Details"}),/*#__PURE__*/t(vo,{height:"16px",width:"16px",strokeWidth:"2",style:{transition:"all 300ms",transform:u?"rotate(180deg)":void 0}})]})}),u&&/*#__PURE__*/t(Br,{children:/*#__PURE__*/n(bc,{children:[/*#__PURE__*/n(Tc,{children:[/*#__PURE__*/n(_c,{children:[d+1," of ",e.length," instructions"]}),/*#__PURE__*/n(Sc,{children:[d>0&&/*#__PURE__*/t(Kr,{backFn:()=>h((e=>e-1))}),d<e.length-1&&/*#__PURE__*/t(Yr,{nextFn:()=>h((e=>e+1))})]})]}),/*#__PURE__*/t(Ic,{children:/*#__PURE__*/t(Ec,{instruction:m,rpcEndpoint:s,solPrice:o})})]})})]}):/*#__PURE__*/t(Ec,{instruction:m,rpcEndpoint:s,solPrice:o,hideAmount:!0})]})};function Ec({instruction:e,rpcEndpoint:r,solPrice:a,hideAmount:i}){return e?/*#__PURE__*/n(qr,{children:[!i&&!!e.amount&&/*#__PURE__*/n(Br,{children:[/*#__PURE__*/t(Vr,{children:"Amount"}),/*#__PURE__*/t(jr,{children:/*#__PURE__*/t(Hr,{quantities:[e.amount],tokenPrice:a,tokenSymbol:e.token?.symbol??"SOL",tokenDecimals:e.token?.decimals??9})})]}),e.to&&/*#__PURE__*/n(Br,{children:[/*#__PURE__*/t(Vr,{children:"To"}),/*#__PURE__*/t(jr,{children:/*#__PURE__*/t(Gr,{walletAddress:e.to,rpcEndpoint:r,network:"solana"})})]}),e.tokenAccount&&/*#__PURE__*/n(Br,{children:[/*#__PURE__*/t(Vr,{children:"Token account"}),/*#__PURE__*/t(jr,{children:/*#__PURE__*/t(Gr,{walletAddress:e.tokenAccount,rpcEndpoint:r,network:"solana"})})]}),e.tokenAccountOwner&&/*#__PURE__*/n(Br,{children:[/*#__PURE__*/t(Vr,{children:"Token account owner"}),/*#__PURE__*/t(jr,{children:/*#__PURE__*/t(Gr,{walletAddress:e.tokenAccountOwner,rpcEndpoint:r,network:"solana"})})]}),e.from&&/*#__PURE__*/n(Br,{children:[/*#__PURE__*/t(Vr,{children:"From"}),/*#__PURE__*/t(jr,{children:/*#__PURE__*/t(Gr,{walletAddress:e.from,rpcEndpoint:r,network:"solana"})})]})]}):null}let bc=/*#__PURE__*/Si.div.withConfig({displayName:"InstructionsBox",componentId:"sc-5a140027-0"})(["display:flex;flex-direction:column;width:100%;overflow:hidden;&&{border:1px solid;border-color:var(--privy-color-foreground-4);border-radius:var(--privy-border-radius-md);}"]),Tc=/*#__PURE__*/Si.header.withConfig({displayName:"InstructionsBoxHeader",componentId:"sc-5a140027-1"})(["display:flex;justify-content:space-between;align-items:center;padding:12px;background-color:var(--privy-color-background-2);"]),_c=/*#__PURE__*/Si.h4.withConfig({displayName:"HeaderTitle",componentId:"sc-5a140027-2"})(["font-size:14px;font-weight:500;line-height:19.6px;"]),Ic=/*#__PURE__*/Si.div.withConfig({displayName:"InstructionsBoxContent",componentId:"sc-5a140027-3"})(["padding:12px;"]),Sc=/*#__PURE__*/Si.div.withConfig({displayName:"NavigationButtonsConatiner",componentId:"sc-5a140027-4"})(["display:flex;gap:8px;align-items:center;"]);const Wc=({instructions:e,fees:a,onClose:i,receiptHeader:o,receiptDescription:s,transactionInfo:l,solPrice:c,rpcEndpoint:d,signOnly:h})=>/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Qt,{onClose:i}),/*#__PURE__*/t(Zt,{style:{marginBottom:"16px"},children:/*#__PURE__*/n("div",{children:[/*#__PURE__*/t(Xr,{color:"var(--privy-color-success-light)"}),/*#__PURE__*/t(Xi,{height:38,width:38,strokeWidth:2,stroke:"var(--privy-color-success)"})]})}),/*#__PURE__*/t(cr,{title:o??`Transaction ${h?"signed":"complete"}!`,description:s??"You're all set."}),/*#__PURE__*/t(Cc,{solPrice:c,instructions:e,fees:a,transactionInfo:l,rpcEndpoint:d}),/*#__PURE__*/t(Jr,{}),/*#__PURE__*/t(xc,{loading:!1,onClick:i,children:"Close"}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]});let xc=/*#__PURE__*/Si(cn).withConfig({displayName:"SubmitButton",componentId:"sc-6f95cdcf-0"})(["&&{margin-top:24px;}transition:color 350ms ease,background-color 350ms ease;"]);const Pc={component:()=>{let{data:e,onUserCloseViaDialogOrKeybindRef:n,setModalData:r,navigate:a}=yn(),{client:i,closePrivyModal:c,walletProxy:d,showFiatPrices:h}=Pe(),u=An(),{user:p,getAccessToken:m}=$t(),[w,y]=l(e?.sendSolanaTransaction?.transactionRequest),[g,f]=l(),[v,k]=l(),[A,C]=l(0),[E,b]=l({value:0n,isLoading:!1}),[T,_]=l(!1),[I,S]=l(),[W,x]=l(),P=e?.sendSolanaTransaction?.connection,N=e?.sendSolanaTransaction?.transactingWallet,U=e?.sendSolanaTransaction?.signOnly??!1,O=g?.instructions.length??1,R=N?.imported?Qr(p):Pn(p),M=Zr(P?.rpcEndpoint||""),{solPrice:L,isSolPriceLoading:D}=ea({enabled:h}),F=o((()=>{let e,t;if(!g)return;let n=g.spender;0===A&&N?.address===n&&(e=ta(g.fee));let r=ta(E.value,3,!0),a=g.instructions[A];if(!a)return{fee:e,spender:n,balance:r};if("unknown"===a.type)return{fee:e,spender:n,program:a.program,balance:r};if("ata-creation"===a.type)return{fee:e,spender:n,balance:r,tokenAccountOwner:a.owner,tokenAccount:a.ata,tokenAddress:a.mint};let i=a.fromAccount,o="sol-transfer"===a.type?a.toAccount:a.toAccount||a.toAta,s="spl-transfer"===a.type?a.token.address:void 0;return null!=e&&"SOL"===a.token.symbol&&(t=ta(a.value+g.fee)),{fee:e,spender:n,from:i,to:o,tokenAddress:s,amount:`${Di(a.value,a.token.decimals)} ${a.token.symbol}`.trim(),total:t,balance:r}}),[g,A,N?.address,E]),z=o((()=>{let e,t;if(!g||!h||!L||D)return;function n(...e){return ia(e.reduce(((e,t)=>e+t),0n),L??0)}0===A&&N?.address===g.spender&&(e=n(g.fee));let r=n(E.value),a=g.instructions[A];return a&&"unknown"!==a.type&&"ata-creation"!==a.type?(null!=e&&"SOL"===a.token.symbol&&(t=n(a.value,g.fee)),{fee:e,amount:"SOL"===a.token.symbol?n(a.value):`${Di(a.value,a.token.decimals)} ${a.token.symbol}`.trim(),total:t,balance:r}):{fee:e,balance:r}}),[g,h,L,D,N?.address,A,E]),q=o((()=>{if(U||!g||E.isLoading||A>0)return!1;let e=g.instructions[A];if(!e)return!1;let t=0n;return N?.address===g.spender&&(t+=g.fee),"value"in e&&N?.address===e.fromAccount&&"SOL"===e.token.symbol&&(t+=e.value),E.value<t}),[g,E,A,U]);if(s((()=>{!async function(){if(w&&P&&i)try{k(void 0);let e=await na({tx:w,connection:P,client:i});f(e),C(0)}catch(e){console.error("Failed to prepare transaction",e),k(e)}}()}),[w,P,i]),s((()=>{(async function(){if(!N||!P)return;b({value:E.value,isLoading:!0});let e=new yo({name:"mainnet-beta",rpcUrl:P.rpcEndpoint});b({value:await e.getBalance(N.address).catch((()=>0n))??0n,isLoading:!1})})().catch(console.error)}),[g,P]),!(w&&e?.sendSolanaTransaction&&N&&P)){let n=Error("Invalid transaction request");/*#__PURE__*/return t(Pr,{error:n,onClick:()=>{e?.sendSolanaTransaction?.onFailure(n),c({shouldCallAuthOnSuccess:!1})}})}let B=()=>{if(!T)return I?e?.sendSolanaTransaction?.onSuccess(I):(e?.sendSolanaTransaction?.onFailure(W??v??Error("User exited the modal before submitting the transaction")),C(0)),c({shouldCallAuthOnSuccess:!1})};n.current=B;let V=e.sendSolanaTransaction?.uiOptions?.transactionInfo?.contractInfo?.imgUrl?/*#__PURE__*/t("img",{src:e.sendSolanaTransaction.uiOptions.transactionInfo.contractInfo.imgUrl,alt:e.sendSolanaTransaction.uiOptions.transactionInfo.contractInfo.imgAltText}):null,j=!!(e.funding&&e.funding.supportedOptions.length>0),H=q&&j;return I?/*#__PURE__*/t(Wc,{instructions:g?.instructions.reduce(((e,t)=>("ata-creation"===t.type&&e.push({tokenAccountOwner:t.owner,tokenAccount:t.ata}),"spl-transfer"===t.type&&e.push({from:t.fromAccount,to:t.toAccount||t.toAta,amount:t.value,token:t.token}),"sol-transfer"===t.type&&e.push({from:t.fromAccount,to:t.toAccount,amount:t.value,token:t.token}),e)),[])??[],fees:0===A?I.fees:0n,onClose:B,transactionInfo:e.sendSolanaTransaction?.uiOptions.transactionInfo,solPrice:L,receiptHeader:e.sendSolanaTransaction?.uiOptions.successHeader,receiptDescription:e.sendSolanaTransaction?.uiOptions.successDescription,rpcEndpoint:P.rpcEndpoint,signOnly:U}):W?/*#__PURE__*/t(ra,{transactionError:W,connection:P,onClose:B,network:"solana",onRetry:async()=>{x(void 0);let{blockhash:e}=await P.getLatestBlockhash();Un(w)?w.message.recentBlockhash=e:w.recentBlockhash=e,y(w)}}):/*#__PURE__*/t(aa,{img:V,title:e.sendSolanaTransaction?.uiOptions?.transactionInfo?.title||"Confirm transaction",subtitle:e.sendSolanaTransaction?.uiOptions?.description||`${u.name} wants your permission to approve the following transaction.`,cta:H?"Add funds":e.sendSolanaTransaction?.uiOptions?.buttonText||"Approve",transactionIndex:A,maxIndex:O-1,network:"mainnet-beta"==M?"Solana":M,blockExplorerUrl:"https://explorer.solana.com",total:h?z?.total:F?.total,amount:h?z?.amount:F?.amount,fee:h?z?.fee:F?.fee,balance:h?z?.balance:F?.balance,from:F?.from,to:F?.to,tokenAccount:F?.tokenAccount,tokenAccountOwner:F?.tokenAccountOwner,tokenAddress:F?.tokenAddress,transactingWalletAddress:N.address,programAddress:F?.program,disabled:q&&!j,isSubmitting:T,isPreparing:!g||E.isLoading,isTokenPriceLoading:h&&D,isMissingFunds:q,submitError:W??void 0,parseError:v,onClick:H?async()=>{if(N){if(!j)throw Error("Funding wallet is not enabled");r({...e,funding:{...e.funding,methodScreen:zn}}),a(zn)}}:async()=>{if(A<(g?.instructions.length??1)-1)C(A+1);else try{_(!0);let t=await m();if(T||!t||!N||!d||!p||!R)return;let{rootWallet:n}=oa(p,N.address);if(!n)throw Error("No root wallet for transacting wallet found");let{entropyId:r,entropyIdVerifier:a}=bt(n);if(U)await sl({tx:w,accessToken:t,walletProxy:d,entropyId:r,entropyIdVerifier:a,transactingWalletAddress:N.address,transactingWalletIndex:N.walletIndex??0}),S(sa("",w,null));else{let{signature:n,receipt:i}=await ll({tx:w,accessToken:t,connection:P,walletProxy:d,entropyId:r,entropyIdVerifier:a,transactingWalletAddress:N.address,transactingWalletIndex:N.walletIndex??0,transactionOptions:e.sendSolanaTransaction?.transactionOptions});S(sa(n,w,i))}}catch(e){console.warn({transaction:w,error:e}),x(e)}finally{_(!1)}},onClose:B,onBack:A>0&&O>1?()=>C(A-1):void 0})}},Nc=/*#__PURE__*/m(((e,a)=>{let[i,o]=l(""),[s,c]=l(""),[d,h]=l(!1),{authenticated:u,user:p}=$t(),{initUpdateEmail:m}=Pe(),{navigate:w,setModalData:y,currentScreen:g}=yn(),{enabled:f,token:v}=jt(),k=An(),A=la(i)&&(k.disablePlusEmails&&i.includes("+")?(s||c("Please enter a valid email address without a '+'."),!1):(s&&c(""),!0)),C=d||!A,E=()=>{!f||v||u?(async e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");h(!0);try{await m(p.email.address,i,e),w(kr)}catch(e){y({errorModalData:{error:e,previousScreen:g||br}})}h(!1)})(v):(y({captchaModalData:{callback:e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");return m(p.email.address,i,e)},userIntentRequired:!1,onSuccessNavigateTo:kr,onErrorNavigateTo:Ar}}),w(pa))};/*#__PURE__*/return n(r,{children:[/*#__PURE__*/n(Uc,{children:[s&&/*#__PURE__*/t(ca,{style:{marginTop:"0.25rem",textAlign:"left"},children:s}),/*#__PURE__*/n(Oc,{$error:!!s,children:[/*#__PURE__*/t(ao,{}),/*#__PURE__*/t("input",{ref:a,id:"email-input",type:"email",placeholder:"your@email.com",onChange:e=>o(e.target.value),onKeyUp:e=>{"Enter"===e.key&&E()},value:i,autoComplete:"email"}),e.stacked?null:/*#__PURE__*/t(da,{isSubmitting:d,onClick:E,disabled:C,children:"Submit"})]})]}),e.stacked?/*#__PURE__*/t(cn,{loadingText:null,loading:d,disabled:C,onClick:E,children:"Submit"}):null]})}));let Uc=ha,Oc=ua;const Rc={component:()=>/*#__PURE__*/n(r,{children:[/*#__PURE__*/t(Qt,{},"header"),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/t(cr,{title:"Update your email",description:"Add the email address you'd like to use going forward. We'll send you a confirmation code",icon:/*#__PURE__*/t(ao,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/t(gr,{children:/*#__PURE__*/t(Nc,{stacked:!0})}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]})},Mc={component:()=>{let{currentScreen:e,data:a,navigate:i,setModalData:o}=yn(),{user:s}=$t(),{initUpdatePhone:l}=Pe();/*#__PURE__*/return n(r,{children:[/*#__PURE__*/t(Qt,{},"header"),/*#__PURE__*/t(Cn,{}),/*#__PURE__*/t(cr,{title:"Update your phone number",description:"Add the phone number you'd like to use going forward. We'll send you a confirmation code",icon:/*#__PURE__*/t(Ri,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/t(gr,{children:/*#__PURE__*/t(vr,{stacked:!0,onSubmit:async function({qualifiedPhoneNumber:t}){try{if(!s?.phone?.number)throw Error("User is required to have an phone number to update it.");await l(s?.phone?.number,t),i(kr)}catch(t){o({errorModalData:{error:t,previousScreen:a?.errorModalData?.previousScreen||e||Ql}}),i(Ar)}},hideRecent:!0})}),/*#__PURE__*/t(bn,{}),/*#__PURE__*/t(Zn,{})]})}};let Lc,Dc,Fc,zc,qc,Bc,Vc,jc;function Hc(){return Lc?Lc.getCustomerAccessToken():Promise.resolve(ze.get(xt)||null)}async function $c(){return Lc?Lc.getAccessToken():Promise.resolve(ze.get(Pt)||ze.get(xt)||null)}const Kc=(e,t)=>Dc(e,t),Yc=(e,t)=>Fc(e,t),Gc=(e,t)=>zc(e,t),Xc=(e,t)=>qc(e,t),Jc=()=>Bc(),Qc=()=>Vc(),Zc=({message:e,options:t})=>jc({message:e,options:t}),ed=({config:e,...n})=>{var r;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new C("Embedded wallet is only available over HTTPS");if("string"!=typeof(r=n.appId)||25!==r.length)throw new C("Cannot initialize the Privy provider with an invalid Privy app ID");Lc||(Lc=new fs({appId:n.appId,appClientId:n.clientId,apiUrl:n.apiUrl}));let a=Object.assign({},e);/*#__PURE__*/
4
- return t(ma,{client:Lc,clientConfig:a,children:/*#__PURE__*/t(wa,{children:/*#__PURE__*/t(td,{...n,client:Lc})})})};let td=e=>{let r=e.client,i=ya();cl();let[c,d]=l(!1),[h,m]=l(!1),[w,y]=l(!1),[g,f]=l(null),[E,b]=l([]),[_,I]=l([]),[S,W]=l([]),[x,P]=l(!1),[N,U]=l(null),[O,R]=l(!1),[L,F]=l({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:Oe}),[z,q]=l({status:"initial"}),[B,V]=l({status:"initial"}),[j,H]=l({status:"initial"}),[$,K]=l({status:"initial"}),[Y,X]=l({status:"initial"}),[J,Q]=l({status:"initial"}),[Z,ee]=l(null),te=An(),ne=In(),[re,ae]=l({}),[ie,oe]=l(null),[se,le]=l(null),[ce,de]=l(!1),[he,ue]=l(!1),[pe,me]=l(te.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),we=u(null),ye=u(null),ge=u(ga),[fe,ve]=l(!1);r.onStoreCustomerAccessToken=e=>{e&&fa(ge,"accessToken","onAccessTokenGranted",{accessToken:e})},r.onDeleteCustomerAccessToken=()=>{f(null),y(!1),fa(ge,"accessToken","onAccessTokenRemoved")};let ke=u(null),Ae=u(null),Ce=u(!1),Ee=({showWalletUIs:e})=>Ce.current?Ce.current:void 0!==e?!e:!te.embeddedWallets.showWalletUIs,be=e=>{U(e),setTimeout((()=>{d(!0)}),15)};s((()=>{let e=[...va(g),Qr(g)].filter((e=>!!e));Z&&W(e.map((e=>({type:"solana",imported:e.imported,address:e.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",walletIndex:e.walletIndex??void 0,meta:{name:"Privy Wallet",icon:void 0,id:"io.privy.solana.wallet"},linked:!0,fund(){throw new C("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new C("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new ol(Z,e.address),async signMessage(t){let n=await $c();if(!n||!Z)throw new C("Must have valid access token and Privy wallet to send transaction",M.MUST_BE_AUTHENTICATED);let r=e.imported?Qr(g):Pn(g);if(!r)throw new C("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:i}=bt(r);if(!await ct.recoverPrimaryWallet().catch((()=>!1)))throw new C("Wallet couldn't be connected",M.UNKNOWN_CONNECT_WALLET_ERROR);if(!g)throw new C("Attempting to sign a transaction with no user initialized");let{response:o}=await Z.rpc({accessToken:n,entropyId:a,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:e.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(o.data.signature,"base64")},async sendTransaction(e,t,n){let{signature:r}=await nt({transaction:e,connection:t,transactionOptions:n,wallet:this,signOnly:!1});return r},async signTransaction(t){let n=await $c();if(!n||!Z)throw new C("Must have valid access token and Privy wallet to send transaction",M.MUST_BE_AUTHENTICATED);if(!await ct.recoverPrimaryWallet().catch((()=>!1)))throw new C("Wallet couldn't be connected",M.UNKNOWN_CONNECT_WALLET_ERROR);let r=e.imported?e:Pn(g);if(!r)throw new C("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:i}=bt(r);return await sl({tx:t,accessToken:n,walletProxy:Z,entropyId:a,entropyIdVerifier:i,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0}),t},async signAllTransactions(t){let n=await $c();if(!n||!Z)throw new C("Must have valid access token and Privy wallet to send transaction",M.MUST_BE_AUTHENTICATED);if(!await ct.recoverPrimaryWallet().catch((()=>!1)))throw new C("Wallet couldn't be connected",M.UNKNOWN_CONNECT_WALLET_ERROR);let r=e.imported?e:Pn(g);if(!r)throw new C("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:i}=bt(r);for(let r of t)await sl({tx:r,accessToken:n,walletProxy:Z,entropyId:a,entropyIdVerifier:i,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0});return t},loginOrLink:async()=>{throw new C("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[Z,g]),s((()=>{if(!g)return void r.connectors?.removeEmbeddedWalletConnectors();let t=ka(g),n=Aa(g),a=Ca(g);t&&n.length||r.connectors?.removeEmbeddedWalletConnectors(),a||r.connectors?.removeImportedWalletConnector(),r.connectors?Z?(t&&r.connectors.addEmbeddedWalletConnectors({walletProxy:Z,rootWallet:t,embeddedWallets:n,defaultChain:te.defaultChain,appId:e.appId}),a&&r.connectors.addImportedWalletConnector(Z,a.address,te.defaultChain,e.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")}),[Z,g]),s((()=>{Z&&se?.(Z)}),[Z]);let Te=u();s((()=>{(async()=>{if(!te.customAuth?.enabled)return void me({status:"not-enabled"});let{getCustomAccessToken:e,isLoading:t}=te.customAuth;if(h&&!t&&"loading"!==pe.status){me({status:"loading"});try{let t=await e();if(t===Te.current)return void me({status:"done"});if(!t&&w)return Te.current=t,await lt.logout(),me({status:"done"}),void fa(ge,"customAuth","onUnauthenticated");if(!t)return Te.current=t,void me({status:"done"});r.startAuthFlow(new Eo(t));let{user:n,isNewUser:a}=await r.authenticate();if(!n)return await lt.logout(),me({status:"error",error:new C("Failed to sync with custom auth provider")}),void fa(ge,"customAuth","onUnauthenticated");void 0!==a&&fa(ge,"login","onComplete",{user:n,isNewUser:a,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),Te.current=t,fa(ge,"customAuth","onAuthenticated",{user:n}),me({status:"done"}),f(n||null),P(a||!1),y(!0),ue(!0)}catch(e){if(console.warn(e),await lt.logout(),fa(ge,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void me({status:"initial"});fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),me({status:"error",error:e})}}})()}),["initial"===pe.status,te.customAuth?.enabled,te.customAuth?.getCustomAccessToken,te.customAuth?.isLoading,h,w]),s((()=>{he&&Z&&g&&(async()=>{let e=Ea(g,te.embeddedWallets.ethereum.createOnLogin),t=ba(g,te.embeddedWallets.solana.createOnLogin),n=await $c();if(n){if(e&&t){let e=await je(g,Ua);return await Z.createSolana({accessToken:n,ethereumAddress:e?.address}),void ue(!1)}if(t)return await Z.createSolana({accessToken:n,ethereumAddress:ka(g)?.address}),await ct.refreshSessionAndUser(),void ue(!1);if(e)return await je(g,Ua),void ue(!1)}})().catch(console.error)}),[he&&Z&&g]),s((()=>{if(te.externalWallets.solana.connectors)return te.externalWallets.solana.connectors.onMount(),()=>te.externalWallets.solana.connectors?.onUnmount()}),[te.externalWallets.solana.connectors]),s((()=>{!h&&ne&&async function(){let e,t=_e(),n=Ie(),i=a();r.initializeConnectorManager({walletConnectCloudProjectId:te.walletConnectCloudProjectId,rpcConfig:te.rpcConfig,chains:te.chains,defaultChain:te.defaultChain,store:i,walletList:te.appearance.walletList,shouldEnforceDefaultChainOnConnect:te.shouldEnforceDefaultChainOnConnect,externalWalletConfig:te.externalWallets,appName:te.name??"Privy",walletChainType:te.appearance.walletChainType}),r.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=r.connectors.walletConnectors.length,n=r.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);n===t?ve(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:n,expected:t}),ve(!0)}),1500)})),r.connectors?.initialize().then((()=>{Ue()}));let o=await r.getAuthenticatedUser(),s=!!o;te.legal.requireUsersAcceptTerms&&o&&!o.hasAcceptedTerms?(await r.logout(),ct.setReadyToTrue(!0),fa(ge,"logout","onSuccess")):(te.customAuth?.enabled||(y(!!o),o&&fa(ge,"login","onComplete",{user:o,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),f(o)),t?Ae.current=s?"link":"login":n&&!s?(Ae.current="login",ae({telegramAuthModalData:{seamlessAuth:!0}}),be(Ha)):ct.setReadyToTrue(!!o))}()}),[r,ie,h,ne]),s((()=>{if(h){if(!g||!g.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void de(!0);de([...E,...S].some((e=>"privy"===e.walletClientType)))}}),[h,g,E,S]),s((()=>{r.connectors?.setWalletList(te.appearance.walletList)}),[te.appearance.walletList.join()]);let _e=()=>{let e=Uo();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(dl).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(r.startAuthFlow(new Wo(e)),be(kc),!0))},Ie=()=>{let e=$a();if(!e||!te.loginMethods.telegram||!te.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new Ia;return r.startAuthFlow(t),"login-url"===e.flowType&&(t.meta.telegramWebAppData=void 0,t.meta.telegramAuthResult=e.authData),"web-app"===e.flowType&&(t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=e.authData),!0},Se=async(e,t,n,a)=>{if("solana_adapter"!==e)We(await(r.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,n,a);else{let e=r.connectors?.findSolanaWalletConnector(t);if(!e)return;We(e,t,n,a)}};async function We(e,t,n,r){if(!e)return F({status:"disconnected",connectedWallet:null,connectError:new G("Unable to connect to wallet."),connector:null,connectRetry:Oe}),r?.(null,n);F({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:Oe}),e instanceof Tt&&t&&await e.resetConnection(t),F({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>We(e,t,n,r)});try{let t=await e.connect({showPrompt:!0});if((!t||It(t))&&te.shouldEnforceDefaultChainOnConnect&&!te.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){F((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:Oe})));try{await(t?.switchChain(te.defaultChain.id)),t&&(t.chainId=Ka(ut(te.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${te.defaultChain.id}`)}}return F((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:Oe}))),t&&fa(ge,"connectWallet","onSuccess",{wallet:t}),r?.(t,n)}catch(e){return e instanceof Ne?(console.warn(e.cause?e.cause:e.message),fa(ge,"connectWallet","onError",e.privyErrorCode||M.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),fa(ge,"connectWallet","onError",M.UNKNOWN_CONNECT_WALLET_ERROR)),F((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),r?.(null,n)}}let xe=async(e,t,n)=>{if(null===e||!It(e))return;let a=new Wt(e,r,t,n);r.startAuthFlow(a)},Pe=async(e,t,n)=>{if(null===e||!Ci(e))return;let a=new Na(e,r,t,n);r.startAuthFlow(a)},Ue=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),n=e.get("privy_wallet_client"),a="true"===e.get("privy_connect_only");if(!t||!n)return;let i=Ya({connectorType:t,walletClientType:n});if(!i||!i.isInstalled)return be(tc);if(!r.connectors)throw new C("Connector not initialized");be(a?Ga:Xa);let o=new URL(window.location.href);o.searchParams.delete("privy_connector"),o.searchParams.delete("privy_wallet_client"),o.searchParams.delete("privy_connect_only"),window.history.pushState({},"",o),Se(t,n,void 0,a?void 0:"solana_adapter"===t?Pe:xe)};s((()=>{h&&w&&null===g&&r.getAuthenticatedUser().then(f)}),[h,w,g,r]);let Le=e=>{if(!w)throw fa(ge,"linkAccount","onError",M.MUST_BE_AUTHENTICATED,{linkMethod:e}),new C("User must be authenticated before linking an account.")},De=e=>{if(!w||!g)return!1;if("privy"===e.walletClientType)return!0;for(let t of g.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},qe=async e=>{let t;if(!r.connectors)throw new C("Connector not initialized");t="ethereum"===e.type?r.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:r.connectors.findSolanaWalletConnector(e.walletClientType)||null,F((n=>({...n,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:Oe}))),te.captchaEnabled&&!w?(ae({captchaModalData:{callback:t=>It(e)?xe(e,t):Pe(e,t),userIntentRequired:!1,onSuccessNavigateTo:Xa,onErrorNavigateTo:Ar}}),be(pa)):(It(e)?await xe(e):await Pe(e),be(Xa))},Ve=()=>{b((e=>{let t=r.connectors?.wallets.filter(It).map((e=>({...e,linked:De(e),loginOrLink:async()=>{if(!await e.isConnected())throw new C("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new C("Cannot link or login with embedded wallet");qe(e)},fund:async t=>{await ct.fundWallet(e.address,t)},unlink:async()=>{if(!w)throw new C("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new C("Cannot unlink an embedded wallet");f(await r.unlinkEthereumWallet(e.address))}})))||[];return Ja(e,t)?e:t})),I((e=>{let t=(r.connectors?.wallets??[]).filter(Ci).map((e=>({...e,linked:De(e),loginOrLink:async()=>{if(!await e.isConnected())throw new C("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new C("Cannot link or login with embedded wallet");qe(e)},fund:async()=>{throw new C("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!w)throw new C("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new C("Cannot unlink an embedded wallet");f(await r.unlinkSolanaWallet(e.address))}})));return Ja(e,t)?e:t}))};s((()=>{Ve()}),[g?.linkedAccounts,w,h]),s((()=>{if(h){if(!r.connectors)throw new C("Connector not initialized");Ve(),r.connectors.on("walletsUpdated",Ve)}}),[h]),s((()=>{[...te.loginMethodsAndOrder?.primary??[],...te.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>r.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!r]);let je=async(e,t,n)=>{let r=ka(e),a=Ta(e);if(n&&"walletIndex"in n&&"number"==typeof n.walletIndex)return Qe(e,t,n.walletIndex,r,a);let i=n&&"createAdditional"in n&&n.createAdditional;if(r&&!i)throw fa(ge,"createWallet","onError",M.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[o,s]=await Promise.all([ct.initializeWalletProxy(t),$c()]);if(!o&&te.customAuth?.enabled)throw fa(ge,"createWallet","onError",M.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||te.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return Je();if(!r)return a&&await ct.recoverPrimaryWallet(),await o.create({accessToken:s,solanaAddress:a?.address}),et(0,"ethereum");{let t=(_a(e)?.walletIndex??0)+1,{entropyId:n,entropyIdVerifier:r}=bt(Pn(e));return await ct.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:n,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:t}),et(t,"ethereum")}},Je=async()=>new Promise(((e,t)=>{ae({createWallet:{onSuccess:t=>{fa(ge,"createWallet","onSuccess",{wallet:t}),e(t)},onFailure:e=>{fa(ge,"createWallet","onError",M.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),be(rr)})),Qe=async(e,t,n,r,a)=>{if(n<0)throw fa(ge,"createWallet","onError",M.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${n}) is invalid.`);let[i,o]=await Promise.all([ct.initializeWalletProxy(t),$c()]);if(!i&&te.customAuth?.enabled)throw fa(ge,"createWallet","onError",M.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!i||!o||te.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==n)return Je();throw fa(ge,"createWallet","onError",M.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==n){if(r)return r;await i.create({accessToken:o,solanaAddress:a?.address})}else{if(!r)throw fa(ge,"createWallet","onError",M.EMBEDDED_WALLET_CREATE_ERROR),Error("A user must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let t=Aa(e).find((e=>e.walletIndex===n));if(t)return t;let{entropyId:a,entropyIdVerifier:s}=bt(Pn(e));await ct.recoverPrimaryWallet(),await i.addWallet({accessToken:o,entropyId:a,entropyIdVerifier:s,chainType:"ethereum",hdWalletIndex:n})}return et(n,"ethereum")},Ze=async({user:e,wp:t,accessToken:n,walletIndex:r,ethereumWallet:a})=>{let i=va(e).find((e=>e.walletIndex===r));if(i)return i;if(0===r)a&&await ct.recoverPrimaryWallet(),await t.createSolana({accessToken:n,ethereumAddress:a?.address});else{let a=Pn(e);if(!a)throw fa(ge,"createWallet","onError",M.EMBEDDED_WALLET_CREATE_ERROR),Error("User must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let{entropyId:i,entropyIdVerifier:o}=bt(a);await ct.recoverPrimaryWallet(),await t.addWallet({accessToken:n,entropyId:i,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:r})}return et(r,"solana")},et=async(e,t)=>{let n=await ct.refreshSessionAndUser(),r=("ethereum"===t?Aa(n):va(n)).find((t=>t.walletIndex===e));if(!r)throw fa(ge,"createWallet","onError",M.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return fa(ge,"createWallet","onSuccess",{wallet:r}),r},tt=({transaction:t,uiOptions:n,fundWalletConfig:r,address:a,signOnly:i})=>new Promise((async(o,s)=>{let{requesterAppId:l}=n||{},c=i?"signTransaction":"sendTransaction";if(!w||!g)return fa(ge,c,"onError",M.MUST_BE_AUTHENTICATED),void s(Error("User must be authenticated before signing with a Privy wallet"));let d=a??ka(g)?.address;if(!d)throw new C("User must have an embedded wallet to send a transaction.");let{signingWallet:h,rootWallet:u}=Wa(g,d);if(!u||!h)return fa(ge,c,"onError",M.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have a Privy wallet before signing"));let p=dt.wallets.find((e=>"privy"===e.walletClientType&&k(e.address)===k(h.address))),m=await(p?.getEthereumProvider());if(!p||!m)throw new C(`Cannot sendTransaction before embedded wallet ${h.address} is connected`);let y=t.chainId?Number(t.chainId):Ei(p.chainId);(e=>{if(!te.chains.map((e=>e.id)).includes(e))throw new G(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,M.UNSUPPORTED_CHAIN_ID)})(y);let f={...t,from:t.from??h.address,chainId:y},v=await $c();if(!v||!Z)return fa(ge,c,"onError",M.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have valid access token and Privy wallet to send transaction"));let A=mt(f.chainId,te.chains,te.rpcConfig,{appId:e.appId});if(Ee({showWalletUIs:n?.showWalletUIs}))(async()=>{try{if(!await ct.recoverPrimaryWallet())return fa(ge,c,"onError",M.UNKNOWN_CONNECT_WALLET_ERROR),void s(Error("Unable to connect to wallet"));let e=await Gt(f,A,f.from),{entropyId:t,entropyIdVerifier:n}=bt(u),r=i?await ei({accessToken:v,entropyId:t,entropyIdVerifier:n,transactingWallet:h,walletProxy:Z,transactionRequest:f,requesterAppId:l}):await si({accessToken:v,entropyId:t,entropyIdVerifier:n,transactingWallet:h,walletProxy:Z,transactionRequest:e,publicClient:A,requesterAppId:l});i?fa(ge,"signTransaction","onSuccess",{signature:r}):fa(ge,"sendTransaction","onSuccess",{hash:r}),o({hash:r})}catch(e){fa(ge,c,"onError",M.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:e,entropyIdVerifier:t}=bt(u),a=Rl(te)?Ai({address:h.address,appConfig:te,fundWalletConfig:r,methodScreen:zn,chainIdOverride:f.chainId,comingFromSendTransactionScreen:!0}):void 0;ae({connectWallet:{entropyId:e,entropyIdVerifier:t,onCompleteNavigateTo:Za,onFailure:e=>{fa(ge,c,"onError",M.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},sendTransaction:{transactionRequest:f,transactingWallet:h,entropyId:e,entropyIdVerifier:t,signOnly:i,onConfirm:i?async()=>await ei({accessToken:v,entropyId:e,entropyIdVerifier:t,transactingWallet:h,walletProxy:Z,transactionRequest:f,requesterAppId:l}):void 0,onSuccess:e=>{i?fa(ge,"signTransaction","onSuccess",{signature:e.hash}):fa(ge,"sendTransaction","onSuccess",{hash:e.hash}),o(e)},onFailure:e=>{fa(ge,c,"onError",M.TRANSACTION_FAILURE),s(e)},uiOptions:n||{},fundWalletConfig:r,requesterAppId:l},funding:a}),be(no)}})),nt=({transaction:e,connection:t,transactionOptions:n,fundWalletConfig:r,uiOptions:a,wallet:i,signOnly:o})=>new Promise((async(s,l)=>{let{requesterAppId:c}=a||{},d=o?"signSolanaTransaction":"sendSolanaTransaction";if(!w||!g)return fa(ge,d,"onError",M.MUST_BE_AUTHENTICATED),void l(new C("User must be authenticated before signing with a Privy wallet",M.MUST_BE_AUTHENTICATED));let h=i?g.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):Ta(g);if(!h)return fa(ge,d,"onError",M.EMBEDDED_WALLET_NOT_FOUND),void l(new C("Must have a Privy wallet before signing",M.EMBEDDED_WALLET_NOT_FOUND));let{rootWallet:u}=oa(g,h.address);if(!await ct.recoverPrimaryWallet().catch((()=>!1))||!u)throw fa(ge,d,"onError",M.EMBEDDED_WALLET_NOT_FOUND),new C(`Cannot sendSolanaTransaction before embedded wallet ${h.address} is connected`,M.EMBEDDED_WALLET_NOT_FOUND);if(Ee({showWalletUIs:a?.showWalletUIs}))(async()=>{let r=await $c();if(!r||!Z)return fa(ge,d,"onError",M.EMBEDDED_WALLET_NOT_FOUND),void l(new C("Must have valid access token and Privy wallet to send transaction",M.EMBEDDED_WALLET_NOT_FOUND));try{let i;if(!await ct.recoverPrimaryWallet())return fa(ge,d,"onError",M.UNKNOWN_CONNECT_WALLET_ERROR),void l(new C("Unable to connect to wallet",M.UNKNOWN_CONNECT_WALLET_ERROR));if(Ee({showWalletUIs:a?.showWalletUIs})&&!o)try{if(!await ti(e,t))return fa(ge,d,"onError",M.INSUFFICIENT_BALANCE),void l(new C("Solana wallet has insufficient funds for this transaction.",M.INSUFFICIENT_BALANCE))}catch(e){return console.error(e),fa(ge,d,"onError",M.TRANSACTION_FAILURE),void l(new C(e instanceof Error?e.message:"Transaction failed.",M.TRANSACTION_FAILURE))}let{entropyId:c,entropyIdVerifier:u}=ni(g);if(o)await sl({accessToken:r,tx:e,walletProxy:Z,entropyId:c,entropyIdVerifier:u,transactingWalletAddress:h.address,transactingWalletIndex:h.walletIndex??0}),i=sa("",e,null),fa(ge,"signSolanaTransaction","onSuccess",{signedTransaction:e});else{let{signature:a,receipt:o}=await ll({accessToken:r,tx:e,connection:t,walletProxy:Z,transactionOptions:n,entropyId:c,entropyIdVerifier:u,transactingWalletAddress:h.address,transactingWalletIndex:h.walletIndex??0});i=sa(a,e,o),fa(ge,"sendSolanaTransaction","onSuccess",{response:i})}s(i)}catch(e){fa(ge,d,"onError",M.TRANSACTION_FAILURE),l(e)}})();else{let{entropyId:i,entropyIdVerifier:p}=bt(u),m=Rl(te)?ki({address:h.address,appConfig:te,methodScreen:zn,fundWalletConfig:r,comingFromSendTransactionScreen:!0}):void 0;ae({connectWallet:{entropyId:i,entropyIdVerifier:p,onCompleteNavigateTo:Pc,onFailure:e=>{fa(ge,d,"onError",M.UNKNOWN_CONNECT_WALLET_ERROR),l(e)}},sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:n,transactingWallet:h,onSuccess:e=>{o?fa(ge,"signSolanaTransaction","onSuccess",{signedTransaction:e.signedTransaction}):fa(ge,"sendSolanaTransaction","onSuccess",{response:e}),s(e)},onFailure:e=>{fa(ge,d,"onError",M.TRANSACTION_FAILURE),l(e)},uiOptions:a||{},requesterAppId:c,signOnly:o},funding:m}),be(no)}}));function rt(){return new Promise((async(e,t)=>{let n=await $c();if(!n||!Z)throw Error("Must have valid access token to enroll in MFA");try{await Z.verifyMfa({accessToken:n}),e()}catch(e){t(e)}}))}let at=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],it=e=>{let t=g?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:n,loginMethod:r}=li(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw fa(ge,"linkAccount","onError",M.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:r}),new C(`User already has an account of type ${n} linked.`)};async function ot({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){U(null);let n=t?"setWalletPassword":"setWalletRecovery";if(!w||!g)throw fa(ge,n,"onError",M.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let r=Pn(g);if(!r||!Z)throw fa(ge,n,"onError",M.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await rt()}catch(e){throw fa(ge,n,"onError",M.MISSING_MFA_CREDENTIALS),e}return new Promise(((a,i)=>{let o={onSuccess:e=>{fa(ge,n,"onSuccess",{method:"user-passcode",wallet:e}),a(e)},onFailure:e=>{fa(ge,n,"onError",M.USER_EXITED_SET_PASSWORD_FLOW),i(e)},callAuthOnSuccessOnClose:!1},s="user-passcode"===r.recoveryMethod,l=ri({walletAction:"update",availableRecoveryMethods:te.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:d}=bt(r);ae({setWalletPassword:o,recoverWallet:{entropyId:c,entropyIdVerifier:d,onFailure:i},createWallet:o,connectWallet:{onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,entropyIdVerifier:d,onFailure:e=>{fa(ge,n,"onError",M.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s}}),be(no)}))}async function st({appId:e,action:t}){let n=await $c();if("link"===t&&!n)throw fa(ge,"linkAccount","onError",M.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new C("User must be authenticated before linking an account.");if("login"===t&&n)throw fa(ge,"login","onError",M.UNKNOWN_AUTH_ERROR),new C("Attempted to log in, but user is already logged in. Use a `link` helper instead.");ke.current=`privy:${e}`,Ae.current=t;let a=Rn();return r.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(n,i)=>{let{name:o,logoUrl:s}=await pl({api:r.api,providerAppId:e,requesterAppId:te.id});ae({crossAppAuth:{appId:e,name:o,logoUrl:s,action:t,popup:a,onSuccess:n,onError:i}}),be(Dl)}))}let lt={ready:h,authenticated:w,user:g,walletConnectors:r.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),ae({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress,walletChainType:e?.walletChainType}}),be(w?Ll:ai)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),Le("siwe"),ke.current="siwe",Ae.current="link",ae({...re,externalConnectWallet:{...re.externalConnectWallet,suggestedAddress:e?.suggestedAddress,walletList:e?.walletList,walletChainType:e?.walletChainType}}),be(Zl)},startCrossAppAuthFlow:st,linkEmail:()=>{Le("email"),it("email"),ke.current="email",Ae.current="link",be(Jl)},linkPhone:()=>{Le("sms"),it("phone"),ke.current="sms",Ae.current="link",be(Ql)},linkGoogle:async()=>{Le("google"),it("google_oauth"),Ae.current="link",await ct.initLoginWithOAuth("google")},linkTwitter:async()=>{Le("twitter"),it("twitter_oauth"),Ae.current="link",await ct.initLoginWithOAuth("twitter")},linkDiscord:async()=>{Le("discord"),it("discord_oauth"),Ae.current="link",await ct.initLoginWithOAuth("discord")},linkGithub:async()=>{Le("github"),it("github_oauth"),Ae.current="link",await ct.initLoginWithOAuth("github")},linkSpotify:async()=>{Le("spotify"),it("spotify_oauth"),Ae.current="link",await ct.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Le("instagram"),it("instagram_oauth"),Ae.current="link",await ct.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Le("tiktok"),it("tiktok_oauth"),Ae.current="link",await ct.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{Le("linkedin"),it("linkedin_oauth"),Ae.current="link",await ct.initLoginWithOAuth("linkedin")},linkApple:async()=>{Le("apple"),it("apple_oauth"),Ae.current="link",await ct.initLoginWithOAuth("apple")},linkPasskey:async()=>{Le("passkey"),it("passkey"),await ct.initLinkWithPasskey(),be(vl)},linkTelegram:async e=>{if(Le("telegram"),it("telegram"),Ae.current="link",ke.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new Ia;r.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=Sa(e.launchParams.initDataRaw),ae({telegramAuthModalData:{seamlessAuth:!0}}),be(Ha)}else fa(ge,"linkAccount","onError",M.INVALID_DATA,{linkMethod:"telegram"});else await ct.initLoginWithTelegram();be(Ha)},linkFarcaster:async()=>{Le("farcaster"),it("farcaster"),await ct.initLoginWithFarcaster(),Ae.current="link",ke.current="farcaster",be(ii)},updateEmail:()=>{if(Le("email"),!g?.email)throw new C("User does not have an email linked to their account.");Ae.current="update",ke.current="email",be(Rc)},updatePhone:()=>{if(Le("sms"),!g?.phone)throw new C("User does not have a phone number linked to their account.");Ae.current="update",ke.current="sms",be(Mc)},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(!h){let e=await new Promise((e=>{oe((t=>e.bind(t)))}));if(oe(null),e)return void console.warn(t)}!g||g.isGuest?(Ae.current="login",ae({login:e}),be(br)):console.warn(t)},connectOrCreateWallet:async()=>{h||(await new Promise((e=>{oe((()=>e))})),oe(null)),w?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(Ae.current="login",be(oi))},logout:async()=>{if(Ae.current=null,ke.current=null,g&&r.clearProviderAcccessTokens(g),U(null),await r.logout(),g&&Z)try{await Z.clearMfa({userId:g.id})}catch(e){}f(null),y(!1),fa(ge,"logout","onSuccess"),d(!1),ze.del(Vt),ze.del(Be(te.id))},getAccessToken:p((()=>r.getCustomerAccessToken()),[r]),unlinkWallet:async e=>{let t;return f(t=e.startsWith("0x")?await r.unlinkEthereumWallet(e):await r.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await r.unlinkEmail(e);return f(t),t},unlinkPhone:async e=>{let t=await r.unlinkPhone(e);return f(t),t},unlinkGoogle:async e=>{let t=await r.unlinkOAuth("google",e);return f(t),t},unlinkTwitter:async e=>{let t=await r.unlinkOAuth("twitter",e);return f(t),t},unlinkDiscord:async e=>{let t=await r.unlinkOAuth("discord",e);return f(t),t},unlinkGithub:async e=>{let t=await r.unlinkOAuth("github",e);return f(t),t},unlinkSpotify:async e=>{let t=await r.unlinkOAuth("spotify",e);return f(t),t},unlinkInstagram:async e=>{let t=await r.unlinkOAuth("instagram",e);return f(t),t},unlinkTiktok:async e=>{let t=await r.unlinkOAuth("tiktok",e);return f(t),t},unlinkLinkedIn:async e=>{let t=await r.unlinkOAuth("linkedin",e);return f(t),t},unlinkApple:async e=>{let t=await r.unlinkOAuth("apple",e);return f(t),t},unlinkFarcaster:async e=>{let t=await r.unlinkFarcaster(e);return f(t),t},unlinkTelegram:async e=>{let t=await r.unlinkTelegram(e);return f(t),t},unlinkPasskey:async e=>{let t=await $c();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!Z)throw Error("Wallet proxy not initialized.");let n=te.passkeys.shouldUnenrollMfaOnUnlink;await Z.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:n});let a=await r.getAuthenticatedUser();return f(a),a},unlinkCrossAppAccount:async({subject:e})=>{let t=g?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new C("Invalid subject");r.storeProviderAccessToken(t.id,null);let n=await r.unlinkOAuth(`privy:${t.id}`,e);return f(n),n},createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let t=await ct.refreshSessionAndUser();if(!t)throw fa(ge,"createWallet","onError",M.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return je(t,15e3,e)},setWalletRecovery:async e=>ot({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>ot({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(n,a)=>{let{requesterAppId:i}=t?.uiOptions||{},o=e.message;if(!w||!g)return fa(ge,"signMessage","onError",M.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let s=t?.address??ka(g)?.address;if(!s)throw new C("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:c}=Wa(g,s);if(!l||!c)return fa(ge,"signMessage","onError",M.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof o||o.length<1)return fa(ge,"signMessage","onError",M.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));let d=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let e=await $c();if(!Z||!e||!await ct.recoverPrimaryWallet())throw Error("Unable to connect to wallet");r.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:l.address,requesterAppId:i}});let{entropyId:t,entropyIdVerifier:n}=bt(c),{response:a}=await Z.rpc({accessToken:e,entropyId:t,entropyIdVerifier:n,chainType:"ethereum",hdWalletIndex:l.walletIndex??0,requesterAppId:i,request:{method:"personal_sign",params:[o,l.address]}}),s=a.data;return r.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:l.address,requesterAppId:i}}),s};if(Ee({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await d();fa(ge,"signMessage","onSuccess",{signature:e}),n({signature:e})}catch(e){fa(ge,"signMessage","onError",M.UNABLE_TO_SIGN),a(e??new xa("Unable to sign message"))}else{let e={method:"personal_sign",data:o,confirmAndSign:d,onSuccess:e=>{fa(ge,"signMessage","onSuccess",{signature:e}),n({signature:e})},onFailure:e=>{fa(ge,"signMessage","onError",M.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},{entropyId:r,entropyIdVerifier:i}=bt(c);ae({signMessage:e,connectWallet:{entropyId:r,entropyIdVerifier:i,onCompleteNavigateTo:eo,onFailure:e=>{fa(ge,"signMessage","onError",M.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),be(no)}})),signTypedData:(e,t)=>new Promise((async(n,a)=>{let{requesterAppId:i}=t?.uiOptions||{};if(!w||!g)return fa(ge,"signTypedData","onError",M.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let o=t?.address??ka(g)?.address;if(!o)throw new C("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=Wa(g,o);if(!l||!s)return fa(ge,"signTypedData","onError",M.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));let c=wt(e),d=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let e=await $c();if(!Z||!e||!await ct.recoverPrimaryWallet())throw Error("Unable to connect to wallet");r.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:s.address,requesterAppId:i}});let{entropyId:t,entropyIdVerifier:n}=bt(l),{response:a}=await Z.rpc({accessToken:e,entropyId:t,entropyIdVerifier:n,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:i,request:{method:"eth_signTypedData_v4",params:[s.address,c]}}),o=a.data;return r.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:s.address,requesterAppId:i}}),o};if(Ee({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await d();fa(ge,"signTypedData","onSuccess",{signature:e}),n({signature:e})}catch(e){fa(ge,"signTypedData","onError",M.UNABLE_TO_SIGN),a(e??new xa("Unable to sign message"))}else{let e={method:"eth_signTypedData_v4",data:c,confirmAndSign:d,onSuccess:e=>{fa(ge,"signTypedData","onSuccess",{signature:e}),n({signature:e})},onFailure:e=>{fa(ge,"signTypedData","onError",M.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},{entropyId:r,entropyIdVerifier:i}=bt(l);ae({signMessage:e,connectWallet:{entropyId:r,entropyIdVerifier:i,onCompleteNavigateTo:eo,onFailure:e=>{fa(ge,"signMessage","onError",M.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),be(no)}})),sendTransaction:async(e,t)=>await tt({transaction:e,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await tt({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:t=>new Promise((async(n,a)=>{if(!w||!g)return void a(Error("User must be authenticated before exporting their Privy wallet"));t&&"target"in t&&t&&(t=void 0);let i=t?.address??ka(g)?.address;if(!i)return void a(Error("User does not have an HD Ethereum wallet. To export an imported wallet, pass the `address` of the wallet to `exportWallet`."));if(!A(i))return void a(Error("Must provide a valid Ethereum address."));let{signingWallet:o,rootWallet:s}=Wa(g,i);if(!o||!s)return void a(Error("Must have a Privy wallet before exporting"));let{entropyId:l,entropyIdVerifier:c}=bt(s);ae(re),await $c()&&Z?Z?(ae({keyExport:{appId:e.appId,appClientId:e.clientId,origin:r.apiUrl,walletToExport:o,primaryWallet:s,onSuccess:n,onFailure:a},connectWallet:{entropyId:l,entropyIdVerifier:c,onCompleteNavigateTo:to,onFailure:a,shouldForceMFA:!0}}),be(no)):a(Error("Must have a Privy wallet before exporting")):a(Error("Must have valid access token to enroll in MFA"))})),promptMfa:rt,async init(e){switch(e){case"sms":return void await r.initMfaSmsVerification();case"passkey":return await r.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 C("Invalid MFA code");we.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{ye.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new C("Invalid authenticator response");let n=await import("@simplewebauthn/browser"),r=(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 n.startAuthentication(t));we.current?.resolve({mfaMethod:e,mfaCode:r,relyingParty:window.origin}),await new Promise(((e,t)=>{ye.current={resolve:e,reject:t}}));break;default:throw we.current?.reject(new C("Unsupported MFA method")),new C(`Unsupported MFA method: ${e}`)}},cancel(){we.current?.reject(new C("MFA canceled"))},async initEnrollmentWithSms(e){let t=await $c();if(!t||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,n)=>{if(!e)return ct.closePrivyModal(),void t();te.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."),ae({mfaEnrollmentFlow:{mfaMethods:te.mfa.methods,shouldUnlinkOnUnenrollMfa:te.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:n}}),be(vc)})),async initEnrollmentWithTotp(){let e=await $c();if(!e||!Z)throw Error("Must have valid access token to enroll in MFA");let t=await Z.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await $c();if(!t||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),f(await r.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await $c();if(!t||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),f(await r.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let n=await $c();if(!n||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.submitEnrollMfa({method:"passkey",accessToken:n,credentialIds:e,removeForLogin:t.removeForLogin}),f(await r.getAuthenticatedUser())},async unenroll(e,t={}){let n=await $c();if(!n||!Z)throw Error("Must have valid access token to remove MFA");"passkey"===e?await Z.submitEnrollMfa({method:"passkey",accessToken:n,credentialIds:[],removeForLogin:t.removeForLogin}):await Z.unenrollMfa({method:e,accessToken:n}),f(await r.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await $c(),t=g?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!Z||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!g?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await ct.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let n=await Z.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===n.status&&f(await r.getAuthenticatedUser()||g||null),ae({farcasterSigner:n}),be($l)},getFarcasterSignerPublicKey:async()=>{let e,t=await $c(),n=g?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Z||!n)throw Error("Must have an embedded wallet to use Farcaster signers");if(!g?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await ct.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!g.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=g.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await $c(),n=g?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Z||!n)throw Error("Must have an embedded wallet to use Farcaster signers");if(!g?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await ct.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!g.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let r=await import("@simplewebauthn/browser"),a=await Z.signFarcasterMessage({address:n.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:r.bufferToBase64URLString(e)},fid:BigInt(g.farcaster.fid),relyingParty:window.origin});return new Uint8Array(r.base64URLStringToBuffer(a.signature))},createGuestAccount:async()=>{if(g&&!g.isGuest)throw Error("User cannot already be authenticated to create a guest account");return g?.isGuest?g:ct.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t,chainId:n}){let a=g?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return ml({user:g,client:r,address:t,requesterAppId:te.id,request:{method:a?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:n},reconnect:st})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:n}){let a=g?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),i=wt(e);return ml({user:g,client:r,address:t,requesterAppId:te.id,request:{method:a?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,i],chainId:n},reconnect:st})},sendTransactionWithCrossAppWallet(e,{address:t}){let n=g?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return ml({user:g,client:r,address:t,requesterAppId:te.id,request:{method:n?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:st})},isModalOpen:c,mfaMethods:te.mfa.methods};Dc=lt.signMessage,Fc=lt.signTypedData,qc=async(e,t)=>await tt({transaction:e,...t,signOnly:!1}),zc=async(e,t)=>({signature:(await tt({transaction:e,...t,signOnly:!0})).hash});let ct={setAuthenticated:y,setUser:f,isNewUserThisSession:x,pendingTransaction:null,walletConnectionStatus:L,connectors:r.connectors?.walletConnectors??[],solanaWallets:_,rpcConfig:te.rpcConfig,chains:te.chains,appId:e.appId,showFiatPrices:"native-token"!==te.embeddedWallets.priceDisplay.primary,clientAnalyticsId:r.clientAnalyticsId,customAuthStatus:pe,hideWalletUIs:Ce,isHeadlessSigning:p(Ee,[te.embeddedWallets.showWalletUIs]),emailOtpState:B,setEmailOtpState:V,smsOtpState:j,setSmsOtpState:H,oAuthState:Y,setOAuthState:X,telegramAuthState:J,setTelegramAuthState:Q,siweState:$,setSiweState:K,isHeadlessOAuthLoading:O,nativeTokenSymbolForChainId:e=>te.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(Z)return Z;let t=new Promise((e=>{le((()=>t=>e(t)))})),n=new Promise((t=>setTimeout((()=>t(null)),e))),r=await Promise.race([t,n]);return le(null),r},getAuthFlow:()=>r.authFlow,getAuthMeta:()=>r.authFlow?.meta,client:r,closePrivyModal:async(t={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let n,a=h&&w&&g;a&&ke.current&&(n=at(g)),"login"===Ae.current?t.shouldCallAuthOnSuccess&&a&&ke.current?fa(ge,"login","onComplete",{user:g,isNewUser:x,wasAlreadyAuthenticated:!1,loginMethod:ke.current,loginAccount:n??null}):fa(ge,"login","onError",M.USER_EXITED_AUTH_FLOW):"link"===Ae.current&&n?t.isSuccess&&a&&ke.current?fa(ge,"linkAccount","onSuccess",{user:g,linkMethod:ke.current,linkedAccount:n}):ke.current&&fa(ge,"linkAccount","onError",M.USER_EXITED_LINK_FLOW,{linkMethod:ke.current}):"update"===Ae.current&&n&&(t.isSuccess&&a&&ke.current?fa(ge,"update","onSuccess",{user:g,updateMethod:ke.current,updatedAccount:n}):ke.current&&fa(ge,"update","onError",M.USER_EXITED_UPDATE_FLOW,{linkMethod:ke.current}));let o=N&&Ol.has(N),s=N===Ar&&re.errorModalData&&Ol.has(re.errorModalData.previousScreen);if((o||s)&&re.funding){let t,n=Ol.get(N)??null;if("solana"===re.funding.chainType){let e=i(Pa);if(e)try{t=BigInt(await e.getBalance({address:re.funding.address,cluster:re.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");fa(ge,"fundSolanaWallet","onUserExited",{address:re.funding.address,cluster:re.funding.cluster,fundingMethod:n,balance:t})}else{let r=mt(re.funding.chain.id,te.chains,te.rpcConfig,{appId:e.appId});try{t=await r.getBalance({address:re.funding.address})}catch{console.error("Unable to pull wallet balance")}fa(ge,"fundWallet","onUserExited",{address:re.funding.address,chain:re.funding.chain,fundingMethod:n,balance:t})}}ae({...re,externalConnectWallet:{suggestedAddress:void 0}}),Ae.current=null,ke.current=null,P(!1),d(!1),setTimeout((()=>{r.authFlow=void 0}),200)},solanaSignMessage:({message:e,options:t})=>new Promise((async(n,a)=>{if(!w||!g)return fa(ge,"signSolanaMessage","onError",M.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let i=t?.address??Ta(g)?.address;if(!i)throw new C("User must have an embedded wallet to sign a message.");let{signingWallet:o,rootWallet:s}=oa(g,i);if(!o||!s)return fa(ge,"signSolanaMessage","onError",M.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return fa(ge,"signMessage","onError",M.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));let l=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let t=await r.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let n=ct.walletProxy??await ct.initializeWalletProxy(15e3);if(!n)throw Error("Failed to initialize embedded wallet proxy.");if(!await ct.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!s)throw Error("No root wallet for signing wallet found");let{entropyId:a,entropyIdVerifier:i}=ni(g),{response:l}=await n.rpc({accessToken:t,entropyId:a,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:o.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return l.data.signature};if(Ee({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await l();fa(ge,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),n({signature:e})}catch(e){a(e)}else{let r={method:"solana_signMessage",data:e,confirmAndSign:l,onSuccess:e=>{fa(ge,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),n({signature:e})},onFailure:e=>{a(e)},uiOptions:t?.uiOptions},{entropyId:i,entropyIdVerifier:o}=bt(s);ae({signMessage:r,connectWallet:{entropyId:i,entropyIdVerifier:o,onCompleteNavigateTo:eo,onFailure:e=>{fa(ge,"signSolanaMessage","onError",M.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),be(no)}})),signSolanaTransaction:async({transaction:e,connection:t,uiOptions:n,transactionOptions:r,address:a})=>{let i=a?S.find((e=>e.address===a)):S.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!i)throw fa(ge,"signSolanaTransaction","onError",M.EMBEDDED_WALLET_NOT_FOUND),new C("Embedded wallet not found",M.EMBEDDED_WALLET_NOT_FOUND);let{signedTransaction:o}=await nt({transaction:e,connection:t,transactionOptions:r,uiOptions:n,wallet:i,signOnly:!0});return o},sendSolanaTransaction:async({transaction:e,connection:t,uiOptions:n,transactionOptions:r,fundWalletConfig:a,address:i})=>{let o=i?S.find((e=>e.address===i)):S.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw fa(ge,"sendSolanaTransaction","onError",M.EMBEDDED_WALLET_NOT_FOUND),new C("Embedded wallet not found",M.EMBEDDED_WALLET_NOT_FOUND);return await nt({transaction:e,connection:t,transactionOptions:r,uiOptions:n,fundWalletConfig:a,wallet:o,signOnly:!1})},openPrivyModal:be,connectWallet:We,initLoginWithWallet:async(e,t,n)=>{It(e)?(ke.current="siwe",xe(e,t,n)):(ke.current="siws",Pe(e,t,n))},loginWithWallet:async()=>{let e,t,n;if(!h)throw new Re;if(r.authFlow instanceof Wt?e="siwe":r.authFlow instanceof Na&&(e="siws"),!e)throw new C("Must initialize SIWE/SIWS flow first.");if(null!==await r.getAccessToken())try{({user:t}=await r.link()),ke.current=e}catch(t){throw fa(ge,"linkAccount","onError",t.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:n}=await r.authenticate()),ke.current=e}catch(e){throw fa(ge,"login","onError",e.privyErrorCode||M.GENERIC_CONNECT_WALLET_ERROR),e}f(t||g||null),P(n||!1),y(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:n})=>new Promise((async(r,a)=>{let i=await $c();if(!w||!g||!i)throw new C("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new C("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let o=ct.walletProxy??await ct.initializeWalletProxy(15e3);if(!o)throw new C("Wallet proxy not initialized.");if((({address:e,chainType:t,user:n})=>!!il(n).find((n=>n.address===e&&n.chainType===t)))({address:e,chainType:t,user:g}))return r();let s=(({address:e,user:t})=>{let n=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!n)throw new C("Address to delegate is not associated with current user.");return{address:n.address,chainType:n.chainType,walletIndex:n.walletIndex??0}})({address:e,user:g}),l=(({address:e,user:t})=>{let n=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!n)throw new C("Address to delegate is not associated with current user.");let r=n.imported?n:Pn(t);if(!r)throw new C("Unable to determine root address for delegated address.");return{address:r.address,chainType:r.chainType,imported:r.imported}})({address:e,user:g}),c=async()=>{await o.createDelegatedAction({accessToken:i,rootWallet:l,delegatedWallets:[s]}),await ct.refreshSessionAndUser()};if(await ct.recoverPrimaryWallet(),n)ae({delegatedActions:{consent:{address:e,onDelegate:c,onSuccess:async()=>{r()},onError:async e=>{a(e)}}}}),be(zl);else try{await c(),r()}catch(e){a(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,n)=>{if(!w||!g)throw new C("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===il(g).length)throw new C("User has no delegated wallets to revoke.");let a=async()=>{await r.revokeDelegatedWallet(),await ct.refreshSessionAndUser()};if(e)ae({delegatedActions:{revoke:{onRevoke:a,onSuccess:async()=>{t()},onError:async e=>{n(e)}}}}),be(Vl);else try{await a(),t()}catch(e){n(e)}})),initLoginWithFarcaster:async(e,t)=>{let n=new Io(e,t);r.startAuthFlow(n);try{ke.current="farcaster",await n.initializeFarcasterConnect()}catch(e){throw"login"===Ae.current?fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR):"link"===Ae.current&&fa(ge,"linkAccount","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!h)throw new Re;if(!(r.authFlow instanceof Io))throw new C("Must initialize Farcaster flow first.");if(null!==await r.getAccessToken())try{({user:e}=await r.link()),ke.current="farcaster"}catch(e){throw fa(ge,"linkAccount","onError",e.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await r.authenticate()),ke.current="farcaster"}catch(e){throw fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}f(e||null),P(t||!1),y(!0)},async loginWithGuestAccountFlow(){let e=new So(this.appId);r.startAuthFlow(e);try{Ae.current="login",ke.current="guest";let{user:e,isNewUser:t}=await r.authenticate();if(t=t||!1,!e)throw new C("Unable to authenticate guest account");let n=await $c(),a=await ct.initializeWalletProxy(Ua);if(n&&a)try{let t=Ea(e,te.embeddedWallets.ethereum.createOnLogin),r=ba(e,te.embeddedWallets.solana.createOnLogin);if(t&&r){let t=await je(e,Ua);await a.createSolana({accessToken:n,ethereumAddress:t?.address}),e=await ct.refreshSessionAndUser()}else r?(await a.createSolana({accessToken:n,ethereumAddress:ka(e)?.address}),e=await ct.refreshSessionAndUser()):t?(await je(e,Ua),e=await ct.refreshSessionAndUser()):f(e)}catch(t){f(e),console.warn("Unable to create embedded wallet for guest account")}return P(t),y(!0),fa(ge,"login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),e}catch(e){throw fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:n}){let a=`privy:${e}`;ke.current=a;let{url:i,stateCode:o,codeVerifier:s}=await async function({api:e,appId:t}){let n=Ke(),r=Ye(),a=await Xe(n);try{let{url:i}=await e.post(D,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:a,state_code:r});return{url:i,stateCode:r,codeVerifier:n}}catch(e){throw T(e)}}({api:r.api,appId:e});if(!i)throw r.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new C("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,n)=>{let r,a=setTimeout((()=>{n(new C("Authorization request timed out after 2 minutes.")),i()}),12e4);function i(){t?.close(),window.removeEventListener("message",s)}let o=setInterval((()=>{t?.closed&&!r&&(i(),clearInterval(o),clearTimeout(a),n(new C("User rejected request")))}),300);function s(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(clearTimeout(a),e(t.data),i()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(a),n(new C(t.data.error)),i()),t.data.type===hl&&((r=new BroadcastChannel(dl)).onmessage=s))}window.addEventListener("message",s)}))}({url:i,popup:t,provider:a}),c=l.stateCode,d=l.authorizationCode;if(c!==o)throw r.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:o??"",returnedStateCode:c??""}}),new C("Unexpected auth flow. This may be a phishing attempt.",void 0,M.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:n,authorizationCode:r,action:a,client:i}){if(!r||!t)throw new C("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===r)throw new C("User denied confirmation during cross-app auth flow");try{let o=new ul({authorizationCode:r,stateCode:t,codeVerifier:n,provider:`privy:${e}`});i.startAuthFlow(o);let s="link"===a?await i.link():await i.authenticate(),l=s.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=T(e);if(t.privyErrorCode)throw new C(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 C("Invalid code during cross-app auth flow.",void 0,M.OAUTH_USER_DENIED);throw new C("Invalid code during cross-app auth flow.",void 0,M.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:s,stateCode:c,authorizationCode:d,action:n,client:r});h&&r.storeProviderAccessToken(e,h);let u=await ct.refreshSessionAndUser();if(!u)throw new C("Unable to update user");return r.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),u}catch(e){throw r.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,n){if(ke.current=e,!Fe())return void be(Gl);if("google"===e&&Oa(window.navigator.userAgent))return void be(Gl);"twitter"===e&&window.opener&&window.opener.postMessage({type:hl},"*"),ze.del(He),ze.del($e);let a=new Wo({provider:e,disableSignup:!!n,withPrivyUi:!0});t&&a.addCaptchaToken(t),r.startAuthFlow(a);let i=await r.authFlow.getAuthorizationUrl();i&&i.url&&("twitter"===e&&v&&(i.url=i.url.replace("x.com","twitter.com")),window.location.assign(i.url))},async initLoginWithTelegram(e,t){if(!h)throw new Re;ke.current="telegram";let n=new Ia(e,t);r.startAuthFlow(n),Q({status:"loading"}),n.meta.telegramWebAppData=void 0,n.meta.telegramAuthResult=await new Promise(((e,t)=>te.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:te.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(n=>n?e(n):t(new C("Telegram auth failed or was canceled by the client")))):t(new C("Telegram was not initialized")):t(new C("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,n;if(!(r.authFlow instanceof Ia))throw new C("Must initialize Telegram flow before calling loginWithTelegram");r.authFlow.meta.captchaToken||=e?.captchaToken;let a=await $c(),i=e?.intent||Ae.current;if("login"===i)try{let e=await r.authenticate();t=e.user,n=e.isNewUser,ke.current="telegram"}catch(e){throw fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}else{if("link"!==i)throw new C("Unknown auth intent");try{t=(await r.link()).user,ke.current="telegram"}catch(e){throw fa(ge,"linkAccount","onError",e.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}f(t),P(n||!1),y(!0),Q({status:"done"});let o=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:n||!1,wasAlreadyAuthenticated:!!a,loginAccount:o}},async recoveryOAuthFlow(e,t,n){let a,i;function o(t){if(!t)throw r.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new C("Recovery OAuth failed")}switch(e){case"google-drive":{let t,s,{url:l,codeVerifier:c,stateCode:d}=await Ra({api:Lc.api,provider:e});o(l);try{let a=await Ml({url:l,popup:n,provider:e});if(t=a.stateCode,s=a.authorizationCode,t!==d)throw r.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:d??"",returnedStateCode:t??""}}),new C("Unexpected auth flow. This may be a phishing attempt.",void 0,M.OAUTH_UNEXPECTED)}catch(t){throw r.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new C("Recovery OAuth failed")}[a,i]=await Promise.all([$c(),Ma({api:Lc.api,provider:e,codeVerifier:c,stateCode:t,authorizationCode:s})]);break}case"icloud":{let{url:t}=await Ra({api:Lc.api,provider:e});o(t);let{ckWebAuthToken:r}=await Ml({url:t,popup:n,provider:e});i=r,a=await $c()}}if(!Z)throw new C("Cannot connect to wallet proxy");if(!a)throw new C("Unable to authorize user");switch(t){case"recover":{let t=re.recoverWallet?.entropyId,n=re.recoverWallet?.entropyIdVerifier;if(!t||!n)throw new C("Recovery OAuth failed");r.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await Z.recover({accessToken:a,entropyId:t,entropyIdVerifier:n,recoveryAccessToken:i}),r.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{r.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await Z.create({accessToken:a,recoveryAccessToken:i,recoveryMethod:e});let t=ka(await ct.refreshSessionAndUser());if(!t)throw fa(ge,"createWallet","onError",M.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");r.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),fa(ge,"createWallet","onSuccess",{wallet:t});break}case"set-recovery":{let t=Pn(g);if(!t)throw fa(ge,"setWalletRecovery","onError",M.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");r.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:n,entropyIdVerifier:o}=bt(t);await Z.setRecovery({accessToken:a,entropyId:n,entropyIdVerifier:o,recoveryMethod:e,recoveryAccessToken:i});let s=Pn(await ct.refreshSessionAndUser());if(!s)throw fa(ge,"createWallet","onError",M.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");r.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),fa(ge,"setWalletRecovery","onSuccess",{method:e,wallet:s});break}default:throw new C("Unsupported recovery action")}},async loginWithOAuth(e){let t,n,a;if(!(r.authFlow instanceof Wo))throw new C("Must initialize OAuth flow before calling loginWithOAuth");let i=ze.get(Ge),o=r.authFlow.meta.stateCode;if(i!==o)throw r.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:i??"",returnedStateCode:o??""}}),new C("Unexpected auth flow. This may be a phishing attempt.",void 0,M.OAUTH_UNEXPECTED);if(null!==await r.getAccessToken())try{let n=await r.link();t=n.user,a=n.oAuthTokens,ke.current=e}catch(t){throw fa(ge,"linkAccount","onError",t.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let i=await r.authenticate();t=i.user,n=i.isNewUser,a=i.oAuthTokens,ke.current=e}catch(t){throw"login"===Ae.current?fa(ge,"login","onError",t.privyErrorCode||M.UNKNOWN_AUTH_ERROR):"link"===Ae.current&&fa(ge,"linkAccount","onError",t.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return f(t),P(n||!1),y(!0),a&&t&&fa(ge,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),a},passkeyAuthState:z,setPasskeyAuthState:q,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let n=new Oo({captchaToken:e,setPasskeyAuthState:q});r.startAuthFlow(n),Ae.current="login";try{ke.current="passkey",q({status:"generating-challenge"}),await n.initRegisterFlow(t),q({status:"awaiting-passkey"})}catch(e){throw q({status:"error",error:e}),fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!h)throw new Re;if(!(r.authFlow instanceof Oo))throw new C("Must initialize Passkey flow first.");if("passkey"!==ke.current){let e=new C("Must init login with Passkey flow first.");throw q({status:"error",error:e}),e}let n=await $c();try{ke.current="passkey",q({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await r.authenticate())}catch(e){throw q({status:"error",error:e}),fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}f(e),P(t||!1),y(!0),q({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!n,loginAccount:a}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let n=new Oo({captchaToken:e,setPasskeyAuthState:q});r.startAuthFlow(n),Ae.current="login";try{ke.current="passkey",q({status:"generating-challenge"}),await n.initAuthenticationFlow(t),q({status:"awaiting-passkey"})}catch(e){throw q({status:"error",error:e}),fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,n;if(!h)throw new Re;if(!(r.authFlow instanceof Oo))throw new C("Must initialize Passkey flow first.");if(e?.credentialIds&&(r.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==ke.current){let e=new C("Must init login with Passkey flow first.");throw q({status:"error",error:e}),e}let a=await $c();try{ke.current="passkey",q({status:"awaiting-passkey"}),({user:t,isNewUser:n}=await r.authenticate())}catch(e){throw q({status:"error",error:e}),fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}f(t),P(n||!1),y(!0),q({status:"done"});let i=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:n||!1,wasAlreadyAuthenticated:!!a,loginAccount:i}},async initLinkWithPasskey(e){let t=new Oo({captchaToken:e});r.startAuthFlow(t),Ae.current="link",ke.current="passkey",q({status:"generating-challenge"});try{await t.initLinkFlow(),q({status:"awaiting-passkey"})}catch(e){throw fa(ge,"linkAccount","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),q({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!h)throw new Re;if(!(r.authFlow instanceof Oo))throw new C("Must initialize Passkey flow first.");if("passkey"!==ke.current)throw new C("Must init login with Passkey flow first.");try{ke.current="passkey",({user:e}=await r.link())}catch(e){throw fa(ge,"linkAccount","onError",e.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return f(e||g||null),q({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,n){if(!Fe())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&&Oa(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 a=new Wo({provider:e,withPrivyUi:!1,disableSignup:n??!1});t&&a.addCaptchaToken(t),X({status:"loading"});let i=await r.startAuthFlow(a).getAuthorizationUrl();i?.url&&window.location.assign(i.url)},async loginWithHeadlessOAuth(e){let t,n,a;R(!0),X({status:"loading"}),r.startAuthFlow(new Wo(e));let i=ze.get(Ge),o=e.stateCode;if(i!==o)throw r.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:i??"",returnedStateCode:o??""}}),R(!1),new C("Unexpected auth flow. This may be a phishing attempt.",void 0,M.OAUTH_UNEXPECTED);if(null!==await r.getAccessToken())try{({user:t,oAuthTokens:a}=await r.link()),ke.current=e.provider;let n=at(t);t&&n&&fa(ge,"linkAccount","onSuccess",{user:t,linkMethod:ke.current,linkedAccount:n})}catch(t){throw R(!1),fa(ge,"linkAccount","onError",t.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:n,oAuthTokens:a}=await r.authenticate()),ke.current=e.provider;let i=at(t);t&&i&&void 0!==n&&fa(ge,"login","onComplete",{user:t,isNewUser:n,wasAlreadyAuthenticated:!1,loginMethod:ke.current,loginAccount:i})}catch(e){throw R(!1),X({status:"error",error:e}),fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}return f(t),P(n||!1),y(!0),R(!1),X({status:"done"}),a&&t&&fa(ge,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:n,withPrivyUi:a})=>{let i=new To({email:e,captchaToken:t,disableSignup:n});r.startAuthFlow(i);try{ke.current="email",V({status:"sending-code"}),await i.sendCodeEmail({withPrivyUi:a}),V({status:"awaiting-code-input"})}catch(e){throw V({status:"error",error:e}),"login"===Ae.current?fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR):"link"===Ae.current&&fa(ge,"linkAccount","onError",e.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,n)=>{let a=new _o(e,t,n);r.startAuthFlow(a);try{await a.sendCodeEmail({withPrivyUi:!0})}catch(e){fa(ge,"update","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR,{linkMethod:ke.current})}},initUpdatePhone:async(e,t,n)=>{let a=new Mo(e,t,n);r.startAuthFlow(a);try{await a.sendSmsCode({withPrivyUi:!0})}catch(e){fa(ge,"update","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR,{linkMethod:ke.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:n,withPrivyUi:a})=>{H({status:"sending-code"});let i=new Ro({phoneNumber:e,captchaToken:t,disableSignup:n});r.startAuthFlow(i);try{ke.current="sms",await i.sendSmsCode({withPrivyUi:a}),H({status:"awaiting-code-input"})}catch(e){throw H({status:"error",error:e}),"login"===Ae.current?fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR):"link"===Ae.current&&fa(ge,"linkAccount","onError",e.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(r.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(r.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,n;function a(e){r.authFlow instanceof To?V(e):r.authFlow instanceof Ro&&H(e)}if(a({status:"submitting-code"}),!h){let e=new Re;throw a({status:"error",error:e}),e}if(r.authFlow instanceof To)r.authFlow.meta.emailCode=e.trim();else{if(!(r.authFlow instanceof Ro)){let e=new C("Must initialize a passwordless code flow first");throw a({status:"error",error:e}),e}r.authFlow.meta.smsCode=e.trim()}let i=await $c();if("link"===Ae.current)try{({user:t}=await r.link())}catch(e){throw a({status:"error",error:e}),fa(ge,"linkAccount","onError",e.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:ke.current}),e}else if("update"===Ae.current)try{({user:t}=await r.link())}catch(e){throw a({status:"error",error:e}),fa(ge,"update","onError",e.privyErrorCode||M.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:ke.current}),e}else try{({user:t,isNewUser:n}=await r.authenticate())}catch(e){throw a({status:"error",error:e}),fa(ge,"login","onError",e.privyErrorCode||M.UNKNOWN_AUTH_ERROR),e}let o=t||g;f(o||null),P(n||!1),y(!0),a({status:"done"});let s=null;return r.authFlow instanceof To?s=o?.linkedAccounts.find((({type:e})=>"email"===e))||null:r.authFlow instanceof Ro&&(s=o?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:o,isNewUser:n||!1,wasAlreadyAuthenticated:!!i,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:n})=>{Ae.current="link",ke.current="siwe",K({status:"generating-message"});let a=await r.generateSiweNonce({address:e,captchaToken:n});return K({status:"awaiting-signature"}),La({address:e,chainId:t.replace("eip155:",""),nonce:a})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let n=await r.generateSiweNonce({address:e});return La({address:e,chainId:t.replace("eip155:",""),nonce:n})},linkSmartWallet:async({message:e,signature:t,smartWalletType:n})=>{let a;a=await r.linkSmartWallet({message:e,signature:t,smartWalletType:n}),f((a=await ct.refreshSessionAndUser()??a)||g||null)},linkWithSiwe:async({message:e,signature:t,chainId:n,walletClientType:a,connectorType:i})=>{let o;Le("siwe");let s=null;try{K({status:"submitting-signature"}),o=await r.linkWithSiwe({message:e,signature:t,chainId:n,walletClientType:a,connectorType:i}),o=await ct.refreshSessionAndUser()??o,K({status:"done"}),(s=at(o)||null)&&fa(ge,"linkAccount","onSuccess",{user:o,linkMethod:"siwe",linkedAccount:s})}catch(e){throw fa(ge,"linkAccount","onError",e.privyErrorCode||M.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),Ae.current=null,ke.current=null,K({status:"error",error:e}),e}let l=o||g;return f(l||null),Ae.current=null,ke.current=null,{user:l,linkedAccount:s}},refreshSessionAndUser:async()=>{let e=await r.getAuthenticatedUser();return y(!!e),f(e),e},walletProxy:Z,createAnalyticsEvent:({eventName:e,payload:t,timestamp:n})=>r.createAnalyticsEvent({eventName:e,payload:t,timestamp:n}),acceptTerms:async()=>{let e=await r.acceptTerms();return f(e),e},getUsdTokenPrice:e=>r.getUsdTokenPrice(e),getUsdPriceForSol:()=>r.getUsdPriceForSol(),getSplTokenMetadata:e=>r.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,n)=>{let a=Pn(e?.user??g)||Ca(e?.user??g)||Qr(e?.user??g);a||t(!0);let i=await $c();if(!i||!Z||!a)return void n(Error("Must have valid access token and Privy wallet to recover wallet"));let{entropyId:o,entropyIdVerifier:s}=bt(a);try{await Z.connect({accessToken:i,entropyId:o,entropyIdVerifier:s}),t(!0)}catch(e){Da(e)&&"privy"===a.recoveryMethod?(r.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:a.address}}),(await Z.recover({entropyId:o,entropyIdVerifier:s,accessToken:i})).entropyId||n(Error("Unable to recover wallet")),r.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:a.address}}),t(!0)):Da(e)&&"privy"!==a.recoveryMethod?(ae({recoverWallet:{entropyId:o,entropyIdVerifier:s,onFailure:n,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:a.recoveryMethod,action:"recover"}}),be(Fa(a.recoveryMethod))):n(e)}})),embeddedSolanaWallets:S,createEmbeddedSolanaWallet:async e=>{e&&"target"in e&&(e=void 0);let t=await ct.refreshSessionAndUser();if(!t)throw fa(ge,"createWallet","onError",M.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,n)=>{let r=ka(e),a=Ta(e),i=n&&"createAdditional"in n&&n.createAdditional,o=n&&"walletIndex"in n?n.walletIndex:void 0,s=(Qa(e)?.walletIndex??-1)+1;if(a&&!i&&"number"!=typeof o)throw fa(ge,"createWallet","onError",M.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof o&&o<0)throw fa(ge,"createWallet","onError",M.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${o}) is invalid.`);let[l,c]=await Promise.all([ct.initializeWalletProxy(t),$c()]);if(!l||!c)throw fa(ge,"createWallet","onError",M.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await Ze({user:e,wp:l,accessToken:c,walletIndex:o??s,ethereumWallet:r})})(t,15e3,e)},exportSolanaWallet:t=>new Promise((async(n,a)=>{if(!w||!g)return void a(Error("User must be authenticated before exporting their Privy wallet"));let i=t?.address??Ta(g)?.address;if(!i)return void a(Error("User does not have an HD Solana wallet."));let{signingWallet:o,rootWallet:s}=oa(g,i);if(!o||!s)return void a(Error("Must have a Privy wallet before exporting"));if(!await $c()||!Z)return void a(Error("Must have valid access token to enroll in MFA"));if(!Z)return void a(Error("Must have a Privy wallet before exporting"));let{entropyId:l,entropyIdVerifier:c}=bt(s),d={appId:e.appId,appClientId:e.clientId,origin:r.apiUrl,walletToExport:o,primaryWallet:s,onSuccess:n,onFailure:a};ae({connectWallet:{entropyId:l,entropyIdVerifier:c,onCompleteNavigateTo:to,onFailure:a,shouldForceMFA:!0},keyExport:d}),be(no)})),setReadyToTrue:e=>{m(!0),ie?.(e)},updateWallets:()=>Ve(),fundWallet:async(e,t)=>{ae({funding:Ai({address:e,appConfig:te,fundWalletConfig:t,methodScreen:zn})}),be(zn)},openModal:be,requestFarcasterSignerStatus:async e=>{let t=await $c(),n=g?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Z||!n)throw Error("Must have an embedded wallet to use Farcaster signers");if(!g?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let a=await r.requestFarcasterSignerStatus(e);return"approved"===a.status&&f(await r.getAuthenticatedUser()||g||null),a},connectCoinbaseSmartWallet:async()=>{te.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=r.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||r.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),We(e);await Se("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:n,externalWalletMetadata:a,telegramAuthResult:i,telegramWebAppData:o,farcasterEmbeddedAddress:s,oAuthUserInfo:l})=>{let c=await r.sendAccountTransferRequest({nonce:e,account:t,accountType:n,externalWalletMetadata:a,telegramAuthResult:i,telegramWebAppData:o,farcasterEmbeddedAddress:s,oAuthUserInfo:l});return f(c),c}};Bc=ct.recoverPrimaryWallet,Vc=ct.recoverPrimaryWallet,jc=ct.solanaSignMessage;let dt=o((()=>({wallets:E,ready:ce&&fe})),[E,ce,fe]),ht=r.authFlow instanceof Ia,pt=!te.headless&&te.captchaEnabled&&!w&&(h||ht);/*#__PURE__*/return t(Jt.Provider,{value:lt,children:/*#__PURE__*/t(za.Provider,{value:ge,children:/*#__PURE__*/t(qa.Provider,{value:dt,children:/*#__PURE__*/t(Ba,{...te,children:/*#__PURE__*/n(Me.Provider,{value:ct,children:[/*#__PURE__*/t(Va,{children:/*#__PURE__*/n(ja,{data:re,setModalData:ae,setInitialScreen:U,initialScreen:N,authenticated:w,open:c,children:[e.children,pt&&/*#__PURE__*/t(ks,{delayedExecution:!1}),/*#__PURE__*/t(Ms,{theme:{...te.appearance.palette||{}}}),!te.render.standalone&&/*#__PURE__*/t($s,{open:c})]})}),/*#__PURE__*/t(al,{appId:e.appId,appClientId:e.clientId,clientAnalyticsId:r.clientAnalyticsId,origin:r.apiUrl,mfaMethods:g?.mfaMethods,mfaPromise:we,mfaSubmitPromise:ye,onLoad:ee,onLoadFailed:()=>null}),te.loginConfig.telegramAuthConfiguration&&
5
- /*#__PURE__*/t(Tn,{$if:!0,children:/*#__PURE__*/t(Gs,{scriptHost:e.apiUrl||qt,botUsername:te.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};const nd=()=>{let{getAccessToken:e,user:t}=$t(),{refreshSessionAndUser:n,initializeWalletProxy:r}=Pe(),a=Sn();return{importWallet:p((({privateKey:i})=>ko({getAccessToken:e,user:t,initializeWalletProxy:r,refreshSessionAndUser:n,emitPrivyEvent:a},{privateKey:i,chainType:"ethereum"})),[t,e,n,r,a])}},rd=()=>{let{importWallet:e}=nd();return{...h(Jt),importWallet:e}},ad=e=>{Ht("login",e);let t=jt(),n=In(),{ready:r,user:a}=$t(),{initLoginWithHeadlessOAuth:i,loginWithHeadlessOAuth:o,oAuthState:l,setOAuthState:c,isHeadlessOAuthLoading:d}=Pe(),h=p((async e=>{try{if(t.enabled&&"success"!==t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);return await i(e.provider,t.token,e.disableSignup)}catch(e){throw c({status:"error",error:e}),e}}),[i,t]),u=p((async()=>{let e=Uo();try{if(a)return console.warn("Cannot login with OAuth when already logged in"),a;if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(e.popupFlow)return}catch(e){throw c({status:"error",error:e}),e}try{return await o(e)}catch(e){throw c({status:"error",error:e}),e}finally{Fr()}}),[o]);return s((()=>{let e=Uo();r&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&u().catch((()=>{}))}),[r,n]),{initOAuth:h,loading:d,state:l}},id=e=>{let t=jt(),{emailOtpState:n,setEmailOtpState:r,initLoginWithEmail:a,loginWithCode:i}=Pe();return{sendCode:p((async({email:n,disableSignup:i})=>{try{let e;if(!n)throw Error("Email required to send OTP code");if(t.enabled&&"error"===t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({email:n,captchaToken:e,disableSignup:i,withPrivyUi:!1})}catch(n){throw r({status:"error",error:n}),e?.onError?.(n.privyErrorCode||M.UNKNOWN_AUTH_ERROR),n}}),[a]),loginWithCode:p((async({code:n})=>{try{if(t.enabled&&"error"===t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);let{user:r,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:s}=await i(n);e?.onComplete?.({user:r,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"email",loginAccount:s})}catch(n){throw r({status:"error",error:n}),e?.onError?.(n.privyErrorCode||M.UNKNOWN_AUTH_ERROR),n}}),[i,t.status]),state:n}},od=e=>{let t=jt(),{initSignupWithPasskey:n,signupWithPasskey:r,passkeyAuthState:a,setPasskeyAuthState:i}=Pe();return{signupWithPasskey:p((async()=>{try{let a;if(t.enabled&&"error"===t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),a=await t.waitForResult()),await n({captchaToken:a,withPrivyUi:!1});let{user:i,isNewUser:o,wasAlreadyAuthenticated:s,loginAccount:l}=await r();e?.onComplete?.({user:i,isNewUser:o,wasAlreadyAuthenticated:s,loginMethod:"passkey",loginAccount:l})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||M.UNKNOWN_AUTH_ERROR),t}}),[r,t.status]),state:a}},sd=e=>{let t=jt(),{initLoginWithPasskey:n,loginWithPasskey:r,passkeyAuthState:a,setPasskeyAuthState:i}=Pe();return{loginWithPasskey:p((async a=>{try{let i;if(t.enabled&&"error"===t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult()),await n({captchaToken:i,withPrivyUi:!1});let{user:o,isNewUser:s,wasAlreadyAuthenticated:l,loginAccount:c}=await r(a);e?.onComplete?.({user:o,isNewUser:s,wasAlreadyAuthenticated:l,loginMethod:"passkey",loginAccount:c})}catch(a){throw i({status:"error",error:a}),e?.onError?.(a.privyErrorCode||M.UNKNOWN_AUTH_ERROR),a}}),[r,t.status]),state:a}},ld=e=>{let{initLinkWithPasskey:t,linkWithPasskey:n,passkeyAuthState:r,setPasskeyAuthState:a}=Pe();return{linkWithPasskey:p((async()=>{try{await t();let r=await n();if(!r)throw Error("Error, user not found");let a=r.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:r,linkMethod:"passkey",linkedAccount:a})}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||M.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[n]),state:r}},cd=e=>{let t=jt(),{smsOtpState:n,setSmsOtpState:r,initLoginWithSms:a,loginWithCode:i}=Pe();return{sendCode:p((async({phoneNumber:n,disableSignup:i})=>{try{let e;if(!n)throw Error("SMS required to send OTP code");if(t.enabled&&"error"===t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({phoneNumber:n,captchaToken:e,disableSignup:i,withPrivyUi:!1})}catch(n){throw r({status:"error",error:n}),e?.onError?.(n.privyErrorCode||M.UNKNOWN_AUTH_ERROR),n}}),[a]),loginWithCode:p((async({code:n})=>{try{if(t.enabled&&"success"!==t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);let{user:r,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:s}=await i(n);e?.onComplete?.({user:r,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"sms",loginAccount:s})}catch(n){throw r({status:"error",error:n}),e?.onError?.(n.privyErrorCode||M.UNKNOWN_AUTH_ERROR),n}}),[i,t.status]),state:n}},dd=e=>{let t=jt(),{siweState:n,setSiweState:r,linkWithSiwe:a,generateSiweMessage:i}=Pe();return{generateSiweMessage:p((async({address:t,chainId:n})=>{try{if(!t||!n)throw Error("wallet address and chainId required to generate nonce");return await i({address:t,chainId:n}).then((e=>e))}catch(t){throw r({status:"error",error:t}),e?.onError?.(t.privyErrorCode||M.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[i]),linkWithSiwe:p((async({signature:n,message:i,chainId:o,walletClientType:s,connectorType:l})=>{try{if(t.enabled&&"success"!==t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);let{user:r,linkedAccount:c}=await a({message:i,signature:n,chainId:o,walletClientType:s,connectorType:l});c&&e?.onSuccess?.({user:r,linkMethod:"siwe",linkedAccount:c})}catch(n){throw r({status:"error",error:n}),e?.onError?.(n.privyErrorCode||M.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),n}}),[a,t.status]),state:n}};function hd(){let{signTransaction:e}=h(Jt);return{signTransaction:e}}function ud(e){let{linkEmail:t,linkPhone:n,linkWallet:r,linkGoogle:a,linkApple:i,linkTwitter:o,linkDiscord:s,linkGithub:l,linkLinkedIn:c,linkTiktok:d,linkSpotify:u,linkInstagram:p,linkTelegram:m,linkFarcaster:w}=h(Jt);return Ht("linkAccount",e),{linkEmail:t,linkPhone:n,linkWallet:r,linkGoogle:a,linkApple:i,linkTwitter:o,linkDiscord:s,linkGithub:l,linkLinkedIn:c,linkTiktok:d,linkSpotify:u,linkInstagram:p,linkFarcaster:w,linkTelegram:m}}function pd(e){let{updateEmail:t,updatePhone:n}=h(Jt);return Ht("update",e),{updateEmail:t,updatePhone:n}}function md(e){let{createWallet:t}=h(Jt);return Ht("createWallet",e),{createWallet:t}}const wd=()=>{let{connectCoinbaseSmartWallet:e}=Pe();return{connectCoinbaseSmartWallet:e}},yd=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:n,signTypedDataWithCrossAppWallet:r,sendTransactionWithCrossAppWallet:a}=$t();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:n,signTypedData:r,sendTransaction:a}};function gd(e){let{sendTransaction:t}=h(Jt);return Ht("sendTransaction",e),{sendTransaction:t}}function fd(e){let{setWalletPassword:t}=h(Jt);return Ht("setWalletPassword",e),{setWalletPassword:t}}function vd(){let{createGuestAccount:e}=h(Jt);return{createGuestAccount:e}}function kd(e){let{setWalletRecovery:t}=h(Jt);return Ht("setWalletRecovery",e),{setWalletRecovery:t}}function Ad(e){let{signMessage:t}=h(Jt);return Ht("signMessage",e),{signMessage:t}}const Cd=()=>{let{ready:e,wallets:t}=Kt(),{user:n}=$t(),{rpcConfig:r,chains:a,appId:i}=Pe();return{signAuthorization:p((async(o,s)=>{if(!n)throw Error("User must be authenticated before signing with a Privy wallet");if(!e)throw Error("Wallets are not ready");let l=s?.address??ka(n)?.address??Fi,c=t.find((e=>zi(e.address)===zi(l)));if(!c)throw Error("Signing wallet not found.");let d=o.chainId??Number(c.chainId.split(":")[1]),h=a.find((e=>e.id===d));if(!h)throw Error("Error, chain not configured in PrivyProvider config");let u=qi({account:l,chain:h,transport:Bi(di(h,r,i))}).extend(Ao()),p=await u.prepareAuthorization({...o,sponsor:o.sponsor||void 0}),m=await c.getEthereumProvider(),w=await m.request({method:"secp256k1_sign",params:[Co(p)]});return{...p,...Vi(w)}}),[e,t,n,a])}};function Ed(e){let{signTypedData:t}=h(Jt);return Ht("signTypedData",e),{signTypedData:t}}const bd=()=>{let{isModalOpen:e}=h(Jt);return{isOpen:e}};function Td(e){let{getAccessToken:t}=h(Jt);return Ht("accessToken",e),{getAccessToken:t}}function _d(e){let{authenticated:t,user:n}=$t(),{initLoginWithOAuth:r}=Pe(),a=Sn();return Ht("oAuthAuthorization",e),{reauthorize:e=>Id(t,n,r,a,e.provider)}}let Id=async(e,t,n,r,a)=>{if(!e)throw r("linkAccount","onError",M.MUST_BE_AUTHENTICATED,{linkMethod:a}),new C("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(a))))throw new C(`OAuth account of type ${a} not linked to the account.`);await n(a)};const Sd=e=>{let{customAuthStatus:t}=Pe();return Ht("customAuth",e),{status:t}};function Wd(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:n}=$t();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:n}}const xd=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=Pe();return{delegateWallet:async({address:e,chainType:n})=>await t({address:e,chainType:n,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},Pd=()=>{let{setUser:e,client:t}=h(Me),{user:n}=h(Jt);return{user:n,refreshUser:p((async()=>{let n=await(t?.updateUserAndIdToken());return e(n??null),n}),[t,e])}},Nd=e=>{let t=jt(),{initLoginWithTelegram:n,loginWithTelegram:r,telegramAuthState:a,setTelegramAuthState:i}=Pe();return{login:p((async a=>{try{if(t.enabled&&"success"!==t.status)throw new ci(t.error,null,M.CAPTCHA_FAILURE);await n(t.token,a?.disableSignup);let{user:i,isNewUser:o,loginAccount:s,wasAlreadyAuthenticated:l}=await r({intent:"login"});e?.onComplete?.({user:i,isNewUser:o,wasAlreadyAuthenticated:l,loginMethod:"telegram",loginAccount:s})}catch(a){throw i({status:"error",error:a}),e?.onError?.(a.privyErrorCode||M.UNKNOWN_AUTH_ERROR),a}}),[n,r,t]),state:a}},Ud=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=Pe();return{delegateWallet:async({address:e,chainType:n})=>await t({address:e,chainType:n,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}};export{ks as Captcha,rs as ConnectorManager,st as EthereumWalletConnector,$s as LoginModal,fs as PrivyClient,ed as PrivyProvider,St as VERSION,fn as errorIndicatesMaxMfaRetries,kn as errorIndicatesMfaTimeout,vn as errorIndicatesMfaVerificationFailed,Hc as getAccessToken,wd as useConnectCoinbaseSmartWallet,md as useCreateWallet,yd as useCrossAppAccounts,Sd as useCustomAuth,xd as useDelegatedActions,Wd as useFarcasterSigner,vd as useGuestAccounts,Ud as useHeadlessDelegatedActions,hs as useIdentityToken,nd as useImportWallet,ud as useLinkAccount,ld as useLinkWithPasskey,dd as useLinkWithSiwe,id as useLoginWithEmail,ad as useLoginWithOAuth,sd as useLoginWithPasskey,cd as useLoginWithSms,Nd as useLoginWithTelegram,Ni as useLogout,Ns as useMfa,nc as useMfaEnrollment,bd as useModalStatus,_d as useOAuthTokens,rd as usePrivy,As as useRegisterMfaListener,gd as useSendTransaction,fd as useSetWalletPassword,kd as useSetWalletRecovery,Cd as useSignAuthorization,Ad as useSignMessage,hd as useSignTransaction,Ed as useSignTypedData,od as useSignupWithPasskey,Td as useToken,pd as useUpdateAccount,Pd as useUser,Kt as useWallets};
1
+ import{u as e,a as i,b as s,c as l,C as d,d as h,s as k,P as C,e as W,f,g as T,G as U,W as R,h as S,i as P,j as N,k as O,l as M}from"./privy-provider-u_cmfixS.mjs";export{o as Captcha,p as ConnectorManager,E as EthereumWalletConnector,L as LoginModal,y as PrivyClient,m as PrivyProvider,H as SUPPORTED_CHAINS,V as VERSION,q as WalletConnector,J as addPrivyRpcToChain,I as addRpcUrlOverrideToChain,w as errorIndicatesMaxMfaRetries,x as errorIndicatesMfaTimeout,v as errorIndicatesMfaVerificationFailed,n as getAccessToken,z as useIdentityToken,F as useImportWallet,A as useLogout,r as useMfa,t as useMfaEnrollment,B as useRegisterMfaListener,D as useSolanaWallets}from"./privy-provider-u_cmfixS.mjs";export{c as useActiveWallet,a as useConnectWallet,b as useFundWallet,u as useLogin}from"./useActiveWallet-Cwj5v4eK.mjs";import{useCallback as _,useEffect as K,useContext as j}from"react";import{u as G,P as Q,a as X,I as $}from"./internal-context-O3TPYUku.mjs";import{zeroAddress as Y,getAddress as Z,createWalletClient as ee,http as te,parseSignature as re}from"viem";import{eip7702Actions as oe,hashAuthorization as ie}from"viem/experimental";export{g as getEmbeddedConnectedWallet}from"./getEmbeddedConnectedWallet-CSSBWE2p.mjs";import"react/jsx-runtime";import"mipd";import"react-device-detect";import"viem/utils";import"uuid";import"jose";import"eventemitter3";import"@coinbase/wallet-sdk";import"@privy-io/js-sdk-core";import"@marsidev/react-turnstile";import"styled-components";import"tinycolor2";import"@heroicons/react/24/outline/ArrowLeftIcon";import"@heroicons/react/24/outline/ArrowRightIcon";import"@heroicons/react/24/outline/QuestionMarkCircleIcon";import"@heroicons/react/24/outline/XMarkIcon";import"@heroicons/react/24/outline/CheckIcon";import"@heroicons/react/24/outline/Square2StackIcon";import"@heroicons/react/24/outline/WalletIcon";import"zustand";import"@walletconnect/ethereum-provider";import"@heroicons/react/24/outline/UserCircleIcon";import"@heroicons/react/24/outline/EnvelopeIcon";import"@heroicons/react/20/solid/CheckIcon";import"@heroicons/react/24/outline/PhoneIcon";import"@heroicons/react/24/outline/ExclamationTriangleIcon";import"@heroicons/react/24/outline/ExclamationCircleIcon";import"@heroicons/react/24/outline/ArrowTopRightOnSquareIcon";import"@heroicons/react/24/solid/DocumentCheckIcon";import"@heroicons/react/24/solid/XCircleIcon";import"fast-password-entropy";import"secure-password-utilities";import"secure-password-utilities/wordlists";import"@heroicons/react/24/outline/LockClosedIcon";import"@heroicons/react/24/outline/PencilSquareIcon";import"@heroicons/react/24/solid/CheckCircleIcon";import"@heroicons/react/24/outline/ArrowPathIcon";import"@heroicons/react/24/outline/EyeIcon";import"@heroicons/react/24/outline/EyeSlashIcon";import"@heroicons/react/24/outline/KeyIcon";import"@heroicons/react/24/outline/ArrowDownTrayIcon";import"@heroicons/react/24/outline/ClipboardDocumentCheckIcon";import"@heroicons/react/24/outline/DocumentDuplicateIcon";import"@heroicons/react/24/solid/LockClosedIcon";import"@heroicons/react/24/outline/ShieldCheckIcon";import"qrcode";import"@heroicons/react/24/outline/FingerPrintIcon";import"@heroicons/react/24/outline/ChevronRightIcon";import"@heroicons/react/24/outline/DevicePhoneMobileIcon";import"@heroicons/react/24/outline/ChevronDownIcon";import"@heroicons/react/24/outline/CalendarIcon";import"@headlessui/react";import"@heroicons/react/24/outline/CheckCircleIcon";import"@heroicons/react/24/outline/InformationCircleIcon";import"@heroicons/react/24/outline/CreditCardIcon";import"@heroicons/react/24/outline/QrCodeIcon";import"@heroicons/react/24/solid/ArrowsRightLeftIcon";import"@heroicons/react/24/outline/GlobeAltIcon";import"ofetch";import"@heroicons/react/24/outline";import"@heroicons/react/24/outline/ClipboardDocumentIcon";import"@heroicons/react/24/outline/CloudArrowUpIcon";import"@heroicons/react/24/outline/NoSymbolIcon";import"@heroicons/react/24/outline/ClockIcon";import"@heroicons/react/24/outline/TrashIcon";import"@heroicons/react/24/solid/CheckBadgeIcon";import"@heroicons/react/24/solid/IdentificationIcon";import"@heroicons/react/24/outline/MinusCircleIcon";import"@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon";import"@heroicons/react/24/solid/ShieldCheckIcon";import"js-cookie";const ne=t=>{e("login",t);let r=i(),o=s(),{ready:n,user:a}=l(),{initLoginWithHeadlessOAuth:c,loginWithHeadlessOAuth:u,oAuthState:p,setOAuthState:w,isHeadlessOAuthLoading:m}=G(),g=_((async e=>{try{if(r.enabled&&"success"!==r.status)throw new d(r.error,null,Q.CAPTCHA_FAILURE);return await c(e.provider,r.token,e.disableSignup)}catch(e){throw w({status:"error",error:e}),e}}),[c,r]),A=_((async()=>{let e=h();try{if(a)return console.warn("Cannot login with OAuth when already logged in"),a;if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(e.popupFlow)return}catch(e){throw w({status:"error",error:e}),e}try{return await u(e)}catch(e){throw w({status:"error",error:e}),e}finally{k()}}),[u]);return K((()=>{let e=h();n&&o&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&A().catch((()=>{}))}),[n,o]),{initOAuth:g,loading:m,state:p}},ae=e=>{let t=i(),{emailOtpState:r,setEmailOtpState:o,initLoginWithEmail:n,loginWithCode:a}=G();return{sendCode:_((async({email:r,disableSignup:i})=>{try{let e;if(!r)throw Error("Email required to send OTP code");if(t.enabled&&"error"===t.status)throw new d(t.error,null,Q.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await n({email:r,captchaToken:e,disableSignup:i,withPrivyUi:!1})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||Q.UNKNOWN_AUTH_ERROR),r}}),[n]),loginWithCode:_((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new d(t.error,null,Q.CAPTCHA_FAILURE);let{user:o,isNewUser:i,wasAlreadyAuthenticated:n,linkedAccount:s}=await a(r);e?.onComplete?.({user:o,isNewUser:i,wasAlreadyAuthenticated:n,loginMethod:"email",loginAccount:s})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||Q.UNKNOWN_AUTH_ERROR),r}}),[a,t.status]),state:r}},se=e=>{let t=i(),{initSignupWithPasskey:r,signupWithPasskey:o,passkeyAuthState:n,setPasskeyAuthState:a}=G();return{signupWithPasskey:_((async()=>{try{let i;if(t.enabled&&"error"===t.status)throw new d(t.error,null,Q.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult()),await r({captchaToken:i,withPrivyUi:!1});let{user:n,isNewUser:a,wasAlreadyAuthenticated:s,loginAccount:c}=await o();e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:s,loginMethod:"passkey",loginAccount:c})}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||Q.UNKNOWN_AUTH_ERROR),t}}),[o,t.status]),state:n}},ce=e=>{let t=i(),{initLoginWithPasskey:r,loginWithPasskey:o,passkeyAuthState:n,setPasskeyAuthState:a}=G();return{loginWithPasskey:_((async i=>{try{let n;if(t.enabled&&"error"===t.status)throw new d(t.error,null,Q.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),n=await t.waitForResult()),await r({captchaToken:n,withPrivyUi:!1});let{user:a,isNewUser:s,wasAlreadyAuthenticated:c,loginAccount:l}=await o(i);e?.onComplete?.({user:a,isNewUser:s,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:l})}catch(i){throw a({status:"error",error:i}),e?.onError?.(i.privyErrorCode||Q.UNKNOWN_AUTH_ERROR),i}}),[o,t.status]),state:n}},le=e=>{let{initLinkWithPasskey:t,linkWithPasskey:r,passkeyAuthState:o,setPasskeyAuthState:i}=G();return{linkWithPasskey:_((async()=>{try{await t();let o=await r();if(!o)throw Error("Error, user not found");let i=o.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:o,linkMethod:"passkey",linkedAccount:i})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||Q.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[r]),state:o}},ue=e=>{let t=i(),{smsOtpState:r,setSmsOtpState:o,initLoginWithSms:n,loginWithCode:a}=G();return{sendCode:_((async({phoneNumber:r,disableSignup:i})=>{try{let e;if(!r)throw Error("SMS required to send OTP code");if(t.enabled&&"error"===t.status)throw new d(t.error,null,Q.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await n({phoneNumber:r,captchaToken:e,disableSignup:i,withPrivyUi:!1})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||Q.UNKNOWN_AUTH_ERROR),r}}),[n]),loginWithCode:_((async({code:r})=>{try{if(t.enabled&&"success"!==t.status)throw new d(t.error,null,Q.CAPTCHA_FAILURE);let{user:o,isNewUser:i,wasAlreadyAuthenticated:n,linkedAccount:s}=await a(r);e?.onComplete?.({user:o,isNewUser:i,wasAlreadyAuthenticated:n,loginMethod:"sms",loginAccount:s})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||Q.UNKNOWN_AUTH_ERROR),r}}),[a,t.status]),state:r}},de=t=>{let{connectOrCreateWallet:r}=l();return e("connectOrCreateWallet",t),{connectOrCreateWallet:r}},he=e=>{let t=i(),{siweState:r,setSiweState:o,linkWithSiwe:n,generateSiweMessage:a}=G();return{generateSiweMessage:_((async({address:t,chainId:r})=>{try{if(!t||!r)throw Error("wallet address and chainId required to generate nonce");return await a({address:t,chainId:r}).then((e=>e))}catch(t){throw o({status:"error",error:t}),e?.onError?.(t.privyErrorCode||Q.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[a]),linkWithSiwe:_((async({signature:r,message:i,chainId:a,walletClientType:s,connectorType:c})=>{try{if(t.enabled&&"success"!==t.status)throw new d(t.error,null,Q.CAPTCHA_FAILURE);let{user:o,linkedAccount:l}=await n({message:i,signature:r,chainId:a,walletClientType:s,connectorType:c});l&&e?.onSuccess?.({user:o,linkMethod:"siwe",linkedAccount:l})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||Q.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[n,t.status]),state:r}};function pe(){let{signTransaction:e}=j(C);return{signTransaction:e}}function we(t){let{linkEmail:r,linkPhone:o,linkWallet:i,linkGoogle:n,linkApple:a,linkTwitter:s,linkDiscord:c,linkGithub:l,linkLinkedIn:u,linkTiktok:d,linkSpotify:h,linkInstagram:p,linkTelegram:w,linkFarcaster:m}=j(C);return e("linkAccount",t),{linkEmail:r,linkPhone:o,linkWallet:i,linkGoogle:n,linkApple:a,linkTwitter:s,linkDiscord:c,linkGithub:l,linkLinkedIn:u,linkTiktok:d,linkSpotify:h,linkInstagram:p,linkFarcaster:m,linkTelegram:w}}function me(t){let{updateEmail:r,updatePhone:o}=j(C);return e("update",t),{updateEmail:r,updatePhone:o}}function ge(t){let{createWallet:r}=j(C);return e("createWallet",t),{createWallet:r}}const Ae=()=>{let{connectCoinbaseSmartWallet:e}=G();return{connectCoinbaseSmartWallet:e}},ye=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:o,sendTransactionWithCrossAppWallet:i}=l();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:o,sendTransaction:i}};function ke(t){let{sendTransaction:r}=j(C);return e("sendTransaction",t),{sendTransaction:r}}function Ce(t){let{setWalletPassword:r}=j(C);return e("setWalletPassword",t),{setWalletPassword:r}}function Ie(){let e=W(),{getAccessToken:t,createWallet:r}=f(),o=T(),{client:i,setUser:n,setAuthenticated:a,setIsNewUser:s,initializeWalletProxy:c,refreshSessionAndUser:l}=G();return{createGuestAccount:async()=>{if(!e.id||!i)throw Error("SDK not yet ready");i.startAuthFlow(new U(e.id));try{let{user:u,isNewUser:d}=await i.authenticate();if(d=d||!1,!u)throw new X("Unable to authenticate guest account");let h=await t(),p=await c(R);if(h&&p)try{let t=S(u,e.embeddedWallets.ethereum.createOnLogin),o=P(u,e.embeddedWallets.solana.createOnLogin);if(t&&o){let e=await r();await p.createSolana({accessToken:h,ethereumAddress:e?.address}),u=await l()}else o?(await p.createSolana({accessToken:h,ethereumAddress:N(u)?.address}),u=await l()):t?(await r(),u=await l()):n(u)}catch(e){n(u),console.warn("Unable to create embedded wallet for guest account")}return s(d),a(!0),o("login","onComplete",{user:u,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),u}catch(e){throw o("login","onError",e.privyErrorCode||Q.UNKNOWN_AUTH_ERROR),e}}}}function We(t){let{setWalletRecovery:r}=j(C);return e("setWalletRecovery",t),{setWalletRecovery:r}}function fe(t){let{signMessage:r}=j(C);return e("signMessage",t),{signMessage:r}}const Ee=()=>{let{ready:e,wallets:t}=O(),{user:r}=l(),{rpcConfig:o,chains:i,appId:n}=G();return{signAuthorization:_((async(a,s)=>{if(!r)throw Error("User must be authenticated before signing with a Privy wallet");if(!e)throw Error("Wallets are not ready");let c=s?.address??N(r)?.address??Y,l=t.find((e=>Z(e.address)===Z(c)));if(!l)throw Error("Signing wallet not found.");let u=a.chainId??Number(l.chainId.split(":")[1]),d=i.find((e=>e.id===u));if(!d)throw Error("Error, chain not configured in PrivyProvider config");let h=ee({account:c,chain:d,transport:te(M(d,o,n))}).extend(oe()),p=await h.prepareAuthorization({...a,sponsor:a.sponsor||void 0}),w=await l.getEthereumProvider(),m=await w.request({method:"secp256k1_sign",params:[ie(p)]});return{...p,...re(m)}}),[e,t,r,i])}};function Te(t){let{signTypedData:r}=j(C);return e("signTypedData",t),{signTypedData:r}}const Ue=()=>{let{isModalOpen:e}=j(C);return{isOpen:e}};function Re(t){let{getAccessToken:r}=j(C);return e("accessToken",t),{getAccessToken:r}}function Se(t){let{authenticated:r,user:o}=l(),{initLoginWithOAuth:i}=G(),n=T();return e("oAuthAuthorization",t),{reauthorize:e=>Pe(r,o,i,n,e.provider)}}let Pe=async(e,t,r,o,i)=>{if(!e)throw o("linkAccount","onError",Q.MUST_BE_AUTHENTICATED,{linkMethod:i}),new X("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(i))))throw new X(`OAuth account of type ${i} not linked to the account.`);await r(i)};const ve=t=>{let{customAuthStatus:r}=G();return e("customAuth",t),{status:r}};function Ne(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=l();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}}const Oe=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=G();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},be=()=>{let{setUser:e,client:t}=j($),{user:r}=j(C);return{user:r,refreshUser:_((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}},Me=e=>{let t=i(),{initLoginWithTelegram:r,loginWithTelegram:o,telegramAuthState:n,setTelegramAuthState:a}=G();return{login:_((async i=>{try{if(t.enabled&&"success"!==t.status)throw new d(t.error,null,Q.CAPTCHA_FAILURE);await r(t.token,i?.disableSignup);let{user:n,isNewUser:a,loginAccount:s,wasAlreadyAuthenticated:c}=await o({intent:"login"});e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:c,loginMethod:"telegram",loginAccount:s})}catch(i){throw a({status:"error",error:i}),e?.onError?.(i.privyErrorCode||Q.UNKNOWN_AUTH_ERROR),i}}),[r,o,t]),state:n}},_e=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=G();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}};export{Ae as useConnectCoinbaseSmartWallet,de as useConnectOrCreateWallet,ge as useCreateWallet,ye as useCrossAppAccounts,ve as useCustomAuth,Oe as useDelegatedActions,Ne as useFarcasterSigner,Ie as useGuestAccounts,_e as useHeadlessDelegatedActions,we as useLinkAccount,le as useLinkWithPasskey,he as useLinkWithSiwe,ae as useLoginWithEmail,ne as useLoginWithOAuth,ce as useLoginWithPasskey,ue as useLoginWithSms,Me as useLoginWithTelegram,Ue as useModalStatus,Se as useOAuthTokens,f as usePrivy,ke as useSendTransaction,Ce as useSetWalletPassword,We as useSetWalletRecovery,Ee as useSignAuthorization,fe as useSignMessage,pe as useSignTransaction,Te as useSignTypedData,se as useSignupWithPasskey,Re as useToken,me as useUpdateAccount,be as useUser,O as useWallets};