@privy-io/react-auth 3.6.0 → 3.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/EmbeddedWalletConnectingScreen-JRafXI8d.js +27 -0
- package/dist/cjs/{SignRequestScreen-DBTM8mH6.js → SignRequestScreen-Dy02euV9.js} +1 -1
- package/dist/cjs/abstract-smart-wallets.js +1 -1
- package/dist/cjs/{events-context-B1SQ9SZZ.js → events-context-7-Gs8c_9.js} +1 -1
- package/dist/cjs/extended-chains.js +1 -1
- package/dist/cjs/index.js +6 -7
- package/dist/cjs/internal.js +1 -1
- package/dist/cjs/{smart-wallets-DS5H3O_R.js → smart-wallets-DaqaXBrW.js} +1 -1
- package/dist/cjs/smart-wallets.js +1 -1
- package/dist/cjs/solana.js +1 -1
- package/dist/cjs/ui.js +1 -1
- package/dist/cjs/use-export-wallet-Cz8MVlvJ.js +2 -0
- package/dist/cjs/{useActiveWallet-DSa22Ge3.js → useActiveWallet-C5D3a-je.js} +1 -1
- package/dist/cjs/{usePrivy-BRFNEdKI.js → usePrivy-BdYU4BZI.js} +1 -1
- package/dist/dts/{events-context-B1q54lAU.d.mts → events-context-CCElA92Y.d.mts} +1 -1
- package/dist/dts/{events-context-B1q54lAU.d.ts → events-context-CCElA92Y.d.ts} +1 -1
- package/dist/dts/extended-chains.d.mts +1 -1
- package/dist/dts/extended-chains.d.ts +1 -1
- package/dist/dts/farcaster.d.mts +1 -1
- package/dist/dts/farcaster.d.ts +1 -1
- package/dist/dts/index.d.mts +93 -6
- package/dist/dts/index.d.ts +93 -6
- package/dist/dts/internal.d.mts +1 -1
- package/dist/dts/internal.d.ts +1 -1
- package/dist/dts/smart-wallets.d.mts +1 -1
- package/dist/dts/smart-wallets.d.ts +1 -1
- package/dist/dts/solana.d.mts +3 -3
- package/dist/dts/solana.d.ts +3 -3
- package/dist/dts/{types-BSeKsLfK.d.mts → types-B6UNnZ2P.d.mts} +8 -1
- package/dist/dts/{types-BSeKsLfK.d.ts → types-B6UNnZ2P.d.ts} +8 -1
- package/dist/dts/ui.d.mts +1 -1
- package/dist/dts/ui.d.ts +1 -1
- package/dist/esm/EmbeddedWalletConnectingScreen-D50stmJi.mjs +25 -0
- package/dist/esm/{SignRequestScreen-B2NV0Hvv.mjs → SignRequestScreen-D9o7VhNz.mjs} +1 -1
- package/dist/esm/abstract-smart-wallets.mjs +1 -1
- package/dist/esm/{events-context-DpXp5E_5.mjs → events-context-ClaboIDc.mjs} +1 -1
- package/dist/esm/extended-chains.mjs +1 -1
- package/dist/esm/index.mjs +5 -6
- package/dist/esm/internal.mjs +1 -1
- package/dist/esm/{smart-wallets-X-vN2hVx.mjs → smart-wallets-BXT3GZwg.mjs} +1 -1
- package/dist/esm/smart-wallets.mjs +1 -1
- package/dist/esm/solana.mjs +1 -1
- package/dist/esm/ui.mjs +2 -2
- package/dist/esm/use-export-wallet-DTiEdSYz.mjs +1 -0
- package/dist/esm/{useActiveWallet-6VCN4YGN.mjs → useActiveWallet-B8DSbnuu.mjs} +1 -1
- package/dist/esm/{usePrivy-DLA1ZqHR.mjs → usePrivy-BCcRF869.mjs} +1 -1
- package/package.json +8 -6
- package/dist/cjs/EmbeddedWalletConnectingScreen-fhtSGmI2.js +0 -27
- package/dist/cjs/use-export-wallet-DPcrptkc.js +0 -2
- package/dist/esm/EmbeddedWalletConnectingScreen-DNdaS6u7.mjs +0 -25
- package/dist/esm/use-export-wallet-CPIcGGw7.mjs +0 -1
package/dist/esm/index.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import{jsx as t,jsxs as r,Fragment as n}from"react/jsx-runtime";import{createStore as a}from"mipd";import i,{useMemo as o,useEffect as s,useState as l,useRef as u,useContext as h,useCallback as p,forwardRef as m,createContext as w}from"react";import{isMobile as y,isIOS as f,isSafari as v,isAndroid as C}from"react-device-detect";import{toHex as k,isAddress as A,getAddress as T,isHex as _,hashAuthorization as E}from"viem/utils";import I,{DEFAULT_SUPPORTED_CHAIN_IDS as S,rpc as U,lastFourDigits as P,getWallet as W,updateWallet as x,generateAuthorizationSignature as N,PrivyClientError as O}from"@privy-io/js-sdk-core";export{DEFAULT_SUPPORTED_CHAINS as SUPPORTED_CHAINS,addPrivyRpcToChain,addRpcUrlOverrideToChain}from"@privy-io/js-sdk-core";import{P as R,u as M,f as F,p as L,a as D,b as q,c as z,d as B,e as H,g as j,o as V,h as $,i as K,j as G,k as Y,l as Z,m as J,n as X,q as Q,r as ee,s as te,t as re,v as ne,w as ae,x as ie,y as oe,z as se,A as le,B as ce,C as de,D as ue,E as he,F as pe,G as me,H as we,I as ye,J as ge,K as fe,L as ve,M as Ce,N as ke,O as Ae,Q as be,R as Te,S as _e,T as Ee,U as Ie,V as Se,W as Ue,X as Pe,Y as We,Z as xe,_ as Ne,$ as Oe,a0 as Re,a1 as Me,a2 as Fe,a3 as Le,a4 as De,a5 as qe,a6 as ze,a7 as Be,a8 as He,a9 as je,aa as Ve,ab as $e,ac as Ke,ad as Ge,ae as Ye,af as Ze}from"./internal-context-eGSwROSk.mjs";import{o as Je,R as Xe,g as Qe,f as et,c as tt,a as rt,d as nt,A as at,T as it,L as ot,b as st,I as lt,S as ct,e as dt,h as ut,G as ht,D as pt,i as mt,j as wt,k as yt,E as gt,B as ft,l as vt,P as Ct,C as kt,t as At,m as bt,n as Tt,p as _t,q as Et,r as It,s as St,M as Ut,u as Pt,v as Wt,w as xt,x as Nt,y as Ot,z as Rt,F as Mt,H as Ft,W as Lt,J as Dt,K as qt,N as zt,O as Bt,Q as Ht,U as jt,V as Vt,X as $t,Y as Kt,Z as Gt,_ as Yt,$ as Zt,a0 as Jt,a1 as Xt,a2 as Qt,a3 as er,a4 as tr,a5 as rr,a6 as nr,a7 as ar,a8 as ir,a9 as or,aa as sr,ab as lr,ac as cr,ad as dr,ae as ur,af as hr,ag as pr,ah as mr,ai as wr,aj as yr,ak as gr,al as fr,am as vr,an as Cr,ao as kr,ap as Ar,aq as br,ar as Tr,as as _r,at as Er,au as Ir,av as Sr,aw as Ur,ax as Pr,ay as Wr,az as xr,aA as Nr,aB as Or,aC as Rr,aD as Mr,aE as Fr,aF as Lr,aG as Dr,aH as qr,aI as zr,aJ as Br,aK as Hr,aL as jr,aM as Vr,aN as $r,aO as Kr,aP as Gr,aQ as Yr,aR as Zr,aS as Jr,aT as Xr,aU as Qr,aV as en,aW as tn,aX as rn,aY as nn,aZ as an,a_ as on,a$ as sn,b0 as ln,b1 as cn,b2 as dn,b3 as un,b4 as hn,b5 as pn,b6 as mn,b7 as wn,b8 as yn,b9 as gn,ba as fn,bb as vn,bc as Cn,bd as kn,be as An,bf as bn,bg as Tn,bh as _n,bi as En,bj as In,bk as Sn,bl as Un,bm as Pn,bn as Wn,bo as xn,bp as Nn,bq as On,br as Rn,bs as Mn,bt as Fn,bu as Ln,bv as Dn,bw as qn,bx as zn,by as Bn,bz as Hn,bA as jn,bB as Vn,bC as $n,bD as Kn,bE as Gn,bF as Yn,bG as Zn,bH as Jn,bI as Xn,bJ as Qn,bK as ea,bL as ta,bM as ra}from"./EmbeddedWalletConnectingScreen-DNdaS6u7.mjs";export{bN as WalletConnector}from"./EmbeddedWalletConnectingScreen-DNdaS6u7.mjs";import{v4 as na}from"uuid";import*as aa from"jose";import{base64url as ia}from"jose";import oa from"eventemitter3";import{createCoinbaseWalletSDK as sa}from"@coinbase/wallet-sdk";import{toViemTransactionSerializable as la}from"@privy-io/ethereum";import{C as ca,H as da,O as ua,S as ha,V as pa,g as ma,a as wa,P as ya,R as ga,b as fa,c as va,D as Ca,d as ka,e as Aa,I as ba,f as Ta,h as _a,i as Ea,j as Ia,u as Sa,k as Ua,l as Pa,m as Wa,n as xa,o as Na,p as Oa,q as Ra,r as Ma,s as Fa,t as La,W as Da}from"./events-context-DpXp5E_5.mjs";import{ofetch as qa}from"ofetch";import za from"js-cookie";import{create as Ba}from"zustand";import{Turnstile as Ha}from"@marsidev/react-turnstile";import{styled as ja,createGlobalStyle as Va,css as $a}from"styled-components";import{u as Ka,a as Ga,C as Ya}from"./useActiveWallet-6VCN4YGN.mjs";export{e as useActiveWallet,c as useConnectWallet,d as useFundWallet,b as useLogin}from"./useActiveWallet-6VCN4YGN.mjs";import Za from"@heroicons/react/24/outline/DevicePhoneMobileIcon";import Ja from"@heroicons/react/24/outline/FingerPrintIcon";import Xa from"@heroicons/react/24/outline/PhoneIcon";import Qa from"@heroicons/react/24/outline/ShieldCheckIcon";import ei from"@heroicons/react/24/outline/CalendarIcon";import ti from"@heroicons/react/24/outline/ExclamationTriangleIcon";import{toHex as ri,zeroAddress as ni,getAddress as ai,createWalletClient as ii,http as oi,parseSignature as si}from"viem";import{Transition as li,Dialog as ci,TransitionChild as di,DialogPanel as ui}from"@headlessui/react";import{constructURL as hi}from"@privy-io/urls";import{i as pi,f as mi,u as wi,p as yi,e as gi,a as fi}from"./usePrivy-DLA1ZqHR.mjs";export{b as useCreateWallet,c as useImportWallet}from"./usePrivy-DLA1ZqHR.mjs";import{CheckCircle as vi,FingerprintIcon as Ci,Trash2 as ki,AlertCircle as Ai,CloudUpload as bi,Ban as Ti,ExternalLink as _i,XCircle as Ei,Mail as Ii}from"lucide-react";import{C as Si,S as Ui}from"./SignRequestScreen-B2NV0Hvv.mjs";import Pi from"@heroicons/react/24/outline/EnvelopeIcon";import Wi from"@heroicons/react/24/outline/QuestionMarkCircleIcon";import xi from"@heroicons/react/24/solid/CheckBadgeIcon";import Ni from"@heroicons/react/24/solid/IdentificationIcon";import Oi from"@heroicons/react/24/outline/ChevronRightIcon";import Ri from"@heroicons/react/24/outline/MinusCircleIcon";import Mi from"@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon";import Fi from"@heroicons/react/24/outline/ClockIcon";import Li from"@heroicons/react/24/outline/CheckCircleIcon";import Di from"@heroicons/react/24/solid/ShieldCheckIcon";import qi from"@heroicons/react/24/outline/GlobeAltIcon";import{F as zi}from"./frame-Dj70FEYB.mjs";import{MfaAuthPasskeyVerify as Bi,MfaAuthPasskeyInit as Hi,MfaAuthTotpVerify as ji,MfaAuthPasskeyEnrollment as Vi,MfaAuthTotpUnenroll as $i,MfaAuthTotpEnroll as Ki,MfaAuthTotpInit as Gi}from"@privy-io/routes";import{u as Yi}from"./use-sign-with-user-signer-DaTvrd5T.mjs";export{g as getEmbeddedConnectedWallet}from"./getEmbeddedConnectedWallet-CM6cDQCS.mjs";import{toAccount as Zi}from"viem/accounts";import"fast-password-entropy";import"secure-password-utilities";import"secure-password-utilities/wordlists";import"@heroicons/react/24/outline/UserCircleIcon";import"@heroicons/react/24/outline/ArrowLeftIcon";import"@heroicons/react/24/outline/ArrowRightIcon";import"@heroicons/react/24/outline/XMarkIcon";import"@heroicons/react/20/solid/CheckIcon";import"@heroicons/react/24/outline/WalletIcon";import"@heroicons/react/24/outline/ExclamationCircleIcon";import"@heroicons/react/24/outline/Square2StackIcon";import"@heroicons/react/24/outline";import"@tanstack/react-virtual";import"@heroicons/react/24/outline/CheckIcon";import"qrcode";import"@scure/base";import"@walletconnect/ethereum-provider";import"@heroicons/react/24/outline/CreditCardIcon";import"@heroicons/react/24/outline/QrCodeIcon";import"@heroicons/react/24/solid/ArrowsRightLeftIcon";import"@heroicons/react/24/outline/InformationCircleIcon";import"@heroicons/react/24/outline/ClipboardDocumentCheckIcon";import"@heroicons/react/24/outline/ClipboardDocumentIcon";import"@heroicons/react/24/outline/ChevronDownIcon";import"@heroicons/react/24/solid/CheckCircleIcon";import"@heroicons/react/24/outline/LockClosedIcon";import"@heroicons/react/24/outline/PencilSquareIcon";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/DocumentDuplicateIcon";import"@heroicons/react/24/solid/XCircleIcon";import"tinycolor2";function Ji(e){return e?{"privy-ui":"t"}:void 0}class Xi{async authenticate(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new R("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(L,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw F(e)}}async link(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new R("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(D,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw F(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new R("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new R("Email must be set when initialzing authentication.");let n=Ji(r);try{return await this.api.post(q,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw F(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class Qi extends Xi{async link(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new R("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(M,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw F(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}class eo{get meta(){return this._meta}async authenticate(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.channelToken)throw new R("Auth flow must be initialized first");try{let e=await this.api.post(z,{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 R("No response from authentication");return e}catch(e){throw F(e)}}async link(){if(!this.api)throw new R("Auth flow has no API instance");try{return await this.api.post(B,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw F(e)}}async _startChannelOnce(){if(!this.api)throw new R("Auth flow has no API instance");let e=await this.api.post(H,{token:this.captchaToken});y&&!f&&e.connect_uri&&Je(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new R("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.channelToken)throw new R("Auth flow must be initialized first");let e=await this.api.get(j,{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 Xe(this._startChannelOnce.bind(this)),this.pollForReady=new Xe(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function to(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function ro(){if(!to())return;let e=window.chrome;return e?.runtime?.id}function no(){if(!to())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function ao(e){return new Promise(((t,r)=>{no()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!to())return;let e=window.chrome;return e?.runtime?.lastError?.message}();if(r||!e){let e=`WebAuthFlow failed: ${r||"Response URI missing"}`;throw Error(e)}let n=new URL(e),a=ro();if(!a)throw Error("Invalid extension context");if("chrome-extension:"===n.protocol){if(n.hostname!==a)throw Error("Invalid responseUri origin")}else{if("https:"!==n.protocol)throw Error("Invalid responseUri protocol");{let e=n.hostname.split(".");if(3!==e.length||"chromiumapp"!==e[1]||"org"!==e[2]||e[0]!==a)throw Error("Invalid responseUri origin")}}let i=n.searchParams.get("privy_oauth_state"),o=n.searchParams.get("privy_oauth_code");if(!i||!o)throw Error("Invalid responseUri - missing required parameters");t({privyOAuthState:i,privyOAuthCode:o})}catch(e){r(e)}})):r(Error("Chrome identity API not available"))}))}class io{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new R("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new R("User denied confirmation during OAuth flow");let e=Qe();try{let t=await this.api.post(V,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return et.del(ca),et.del(da),et.del(ua),t}catch(e){let t=F(e);if(t.privyErrorCode)throw new R(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new R("Invalid code during oauth flow.",void 0,$.OAUTH_USER_DENIED);throw new R("Invalid code during OAuth flow.",void 0,$.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new R("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new R("User denied confirmation during OAuth flow");let e=et.get(ca);if(!e)throw new R("Authentication error.");try{let t=await this.api.post(K,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return et.del(ca),t}catch(e){throw F(e)}}async getAuthorizationUrl(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.provider)throw new R("Provider must be set when initializing OAuth authentication.");let e=tt();et.put(ca,e);let t=rt();et.put(ha,t);let r=await nt(e);this.meta.withPrivyUi||et.put(da,!0),this.meta.disableSignup?et.put(ua,!0):et.del(ua);let n=Ji(this.meta.withPrivyUi),a=window.location.href,i=function(){let e=ro();if(e)return`https://${e}.chromiumapp.org`}();i&&(a=i);try{return await this.api.post(G,{provider:this.meta.provider,redirect_to:this.meta.customOAuthRedirectUrl||a,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw F(e)}}constructor(e){this.meta=e}}const oo=({style:e})=>/*#__PURE__*/t(qi,{style:{color:"var(--privy-color-error)",...e}});let so={google:{name:"Google",component:mt},discord:{name:"Discord",component:pt},github:{name:"Github",component:ht},linkedin:{name:"LinkedIn",component:ut},twitter:{name:"Twitter",component:dt},spotify:{name:"Spotify",component:ct},instagram:{name:"Instagram",component:lt},tiktok:{name:"Tiktok",component:st},line:{name:"LINE",component:ot},twitch:{name:"Twitch",component:it},apple:{name:"Apple",component:at}},lo=({iconUrl:e,...t})=>i.createElement("svg",{width:"33",height:"32",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t},i.createElement("foreignObject",{x:"2",y:"2",width:"29",height:"28"},i.createElement("img",{src:e,width:"29",height:"28",style:{display:"block",objectFit:"contain",borderRadius:"4px"},alt:"Provider icon"})));const co=(e,t)=>{if(e in so)return so[e];if(wt(e)&&t){let r=t.find((t=>t.provider===e));if(r)return{name:r.provider_display_name,component:e=>i.createElement(lo,{...e,iconUrl:r.provider_icon_url})}}return{name:"Unknown",component:oo}};function uo(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),n=e.get("privy_oauth_provider");if(!t||!r||!n)return{inProgress:!1};let a=!1;try{a=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:n,withPrivyUi:!et.get(da),popupFlow:null!==window.opener&&a,disableSignup:!!et.get(ua)}}class ho{async initRegisterFlow(e){if(!this.api)throw new R("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 R("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new R("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 R("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new R("WebAuthn is not supported in this browser");this.meta.initRegisterResponse||(this.meta.initRegisterResponse=await this.initRegisterOnce.execute());try{let t=this.meta.initRegisterResponse.options,r=await e.startRegistration({optionsJSON:this._transformInitLinkOptionsToCamelCase(t)});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(Y,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new R("Passkey request timed out or rejected by user.",void 0,$.PASSKEY_NOT_ALLOWED);throw F(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new R("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new R("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 r=await e.startAuthentication({optionsJSON: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(r)})}catch(e){if("NotAllowedError"===e.name)throw new R("Passkey request timed out or rejected by user.",void 0,$.PASSKEY_NOT_ALLOWED);throw F(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new R("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new R("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let t=this.meta.initLinkResponse.options,r=await e.startRegistration({optionsJSON:this._transformInitLinkOptionsToCamelCase(t)});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(J,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new R("Passkey request timed out or rejected by user.",void 0,$.PASSKEY_NOT_ALLOWED);throw F(e)}}async _initRegisterOnce(e){if(!this.api)throw new R("Auth flow has no API instance");let t=Ji(e);return await this.api.post(X,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new R("Auth flow has no API instance");let t=Ji(e);return await this.api.post(Q,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new R("Auth flow has no API instance");return await this.api.post(ee,{})}_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},hints:this.meta.hints}}_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,hints:r}){this.authenticateForRegistration=!1,this.initRegisterOnce=new Xe(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new Xe(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new Xe(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t,hints:r}}}class po{async authenticate(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new R("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(te,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw F(e)}}async link(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new R("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(re,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw F(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new R("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new R("phone nNumber must be set when initialzing authentication.");let n=Ji(r);try{return await this.api.post(ne,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw F(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class mo extends po{async link(){if(!this.api)throw new R("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new R("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(ae,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw F(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}class wo{static parse(e){try{return new wo(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return aa.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=aa.decodeJwt(e)}}class yo extends wo{static parse(e){try{return new yo(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let go,fo;class vo extends gt{async initialize(){await this.importPromise,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:ft,id:"com.coinbase.wallet"}}async promptConnection(){try{await this.importPromise;let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new ie("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw vt(e)}}constructor(e,t,r,n,a){super("base_account",e,t,r),this.connectorType="base_account",this.walletClientType="base_account",this.displayName="Base",this.setBaseAccountSdk=a,this.proxyProvider=new Ct(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},go?(this.proxyProvider.setWalletProvider(go.getProvider()),this.setBaseAccountSdk(go),console.log("Base Account SDK Initialized")):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{go=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(go.getProvider()),this.setBaseAccountSdk(go),console.log("Base Account SDK Initialized")})).catch(console.error)}}let Co=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class ko extends gt{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:kt,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 ie("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw vt(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",fo=sa({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(fo.getProvider())}constructor(e,t,r,n){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new Ct(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.coinbaseWalletConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},this.walletClientType="smartWalletOnly"===this.coinbaseWalletConfig.preference?.options?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!fo){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!Co.includes(e))):[];e.length>0&&!e.every((e=>S.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${e.join(", ")}`),fo=sa(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(fo.getProvider())}}class Ao extends gt{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:[At(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:bt,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}constructor({provider:e,chains:t,defaultChain:r,rpcConfig:n,imported:a,walletIndex:i}){super("privy",t,r,n),this.connectorType="embedded",this.proxyProvider=e,this.walletIndex=i,a&&(this.connectorType="embedded_imported"),this.subscribeListeners()}}const bo=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];class To extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class _o extends oa{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new To(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Kc()||!this.address)throw new To("Disconnected",4900);let{hash:r}=await Jc(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new To(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Kc()||!this.address)throw new To("Disconnected",4900);let{signature:r}=await Zc(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new To(`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 To(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=Tt(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],r=e.params[1],{signature:n}=await Gc({message:t},{address:r});return n}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],r="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1],{signature:n}=await Yc(_t(r),{address:t});return n}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:At(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...la(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 At(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=>bo.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await Kc();if(await Xc({address:this.address}),!t||!this.address)throw new To("Disconnected",4900);try{let r={method:e.method,params:e.params},n=this.walletAccount;return n&&Et(n)?this.handleWalletApiRequest(r,n,t):(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:r})).response.data}catch(e){throw console.error(e),new To("Disconnected",4900)}}}async handleWalletApiRequest(e,t,r){let n=this.privyClient;if(!n)throw new To("Disconnected",4900);if("secp256k1_sign"===e.method){let a=await U(n,(async({message:e})=>this.walletProxy.signWithUserSigner({accessToken:r,message:e})),{chain_type:"ethereum",method:"secp256k1_sign",wallet_id:t.id,params:{hash:e.params[0]}});if("secp256k1_sign"!==a.method)throw new To(`Invalid params for ${e.method}`,4200);return a.data.signature}throw new To(`Method not supported: ${e.method}`,4200)}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:a,chains:i,appId:o,chainId:s=1,walletIndex:l,privyClient:c,walletAccount:d}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=s,this.rpcConfig=a,this.chains=i,this.publicClient=Tt(s,this.chains,a,{appId:o}),this.rpcTimeoutDuration=It(a,"privy"),this.appId=o,this.walletIndex=l,this.privyClient=c,this.walletAccount=d}}function Eo(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var Io=0;class So extends gt{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 ie("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw vt(e)}}constructor(e,t,r,n,a){super(a||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new Ct(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let i=n.provider;this.proxyProvider.setWalletProvider(i)}}var Uo="__private_"+Io+++"__walletBranding";class Po extends gt{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 Eo(this,Uo)[Uo]??{name:"Browser Extension",icon:St,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 ie("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw vt(e)}}constructor(e,t,r,n,a){super(a??"unknown",e,t,r),Object.defineProperty(this,Uo,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new Ct(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===a?Eo(this,Uo)[Uo]={name:"MetaMask",icon:Ut,id:"io.metamask"}:"phantom"===a&&(Eo(this,Uo)[Uo]={name:"Phantom",icon:Pt,id:"phantom"})}}class Wo extends So{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{y||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 ie("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw vt(e)}}}class xo extends oa{get wallets(){let e=new Set;return this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(r)&&(e.add(r),!0)}))}async initialize(e){if(this.initialized&&!e||(e&&this.removeAllConnectors(),this.externalWalletConfig.disableAllExternalWallets))return;let t=Wt({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:r}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),this.walletList.includes("base_account")&&this.createEthereumWalletConnector({connectorType:"base_account",walletClientType:"base_account"}),Object.values(xt)))!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 Nt({id:e.client,name:e.name})));this.externalWalletConfig.walletConnect.enabled&&(this.walletList.includes("wallet_connect_qr")||this.walletList.includes("wallet_connect"))&&"solana-only"!==this.walletChainType&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"});let r=this.walletList.includes("wallet_connect_qr_solana"),n=this.externalWalletConfig.solana.connectors?.get()||[],a=async e=>{if(!r)return;let t=e.find((e=>"walletconnect_solana"===e.walletBranding?.id));t&&t.wallet&&await t.wallet.initialize({walletConnectCloudProjectId:this.walletConnectCloudProjectId,privyAppName:this.privyAppName})};a(n),n.filter((e=>r||"walletconnect_solana"!==e.walletBranding?.id)).forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{a(e),e?.filter((e=>r||"walletconnect_solana"!==e.walletBranding?.id)).forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t,r){return"wallet_connect_v2"===e?this.walletConnectors.filter(Ot).find((t=>t.connectorType===e&&(!r||t.wallets.some((e=>e.address===r)))))??null:this.walletConnectors.filter(Ot).find((n=>n.connectorType===e&&n.walletClientType===t&&(!r||n.wallets.some((e=>e.address===r)))))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(Rt).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}findImportedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded_imported"===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.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&this.emit("walletsUpdated")}addEmbeddedWalletConnectors({walletProxy:e,user:t,embeddedWallets:r,defaultChain:n,appId:a,privyClient:i}){let{entropyId:o,entropyIdVerifier:s}=Mt(t);for(let t of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===t.walletIndex));if(r&&Ot(r))r.proxyProvider.walletProxy=e;else{let r=new Ao({provider:new _o({walletProxy:e,address:t.address,entropyId:o,entropyIdVerifier:s,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:n.id,walletIndex:t.walletIndex,privyClient:i,walletAccount:t}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:t.walletIndex});this.addWalletConnector(r)}}}addImportedWalletConnector(e,t,r,n){let a=this.findWalletConnector("embedded_imported","privy",t);if(a&&Ot(a))a.proxyProvider.walletProxy=e;else{let a=new Ao({provider:new _o({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(a)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.storedConnections=Ft(),this.emit("walletsUpdated")}removeImportedWalletConnectors(){let e=this.findImportedWalletConnectors();e.length&&(e.forEach((e=>{let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1)})),this.storedConnections=Ft(),this.emit("walletsUpdated"))}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let a=this.findWalletConnector(e,t);if(a&&Ot(a))return a instanceof Lt&&a.resetConnection(t),a;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new ko(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new vo(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new Lt({walletConnectCloudProjectId:this.walletConnectCloudProjectId,rpcConfig:this.rpcConfig,chains:this.chains,defaultChain:this.defaultChain,shouldEnforceDefaultChainOnConnect:this.shouldEnforceDefaultChainOnConnect,privyAppId:this.privyAppId,privyAppName:this.privyAppName,walletClientType:t}):n?new Dt({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new Wo(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Po(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Po(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Po(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new So(this.chains,this.defaultChain,this.rpcConfig,r?.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)}))}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,r,n,a,i,o,s,l,c,d,u){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.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=a,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=s,this.externalWalletConfig=l,this.privyAppName=c,this.walletChainType=u||"ethereum-only",this.setBaseAccountSdk=d,this.storedConnections=Ft()}}let No=[se,le,ce];class Oo{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw F(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw F(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw F(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=pa,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=qa.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 r=new Headers(t.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-ca-id",this.clientAnalyticsId||""),r.set("privy-client",`react-auth:${this.sdkVersion}`);let n=No.includes(e.toString());if(!r.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:n});null!==e&&r.set("authorization",`Bearer ${e}`)}t.headers=r,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new oe}})}}let Ro=/paymaster\.biconomy\.io\/api/i,Mo={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const Fo=(e,t)=>e&&Ro.test(e)?Mo:t&&t.policy_id?{policyId:t.policy_id}:void 0,Lo=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});class Do{async authenticate(){if(!this.api)throw new R("Auth flow has no API instance");try{return await this.api.post(de,{token:this.meta.token})}catch(e){throw F(e)}}async link(){if(!this.api)throw new R("Auth flow has no API instance");try{return await this.api.post(ue,{token:this.meta.token})}catch(e){throw F(e)}}constructor(e){this.meta={token:e}}}class qo{getOrCreateGuestCredential(e){let t=ma(e);if(qt()){if(et.get(t))return et.get(t);{let e=ia.encode(zt(32));return et.put(t,e),e}}return ia.encode(zt(32))}async authenticate(){if(!this.api)throw new R("Auth flow has no API instance");try{return await this.api.post(he,{guest_credential:this.meta.guestCredential})}catch(e){throw F(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function zo(){return!(v&&window.location.origin.startsWith("http://localhost"))}const Bo=Ba((()=>({identityToken:null})));function Ho(){let{identityToken:e}=Bo();return{identityToken:e}}var jo,Vo=((jo={}).PRIVY="privy_access_token",jo.CUSTOMER="customer_access_token",jo);class $o{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(wa)}get privyAccessToken(){return this._getToken(ya)}_getToken(e){try{let t=et.get(e);return"string"==typeof t?wo.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=et.get(ga);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=et.get(fa(e));if("string"!=typeof t)return null;{let r=new wo(t);return r.isExpired()?(et.del(fa(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=za.get(va);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),r="string"==typeof this.refreshToken&&this.refreshToken!==Ca;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=wo.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?et.put(fa(e),t):et.del(fa(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:r,is_new_user:n,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,n),{user:Ht(r),isNewUser:n,oAuthTokens:i}}catch(e){throw console.warn("Error authenticating session"),pe(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof Xi?"email":e instanceof po?"sms":e instanceof Bt?"siwe":e instanceof qo?"guest":e instanceof Do?"custom_auth":e instanceof io?e.meta.provider:null}(e);r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:r,isNewUser:t}}),"siwe"===r&&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(),r=t.oauth_tokens,n=r?{provider:r.provider,accessToken:r.access_token,accessTokenExpiresInSeconds:r.access_token_expires_in_seconds,refreshToken:r.refresh_token,refreshTokenExpiresInSeconds:r.refresh_token_expires_in_seconds,scopes:r.scopes}:void 0;return{user:Ht(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),pe(e)}}async _refresh(){if(!this.api)throw new R("Session has no API instance");if(!this.client)throw new R("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 r;if(!(e&&t||this.mightHaveServerCookies))return null;{let n={};e&&(n.authorization=`Bearer ${e}`),r=await this.api.post(se,t?{refresh_token:t}:{},{headers:n})}return this.handleTokenResponse(r),Ht(r.user)}catch(e){if(e instanceof me&&e.privyErrorCode===$.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw pe(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(le,{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=et.get(wa);if(et.put(wa,e),!this.client?.useServerCookies){let t=wo.parse(e)?.expiration;za.set(ka,e,{sameSite:"Strict",secure:zo(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else et.del(wa),za.remove(ka),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(et.put(ga,e),this.client?.useServerCookies||za.set(va,"t",{sameSite:"Strict",secure:zo(),expires:30})):(et.del(ga),za.remove(Aa),za.remove(va))}storePrivyAccessToken(e){"string"==typeof e?et.put(ya,e):et.del(ya)}storeIdentityToken(e){if(Bo.setState({identityToken:e}),this.client?.useServerCookies)return;et.put(ba,e);let t=wo.parse(e)?.expiration;za.set(Ta,e,{sameSite:"Strict",secure:zo(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){et.del(ba),Bo.setState({identityToken:null}),za.remove(Ta)}constructor(){this.authenticateOnce=new Xe((async e=>this._authenticate(e))),this.linkOnce=new Xe((async e=>this._link(e))),this.refreshOnce=new Xe(this._refresh.bind(this)),this.destroyOnce=new Xe(this._destroy.bind(this))}}let Ko;var Go=0,Yo="__private_"+Go+++"__getOrGenerateClientAnalyticsId";class Zo{getAppId(){return this.appId}initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,store:a,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c,setBaseAccountSdk:d}){this.connectors||(this.connectors=new xo(this.appId,e,t,r,n,a,i,o,s,l,d,c))}generateApi(){let e=new Oo({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 R("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new R("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(we,{action:"verify"})}catch(e){throw F(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(ye,{});return Lo(e.options)}catch(e){throw F(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(ge,{});return Ht(e)}catch(e){throw pe(e)}}async unlinkEmail(e){try{let t=await this.api.post(fe,{address:e});return await this.getAuthenticatedUser()??Ht(t)}catch(e){throw pe(e)}}async unlinkPhone(e){try{let t=await this.api.post(ve,{phoneNumber:e});return await this.getAuthenticatedUser()??Ht(t)}catch(e){throw pe(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(Ce,{address:e});return await this.getAuthenticatedUser()??Ht(t)}catch(e){throw pe(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(ke,{address:e});return await this.getAuthenticatedUser()??Ht(t)}catch(e){throw pe(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(Ae,{provider:e,subject:t});return await this.getAuthenticatedUser()??Ht(r)}catch(e){throw pe(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(be,{fid:e});return await this.getAuthenticatedUser()??Ht(t)}catch(e){throw pe(e)}}async unlinkTelegram(e){try{let t=await this.api.post(Te,{telegram_user_id:e});return await this.getAuthenticatedUser()??Ht(t)}catch(e){throw pe(e)}}async revokeDelegatedWallet(){try{await this.api.post(_e,{})}catch(e){throw pe(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:n}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(ce,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:n?.keepAlive??!1})}catch(e){console.log("Unable to submit event. This is not an issue.")}}async signMoonpayOnRampUrl(e){try{return this.api.post(Ee,e)}catch(e){throw pe(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(Ie,e)}catch(e){throw pe(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${Se}?partnerUserId=${e}`)}catch(e){throw pe(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(Vo.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Vo.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?yo.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 r=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return r.enabled?{enabled:r.enabled,smartWalletVersion:r.smart_wallet_version,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:Fo(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw pe(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(r){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(Ue,{address:e,token:t})).nonce}catch(e){throw pe(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a,mode:i}){return await this.api.post(Pe,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:a,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}){return await this.api.post(We,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:a})}async linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:n}){try{let a=await this.api.post(xe,{message:e,signature:t,smart_wallet_type:r,smart_wallet_version:n});return Ht(a)}catch(e){throw pe(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a});return Ht(i)}catch(e){throw pe(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(Ne,{address:e,token:t})).nonce}catch(e){throw pe(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:a,messageType:i="plain"}){return await this.api.post(Oe,{message:e,signature:t,walletClientType:r,connectorType:n,mode:a,message_type:i})}async authenticateWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,mode:a,messageType:i="plain"}){let o=await this.authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:a,messageType:i});this.session.handleTokenResponse(o);let s=Ht(o.user);if(!s)throw Error("Authentication failed - no user returned");return{user:s,isNewUser:o.is_new_user||!1}}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s}){try{let l,c;switch(r){case"email":l=ze,c={nonce:e,email:t};break;case"sms":l=qe,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=De,!n)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...n};break;case"farcaster":l=Le,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=Fe,c={nonce:e,telegram_auth_result:a,telegram_web_app_data:i};break;case"siws":l=Me,c={nonce:e,address:t,...n};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:l=Re,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??Ht(d)}catch(e){throw pe(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:a="plain"}){return await this.api.post(Be,{message:e,signature:t,walletClientType:r,connectorType:n,message_type:a})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,messageType:a="plain"}){try{let i=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:a});return Ht(i)}catch(e){throw pe(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(He);return this.session.updateIdentityToken(e.identity_token),Ht(e.user)}catch(e){throw pe(e)}}async scanTransaction(e){try{return await this.api.post(je,e)}catch(e){throw pe(e)}}constructor({apiUrl:e=_a,appId:t,appClientId:r,timeout:n=Ea}){Object.defineProperty(this,Yo,{value:Jo}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==_a&&e.startsWith("https://privy."),this.timeout=n,this.appId=t,this.appClientId=r,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,Yo)[Yo](),Ko||(Ko=new $o),this.session=Ko,this.api=this.generateApi(),this.session.client=this}}function Jo(){if("undefined"==typeof window)return null;try{let e=et.get(Ia);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=na();try{return et.put(Ia,e),e}catch(t){return e}}const Xo=({delayedExecution:e,...r})=>{let{enabled:n,siteKey:a,appId:i,setError:l,setToken:c,setExecuting:d,ref:u}=jt(),[,h]=o((()=>a?.split("t:")||[]),[a]);if(s((()=>u.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(Ha,{...r,ref:u,siteKey:h,options:{action:i,size:"invisible",...e?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{r.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:e=>{r.onError?.(e),l("Captcha failed"),d(!1)},onSuccess:e=>{r.onSuccess?.(e),c(e),d(!1)},onExpire:e=>{r.onExpire?.(e);try{u.current?.reset(),l(void 0),c(void 0)}catch(e){l("expired_and_failed_reset")}}})})};function Qo(e){Sa("configureMfa",e)}const es=/*#__PURE__*/ja.div.withConfig({displayName:"AppLogoContainer",componentId:"sc-ba98f772-0"})(["display:flex;flex-direction:column;align-items:center;padding:0px 0px 30px;@media (max-width:440px){padding:10px 10px 20px;}"]),ts=/*#__PURE__*/ja.div.withConfig({displayName:"Title",componentId:"sc-ba98f772-1"})(["font-size:18px;line-height:30px;text-align:center;font-weight:600;margin-bottom:10px;"]),rs=/*#__PURE__*/ja.div.withConfig({displayName:"SubTitle",componentId:"sc-ba98f772-2"})(["font-size:0.875rem;text-align:center;"]),ns=/*#__PURE__*/ja.div.withConfig({displayName:"Container",componentId:"sc-ba98f772-3"})(["display:flex;flex-direction:column;align-items:center;gap:10px;flex-grow:1;padding:20px 0;@media (max-width:440px){padding:10px 10px 20px;}"]),as=/*#__PURE__*/ja.div.withConfig({displayName:"List",componentId:"sc-ba98f772-4"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.75rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),is=/*#__PURE__*/ja.div.withConfig({displayName:"ListItemIcon",componentId:"sc-ba98f772-5"})(["width:25px;display:flex;align-items:center;justify-content:flex-start;> svg{z-index:2;height:25px !important;width:25px !important;color:var(--privy-color-accent);}"]),os=/*#__PURE__*/ja.div.withConfig({displayName:"ListItem",componentId:"sc-ba98f772-6"})(["display:flex;align-items:center;gap:10px;font-size:0.875rem;line-height:1rem;text-align:left;"]),ss=/*#__PURE__*/ja.div.withConfig({displayName:"BottomSection",componentId:"sc-ba98f772-7"})(["display:flex;flex-direction:column;gap:10px;padding-top:20px;"]),ls=/*#__PURE__*/ja.div.withConfig({displayName:"MethodList",componentId:"sc-ba98f772-8"})(["display:flex;flex-direction:column;align-items:stretch;gap:1rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),cs=/*#__PURE__*/ja.div.withConfig({displayName:"MethodListItem",componentId:"sc-ba98f772-9"})(["display:flex;gap:5px;width:100%;position:relative;"]),ds=/*#__PURE__*/ja.button.withConfig({displayName:"RemoveMethodButton",componentId:"sc-ba98f772-10"})(["&&{background-color:transparent;color:var(--privy-color-foreground-3);padding:0 0.75rem;display:flex;align-items:center;height:100%;> svg{z-index:2;height:20px !important;width:20px !important;}}&&:hover{color:var(--privy-color-error);}"]),us=/*#__PURE__*/ja.div.withConfig({displayName:"MethodText",componentId:"sc-ba98f772-11"})(["display:flex;align-items:center;gap:0.5rem;> svg{z-index:2;height:20px !important;width:20px !important;}"]),hs=/*#__PURE__*/ja.div.withConfig({displayName:"ExtraText",componentId:"sc-ba98f772-12"})(["display:flex;align-items:center;gap:6px;font-weight:400 !important;color:",";> svg{z-index:2;height:18px !important;width:18px !important;display:flex !important;align-items:flex-end;}"],(e=>e.$isAccent?"var(--privy-color-accent)":"var(--privy-color-foreground-3)")),ps=/*#__PURE__*/ja.div.withConfig({displayName:"SmsInsecureText",componentId:"sc-ba98f772-13"})(["width:100%;display:flex;justify-content:space-between;"]),ms=/*#__PURE__*/ja.p.withConfig({displayName:"TermsText",componentId:"sc-ba98f772-14"})(["text-align:left;width:100%;color:var(--privy-color-foreground-3) !important;"]),ws=/*#__PURE__*/ja.button.withConfig({displayName:"PrimaryTextButton",componentId:"sc-ba98f772-15"})(["display:flex;flex-direction:row;align-items:center;justify-content:center;user-select:none;&{width:100%;cursor:pointer;border-radius:var(--privy-border-radius-md);font-size:0.875rem;line-height:1rem;font-style:normal;font-weight:500;line-height:22px;letter-spacing:-0.016px;}&&{color:",";background-color:transparent;padding:0.5rem 0px;}&:hover{text-decoration:underline;}"],(e=>"dark"===e.theme?"var(--privy-color-foreground-2)":"var(--privy-color-accent)")),ys=/*#__PURE__*/ja.div.withConfig({displayName:"IconWrapper",componentId:"sc-ba98f772-16"})(["display:flex;align-items:center;justify-content:center;color:var(--privy-color-accent);width:100%;> svg{z-index:2;width:3rem;height:3rem;}"]),gs=/*#__PURE__*/ja.div.withConfig({displayName:"ErrorMessage",componentId:"sc-ba98f772-17"})(["color:var(--privy-color-error);"]),fs=({handleClose:e,user:n,onSelect:a})=>/*#__PURE__*/r(Vt,{title:"Verify your identity",subtitle:"Choose a verification method",icon:Qa,iconVariant:"subtle",onClose:e,showClose:!0,watermark:!0,children:[/*#__PURE__*/r(ls,{children:[n.mfaMethods.includes("totp")&&/*#__PURE__*/r($t,{onClick:()=>a("totp"),children:[/*#__PURE__*/t(Kt,{children:/*#__PURE__*/t(Za,{})}),"Authenticator app"]},"totp"),n.mfaMethods.includes("sms")&&/*#__PURE__*/r($t,{onClick:()=>a("sms"),children:[/*#__PURE__*/t(Kt,{children:/*#__PURE__*/t(Xa,{})}),"SMS"]},"sms"),n.mfaMethods.includes("passkey")&&/*#__PURE__*/r($t,{onClick:()=>a("passkey"),children:[/*#__PURE__*/t(Kt,{children:/*#__PURE__*/t(Ja,{})}),"Passkey"]},"passkey")]}),/*#__PURE__*/t(Gt,{})]}),vs=({pendingTransaction:e})=>{let{wallets:r}=Yt(),{walletProxy:n,rpcConfig:a,chains:i,appId:c,nativeTokenSymbolForChainId:d}=Ve(),[u,h]=l(null),[p,m]=l(e),{tokenPrice:w}=Zt(p.chainId),y=d(e.chainId)||"ETH",g=o((()=>r.find((e=>"privy"===e.walletClientType))),[r]);return s((()=>{(async function(){if(!n||!g)return p;let e=Tt(p.chainId,i,a,{appId:c}),t=await Jt(p,e,g.address);return h(ri(BigInt(t.gas??0))),t})().then(m).catch(console.error)}),[n]),g?/*#__PURE__*/t(Cs,{children:/*#__PURE__*/t(Xt,{from:g.address,to:p.to,txn:p,gas:u??void 0,tokenPrice:w,tokenSymbol:y})}):null};let Cs=/*#__PURE__*/ja.div.withConfig({displayName:"TransactionInfoWrapper",componentId:"sc-8d9a2f57-0"})(["width:100%;padding:1rem 0;"]);const ks=({style:e,...r})=>/*#__PURE__*/t("svg",{x:0,y:0,width:"65",height:"64",viewBox:"0 0 65 64",style:{height:"64px",width:"65px",...e},fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:/*#__PURE__*/t("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M3.71369 17.5625V10.375C3.71369 6.44625 6.85845 3.25 10.7238 3.25H17.7953C18.6783 3.25 19.3941 2.52244 19.3941 1.625C19.3941 0.727562 18.6783 0 17.7953 0H10.7238C5.09529 0 0.516113 4.65419 0.516113 10.375V17.5625C0.516113 18.4599 1.23194 19.1875 2.1149 19.1875C2.99787 19.1875 3.71369 18.4599 3.71369 17.5625ZM17.7953 60.7501C18.6783 60.7501 19.3941 61.4777 19.3941 62.3751C19.3941 63.2726 18.6783 64.0001 17.7953 64.0001H10.7238C5.09529 64.0001 0.516113 59.3459 0.516113 53.6251V46.4376C0.516113 45.5402 1.23194 44.8126 2.1149 44.8126C2.99787 44.8126 3.71369 45.5402 3.71369 46.4376V53.6251C3.71369 57.5538 6.85845 60.7501 10.7238 60.7501H17.7953ZM63.4839 46.4376V53.6251C63.4839 59.3459 58.9048 64.0001 53.2763 64.0001H46.2047C45.3217 64.0001 44.6059 63.2726 44.6059 62.3751C44.6059 61.4777 45.3217 60.7501 46.2047 60.7501H53.2763C57.1416 60.7501 60.2864 57.5538 60.2864 53.6251V46.4376C60.2864 45.5402 61.0022 44.8126 61.8851 44.8126C62.7681 44.8126 63.4839 45.5402 63.4839 46.4376ZM63.4839 10.375V17.5625C63.4839 18.4599 62.7681 19.1875 61.8851 19.1875C61.0022 19.1875 60.2864 18.4599 60.2864 17.5625V10.375C60.2864 6.44625 57.1416 3.25 53.2763 3.25H46.2047C45.3217 3.25 44.6059 2.52244 44.6059 1.625C44.6059 0.727562 45.3217 0 46.2047 0H53.2763C58.9048 0 63.4839 4.65419 63.4839 10.375ZM43.0331 47.3022C43.7067 46.6698 43.7483 45.6022 43.1262 44.9176C42.5039 44.233 41.4536 44.1906 40.78 44.823C38.3832 47.0732 35.265 48.3125 31.9997 48.3125C28.7344 48.3125 25.6162 47.0732 23.2194 44.823C22.5457 44.1906 21.4955 44.233 20.8732 44.9176C20.251 45.6022 20.2927 46.6698 20.9663 47.3022C23.9784 50.1301 27.8968 51.6875 31.9997 51.6875C36.1026 51.6875 40.021 50.1301 43.0331 47.3022ZM35.3207 24.1249V36.1249C35.3207 38.5029 33.4173 40.4374 31.0777 40.4374H29.7249C28.8079 40.4374 28.0646 39.6819 28.0646 38.7499C28.0646 37.8179 28.8079 37.0624 29.7249 37.0624H31.0777C31.5863 37.0624 32.0001 36.6419 32.0001 36.1249V24.1249C32.0001 23.1929 32.7434 22.4374 33.6604 22.4374C34.5774 22.4374 35.3207 23.1929 35.3207 24.1249ZM46.7581 28.8437V24.0312C46.7581 23.151 46.056 22.4374 45.19 22.4374C44.324 22.4374 43.622 23.151 43.622 24.0312V28.8437C43.622 29.7239 44.324 30.4374 45.19 30.4374C46.056 30.4374 46.7581 29.7239 46.7581 28.8437ZM17.6109 28.8437C17.6109 29.7239 18.313 30.4374 19.1789 30.4374C20.0449 30.4374 20.747 29.7239 20.747 28.8437V24.0312C20.747 23.151 20.0449 22.4374 19.1789 22.4374C18.313 22.4374 17.6109 23.151 17.6109 24.0312V28.8437Z"})}),As=({hasBlockingError:e,error:a,onClose:i,onBack:o,handleSubmit:s,account:l,submitSuccess:c})=>{let{pendingTransaction:d}=Ve();/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{onClose:i},"header"),/*#__PURE__*/t(er,{children:/*#__PURE__*/r("div",{children:[/*#__PURE__*/t(tr,{success:c,fail:!!a}),/*#__PURE__*/t(a?ti:ks,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/t(ts,{style:{marginTop:"1rem"},children:"Verifying with passkey"}),/*#__PURE__*/r(as,{children:[/*#__PURE__*/r(os,{children:[/*#__PURE__*/t(is,{children:/*#__PURE__*/t(Qa,{})}),"Approve this action using your touch, face, PIN, or hardware key."]}),/*#__PURE__*/r(os,{children:[/*#__PURE__*/t(is,{children:/*#__PURE__*/t(ei,{})}),"You last added a passkey on"," ",l?.firstVerifiedAt?.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),"."]})]}),d&&/*#__PURE__*/t(ns,{children:/*#__PURE__*/t(vs,{pendingTransaction:d})}),a&&/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(gs,{style:{marginTop:"1.25rem"},children:a.message}),/*#__PURE__*/t(rr,{disabled:e,onClick:s,style:{margin:"1.25rem auto 0"},children:"Try again"})]}),o&&/*#__PURE__*/t(ws,{style:{marginTop:"1rem"},onClick:o,children:"Choose another method"}),/*#__PURE__*/t(Gt,{})]})};let bs=Array(6).fill("");var Ts,_s=((Ts=_s||{})[Ts.RESET_AFTER_DELAY=0]="RESET_AFTER_DELAY",Ts[Ts.CLEAR_ON_NEXT_VALID_INPUT=1]="CLEAR_ON_NEXT_VALID_INPUT",Ts);function Es(e){return/^[0-9]{1}$/.test(e)}function Is(e){return 6===e.length&&e.every(Es)}const Ss=({onChange:e,disabled:a,errorReasonOverride:i,success:o})=>{let[s,c]=l(bs),[d,u]=l(null),[h,p]=l(null),m=async t=>{t.preventDefault();let r=t.currentTarget.value.replace(/\s+/g,"");if(""===r)return;let n=s.reduce(((e,t)=>e+Number(Es(t))),0),a=r.split(""),i=!a.every(Es),o=a.length+n>6;if(i)return u("Passcode can only be numbers"),void p(1);if(o)return u("Passcode must be exactly 6 numbers"),void p(1);u(null),p(null);let l=Number(t.currentTarget.name?.charAt(4)),d=[...r||[""]].slice(0,6-l),h=[...s.slice(0,l),...d,...s.slice(l+d.length)];c(h);let m=Math.min(Math.max(l+d.length,0),5),w=document.querySelector(`input[name=pin-${m}]`);if(w?.focus(),Is(h))try{await e(h.join(""));let t=document.querySelector(`input[name=pin-${m}]`);t?.blur()}catch(t){p(1),u(t.message)}else try{await e(null)}catch(t){p(1),u(t.message)}},w=o?"success":!(!i&&!d)?"fail":"";/*#__PURE__*/return t(n,{children:/*#__PURE__*/r(Us,{children:[/*#__PURE__*/t("div",{children:s.map(((r,n)=>/*#__PURE__*/t("input",{name:`pin-${n}`,type:"text",value:s[n],onChange:m,onKeyUp:t=>{"Backspace"===t.key&&(t=>{1===h&&(u(null),p(null));let r=[...s.slice(0,t),"",...s.slice(t+1)];if(c(r),t>0){let e=document.querySelector(`input[name=pin-${t-1}]`);e?.focus()}Is(r)?e(r.join("")):e(null)})(n)},inputMode:"numeric",autoFocus:0===n,pattern:"[0-9]",className:w,autoComplete:y?"one-time-code":"off",disabled:a},n)))}),/*#__PURE__*/t("div",{children:/*#__PURE__*/t(Ps,{$fail:!!i||!!d,children:i||d})})]})})};let Us=/*#__PURE__*/ja.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);}}"]),Ps=/*#__PURE__*/ja.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 Ws=({selectedMethod:e,submitSuccess:a,hasBlockingError:i,onClose:o,onBack:s,handleSubmitCode:l})=>{let c=Ua(),{pendingTransaction:d}=Ve();switch(e){case"sms":/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{onClose:o},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Xa,{})}),/*#__PURE__*/t(ts,{children:"Enter verification code"}),/*#__PURE__*/r(ns,{children:[/*#__PURE__*/t(Ss,{success:a,disabled:i,onChange:l}),/*#__PURE__*/r(rs,{children:["To continue, please enter the 6-digit code sent to your ",/*#__PURE__*/t("strong",{children:"mobile device"})]}),d&&/*#__PURE__*/t(vs,{pendingTransaction:d})]}),s&&/*#__PURE__*/t(ws,{theme:c?.appearance.palette.colorScheme,onClick:s,children:"Choose another method"}),/*#__PURE__*/t(nr,{onClick:o,children:"Cancel"}),/*#__PURE__*/t(Gt,{})]});case"totp":/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{onClose:o},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Za,{})}),/*#__PURE__*/t(ts,{children:"Enter verification code"}),/*#__PURE__*/r(ns,{children:[/*#__PURE__*/t(Ss,{success:a,disabled:i,onChange:l}),/*#__PURE__*/r(rs,{children:["To continue, please enter the 6-digit code generated from your"," ",/*#__PURE__*/t("strong",{children:"authenticator app"})]}),d&&/*#__PURE__*/t(vs,{pendingTransaction:d})]}),s&&/*#__PURE__*/t(ws,{theme:c?.appearance.palette.colorScheme,onClick:s,children:"Choose another method"}),/*#__PURE__*/t(nr,{onClick:o,children:"Cancel"}),/*#__PURE__*/t(Gt,{})]});default:return null}},xs=e=>ar(e)?{isBlocking:!0,error:Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.")}:ir(e)?{isBlocking:!1,error:Error("The code you entered is not valid")}:or(e)?{isBlocking:!0,error:Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.")}:(console.error(e),{isBlocking:!1,error:Error("Something went wrong.")}),Ns={component:()=>{let{user:e}=sr(),{data:r}=lr(),[n,a]=l(e?.mfaMethods[0]),[i,o]=l(!1),[c,d]=l(),[h,p]=l();if(s((()=>{a(e?.mfaMethods[0])}),[e?.mfaMethods]),!r?.mfaVerify)throw Error("Missing modal data for MFA verification screen.");let{onFailure:m,onSuccess:w,generateOptions:y,verifyTotpCode:g,verifyPasskey:f,verifySmsCode:v,sendSmsCode:C}=r.mfaVerify,k=async e=>{if("passkey"!==e)try{a(e),"sms"===e&&(a(e),await C()),"totp"===e&&a(e)}catch(e){console.error(e)}else try{a(e);let t=await y();if(!t)throw Error("something went wrong");d(t),await f(t),o(!0),p(void 0),w()}catch(e){p(xs(e))}},A=async e=>{p(void 0);try{if(!e||!n)return;if("passkey"===n){if(!c)throw Error("Missing passkey challenge");await f(c)}else"sms"===n?await v(e):"totp"===n&&await g(e);p(void 0),o(!0),w()}catch(e){throw xs(e).error}},b=()=>{h||!i?m(h?.error??Error("Canceled MFA verification.")):w()},T=u(!1);return s((()=>{!T.current&&n&&(T.current=!0,k(n).finally((()=>{T.current=!1})))}),[open]),e?"passkey"===n?/*#__PURE__*/t(As,{account:e.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],submitSuccess:i,hasBlockingError:h?.isBlocking??!1,error:h?.error,onClose:b,onBack:()=>{a(void 0),p(void 0)},handleSubmit:()=>A(c).catch(p)}):"sms"===n||"totp"===n?/*#__PURE__*/t(Ws,{selectedMethod:n,submitSuccess:i,hasBlockingError:h?.isBlocking??!1,handleSubmitCode:A,onClose:b,onBack:e.mfaMethods.length>1?()=>a(void 0):void 0}):/*#__PURE__*/t(fs,{user:e,onSelect:k,handleClose:b}):null}};function Os(){let{promptMfa:e,init:t,submit:r,cancel:n,mfaMethods:a}=h(cr);return{promptMfa:e,init:t,submit:r,cancel:n,mfaMethods:a}}const Rs=({onClose:e})=>{let{user:r}=sr(),[n,a]=l(r?.mfaMethods[0]??null),{init:i,cancel:o,submit:c}=Os(),[d,h]=l(!1),[p,m]=l(null),[w,y]=l();s((()=>{a(r?.mfaMethods[0]??null)}),[r?.mfaMethods]);let g=u(!1);async function f(t){y(void 0);try{if(!t||!n)return;await c(n,t),h(!0),y(void 0),e()}catch(t){throw xs(t).error}}async function v(t){if("passkey"!==t)try{a(t),await i(t)}catch(t){console.error(t)}else try{a(t);let r=await i(t);if(!r)throw Error("something went wrong");m(r),await c(t,r),h(!0),y(void 0),e()}catch(t){y(xs(t))}}s((()=>{!g.current&&n&&(g.current=!0,v(n).finally((()=>{g.current=!1})))}),[]);let C=()=>{a(null),y(void 0),o(),e()};return r?"passkey"===n?/*#__PURE__*/t(As,{account:r.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],submitSuccess:d,hasBlockingError:w?.isBlocking??!1,error:w?.error,onClose:C,onBack:()=>{a(null),y(void 0)},handleSubmit:()=>f(p).catch(y)}):n?/*#__PURE__*/t(Ws,{submitSuccess:d,hasBlockingError:w?.isBlocking??!1,handleSubmitCode:f,selectedMethod:n,onClose:C,onBack:r.mfaMethods.length>1?()=>a(null):void 0}):/*#__PURE__*/t(fs,{user:r,onSelect:v,handleClose:C}):null},Ms=Ba((()=>({inProgressMfaFlow:void 0})));const Fs=/*#__PURE__*/Va([":root{","};"],(e=>Ls(e.palette)));const Ls=e=>
|
|
2
|
-
/*#__PURE__*/$a(["",""],Object.entries(function(e){return{"--privy-color-background":e.background,"--privy-color-background-2":e.background2,"--privy-color-background-3":e.background3,"--privy-color-foreground":e.foreground,"--privy-color-foreground-2":e.foreground2,"--privy-color-foreground-3":e.foreground3,"--privy-color-foreground-4":e.foreground4,"--privy-color-foreground-accent":e.foregroundAccent,"--privy-color-accent":e.accent,"--privy-color-accent-light":e.accentLight,"--privy-color-accent-hover":e.accentHover,"--privy-color-accent-dark":e.accentDark,"--privy-color-accent-darkest":e.accentDarkest,"--privy-color-success":e.success,"--privy-color-success-dark":e.successDark,"--privy-color-success-light":e.successLight,"--privy-color-success-bg":e.successBg,"--privy-color-error":e.error,"--privy-color-error-light":e.errorLight,"--privy-color-error-bg":e.errorBg,"--privy-color-error-bg-hover":e.errorBgHover,"--privy-color-warn":e.warn,"--privy-color-warn-light":e.warnLight,"--privy-color-warn-bg":e.warnBg,"--privy-color-warning-dark":e.warningDark,"--privy-color-error-dark":e.errorDark,"--privy-color-info-bg":e.infoBg,"--privy-color-info-bg-hover":e.infoBgHover,"--privy-color-border-default":e.borderDefault,"--privy-color-border-hover":e.borderHover,"--privy-color-border-focus":e.borderFocus,"--privy-color-border-error":e.borderError,"--privy-color-border-success":e.borderSuccess,"--privy-color-border-warning":e.borderWarning,"--privy-color-border-info":e.borderInfo,"--privy-color-border-interactive":e.borderInteractive,"--privy-color-border-interactive-hover":e.borderInteractiveHover,"--privy-color-background-hover":e.backgroundHover,"--privy-color-background-clicked":e.backgroundClicked,"--privy-color-background-disabled":e.backgroundDisabled,"--privy-color-background-interactive":e.backgroundInteractive,"--privy-color-background-interactive-hover":e.backgroundInteractiveHover,"--privy-color-background-interactive-clicked":e.backgroundInteractiveClicked,"--privy-color-background-interactive-disabled":e.backgroundInteractiveDisabled,"--privy-color-foreground-hover":e.foregroundHover,"--privy-color-foreground-clicked":e.foregroundClicked,"--privy-color-foreground-disabled":e.foregroundDisabled,"--privy-color-foreground-interactive":e.foregroundInteractive,"--privy-color-foreground-interactive-hover":e.foregroundInteractiveHover,"--privy-link-navigation-color":e.linkNavigationColor,"--privy-link-navigation-decoration":e.linkNavigationDecoration,"--privy-accent-has-good-contrast":e.accentHasGoodContrast,"--privy-color-icon-default":e.iconDefault,"--privy-color-icon-muted":e.iconMuted,"--privy-color-icon-subtle":e.iconSubtle,"--privy-color-icon-inverse":e.iconInverse,"--privy-color-icon-success":e.iconSuccess,"--privy-color-icon-warning":e.iconWarning,"--privy-color-icon-error":e.iconError,"--privy-color-icon-interactive":e.iconInteractive,"--privy-color-icon-default-hover":e.iconDefaultHover,"--privy-color-icon-muted-hover":e.iconMutedHover,"--privy-color-icon-subtle-hover":e.iconSubtleHover,"--privy-color-icon-default-clicked":e.iconDefaultClicked,"--privy-color-icon-muted-clicked":e.iconMutedClicked,"--privy-color-icon-subtle-clicked":e.iconSubtleClicked,"--privy-color-icon-default-disabled":e.iconDefaultDisabled,"--privy-color-icon-muted-disabled":e.iconMutedDisabled,"--privy-color-icon-subtle-disabled":e.iconSubtleDisabled,"--privy-color-icon-error-hover":e.iconErrorHover,"--privy-color-icon-interactive-hover":e.iconInteractiveHover,"--privy-color-icon-error-clicked":e.iconErrorClicked,"--privy-color-icon-interactive-clicked":e.iconInteractiveClicked,"--privy-color-icon-muted-disabled-alt":e.iconMutedDisabledAlt,"--privy-color-icon-subtle-disabled-alt":e.iconSubtleDisabledAlt,"--privy-border-radius-xs":"6px","--privy-border-radius-sm":"8px","--privy-border-radius-md":"12px","--privy-border-radius-mdlg":"16px","--privy-border-radius-lg":"24px","--privy-border-radius-full":"9999px","--privy-height-modal-full":"620px","--privy-height-modal-compact":"480px"}}(e)).map((([e,t])=>`${e}: ${t};`)).join("\n")),Ds=/*#__PURE__*/ja.div.withConfig({displayName:"StylesWrapper",componentId:"sc-188229e4-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 3px var(--privy-color-border-focus);}.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"),qs=({children:e,open:n,onClick:a,...o})=>/*#__PURE__*/t(li,{show:n,as:i.Fragment,children:/*#__PURE__*/r(ci,{onClose:a,...o,as:Bs,children:[/*#__PURE__*/t(di,{as:i.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/t(zs,{id:"privy-dialog-backdrop","aria-hidden":"true"})}),/*#__PURE__*/t(Hs,{children:/*#__PURE__*/t(di,{as:i.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/t(ui,{as:js,children:e})})})]})});let zs=/*#__PURE__*/ja.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;}"]),Bs=/*#__PURE__*/ja.div.withConfig({displayName:"DialogWrapper",componentId:"sc-3cfde0b5-1"})(["position:relative;z-index:999999;"]),Hs=/*#__PURE__*/ja.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 js=/*#__PURE__*/ja.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__*/ja.div.withConfig({displayName:"CenterItem",componentId:"sc-3cfde0b5-4"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;"]);let $s=()=>{let{ready:e,isModalOpen:a}=sr(),{headless:i}=Ua(),{currentScreen:o}=lr(),{status:l,execute:c,reset:d,enabled:u}=jt(),h=Ms((e=>e.inProgressMfaFlow)),p=()=>Ms.setState({inProgressMfaFlow:void 0}),m=a&&o&&o.isCaptchaRequired&&!i&&"ready"===l;return s((()=>{m&&c()}),[m]),s((()=>{!a&&u&&d()}),[a,u]),o&&!e&&o.isShownBeforeReady?/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(Qt,{}),/*#__PURE__*/t(dr,{}),/*#__PURE__*/t(Vs,{children:/*#__PURE__*/t(ur,{})}),/*#__PURE__*/t(hr,{}),/*#__PURE__*/t(Gt,{})]}):o||"txn"!==h?o?
|
|
3
|
-
/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(
|
|
4
|
-
/*#__PURE__*/t("iframe",{ref:n,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>c(!0),src:hi({origin:e.origin,path:`/apps/${e.appId}/embedded-wallets`,query:{caid:e.clientAnalyticsId,client_id:e.appClientId}})}):null}const ll=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new R("Address to delegate is not associated with current user.");if(!pi(r))throw new R(`useDelegatedActions is not supported for ${r.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}},cl=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new R("Address to delegate is not associated with current user.");let n=r.imported?r:yr(t);if(!n)throw new R("Unable to determine root address for delegated address.");if(!pi(n))throw new R(`useDelegatedActions is not supported for ${n.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:n.address,chainType:n.chainType,imported:n.imported}},dl=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));const ul="popup-privy-oauth",hl="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class pl{async authenticate(){if(!this.api)throw new R("Auth flow has no API instance");try{return await this.api.post(V,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw F(e)}}async link(){if(!this.api)throw new R("Auth flow has no API instance");try{return await this.api.post(K,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw F(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}}}async function ml({api:e,requesterAppId:t,providerAppId:r}){let n=(await e.get(`/api/v1/apps/${t}/cross-app/connections`)).connections.find((e=>e.provider_app_id===r));if(!n)throw new R("Invalid connected app");return{name:n.provider_app_name,logoUrl:n.provider_app_icon_url||void 0,apiUrl:n.provider_app_custom_api_url,readOnly:n.read_only,customAuthAuthorizeUrl:n.provider_app_custom_auth_authorize_url,customAuthTransactUrl:n.provider_app_custom_auth_transact_url}}const wl=async({user:e,address:t,client:r,request:n,requesterAppId:a,reconnect:i})=>{r.createAnalyticsEvent({eventName:"cross_app_request_started",payload:{address:t,method:n.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 r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Cannot request a signature with this wallet address",address:t}}),new R("Cannot request a signature with this wallet address");let s=r.getProviderAccessToken(o.providerApp.id),l=await ml({api:r.api,requesterAppId:a,providerAppId:o.providerApp.id});if(!s){if(l.readOnly)throw console.error("cannot transact against a read-only provider app"),new R("Cannot transact against a read-only provider app");await i({appId:o.providerApp.id,action:"link"})&&(s=r.getProviderAccessToken(o.providerApp.id))}if(!s)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Transactions require a valid token",address:t}}),new R("Transactions require a valid token");let c=gr();if(!c)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new R("Failed to initialize signature request");let d=new URL(l.customAuthTransactUrl||`${l.apiUrl}/oauth/transact`);return d.searchParams.set("token",s||""),d.searchParams.set("request",yl(n)),c.location=d.href,new Promise(((e,a)=>{let i=setTimeout((()=>{d(),a(new R("Request timeout")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),s=setInterval((()=>{c.closed&&(d(),a(new R("User rejected request")),r.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?r.storeProviderAccessToken(o.providerApp.id,i.data.token.value):"clear"===i.data.token?.action&&r.storeProviderAccessToken(o.providerApp.id,null),"PRIVY_CROSS_APP_ACTION_RESPONSE"===i.data.type&&i.data.result&&(d(),e(i.data.result),r.createAnalyticsEvent({eventName:"cross_app_request_success",payload:{address:t,method:n.method}})),"PRIVY_CROSS_APP_ACTION_ERROR"===i.data.type&&i.data.error&&(d(),a(i.data.error),r.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 yl=e=>JSON.stringify({content:{request:{request:gl(e,ri)}},timestamp:Date.now(),callbackUrl:window.origin});const gl=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>gl(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,gl(r,t)]))):e,fl=({passkeys:e,isLoading:r,errorReason:n,success:a,expanded:i,onLinkPasskey:o,onUnlinkPasskey:s,onExpand:l,onBack:c,onClose:d})=>/*#__PURE__*/t(Vt,a?{title:"Passkeys updated",icon:vi,iconVariant:"success",primaryCta:{label:"Done",onClick:d},onClose:d,watermark:!0}:i?{icon:Ci,title:"Your passkeys",onBack:c,onClose:d,watermark:!0,children:/*#__PURE__*/t(Cl,{passkeys:e,expanded:i,onUnlink:s,onExpand:l})}:{icon:Ci,title:"Set up passkey verification",subtitle:"Verify with passkey",primaryCta:{label:"Add new passkey",onClick:o,loading:r},onClose:d,watermark:!0,helpText:n||void 0,children:0===e.length?/*#__PURE__*/t(kl,{}):/*#__PURE__*/t(vl,{children:/*#__PURE__*/t(Cl,{passkeys:e,expanded:i,onUnlink:s,onExpand:l})})});let vl=/*#__PURE__*/ja.div.withConfig({displayName:"ContentContainer",componentId:"sc-d4c46a0c-0"})(["margin-bottom:12px;"]),Cl=({passkeys:e,expanded:n,onUnlink:a,onExpand:i})=>{let[o,s]=l([]),c=n?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 r("div",{children:[/*#__PURE__*/t(Il,{children:"Your passkeys"}),/*#__PURE__*/r(El,{children:[e.slice(0,c).map((e=>/*#__PURE__*/r(Pl,{children:[/*#__PURE__*/r("div",{children:[/*#__PURE__*/t(Sl,{children:d(e)}),/*#__PURE__*/r(Ul,{children:["Last used:"," ",(e.latestVerifiedAt??e.firstVerifiedAt)?.toLocaleString()??"N/A"]})]}),/*#__PURE__*/t(xl,{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(fr,{}):/*#__PURE__*/t(ki,{size:16})})]},e.credentialId))),e.length>2&&!n&&/*#__PURE__*/t(_l,{onClick:i,children:"View all"})]})]})},kl=()=>/*#__PURE__*/r(vr,{style:{color:"var(--privy-color-foreground)"},children:[/*#__PURE__*/t(Cr,{children:"Verify with Touch ID, Face ID, PIN, or hardware key"}),/*#__PURE__*/t(Cr,{children:"Takes seconds to set up and use"}),/*#__PURE__*/t(Cr,{children:"Use your passkey to verify transactions and login to your account"})]});const Al={component:()=>{let{user:e,unlinkPasskey:r}=sr(),{linkWithPasskey:n,closePrivyModal:a}=Ve(),i=e?.linkedAccounts.filter((e=>"passkey"===e.type)),[o,c]=l(!1),[d,u]=l(""),[h,p]=l(!1),[m,w]=l(!1);return s((()=>{0===i.length&&w(!1)}),[i.length]),/*#__PURE__*/t(fl,{passkeys:i,isLoading:o,errorReason:d,success:h,expanded:m,onLinkPasskey:()=>{c(!0),n().then((()=>p(!0))).catch((e=>{if(e instanceof $e){if(e.privyErrorCode===$.CANNOT_LINK_MORE_OF_TYPE)return void u("Cannot link more passkeys to account.");if(e.privyErrorCode===$.PASSKEY_NOT_ALLOWED)return void u("Passkey request timed out or rejected by user.")}u("Unknown error occurred.")})).finally((()=>{c(!1)}))},onUnlinkPasskey:async e=>(c(!0),await r(e).then((()=>p(!0))).catch((e=>{e instanceof $e&&e.privyErrorCode===$.MISSING_MFA_CREDENTIALS?u("Cannot unlink a passkey enrolled in MFA"):u("Unknown error occurred.")})).finally((()=>{c(!1)}))),onExpand:()=>w(!0),onBack:()=>w(!1),onClose:()=>a()})}},bl=/*#__PURE__*/ja.div.withConfig({displayName:"DoubleIconWrapper",componentId:"sc-d4c46a0c-1"})(["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 Tl=/*#__PURE__*/$a(["&&{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 _l=/*#__PURE__*/ja.button.withConfig({displayName:"LinkButton",componentId:"sc-d4c46a0c-2"})(["",""],Tl);let El=/*#__PURE__*/ja.div.withConfig({displayName:"List",componentId:"sc-d4c46a0c-3"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.8rem;padding:0.5rem 0rem 0rem;flex-grow:1;width:100%;"]),Il=/*#__PURE__*/ja.div.withConfig({displayName:"PasskeyListTitle",componentId:"sc-d4c46a0c-4"})(["line-height:20px;height:20px;font-size:1em;font-weight:450;display:flex;justify-content:flex-beginning;width:100%;"]),Sl=/*#__PURE__*/ja.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-d4c46a0c-5"})(["font-size:1em;line-height:1.3em;font-weight:500;color:var(--privy-color-foreground-2);padding:0.2em 0;"]),Ul=/*#__PURE__*/ja.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-d4c46a0c-6"})(["font-size:0.875rem;line-height:1rem;color:#64668b;padding:0.2em 0;"]),Pl=/*#__PURE__*/ja.div.withConfig({displayName:"PasskeyListItem",componentId:"sc-d4c46a0c-7"})(["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;"]),Wl=/*#__PURE__*/$a([":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);}"]),xl=/*#__PURE__*/ja.button.withConfig({displayName:"PasskeyItemUnlinkButton",componentId:"sc-d4c46a0c-8"})(["",""],Wl);const Nl=new Map([[kr,null],[Ar,"external"],[br,"external"],[Tr,"external"],[_r,"external"],[Er,"manual"],[Ir,"moonpay"]]),Ol=()=>{let e=Ua(),{user:t}=sr(),{client:r,refreshSessionAndUser:n,walletProxy:a}=Ve();return{migrate:p((async()=>{if("legacy-embedded-wallets-only"===e.embeddedWallets.mode)return{success:!0};if(!t)throw new R("User must be authenticated before migrating wallets",$.MUST_BE_AUTHENTICATED);let i=yr(t);if(!i||Et(i)||!pi(i))return{success:!0};if(!a)throw new R("Cannot connect to wallet proxy");let o=await r.getAccessToken();if(!o)throw new R("User must be authenticated before migrating wallets",$.MUST_BE_AUTHENTICATED);let s=i.imported?[i]:t.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&!e.imported)).filter(pi),{entropyId:l,entropyIdVerifier:c}=Mt(t,i);try{await a.connect({accessToken:o,entropyId:l,entropyIdVerifier:c})}catch(e){if(!Sr(e)||"privy"!==i.recoveryMethod)throw e;await a.recover({accessToken:o,entropyId:l,entropyIdVerifier:c})}return await a.createDelegatedAction({accessToken:o,rootWallet:{address:i.address,chainType:i.chainType,imported:i.imported},delegatedWallets:s}),await n(),{success:!0}}),[e.embeddedWallets.mode,t,a,r,n])}},Rl=({disabled:e})=>{let{migrate:t}=Ol(),{user:r}=sr(),{walletProxy:n}=Ve();return s((()=>{!e&&r&&n&&t().catch((e=>{console.debug("Unable to migrate wallets: ",e)}))}),[r,n,e,t]),null},Ml=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}),Fl=({providerApp:e,success:r,error:n,onClose:a})=>{let{title:i,subtitle:s}=o((()=>r?{title:`Successfully connected with ${e.name}`,subtitle:"You're good to go!"}:n?{title:"Authentication failed",subtitle:n.message}:{title:`Connecting to ${e.name}`,subtitle:`Please check the pop-up from ${e.name} to continue`}),[r,n,e.name]);/*#__PURE__*/return t(Vt,{title:i,subtitle:s,icon:e.logoUrl,iconVariant:"loading",iconLoadingStatus:{success:r,fail:!!n},onBack:a,watermark:!0})},Ll={component:()=>{let e=Ua(),{data:r,navigate:n,setModalData:a,onUserCloseViaDialogOrKeybindRef:i}=lr(),{crossAppAuthFlow:o,updateWallets:c,closePrivyModal:d,createAnalyticsEvent:u}=Ve(),{logout:h}=Ga(),[p,m]=l({}),w=r?.crossAppAuth,y={id:w.appId,name:w.name,logoUrl:w.logoUrl},g=new R(`There was an issue connecting your ${y.name} account. Please try again.`),f=new Xe((async e=>{if(w.popup)try{let t=await o({appId:e,popup:w.popup,action:w.action});m({data:t})}catch(e){if(e instanceof R)m({error:e});else if(e instanceof me){if(e.privyErrorCode===$.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return a({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:`privy:${y.id}`,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void n(xr);w.popup&&w.popup.close(),m({error:g})}else m({error:g})}else m({error:g})})),v=()=>{p.data&&(c(),w.onSuccess(p.data),d({shouldCallAuthOnSuccess:!0,isSuccess:!0})),w.onError(p.error??new R("User canceled flow")),d({shouldCallAuthOnSuccess:!1,isSuccess:!1})};return i.current=v,s((()=>{y.id.length&&f.execute(y.id)}),[y.id]),s((()=>{if(!p.data)return;let t=p.data;if(e.legal.requireUsersAcceptTerms&&!t.hasAcceptedTerms){let e=setTimeout((()=>{n(Ur)}),Na);return()=>clearTimeout(e)}if(Pr(t,e.embeddedWallets)){let e=setTimeout((()=>{a({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),u({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:`privy:${y.id}`,screen:"CrossAppAuthScreen"}}),h()},callAuthOnSuccessOnClose:!0}}),n(Wr)}),Na);return()=>clearTimeout(e)}let r=setTimeout(v,Na);return()=>clearTimeout(r)}),[p.data]),/*#__PURE__*/t(Fl,{providerApp:y,success:!!p.data,error:p.error,onClose:v})}},Dl=({appName:e,address:r,success:n,error:a,onAccept:i,onDecline:o,onClose:s})=>/*#__PURE__*/t(Vt,n||a?{title:a?"Something went wrong":"Success!",subtitle:a?"Please try again.":`You've successfully granted delegated action permissions to ${e}.`,icon:a?Ai:vi,iconVariant:a?"error":"success",onBack:s,watermark:!0}:{title:"Enable offline access",subtitle:`By confirming, ${e} will be able to use your wallet for you even when you're not around. You can revoke this later.`,icon:bi,primaryCta:{label:"Accept",onClick:i},secondaryCta:{label:"Not now",onClick:o},onBack:s,watermark:!0,children:/*#__PURE__*/t(Nr,{address:r,title:"Wallet"})}),ql={component:()=>{let{data:e}=lr(),r=Ua(),{closePrivyModal:n}=Ve(),[a,i]=l(!1),[o,c]=l(),{address:d,onDelegate:u,onSuccess:h,onError:p}=e.delegatedActions.consent,m=async()=>{a?h():p(o??new R("User declined delegating actions.")),n({shouldCallAuthOnSuccess:!1})};return s((()=>{if(!a&&!o)return;let e=setTimeout(m,Oa);return()=>clearTimeout(e)}),[a,o]),/*#__PURE__*/t(Dl,{appName:r.name,address:d,success:a,error:o,onAccept:async()=>{try{await u(),i(!0)}catch(e){c(e)}},onDecline:()=>{m()},onClose:m})}},zl=({appName:e,success:r,error:n,onRevoke:a,onDeny:i,onClose:o})=>/*#__PURE__*/t(Vt,r||n?{title:n?"Something went wrong":"Success!",subtitle:n?"Please try again.":"You've successfully revoked permissions.",icon:n?Ai:vi,iconVariant:n?"error":"success",onBack:o,watermark:!0}:{title:"Revoke offline access to wallet",subtitle:`By confirming, ${e} will no longer be able to use this wallet on your behalf when you are not online.`,icon:Ti,primaryCta:{label:"Confirm",onClick:a},secondaryCta:{label:"Deny",onClick:i},onBack:o,watermark:!0}),Bl={component:()=>{let{data:e}=lr(),r=Ua(),{closePrivyModal:n}=Ve(),[a,i]=l(!1),[o,c]=l(),{onRevoke:d,onSuccess:u,onError:h}=e.delegatedActions.revoke,p=async()=>{a?u():h(o??new R("User declined revoking access to their delegated wallet.")),n({shouldCallAuthOnSuccess:!1})};return s((()=>{if(!a&&!o)return;let e=setTimeout(p,Oa);return()=>clearTimeout(e)}),[a,o]),/*#__PURE__*/t(zl,{appName:r.name,success:a,error:o,onRevoke:async()=>{try{await d(),i(!0)}catch(e){c(e)}},onDeny:()=>{p()},onClose:p})}};let Hl="#8a63d2";const jl=({appName:e,loading:n,success:a,errorMessage:i,connectUri:o,onBack:s,onClose:l,onOpenFarcaster:c})=>/*#__PURE__*/t(Vt,y||n?f?{title:i?i.message:"Add a signer to Farcaster",subtitle:i?i.detail:`This will allow ${e} to add casts, likes, follows, and more on your behalf.`,icon:Or,iconVariant:"loading",iconLoadingStatus:{success:a,fail:!!i},primaryCta:o&&c?{label:"Open Farcaster app",onClick:c}:void 0,onBack:s,onClose:l,watermark:!0}:{title:i?i.message:"Requesting signer from Farcaster",subtitle:i?i.detail:"This should only take a moment",icon:Or,iconVariant:"loading",iconLoadingStatus:{success:a,fail:!!i},onBack:s,onClose:l,watermark:!0,children:o&&y&&/*#__PURE__*/t(Vl,{children:/*#__PURE__*/t(Rr,{text:"Take me to Farcaster",url:o,color:Hl})})}:{title:"Add a signer to Farcaster",subtitle:`This will allow ${e} to add casts, likes, follows, and more on your behalf.`,onBack:s,onClose:l,watermark:!0,children:/*#__PURE__*/r($l,{children:[/*#__PURE__*/t(Kl,{children:o?/*#__PURE__*/t(Mr,{url:o,size:275,squareLogoElement:Or}):/*#__PURE__*/t(Zl,{children:/*#__PURE__*/t(ur,{})})}),/*#__PURE__*/r(Gl,{children:[/*#__PURE__*/t(Yl,{children:"Or copy this link and paste it into a phone browser to open the Farcaster app."}),o&&/*#__PURE__*/t(Si,{text:o,itemName:"link",color:Hl})]})]})});let Vl=/*#__PURE__*/ja.div.withConfig({displayName:"MobileLinkContainer",componentId:"sc-75c99bb6-0"})(["margin-top:24px;"]),$l=/*#__PURE__*/ja.div.withConfig({displayName:"ContentContainer",componentId:"sc-75c99bb6-1"})(["display:flex;flex-direction:column;align-items:center;gap:24px;"]),Kl=/*#__PURE__*/ja.div.withConfig({displayName:"QrContainer",componentId:"sc-75c99bb6-2"})(["padding:24px;position:relative;display:flex;align-items:center;justify-content:center;min-height:275px;"]),Gl=/*#__PURE__*/ja.div.withConfig({displayName:"InstructionsContainer",componentId:"sc-75c99bb6-3"})(["display:flex;flex-direction:column;align-items:center;gap:16px;"]),Yl=/*#__PURE__*/ja.div.withConfig({displayName:"InstructionText",componentId:"sc-75c99bb6-4"})(["font-size:0.875rem;text-align:center;color:var(--privy-color-foreground-2);"]),Zl=/*#__PURE__*/ja.div.withConfig({displayName:"LoaderWrapper",componentId:"sc-75c99bb6-5"})(["position:relative;width:82px;height:82px;"]);const Jl={component:()=>{let{lastScreen:e,navigateBack:r,data:n}=lr(),a=Ua(),{requestFarcasterSignerStatus:i,closePrivyModal:o}=Ve(),[c,d]=l(void 0),[h,p]=l(!1),[m,w]=l(!1),y=u([]),g=n?.farcasterSigner;s((()=>{let e=Date.now(),t=setInterval((async()=>{if(!g?.public_key)return clearInterval(t),void d({retryable:!0,message:"Connect failed",detail:"Something went wrong. Please try again."});"approved"===g.status&&(clearInterval(t),p(!1),w(!0),y.current.push(setTimeout((()=>o({shouldCallAuthOnSuccess:!1,isSuccess:!0})),Na)));let r=await i(g?.public_key),n=Date.now()-e;"approved"===r.status?(clearInterval(t),p(!1),w(!0),y.current.push(setTimeout((()=>o({shouldCallAuthOnSuccess:!1,isSuccess:!0})),Na))):n>3e5?(clearInterval(t),d({retryable:!0,message:"Connect failed",detail:"The request timed out. Try again."})):"revoked"===r.status&&(clearInterval(t),d({retryable:!0,message:"Request rejected",detail:"The request was rejected. Please try again."}))}),2e3);return()=>{clearInterval(t),y.current.forEach((e=>clearTimeout(e)))}}),[]);let f="pending_approval"===g?.status?g.signer_approval_url:void 0;/*#__PURE__*/return t(jl,{appName:a.name,loading:h,success:m,errorMessage:c,connectUri:f,onBack:e?r:void 0,onClose:o,onOpenFarcaster:()=>{f&&(window.location.href=f)}})}},Xl=({onClose:e})=>/*#__PURE__*/t(Vt,{title:"Could not log in with provider",subtitle:"It looks like you're using an in-app browser. To log in, please try again using an external browser.",icon:_i,primaryCta:{label:"Close",onClick:e},watermark:!0}),Ql={component:()=>{let{closePrivyModal:e}=Ve();/*#__PURE__*/return t(Xl,{onClose:()=>e()})}},ec=({title:e="Connect your email",subtitle:r="Add your email to your account"})=>/*#__PURE__*/t(Vt,{title:e,subtitle:r,icon:Pi,watermark:!0,children:/*#__PURE__*/t(Fr,{children:/*#__PURE__*/t(Lr,{stacked:!0})})}),tc={component:()=>{let e=Ua();/*#__PURE__*/return t(ec,{subtitle:`Add your email to your ${e?.name} account`})}},rc=({title:e="Connect your phone",subtitle:r="Add your number to your account",onSubmit:n,isSubmitting:a=!1})=>{let[i,o]=l(null),s=async()=>{i?.qualifiedPhoneNumber&&await n(i)};/*#__PURE__*/return t(Vt,{title:e,subtitle:r,icon:Xa,primaryCta:{label:a?"Submitting":"Submit",onClick:s,disabled:!i?.isValid||a},watermark:!0,children:/*#__PURE__*/t(Dr,{onChange:e=>{o(e)},onSubmit:s,noIncludeSubmitButton:!0,hideRecent:!0})})},nc={component:()=>{let{currentScreen:e,data:r,navigate:n,setModalData:a}=lr(),i=Ua(),{initLoginWithSms:o}=Ve(),[s,c]=l(!1);/*#__PURE__*/return t(rc,{subtitle:`Add your number to your ${i?.name} account`,onSubmit:async t=>{c(!0);try{await o({phoneNumber:t.qualifiedPhoneNumber,withPrivyUi:!0}),n(qr)}catch(t){a({errorModalData:{error:t,previousScreen:r?.errorModalData?.previousScreen||e||nc}}),n(zr)}finally{c(!1)}},isSubmitting:s})}},ac=({title:e="Could not connect with wallet",subtitle:r="Please check that Phantom multichain is enabled and try again.",primaryCtaText:n="Try again",secondaryCtaText:a="Cancel",onTryAgain:i,onCancel:o})=>/*#__PURE__*/t(Vt,{title:e,subtitle:r,icon:Ei,iconVariant:"error",primaryCta:{label:n,onClick:i},secondaryCta:{label:a,onClick:o},watermark:!0}),ic={component:()=>{let{closePrivyModal:e}=Ve(),{navigate:r}=lr();/*#__PURE__*/return t(ac,{onTryAgain:()=>{r(Br)},onCancel:async()=>{await e()}})}};function oc(){let{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:r,submitEnrollmentWithSms:n,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:i,unenroll:o,enrollInMfa:s}=h(cr);return{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:r,submitEnrollmentWithSms:n,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:i,unenrollWithSms:()=>o("sms"),unenrollWithTotp:()=>o("totp"),unenrollWithPasskey:e=>o("passkey",e),showMfaEnrollmentModal:()=>s(!0),closeMfaEnrollmentModal:()=>s(!1)}}const sc=e=>/*#__PURE__*/r(lc,{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 lc=/*#__PURE__*/ja.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 cc=({showIntro:e,userMfaMethods:a,appMfaMethods:i,userHasAuthSms:o,isTotpLoading:s,isPasskeyLoading:l,error:c,onClose:d,backFn:u,handleSelectMethod:h,setRemovingMfaMethod:p})=>{let m=a.reduce(((e,t)=>({...e,[t]:!0})),{}),w=i.reduce(((e,t)=>({...e,[t]:!0})),{});/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{backFn:e?u:void 0,onClose:d},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Qa,{})}),/*#__PURE__*/t(ts,{children:"Choose a verification method"}),a.length>0?/*#__PURE__*/t(rs,{children:"To add or delete verification methods, verification is required."}):/*#__PURE__*/t(rs,{children:"How would you like to verify your identity?"}),c&&/*#__PURE__*/t(gs,{style:{marginTop:"1.25rem"},children:c.message}),/*#__PURE__*/r(ls,{children:[(w.passkey||m.passkey)&&/*#__PURE__*/r(cs,{children:[/*#__PURE__*/t($t,{style:{justifyContent:"center"},onClick:()=>h("passkey"),disabled:m.passkey||l,children:l?/*#__PURE__*/t(ur,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/r(ps,{children:[/*#__PURE__*/r(us,{children:[/*#__PURE__*/t(Ja,{}),"Passkey"]}),m.passkey?/*#__PURE__*/t(dc,{color:"green",children:"Enabled"}):/*#__PURE__*/t(hs,{$isAccent:!0,children:/*#__PURE__*/t(Oi,{})})]})}),m.passkey&&/*#__PURE__*/t(ds,{style:{position:"absolute",right:0},onClick:()=>p("passkey"),children:/*#__PURE__*/t(Ri,{})})]},"passkey"),(w.totp||m.totp)&&/*#__PURE__*/r(cs,{children:[/*#__PURE__*/t($t,{style:{justifyContent:"center"},disabled:m.totp||s,onClick:()=>h("totp"),children:s?/*#__PURE__*/t(ur,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/r(ps,{children:[/*#__PURE__*/r(us,{children:[/*#__PURE__*/t(Za,{}),"Authenticator app"]}),m.totp&&/*#__PURE__*/t(dc,{color:"green",children:"Enabled"})]})}),m.totp&&/*#__PURE__*/t(ds,{style:{position:"absolute",right:0},onClick:()=>p("totp"),children:/*#__PURE__*/t(Ri,{})})]},"totp"),(w.sms||m.sms)&&/*#__PURE__*/r(cs,{children:[/*#__PURE__*/t($t,{disabled:m.sms||o,onClick:()=>h("sms"),children:/*#__PURE__*/r(ps,{children:[/*#__PURE__*/r(us,{children:[/*#__PURE__*/t(Xa,{}),"SMS"]}),m.sms&&/*#__PURE__*/t(dc,{color:"green",children:"Enabled"}),o&&/*#__PURE__*/t(hs,{children:"Disabled"})]})}),m.sms&&/*#__PURE__*/t(ds,{style:{position:"absolute",right:0},onClick:()=>p("sms"),children:/*#__PURE__*/t(Ri,{})})]},"sms")]}),/*#__PURE__*/t(uc,{children:"You can always change your selection later"}),/*#__PURE__*/t(Gt,{})]})};let dc=/*#__PURE__*/ja(Hr).withConfig({displayName:"StyledChip",componentId:"sc-5f06df7f-0"})(["margin-right:1.5rem;"]),uc=/*#__PURE__*/ja(ms).withConfig({displayName:"StyledTerms",componentId:"sc-5f06df7f-1"})(["&&{margin-top:1rem;}text-align:center;"]);const hc=({style:e,...n})=>/*#__PURE__*/r("svg",{x:0,y:0,width:"65",height:"64",viewBox:"0 0 65 64",style:{height:"64px",width:"65px",...e},xmlns:"http://www.w3.org/2000/svg",...n,children:[/*#__PURE__*/r("g",{clipPath:"url(#clip0_113_33841)",children:[/*#__PURE__*/t("path",{d:"M39.1193 0.943398C34.636 -0.174912 29.9185 -0.334713 25.328 0.656273C24.9732 0.732859 24.7477 1.08253 24.8243 1.43729C24.9009 1.79205 25.2506 2.01756 25.6053 1.94097C30.0015 0.991934 34.53 1.14842 38.8375 2.22802C49.1385 4.80983 57.7129 12.5548 60.9786 22.6718C62.2416 26.5843 62.7781 30.7505 62.8855 35.1167C62.8945 35.4795 63.1958 35.7664 63.5586 35.7575C63.9215 35.7485 64.2083 35.4472 64.1994 35.0843C64.0905 30.6582 63.5477 26.3849 62.2536 22.3432C58.8621 11.7515 49.9005 3.63265 39.1193 0.943398Z"}),/*#__PURE__*/t("path",{d:"M21.9931 2.93163C22.343 2.83511 22.5484 2.47325 22.4518 2.12339C22.3553 1.77352 21.9935 1.56815 21.6436 1.66466C16.8429 2.98903 10.0898 7.56519 5.91628 13.6786C5.91465 13.681 5.91304 13.6834 5.91145 13.6858C2.24684 19.2083 -0.0503572 26.1484 0.591012 32.8828C0.591623 32.8892 0.592328 32.8956 0.593127 32.902C0.746837 34.1317 1.00488 35.3591 1.26323 36.5879C1.80735 39.1761 2.35282 41.7706 1.92765 44.4064C1.86986 44.7647 2.11347 45.102 2.47177 45.1598C2.83007 45.2176 3.16738 44.974 3.22518 44.6157C3.66961 41.8605 3.11776 39.173 2.56581 36.4851C2.31054 35.2419 2.05525 33.9987 1.89847 32.7486C1.29525 26.3851 3.46802 19.7466 7.00418 14.416C11.0189 8.5373 17.5201 4.16562 21.9931 2.93163Z"}),/*#__PURE__*/t("path",{d:"M30.6166 4.39985C38.8671 3.89603 47.1159 7.26314 52.6556 13.7139C52.8921 13.9893 52.8605 14.4042 52.5852 14.6406C52.3099 14.8771 51.895 14.8455 51.6585 14.5702C46.3904 8.43576 38.541 5.23144 30.6927 5.71195C30.6899 5.71212 30.6871 5.71227 30.6843 5.71241C20.7592 6.19265 11.4643 12.9257 8.04547 22.3603C7.92183 22.7016 7.54498 22.8779 7.20375 22.7543C6.86253 22.6306 6.68616 22.2538 6.80981 21.9126C10.4114 11.9735 20.1717 4.90702 30.6166 4.39985Z"}),/*#__PURE__*/t("path",{d:"M54.6576 16.5848C54.4553 16.2836 54.047 16.2033 53.7457 16.4057C53.4444 16.608 53.3642 17.0163 53.5665 17.3176C56.6376 21.8904 57.9074 26.8665 58.4094 32.7717C58.4401 33.1333 58.7582 33.4016 59.1199 33.3708C59.4815 33.3401 59.7497 33.022 59.719 32.6604C59.206 26.6261 57.8965 21.4076 54.6576 16.5848Z"}),/*#__PURE__*/t("path",{d:"M59.2796 35.4504C59.6419 35.4277 59.9539 35.703 59.9765 36.0653C60.2242 40.0279 60.2265 44.5112 59.7881 47.8243C59.7405 48.1841 59.4102 48.4372 59.0504 48.3896C58.6906 48.342 58.4376 48.0117 58.4852 47.6519C58.9077 44.4586 58.91 40.0704 58.6648 36.1473C58.6421 35.785 58.9174 35.473 59.2796 35.4504Z"}),/*#__PURE__*/t("path",{d:"M7.05311 25.5432C7.13829 25.1904 6.92135 24.8354 6.56855 24.7502C6.21576 24.665 5.86071 24.882 5.77553 25.2348C5.2932 27.2325 5.0428 29.2847 5.03288 31.3388C5.02266 33.4559 5.41742 35.5225 5.81234 37.5899C6.1354 39.2811 6.45855 40.9728 6.5602 42.6932C6.69373 44.9531 6.21839 47.2163 5.39698 49.3703C5.26766 49.7094 5.43774 50.0891 5.77685 50.2184C6.11596 50.3477 6.4957 50.1777 6.62502 49.8386C7.49325 47.5617 8.01954 45.1092 7.87221 42.6157C7.77126 40.9071 7.44813 39.2252 7.12512 37.5439C6.73099 35.4925 6.33704 33.442 6.34716 31.3451C6.35659 29.3933 6.59455 27.4425 7.05311 25.5432Z"}),/*#__PURE__*/t("path",{d:"M24.2964 10.94C24.4317 11.2768 24.2683 11.6595 23.9315 11.7947C17.1187 14.5307 12.0027 20.7047 10.959 27.9852C10.523 31.0269 10.9941 34.0398 11.465 37.052C11.7303 38.7483 11.9954 40.4443 12.0985 42.1451C12.3221 45.833 11.902 49.8839 9.50192 53.5696C9.30387 53.8737 8.89677 53.9597 8.59264 53.7617C8.28851 53.5636 8.20251 53.1565 8.40056 52.8524C10.5873 49.4944 11.0012 45.7644 10.7867 42.2246C10.6821 40.499 10.4185 38.7833 10.1552 37.0686C9.68265 33.9923 9.21067 30.9195 9.65804 27.7987C10.7724 20.025 16.221 13.4748 23.4417 10.5751C23.7785 10.4399 24.1612 10.6032 24.2964 10.94Z"}),/*#__PURE__*/t("path",{d:"M47.3662 14.6814C41.9915 9.64741 34.2017 7.89046 27.122 9.4433C26.7675 9.52105 26.5432 9.87147 26.6209 10.226C26.6987 10.5805 27.0491 10.8048 27.4036 10.7271C34.1075 9.25665 41.4426 10.934 46.4677 15.6406C50.7033 19.6077 53.1628 25.38 53.8066 31.6779C53.8435 32.0389 54.1661 32.3017 54.5272 32.2648C54.8883 32.2279 55.151 31.9053 55.1141 31.5442C54.4456 25.0047 51.8822 18.9111 47.3662 14.6814Z"}),/*#__PURE__*/t("path",{d:"M54.9766 34.6738C55.3376 34.6368 55.6604 34.8994 55.6975 35.2604C56.3216 41.337 56.0526 47.9003 55.1104 54.2496C55.0571 54.6086 54.7229 54.8565 54.3639 54.8032C54.0049 54.7499 53.7571 54.4157 53.8103 54.0567C54.7394 47.7957 55.001 41.3439 54.39 35.3947C54.353 35.0336 54.6156 34.7109 54.9766 34.6738Z"}),/*#__PURE__*/t("path",{d:"M32.0659 13.3553C21.9959 13.3553 13.814 21.3892 13.814 31.3219C13.814 32.3829 13.9081 33.4225 14.0876 34.4334C14.1511 34.7907 14.4922 35.029 14.8495 34.9655C15.2069 34.9021 15.4451 34.561 15.3817 34.2036C15.2155 33.2677 15.1283 32.305 15.1283 31.3219C15.1283 22.1352 22.7014 14.6696 32.0659 14.6696C36.2978 14.6696 40.1642 16.1949 43.1319 18.7152C43.4086 18.9501 43.8233 18.9163 44.0582 18.6396C44.2931 18.363 44.2593 17.9483 43.9827 17.7134C40.7847 14.9975 36.6188 13.3553 32.0659 13.3553Z"}),/*#__PURE__*/t("path",{d:"M45.455 20.1635C45.717 19.9123 46.133 19.921 46.3842 20.183C49.2843 23.2072 50.2126 27.9605 50.8269 31.9494C51.5188 36.4426 51.6244 40.826 51.6244 42.8585C51.6244 43.2214 51.3302 43.5156 50.9673 43.5156C50.6044 43.5156 50.3101 43.2214 50.3101 42.8585C50.3101 40.8589 50.2055 36.5497 49.5279 32.1494C48.9577 28.4462 48.1356 23.9082 45.4356 21.0927C45.1844 20.8307 45.1931 20.4147 45.455 20.1635Z"}),/*#__PURE__*/t("path",{d:"M51.4576 46.6219C51.4864 46.2601 51.2165 45.9435 50.8547 45.9146C50.493 45.8858 50.1763 46.1557 50.1474 46.5175C49.8247 50.5654 49.403 54.6088 48.5474 58.3439C48.4663 58.6977 48.6874 59.0502 49.0412 59.1312C49.3949 59.2123 49.7474 58.9912 49.8285 58.6374C50.7067 54.8039 51.134 50.6806 51.4576 46.6219Z"}),/*#__PURE__*/t("path",{d:"M15.1454 36.852C15.5015 36.7819 15.847 37.0137 15.9171 37.3698C17.3066 44.4257 16.3467 50.8355 12.6672 56.4502C12.4682 56.7537 12.0609 56.8385 11.7573 56.6396C11.4538 56.4407 11.369 56.0333 11.5679 55.7298C15.0299 50.4469 15.9617 44.3985 14.6276 37.6238C14.5575 37.2677 14.7893 36.9221 15.1454 36.852Z"}),/*#__PURE__*/t("path",{d:"M32.0659 17.631C25.5291 17.631 19.1165 22.691 18.462 29.0504C18.1754 31.8345 18.578 34.5769 18.9807 37.3204C19.3323 39.7159 19.684 42.1124 19.5772 44.5381C19.3328 50.0898 17.7039 54.6726 14.905 58.4471C14.6888 58.7386 14.7499 59.1502 15.0414 59.3663C15.333 59.5825 15.7445 59.5214 15.9607 59.2299C18.9293 55.2266 20.6354 50.386 20.8903 44.5959C20.9966 42.1811 20.6438 39.7923 20.2912 37.4051C19.888 34.6752 19.4851 31.9473 19.7694 29.1849C20.3444 23.5983 26.0946 18.9453 32.0659 18.9453C34.851 18.9453 42.057 20.4534 44.3492 27.9205C45.7856 32.5998 46.1774 38.9326 45.8295 45.0849C45.4816 51.2364 44.3994 57.12 42.9442 60.8928C42.8136 61.2314 42.9822 61.6118 43.3208 61.7424C43.6594 61.873 44.0398 61.7044 44.1704 61.3658C45.6929 57.4186 46.7895 51.386 47.1417 45.1591C47.4938 38.9329 47.1068 32.4249 45.6056 27.5348C43.0612 19.2461 35.0851 17.631 32.0659 17.631Z"}),/*#__PURE__*/t("path",{d:"M21.9529 56.4512C22.2569 56.6494 22.3426 57.0566 22.1444 57.3606C21.7369 57.9854 21.3784 58.6391 21.0199 59.2928C20.6614 59.9465 20.3028 60.6004 19.8953 61.2253C19.697 61.5293 19.2898 61.615 18.9858 61.4167C18.6819 61.2184 18.5962 60.8113 18.7944 60.5073C19.2019 59.8825 19.5604 59.2288 19.9189 58.5751C20.2774 57.9213 20.636 57.2675 21.0435 56.6426C21.2418 56.3386 21.649 56.2529 21.9529 56.4512Z"}),/*#__PURE__*/t("path",{d:"M27.5799 24.4525C27.8816 24.2508 27.9625 23.8426 27.7608 23.541C27.559 23.2393 27.1509 23.1583 26.8492 23.3601C24.247 25.1006 22.6505 27.494 22.6505 31.0002C22.6505 33.088 23.0203 34.7946 23.3997 36.5449C23.9674 39.1641 24.3524 41.7777 24.2832 44.468C24.1992 47.7349 23.56 50.7201 22.3313 53.564C22.1873 53.8971 22.3407 54.2839 22.6739 54.4278C23.0071 54.5718 23.3938 54.4184 23.5378 54.0852C24.8369 51.0784 25.509 47.9266 25.5971 44.5018C25.6689 41.7062 25.2732 38.9892 24.6845 36.267C24.3042 34.509 23.9648 32.9394 23.9648 31.0002C23.9648 27.9961 25.2863 25.9866 27.5799 24.4525Z"}),/*#__PURE__*/t("path",{d:"M30.1447 22.1436C32.8717 21.5877 35.8061 22.2746 37.966 24.0228C41.8241 27.1455 42.3372 32.8403 42.753 37.4549L42.7742 37.69C43.3115 43.6385 42.6964 49.4163 41.4575 55.2186C41.3817 55.5736 41.0326 55.7999 40.6776 55.7241C40.3227 55.6483 40.0964 55.2991 40.1722 54.9442C41.3926 49.2288 41.9873 43.5885 41.4652 37.8082C41.4479 37.6169 41.4307 37.4228 41.4133 37.2264L41.4131 37.2235C41.0438 33.0534 40.5812 27.8304 37.1392 25.0444C35.2926 23.5498 32.7599 22.9518 30.4073 23.4314C30.0517 23.5039 29.7046 23.2744 29.6321 22.9188C29.5596 22.5632 29.7891 22.2161 30.1447 22.1436Z"}),/*#__PURE__*/t("path",{d:"M40.5287 58.4885C40.6183 58.1368 40.4057 57.7791 40.054 57.6896C39.7023 57.6 39.3446 57.8126 39.2551 58.1643C38.8578 59.7247 38.2456 61.1333 37.4695 62.4301C37.2831 62.7415 37.3844 63.145 37.6958 63.3314C38.0072 63.5178 38.4108 63.4165 38.5972 63.1051C39.4336 61.7075 40.0977 60.1816 40.5287 58.4885Z"}),/*#__PURE__*/t("path",{d:"M37.3152 48.9521C37.6756 48.9948 37.9332 49.3215 37.8906 49.682C37.2699 54.9267 35.8688 59.6042 33.6205 63.6613C33.4446 63.9787 33.0446 64.0934 32.7272 63.9175C32.4097 63.7416 32.295 63.3417 32.4709 63.0242C34.6226 59.1416 35.9811 54.6339 36.5854 49.5275C36.6281 49.1671 36.9548 48.9095 37.3152 48.9521Z"}),/*#__PURE__*/t("path",{d:"M37.1798 30.6556C36.7242 28.2212 34.6349 26.3591 32.0985 26.3591C28.6638 26.3591 26.254 29.8212 27.1032 33.0422C28.54 38.7279 28.7759 44.2077 27.8032 49.4855L27.8025 49.4893C26.9584 54.228 25.3374 58.4908 23.1263 62.1031C22.9368 62.4127 23.0342 62.8172 23.3437 63.0067C23.6533 63.1962 24.0578 63.0988 24.2473 62.7893C26.5488 59.0292 28.2249 54.6109 29.0961 49.7218C30.106 44.2403 29.8558 38.5684 28.3765 32.7168L28.3748 32.7099C27.7378 30.3005 29.5133 27.6734 32.0985 27.6734C33.9641 27.6734 35.5393 29.0459 35.8871 30.8929C36.8436 36.4411 37.3418 41.5862 36.9871 46.016C36.9581 46.3778 37.2279 46.6945 37.5897 46.7235C37.9515 46.7525 38.2682 46.4827 38.2972 46.1209C38.6649 41.5294 38.1459 36.2576 37.1815 30.6648C37.1809 30.6617 37.1804 30.6586 37.1798 30.6556Z"}),/*#__PURE__*/t("path",{d:"M30.1376 59.1171C30.4604 59.283 30.5876 59.6792 30.4217 60.002L28.6804 63.3906C28.5145 63.7134 28.1184 63.8406 27.7956 63.6747C27.4728 63.5088 27.3456 63.1127 27.5114 62.7899L29.2527 59.4013C29.4186 59.0785 29.8147 58.9513 30.1376 59.1171Z"}),/*#__PURE__*/t("path",{d:"M32.5872 31.2892C32.5042 30.9359 32.1505 30.7168 31.7972 30.7998C31.4439 30.8828 31.2247 31.2365 31.3077 31.5898C33.5238 41.0232 33.2194 49.3066 30.5201 56.363C30.3905 56.702 30.5602 57.0819 30.8991 57.2115C31.2381 57.3412 31.618 57.1715 31.7477 56.8326C34.5622 49.475 34.8483 40.9141 32.5872 31.2892Z"})]}),/*#__PURE__*/t("defs",{children:/*#__PURE__*/t("clipPath",{id:"clip0_113_33841",children:/*#__PURE__*/t("rect",{width:"64",height:"64",fill:"white",transform:"translate(0.483887)"})})})]}),pc=({onClose:e,onReset:r,submitEnrollmentWithPasskey:n})=>{let{user:a}=sr(),{initLinkWithPasskey:i,linkWithPasskey:s}=Ve(),c=Ua(),[d,u]=l(!1),[h,p]=l(!1),[m,w]=l(null),y=o((()=>a?.linkedAccounts.filter((e=>"passkey"===e.type))??[]),[a]),g=async e=>{u(!0);try{await n(e)}catch(e){w(e)}finally{u(!1)}},f=async()=>{p(!0),w(null);try{await i();let e=await s(),t=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];await g(t)}catch(e){w(e)}finally{p(!1)}};return 0===y.length||h?/*#__PURE__*/t(mc,{onReset:r,onClose:e,onClick:f,isCreating:h}):m?/*#__PURE__*/t(jr,{allowlistConfig:c.allowlistConfig,error:m,onBack:()=>w(null),onRetry:()=>w(null)}):/*#__PURE__*/t(wc,{passkeys:y,isSubmitting:d,isCreating:h,onReset:r,onClose:e,onSubmitEnrollment:()=>g(y.map((e=>e.credentialId))),onAddPasskey:f})};let mc=({onReset:e,onClose:a,onClick:i,isCreating:o})=>/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(Qt,{backFn:e,onClose:a},"header"),/*#__PURE__*/t(es,{children:/*#__PURE__*/r(bl,{children:[/*#__PURE__*/t(ks,{}),/*#__PURE__*/t(hc,{})]})}),/*#__PURE__*/t(ts,{children:"Set up passkey verification"}),/*#__PURE__*/r(as,{children:[/*#__PURE__*/r(os,{children:[/*#__PURE__*/t(is,{children:/*#__PURE__*/t(Qa,{})}),"Verify with Touch ID, Face ID, PIN, or hardware key"]}),/*#__PURE__*/r(os,{children:[/*#__PURE__*/t(is,{children:/*#__PURE__*/t(Fi,{})}),"Takes seconds to set up and use"]}),/*#__PURE__*/r(os,{children:[/*#__PURE__*/t(is,{children:/*#__PURE__*/t(Mi,{})}),"Use your passkey to verify transactions and login to your account"]})]}),/*#__PURE__*/t(rr,{style:{marginTop:"2.25rem"},onClick:i,loading:o,children:"Add a new passkey"}),/*#__PURE__*/t(Gt,{})]}),wc=({onReset:e,onClose:a,onAddPasskey:i,onSubmitEnrollment:o,passkeys:s,isSubmitting:c,isCreating:d})=>{let[u,h]=l(!1),p=u?s.length:s.length>3?2:3;/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{backFn:u?()=>h(!1):e,onClose:a},"header"),!u&&/*#__PURE__*/t(es,{children:/*#__PURE__*/r(bl,{children:[/*#__PURE__*/t(ks,{}),/*#__PURE__*/t(hc,{})]})}),/*#__PURE__*/t(ts,{children:"Enable your passkeys for verification"}),/*#__PURE__*/r(as,{children:[s.slice(0,p).map((e=>/*#__PURE__*/r(yc,{children:[/*#__PURE__*/t(gc,{children:vc(e)}),/*#__PURE__*/r(fc,{children:["Last used: ",e.latestVerifiedAt?.toLocaleString()]})]},e.credentialId))),!u&&s.length>3&&/*#__PURE__*/t(Cc,{onClick:()=>h(!0),children:"View All"})]}),/*#__PURE__*/t(rr,{style:{marginTop:"1.5rem"},onClick:o,loading:c,children:"Enable passkeys"}),s.length<5&&/*#__PURE__*/t(Cc,{style:{marginTop:"0.5rem"},onClick:i,disabled:d,children:d?/*#__PURE__*/t(ur,{style:{height:"1rem",width:"1rem",borderWidth:2}}):"Add new passkey"}),/*#__PURE__*/t(Gt,{})]})},yc=/*#__PURE__*/ja.div.withConfig({displayName:"PasskeyItem",componentId:"sc-23451ce2-0"})(["&&{padding:0.75rem 1rem;text-align:left;border-radius:0.5rem;border:1px solid var(--privy-color-foreground-4);width:100%;}"]),gc=/*#__PURE__*/ja.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-23451ce2-1"})(["font-size:0.875rem;line-height:1.375rem;font-weight:500;color:var(--privy-color-foreground-1);"]),fc=/*#__PURE__*/ja.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-23451ce2-2"})(["font-size:0.75rem;font-weight:400;line-height:1.125rem;color:var(--privy-color-foreground-2);"]),vc=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 Cc=/*#__PURE__*/ja.button.withConfig({displayName:"StyledLink",componentId:"sc-23451ce2-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;}}"]),kc=({appName:e,onComplete:a,onReset:i,onClose:o})=>{let[s,c]=l(""),[d,u]=l(!1),[h,p]=l(null),[m,w]=l("enroll"),{initEnrollmentWithSms:y,submitEnrollmentWithSms:g}=oc(),{data:f}=lr(),v=Ua();function C(){f?.mfaEnrollmentFlow?.onSuccess(),a()}return h?/*#__PURE__*/t(jr,{allowlistConfig:v.allowlistConfig,error:h,onBack:()=>p(null),onRetry:()=>p(null)}):/*#__PURE__*/r(n,"enroll"===m?{children:[/*#__PURE__*/t(Qt,{backFn:i,onClose:o},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Xa,{})}),/*#__PURE__*/t(ts,{children:"Set up SMS verification"}),/*#__PURE__*/r(rs,{children:["We'll text a verification code to this mobile device whenever you use your ",e," ","wallet."]}),/*#__PURE__*/r(ns,{children:[/*#__PURE__*/t(Dr,{onSubmit:async function({qualifiedPhoneNumber:e}){try{await y({phoneNumber:e}),c(e),w("verify")}catch(e){p(e)}},hideRecent:!0}),/*#__PURE__*/r(ms,{children:["By providing your mobile number, you agree to receive text messages from ",v?.name,". Some carrier charges may apply"]})]}),/*#__PURE__*/t(Gt,{})]}:d?{children:[/*#__PURE__*/t(Qt,{onClose:C},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Li,{})}),/*#__PURE__*/t(ts,{children:"SMS verification added"}),/*#__PURE__*/r(rs,{children:["From now on, you'll enter the verification code sent to your mobile device whenever you use your ",e," wallet."]}),/*#__PURE__*/t(ss,{children:/*#__PURE__*/t(rr,{onClick:C,children:"Done"})}),/*#__PURE__*/t(Gt,{})]}:{children:[/*#__PURE__*/t(Qt,{backFn:function(){"verify"===m?w("enroll"):i()},onClose:o},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Xa,{})}),/*#__PURE__*/t(ts,{children:"Enter enrollment code"}),/*#__PURE__*/r(ns,{children:[/*#__PURE__*/t(Ss,{onChange:async function(e){try{if(!e)return;await g({phoneNumber:s,mfaCode:e}),u(!0)}catch(e){if(Vr(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(ir(e))throw Error("The code you entered is not valid");if(or(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw $r(e)?Error("Verification canceled"):Error("Unknown error")}}}),/*#__PURE__*/r(rs,{children:["To continue, enter the 6-digit code sent to ",/*#__PURE__*/t("strong",{children:P(s)})]})]}),/*#__PURE__*/t(Gt,{})]})},Ac=({size:e,authUrl:r})=>/*#__PURE__*/t(Mr,{url:r,squareLogoElement:Di,size:e,fgColor:"#1F1F1F"}),bc=({onClose:e,onReset:a,totpInfo:i,submitEnrollmentWithTotp:o,error:s})=>{let[c,d]=l("enroll");/*#__PURE__*/return r(n,"enroll"===c?{children:[/*#__PURE__*/t(Qt,{backFn:a,onClose:e},"header"),/*#__PURE__*/t(Kr,{children:"Scan QR code"}),/*#__PURE__*/t(Gr,{children:"Open your authenticator app and scan this code to continue"}),/*#__PURE__*/t(Yr,{children:/*#__PURE__*/t(Ac,{authUrl:i.authUrl,size:240})}),/*#__PURE__*/t(Zr,{style:{textAlign:"left"},children:"Setup key"}),/*#__PURE__*/r(Jr,{style:{marginTop:"0.25rem"},children:[/*#__PURE__*/t(Ya,{children:"•".repeat(16)}),/*#__PURE__*/t(Si,{itemName:" ",text:i.secret})]}),/*#__PURE__*/t(rr,{style:{marginTop:"1rem"},onClick:function(){d("verify")},children:"Continue"}),/*#__PURE__*/t(Gt,{})]}:{children:[/*#__PURE__*/t(Qt,{backFn:function(){"verify"===c?d("enroll"):a()},onClose:e},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Za,{})}),/*#__PURE__*/t(Kr,{children:"Enter enrollment code"}),/*#__PURE__*/t(Gr,{children:"To continue, enter the 6-digit code generated from your authenticator app"}),/*#__PURE__*/t(ns,{children:/*#__PURE__*/t(Ss,{onChange:async function(e){try{if(!e)return;await o({mfaCode:e})}catch(e){if(Vr(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(ir(e))throw Error("The code you entered is not valid");if(or(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw $r(e)?Error("Verification canceled"):Error("Unknown error")}},errorReasonOverride:s?.message})}),/*#__PURE__*/t(Gt,{})]})},Tc={component:()=>{let{user:e,enrollInMfa:a,ready:i}=sr(),[o,c]=l(null),{unenrollWithSms:d,unenrollWithTotp:u,unenrollWithPasskey:h,submitEnrollmentWithTotp:p,initEnrollmentWithPasskey:m,submitEnrollmentWithPasskey:w,initEnrollmentWithTotp:y}=oc(),{data:g,onUserCloseViaDialogOrKeybindRef:f}=lr(),v=Ua(),{closePrivyModal:C}=Ve(),{promptMfa:k}=Os(),[A,b]=l(!1),[T,_]=l(null),[E,I]=l(null),S=()=>{C({shouldCallAuthOnSuccess:!0}),a(!1),setTimeout((()=>{c(null),_(null)}),500)},[U,P]=l(!1),[W,x]=l();f.current=S;let N=e?.mfaMethods.includes("sms"),O=!!e?.phone,R=e?.mfaMethods.includes("totp"),M=e?.mfaMethods.includes("passkey"),F=N||R||M,L=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function D(){c(null),_(null)}async function q(e=L){P(!0);try{return await m(),await w({credentialIds:e},{removeForLogin:g?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa}),g?.mfaEnrollmentFlow?.onSuccess(),S()}catch(e){x(e)}finally{P(!1)}}if(s((()=>{F&&b(!0)}),[F]),!i||!e||!v/*#__PURE__*/)return r(n,{children:[/*#__PURE__*/t(Qt,{onClose:S},"header"),/*#__PURE__*/t(es,{children:/*#__PURE__*/t(sc,{})}),/*#__PURE__*/t(ns,{children:/*#__PURE__*/t(ur,{})}),/*#__PURE__*/t(Gt,{})]});if("sms"===o)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{backFn:D,onClose:S},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Wi,{})}),/*#__PURE__*/t(ts,{children:"Remove SMS verification?"}),/*#__PURE__*/r(rs,{children:["MFA adds an extra layer of security to your ",v?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/t(ss,{children:/*#__PURE__*/t(rr,{$warn:!0,onClick:async function(){c(null);try{await d()}catch(e){c(null)}},children:"Remove"})}),/*#__PURE__*/t(Gt,{})]});if("totp"===o)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{backFn:D,onClose:S},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Wi,{})}),/*#__PURE__*/t(ts,{children:"Remove authenticator app verification?"}),/*#__PURE__*/r(rs,{children:["MFA adds an extra layer of security to your ",v?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/t(ss,{children:/*#__PURE__*/t(rr,{$warn:!0,onClick:async function(){c(null);try{await u()}catch(e){c(null)}},children:"Remove"})}),/*#__PURE__*/t(Gt,{})]});if("passkey"===o){let e=g?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{backFn:D,onClose:S},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Wi,{})}),/*#__PURE__*/t(ts,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/t(rs,{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(ss,{children:/*#__PURE__*/t(rr,{$warn:!0,onClick:async function(){c(null);try{await h({removeForLogin:g?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){c(null)}},children:"Remove"})}),/*#__PURE__*/t(Gt,{})]})}if(0===g.mfaEnrollmentFlow.mfaMethods.length&&!F)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{onClose:S},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Qa,{})}),/*#__PURE__*/t(ts,{children:"Add more security"}),/*#__PURE__*/r(rs,{children:[v?.name," does not have any verification methods enabled."]}),/*#__PURE__*/t(ss,{children:/*#__PURE__*/t(rr,{onClick:S,children:"Close"})}),/*#__PURE__*/t(Gt,{})]});let z=!F&&!A;return z?/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(Qt,{onClose:S},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Qa,{})}),/*#__PURE__*/t(ts,{children:"Transaction Protection"}),/*#__PURE__*/t(rs,{children:"Set up transaction protection to add an extra layer of security to your account"}),/*#__PURE__*/r(as,{children:[/*#__PURE__*/r(os,{children:[/*#__PURE__*/t(is,{children:/*#__PURE__*/t(xi,{})}),"Enable 2-Step verification for your ",v?.name," wallet."]}),/*#__PURE__*/r(os,{children:[/*#__PURE__*/t(is,{children:/*#__PURE__*/t(Ni,{})}),"You'll be prompted to authenticate to complete transactions."]})]}),/*#__PURE__*/r(ss,{children:[/*#__PURE__*/t(rr,{onClick:()=>b(!0),children:"Continue"}),/*#__PURE__*/t(nr,{onClick:S,children:"Not now"})]}),/*#__PURE__*/t(Gt,{})]}):"sms"===T?/*#__PURE__*/t(kc,{appName:v?.name||"Privy",onComplete:S,onReset:D,onClose:S}):"totp"===T&&E?/*#__PURE__*/t(bc,{onClose:S,onReset:D,submitEnrollmentWithTotp:({mfaCode:e})=>async function(e){try{return x(void 0),await p({mfaCode:e}),g?.mfaEnrollmentFlow?.onSuccess(),S()}catch(e){x(e)}finally{c(null)}}(e),totpInfo:{...E,appName:v?.name||"Privy"}}):"passkey"===T?/*#__PURE__*/t(pc,{onReset:D,onClose:S,submitEnrollmentWithPasskey:q}):/*#__PURE__*/t(cc,{showIntro:z,userMfaMethods:e.mfaMethods,appMfaMethods:v.mfa.methods,userHasAuthSms:O,backFn:function(){b(!1)},handleSelectMethod:async function(e){try{await k()}catch(e){return void x(e)}return"totp"===e?(_(e),I(null),void y().then((e=>{I(e)})).catch((()=>{I(null),D()}))):"passkey"===e&&1===L.length?await q():void _(e)},isTotpLoading:"totp"===T&&!E,isPasskeyLoading:U,error:W,onClose:S,setRemovingMfaMethod:async e=>{try{await k()}catch(e){return void x(e)}c(e)}})}},_c=({providerName:e,ProviderLogo:r,success:n,errorMessage:a,onRetry:i})=>{let o=n?`Successfully connected with ${e}`:a?a.message:`Verifying connection to ${e}`;/*#__PURE__*/return t(Vt,{title:o,subtitle:n?"You're good to go!":a?a.detail:"Just a few moments more",icon:r,iconVariant:"loading",iconLoadingStatus:{success:n,fail:!!a},secondaryCta:a?.retryable&&i?{label:"Retry",onClick:i}:void 0,watermark:!0})},Ec={component:()=>{let{authenticated:e,logout:r,ready:n,user:a}=sr(),{setModalData:i,navigate:o,resetNavigation:c}=lr(),d=Ua(),{getAuthMeta:u,initLoginWithOAuth:h,loginWithOAuth:p,updateWallets:m,setReadyToTrue:w,closePrivyModal:y,createAnalyticsEvent:g}=Ve(),[f,v]=l(!1),[C,k]=l(void 0),A=u()?.provider||"google",{name:b,component:T}=co(A,d.customOAuthProviders);return s((()=>{p(A).then((()=>{v(!0),w(!0)})).catch((e=>{if(w(!1),e?.privyErrorCode===$.ALLOWLIST_REJECTED)return k(void 0),c(),void o(Xr);if(e?.privyErrorCode===$.USER_LIMIT_REACHED)return console.error(new Ke(e).toString()),k(void 0),c(),void o(Qr);if(e?.privyErrorCode===$.USER_DOES_NOT_EXIST)return k(void 0),c(),void o(en);if(e?.privyErrorCode===$.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return k(void 0),c(),i({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:u()?.provider,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void o(xr);let{retryable:t,detail:r}=function(e,t,r){let n={detail:"",retryable:!1},a=yt(t);if(e?.privyErrorCode===$.LINKED_TO_ANOTHER_USER&&(n.detail="This account has already been linked to another user."),e?.privyErrorCode===$.INVALID_CREDENTIALS&&(n.retryable=!0,n.detail="Something went wrong. Try again."),e.privyErrorCode===$.OAUTH_USER_DENIED&&(n.detail=`Retry and check ${a} to finish connecting your account.`,n.retryable=!0),e?.privyErrorCode===$.TOO_MANY_REQUESTS&&(n.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===$.TOO_MANY_REQUESTS&&e.message.includes("provider rate limit")){let e=co(t,r).name;n.detail=`Request limit reached for ${e}. Please wait a moment and try again.`}if(e?.privyErrorCode===$.OAUTH_ACCOUNT_SUSPENDED){let e=co(t,r).name;n.detail=`Your ${e} account is suspended. Please try another login method.`}return e?.privyErrorCode===$.CANNOT_LINK_MORE_OF_TYPE&&(n.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode===$.OAUTH_UNEXPECTED&&t.startsWith("privy:")&&(n.detail="Something went wrong. Please try again."),n}(e,A,d.customOAuthProviders);k({retryable:t,detail:r,message:"Authentication failed"})})).finally((()=>{tn()}))}),[b,A]),s((()=>{if(n&&e&&f&&a){if(d?.legal.requireUsersAcceptTerms&&!a.hasAcceptedTerms){let e=setTimeout((()=>{o(Ur)}),Na);return()=>clearTimeout(e)}if(Pr(a,d.embeddedWallets)){let e=setTimeout((()=>{i({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),g({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:A,screen:"OAuthStatusScreen"}}),r()},callAuthOnSuccessOnClose:!0}}),o(Wr)}),Na);return()=>clearTimeout(e)}{let e=setTimeout((()=>y({shouldCallAuthOnSuccess:!0,isSuccess:!0})),Na);return m(),()=>clearTimeout(e)}}}),[n,e,f,a]),/*#__PURE__*/t(_c,{providerName:b,ProviderLogo:T,success:f,errorMessage:C,onRetry:C?.retryable?()=>{tn(),h(A),k(void 0)}:void 0})}},Ic=/*#__PURE__*/m(((e,a)=>{let[i,o]=l(""),[s,c]=l(""),[d,u]=l(!1),{authenticated:h,user:p}=sr(),{initUpdateEmail:m}=Ve(),{navigate:w,setModalData:y,currentScreen:g}=lr(),{enabled:f,token:v}=jt(),C=Ua(),k=rn(i)&&(C.disablePlusEmails&&i.includes("+")?(s||c("Please enter a valid email address without a '+'."),!1):(s&&c(""),!0)),A=d||!k,b=()=>{!f||v||h?(async e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");u(!0);try{await m({oldAddress:p.email.address,newAddress:i,captchaToken:e}),w(qr)}catch(e){y({errorModalData:{error:e,previousScreen:g||Br}}),w(zr)}u(!1)})(v):(y({captchaModalData:{callback:e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");return m({oldAddress:p.email.address,newAddress:i,captchaToken:e})},userIntentRequired:!1,onSuccessNavigateTo:qr,onErrorNavigateTo:zr}}),w(ln))};/*#__PURE__*/return r(n,{children:[/*#__PURE__*/r(Sc,{children:[s&&/*#__PURE__*/t(an,{style:{marginTop:"0.25rem",textAlign:"left"},children:s}),/*#__PURE__*/r(Uc,{$error:!!s,children:[/*#__PURE__*/t(Kt,{children:/*#__PURE__*/t(Ii,{})}),/*#__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&&b()},value:i,autoComplete:"email"}),e.stacked?null:/*#__PURE__*/t(sn,{isSubmitting:d,onClick:b,disabled:A,children:"Submit"})]})]}),e.stacked?/*#__PURE__*/t(rr,{loadingText:null,loading:d,disabled:A,onClick:b,style:{width:"100%"},children:"Submit"}):null]})}));let Sc=nn,Uc=on;const Pc=({title:e="Update your email",subtitle:r="Add the email address you'd like to use going forward. We'll send you a confirmation code"})=>/*#__PURE__*/t(Vt,{title:e,subtitle:r,icon:Pi,watermark:!0,children:/*#__PURE__*/t(Fr,{children:/*#__PURE__*/t(Ic,{stacked:!0})})}),Wc={component:()=>/*#__PURE__*/t(Pc,{})},xc=({title:e="Update your phone number",subtitle:r="Add the phone number you'd like to use going forward. We'll send you a confirmation code",onSubmit:n,isSubmitting:a=!1})=>{let[i,o]=l(null);/*#__PURE__*/return t(Vt,{title:e,subtitle:r,icon:Xa,primaryCta:{label:a?"Submitting":"Update",onClick:async()=>{i?.qualifiedPhoneNumber&&await n(i)},disabled:!i?.isValid||a},watermark:!0,children:/*#__PURE__*/t(Dr,{onChange:e=>{o(e)},onSubmit:async()=>{},noIncludeSubmitButton:!0,hideRecent:!0})})},Nc={component:()=>{let{currentScreen:e,data:r,navigate:n,setModalData:a}=lr(),{user:i}=sr(),{initUpdatePhone:o}=Ve(),[s,c]=l(!1);/*#__PURE__*/return t(xc,{onSubmit:async t=>{c(!0);try{if(!i?.phone?.number)throw Error("User is required to have an phone number to update it.");await o(i?.phone?.number,t.qualifiedPhoneNumber),n(qr)}catch(t){a({errorModalData:{error:t,previousScreen:r?.errorModalData?.previousScreen||e||nc}}),n(zr)}finally{c(!1)}},isSubmitting:s})}},Oc=Ba((()=>({ethereum:[]}))),Rc=()=>Oc.getState().ethereum;function Mc({subscribe:e,getExternalJwt:t,enabled:r=!0,onAuthenticated:n,onUnauthenticated:a,onError:i}){let{client:o,onCustomAuthAuthenticated:c}=Ve(),{logout:d,authenticated:h,ready:p}=wi();if(!o)throw new R("`useSyncJwtBasedAuthState` must be used within a `PrivyProvider`");let[m,w]=l({status:"initial"}),y=u(),g=u(!1),f=u(t);s((()=>{f.current=t}),[t]);let v=u(n);s((()=>{v.current=n}),[n]);let C=u(a);s((()=>{C.current=a}),[a]);let k=u(i);return s((()=>{k.current=i}),[i]),s((()=>{if(!r||!p)return;let t=async()=>{if(!g.current){g.current=!0;try{w({status:"loading"});let e=await f.current();if(void 0!==y.current&&y.current===e)return void w({status:"done"});if(!e)return h&&(await d(),C.current?.()),y.current=e,void w({status:"done"});o.startAuthFlow(new Do(e));let{user:t,isNewUser:r=!1}=await o.authenticate();if(!t)throw new R("Failed to sync with custom auth provider");v.current?.({user:t,isNewUser:r}),c(t,r),y.current=e,w({status:"done"})}catch(e){if(console.warn(e),await d().catch((()=>{})),C.current?.(),e instanceof me&&e.privyErrorCode===$.LINKED_TO_ANOTHER_USER)return w({status:"initial"}),void setTimeout((()=>{t()}),0);k.current?.(e),w({status:"error",error:e})}finally{g.current=!1}}};return t(),e(t)}),[e,o,c,h,d,r,p]),r?{state:m}:{state:{status:"not-enabled"}}}let Fc=Ba((()=>({jwtAuthFlowState:{status:"not-enabled"}})));function Lc({customAuth:e}){let{jwtAuthFlowState:t}=function({customAuth:e}){let t=xa(),r=u(),n=p((e=>(r.current=e,()=>{r.current=void 0})),[]),a=e?.getCustomAccessToken??(()=>Promise.resolve(void 0)),{state:i}=Mc({enabled:!0===e?.enabled,subscribe:n,getExternalJwt:a,onAuthenticated:({user:e,isNewUser:r})=>{t("login","onComplete",{user:e,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),t("customAuth","onAuthenticated",{user:e})},onUnauthenticated:()=>{t("customAuth","onUnauthenticated")},onError:e=>{t("login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR)}});return s((()=>{(async()=>{e&&!e.isLoading&&r.current?.()})()}),[e?.enabled,e?.getCustomAccessToken,e?.isLoading]),{jwtAuthFlowState:i}}({customAuth:e});return s((()=>{Fc.setState({jwtAuthFlowState:t})}),[t]),null}const Dc=/*#__PURE__*/w(!1);let qc,zc,Bc,Hc,jc,Vc;function $c(){return qc?qc.getCustomerAccessToken():Promise.resolve(et.get(wa)||null)}async function Kc(){return qc?qc.getAccessToken():Promise.resolve(et.get(ya)||et.get(wa)||null)}const Gc=(e,t)=>zc(e,t),Yc=(e,t)=>Bc(e,t),Zc=(e,t)=>Hc(e,t),Jc=(e,t)=>jc(e,t),Xc=e=>Vc(e),Qc=({config:e,...r})=>{var n;if((()=>{if(h(Dc))throw new R("Multiple PrivyProvider instances found","Found multiple instances of PrivyProvider, ensure there is only one mounted in your application tree.")})(),"undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol&&"chrome-extension:"!==window.location.protocol)throw new R("Embedded wallet is only available over HTTPS");if("string"!=typeof(n=r.appId)||25!==n.length)throw new R("Cannot initialize the Privy provider with an invalid Privy app ID");qc||(qc=new Zo({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let a=Object.assign({},e),i=o((()=>new I({appId:r.appId,clientId:r.clientId,storage:et,baseUrl:r.apiUrl,sdkVersion:"react-auth:3.6.0"})),[]);/*#__PURE__*/
|
|
5
|
-
return t(Ra,{client:i,legacyClient:qc,appClientId:r.clientId,clientConfig:a,children:/*#__PURE__*/t(cn,{children:/*#__PURE__*/t(ed,{...r,client:qc,privy:i})})})};let ed=e=>{let n=e.client,i=e.privy,c=dn(),d=Ua();un(hn(d?.appearance.walletList??[]));let[h,m]=l(!1),w=Ms((e=>e.inProgressMfaFlow)),[y,g]=l(!1),[f,v]=l(!1),[b,E]=l(null),I=Oc((e=>e.ethereum)),[S,P]=l(void 0),[W,x]=l(!1),[N,O]=l(null),[M,L]=l(!1),[D,q]=l({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:Ge}),[z,B]=l({status:"initial"}),[H,j]=l({status:"initial"}),[V,K]=l({status:"initial"}),[Y,Z]=l({status:"initial"}),[J,X]=l({status:"initial"}),[Q,ee]=l({status:"initial"}),[te,re]=l(null),ne=Wa(),[ae,oe]=l({}),[se,le]=l(null),ce=u(null),[de,ue]=l(!1),[he,pe]=l(!1),me=u(null),we=u(null),ye=u(Ma),[ge,fe]=l(!1);n.onStoreCustomerAccessToken=e=>{e&&Fa(ye,"accessToken","onAccessTokenGranted",{accessToken:e})},n.onDeleteCustomerAccessToken=()=>{E(null),v(!1),Fa(ye,"accessToken","onAccessTokenRemoved")};let ve=u(null),Ce=u(null),ke=u(!1),Ae=({showWalletUIs:e})=>ke.current?ke.current:void 0!==e?!e:!d.embeddedWallets.showWalletUIs,be=e=>{O(e),setTimeout((()=>{m(!0)}),15)};s((()=>{if(!b)return void n.connectors?.removeEmbeddedWalletConnectors();let t=pn(b),r=mn(b),a=wn(b);t&&r.length||n.connectors?.removeEmbeddedWalletConnectors(),a.length||n.connectors?.removeImportedWalletConnectors(),n.connectors?te?(t&&n.connectors.addEmbeddedWalletConnectors({walletProxy:te,user:b,embeddedWallets:r,defaultChain:d.defaultChain,appId:e.appId,privyClient:i}),a.forEach((t=>n.connectors?.addImportedWalletConnector(te,t.address,d.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")}),[te,b]),s((()=>{te&&ce.current?.(te)}),[te]);let Te=p(((e,t)=>{E(e),x(t),v(!0),pe(!0)}),[]);s((()=>{he&&te&&b&&(async()=>{let e=yn(b,d.embeddedWallets.ethereum.createOnLogin),t=gn(b,d.embeddedWallets.solana.createOnLogin),r=await Kc();if(r){if(e&&t){let e=await te.create({accessToken:r});return await te.createSolana({accessToken:r,ethereumAddress:e?.address}),void pe(!1)}if(t)return await te.createSolana({accessToken:r,ethereumAddress:pn(b)?.address}),await Be.refreshSessionAndUser(),void pe(!1);if(e)return await te.create({accessToken:r}),void pe(!1)}})().catch(console.error)}),[he&&te&&b]),s((()=>{if(d.externalWallets.solana.connectors)return d.externalWallets.solana.connectors.onMount(),()=>d.externalWallets.solana.connectors?.onUnmount()}),[d.externalWallets.solana.connectors]),s((()=>{!y&&ne&&async function(){let e,t=_e(),r=Ee(),i=a();n.initializeConnectorManager({walletConnectCloudProjectId:d.walletConnectCloudProjectId,rpcConfig:d.rpcConfig,chains:d.chains,defaultChain:d.defaultChain,store:i,walletList:d.appearance.walletList,shouldEnforceDefaultChainOnConnect:d.shouldEnforceDefaultChainOnConnect,externalWalletConfig:d.externalWallets,appName:d.name??"Privy",walletChainType:d.appearance.walletChainType,setBaseAccountSdk:P}),n.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=n.connectors.walletConnectors.length,r=n.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?fe(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),fe(!0)}),1500)})),n.connectors?.initialize().then((()=>{We()}));let o=await n.getAuthenticatedUser(),s=!!o;d.legal.requireUsersAcceptTerms&&o&&!o.hasAcceptedTerms?(await n.logout(),Be.setReadyToTrue(!0),Fa(ye,"logout","onSuccess")):(d.customAuth?.enabled||(v(!!o),o&&Fa(ye,"login","onComplete",{user:o,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),E(o)),t?Ce.current=s?"link":"login":r&&!s?(Ce.current="login",oe({telegramAuthModalData:{seamlessAuth:!0}}),be(On)):Be.setReadyToTrue(!!o))}()}),[n,se,y,ne]),s((()=>{if(y){if(!b||!b.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void ue(!!te);if([...I].some((e=>"privy"===e.walletClientType)))return void ue(!0);ue(!!te)}}),[y,b,I,te]),s((()=>{n.connectors?.setWalletList(d.appearance.walletList)}),[d.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(ul).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(n.startAuthFlow(new io({...e,customOAuthRedirectUrl:d.customOAuthRedirectUrl})),be(Ec),!0))},Ee=()=>{let e=Yn();if(!e||!d.loginMethods.telegram||!d.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new En;return n.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},Ie=async(e,t,r,a)=>{if("solana_adapter"!==e)Se(await(n.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,a);else{let e=n.connectors?.findSolanaWalletConnector(t);if(!e)return;Se(e,t,r,a)}};async function Se(e,t,r,n){if(!e)return q({status:"disconnected",connectedWallet:null,connectError:new ie("Unable to connect to wallet."),connector:null,connectRetry:Ge}),n?.(null,r);q({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:Ge}),e instanceof Lt&&t&&await e.resetConnection(t),q({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Se(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||fn(t))&&d.shouldEnforceDefaultChainOnConnect&&!d.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){q((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:Ge})));try{await(t?.switchChain(d.defaultChain.id)),t&&(t.chainId=vn(k(d.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${d.defaultChain.id}`)}}return q((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:Ge}))),t&&Fa(ye,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof $e?(console.warn(e.cause?e.cause:e.message),Fa(ye,"connectWallet","onError",e.privyErrorCode||$.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),Fa(ye,"connectWallet","onError",$.UNKNOWN_CONNECT_WALLET_ERROR)),q((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Ue=async(e,t,r)=>{if(null===e||!fn(e))return;let a=new Bt(n,e,t,r);n.startAuthFlow(a)},Pe=async(e,t,r,a="plain")=>{let i=c(Mn);if("transaction"===a&&!i)throw new R("useSolanaLedger plugin hook must be mounted");if(null===e||!Fn(e))return;let o=new In(e,n,t,r,a,i);n.startAuthFlow(o)},We=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),a="true"===e.get("privy_connect_only");if(!t||!r)return;let i=Zn({connectorType:t,walletClientType:r});if(!i||!i.isInstalled)return be(ic);if(!n.connectors)throw new R("Connector not initialized");be(a?Jn:Rn);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),Ie(t,r,void 0,a?void 0:"solana_adapter"===t?Pe:Ue)};s((()=>{y&&f&&null===b&&n.getAuthenticatedUser().then(E)}),[y,f,b,n]);let xe=e=>{if(!f)throw Fa(ye,"linkAccount","onError",$.MUST_BE_AUTHENTICATED,{linkMethod:e}),new R("User must be authenticated before linking an account.")},Ne=e=>{if(!f||!b)return!1;if("privy"===e.walletClientType)return!0;for(let t of b.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Oe=()=>{Oc.setState((e=>{let t=n.connectors?.wallets.filter(fn).map((e=>({...e,linked:Ne(e),loginOrLink:async()=>{if(!await e.isConnected())throw new R("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new R("Cannot link or login with embedded wallet");(async e=>{let t;if(!n.connectors)throw new R("Connector not initialized");t="ethereum"===e.type?n.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:n.connectors.findSolanaWalletConnector(e.walletClientType)||null,q((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:Ge}))),d.captchaEnabled&&!f?(oe({captchaModalData:{callback:t=>fn(e)?Ue(e,t):Pe(e,t),userIntentRequired:!1,onSuccessNavigateTo:Rn,onErrorNavigateTo:zr}}),be(ln)):(fn(e)?await Ue(e):await Pe(e),be(Rn))})(e)},fund:async t=>{await Be.fundWallet(e.address,t)},unlink:async()=>{if(!f)throw new R("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new R("Cannot unlink an embedded wallet");E(await n.unlinkEthereumWallet(e.address))}})))||[];return Cn(e.ethereum,t)?{}:{ethereum:t}}))};s((()=>{Oe()}),[b?.linkedAccounts,f,y]),s((()=>{if(y){if(!n.connectors)throw new R("Connector not initialized");Oe(),n.connectors.on("walletsUpdated",Oe)}}),[y]),s((()=>{[...d.loginMethodsAndOrder?.primary??[],...d.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>n.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!n]);let Re=({transaction:t,sponsor:r,uiOptions:a,fundWalletConfig:o,address:s,signOnly:l})=>new Promise((async(c,u)=>{let{requesterAppId:h}=a||{},p=l?"signTransaction":"sendTransaction",m=s?kn(b,s):pn(b);if(!m&&s){let e=qn(Rc(),s);if(e){if(r)throw new R("Cannot sponsor transactions for externally connected wallet.");try{let r=await e.getEthereumProvider(),n={...t,from:s,chainId:t.chainId||Number(e.chainId.replace("eip155:","")),value:void 0!==t.value?k(t.value):void 0},a=await r.request({method:"sendTransaction"===p?"eth_sendTransaction":"eth_signTransaction",params:[n]});return Fa(ye,p,"onSuccess",{hash:a}),void c({hash:a})}catch(e){return Fa(ye,p,"onError",$.TRANSACTION_FAILURE),void u(e??new zn("Unable to "+p+e))}}}if(!m)return Fa(ye,p,"onError",$.EMBEDDED_WALLET_NOT_FOUND),void u(new R("No embedded or connected wallet found for address."));if(!f||!b)return Fa(ye,p,"onError",$.MUST_BE_AUTHENTICATED),void u(Error("User must be authenticated before signing with a Privy wallet"));let w=m.address,y=m.walletIndex??0,{entropyId:g,entropyIdVerifier:v}=Mt(b,m),C=He.wallets.find((e=>"privy"===e.walletClientType&&T(e.address)===T(w)));if(!C)return Fa(ye,p,"onError",$.EMBEDDED_WALLET_NOT_FOUND),void u(Error("Must have a Privy wallet before signing"));let A=await C.getEthereumProvider(),E=await A.request({method:"eth_chainId"}),I=t.chainId?Number(t.chainId):gi(E);(e=>{if(!d.chains.map((e=>e.id)).includes(e))throw new ie(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,$.UNSUPPORTED_CHAIN_ID)})(I);let S={...t,from:t.from??w,chainId:I},P=await Kc();if(!P||!te)return Fa(ye,p,"onError",$.EMBEDDED_WALLET_NOT_FOUND),void u(Error("Must have valid access token and Privy wallet to send transaction"));let W=Tt(S.chainId,d.chains,d.rpcConfig,{appId:e.appId}),x=Et(m),N=async({transactionRequest:e})=>{try{let t;if(!await Be.recoverEmbeddedWallet({address:w}))throw Fa(ye,p,"onError",$.UNKNOWN_CONNECT_WALLET_ERROR),u(Error("Unable to connect to wallet")),Error("Unable to connect to wallet");if(r){let t=await(async({transactionRequest:e})=>{if(!x)throw new R("Sponsoring is only supported for wallets on the TEE stack");if(l)throw new R("Cannot sponsor a sign transaction request");let t=e=>null==e?void 0:k(e),r=await U(i,(async({message:e})=>await te.signWithUserSigner({accessToken:P,requesterAppId:h,message:e})),{chain_type:"ethereum",method:"eth_sendTransaction",caip2:vn(k(e.chainId)),sponsor:!0,params:{transaction:{from:e.from,to:e.to,chain_id:t(e.chainId),data:_(e.data)?e.data?e.data:k(Uint8Array.from(e.data)):void 0,value:t(e.value)}},wallet_id:m.id});if(r.data&&"hash"in r.data)return r.data.hash;throw new zn("Unable to sign transaction")})({transactionRequest:e});return Fa(ye,"sendTransaction","onSuccess",{hash:t}),t}if(x){let r=e=>null==e?void 0:k(e),n=await U(i,(async({message:e})=>await te.signWithUserSigner({accessToken:P,requesterAppId:h,message:e})),{chain_type:"ethereum",method:"eth_signTransaction",params:{transaction:{from:e.from,to:e.to,nonce:r(e.nonce),chain_id:r(e.chainId),data:_(e.data)?e.data?e.data:k(Uint8Array.from(e.data)):void 0,value:r(e.value),type:e.type,gas_limit:r(e.gasLimit??e.gas),gas_price:r(e.gasPrice??e.gas),max_fee_per_gas:r(e.maxFeePerGas),max_priority_fee_per_gas:r(e.maxPriorityFeePerGas)}},wallet_id:m.id});if(!n.data||!("signed_transaction"in n.data))throw new zn("Unable to sign transaction");t=n.data.signed_transaction}else t=await async function({accessToken:e,entropyId:t,entropyIdVerifier:r,transactingWalletIndex:n,walletProxy:a,transactionRequest:i,requesterAppId:o}){return(await a.rpc({entropyId:t,entropyIdVerifier:r,hdWalletIndex:n??0,chainType:"ethereum",accessToken:e,requesterAppId:o,request:{method:"eth_signTransaction",params:[i]}})).response.data}({accessToken:P,entropyId:g,entropyIdVerifier:v,transactingWalletIndex:y,walletProxy:te,transactionRequest:e,requesterAppId:h});if(l)return Fa(ye,"signTransaction","onSuccess",{signature:t}),t;{let e=await W.sendRawTransaction({serializedTransaction:t});return Fa(ye,"sendTransaction","onSuccess",{hash:e}),e}}catch(e){throw Fa(ye,p,"onError",$.TRANSACTION_FAILURE),e}};if(Ae({showWalletUIs:a?.showWalletUIs})){let e=l||r?S:await Jt(S,W,S.from);try{let t=await N({transactionRequest:e});l?Fa(ye,"signTransaction","onSuccess",{signature:t}):Fa(ye,"sendTransaction","onSuccess",{hash:t}),c({hash:t})}catch(e){Fa(ye,p,"onError",$.TRANSACTION_FAILURE),u(e)}}else{let e={connectingWalletAddress:w,recoveryMethod:m.recoveryMethod,entropyId:g,entropyIdVerifier:v,onCompleteNavigateTo:Kn,isUnifiedWallet:x,onFailure:e=>{Fa(ye,p,"onError",$.UNKNOWN_CONNECT_WALLET_ERROR),u(e)}},t=(e=>!!e.fundingConfig&&mi(e.fundingConfig.options).length>=1)(d)?yi({address:w,appConfig:d,fundWalletConfig:o,methodScreen:kr,chainIdOverride:S.chainId,comingFromSendTransactionScreen:!0}):void 0;oe({connectWallet:e,sendTransaction:{transactionRequest:S,transactingWalletIndex:y,transactingWalletAddress:w,entropyId:g,entropyIdVerifier:v,signOnly:l,scanTransaction:async()=>{let e=await Jt(S,W,S.from);return await n.scanTransaction({metadata:{domain:d.embeddedWallets.transactionScanning.domain},chain_id:e.chainId.toString(),request:{method:"eth_sendTransaction",params:[{from:e.from,to:e.to,value:e.value?.toString(),gas:e.gas?.toString(),gasPrice:e.gasPrice?.toString(),nonce:e.nonce?.toString(),data:e.data}]}})},getIsSponsored:async()=>!!r,onConfirm:({transactionRequest:e})=>N({transactionRequest:e}),onSuccess:e=>{l?Fa(ye,"signTransaction","onSuccess",{signature:e.hash}):Fa(ye,"sendTransaction","onSuccess",{hash:e.hash}),c(e)},onFailure:e=>{Fa(ye,p,"onError",$.TRANSACTION_FAILURE),u(e)},uiOptions:a||{},fundWalletConfig:o,requesterAppId:h},funding:t}),be(Dn)}}));function Me(){return new Promise((async(e,t)=>{let r=await Kc();if(!r||!te)throw Error("Must have valid access token to enroll in MFA");try{await te.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let Fe=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],Le=e=>{let t=b?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=Xn(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw Fa(ye,"linkAccount","onError",$.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new R(`User already has an account of type ${r} linked.`)};async function De({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){O(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!f||!b)throw Fa(ye,r,"onError",$.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=yr(b);if(!n||!te)throw Fa(ye,r,"onError",$.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");let a=Et(n);if(a)throw Fa(ye,r,"onError",$.UNSUPPORTED_WALLET_TYPE),new R("User owned wallet recovery is only supported for on-device execution and this app uses TEE execution. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");try{await Me()}catch(e){throw Fa(ye,r,"onError",$.MISSING_MFA_CREDENTIALS),e}return new Promise(((i,o)=>{let s="user-passcode"===n.recoveryMethod,l=Gn({walletAction:"update",availableRecoveryMethods:d.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:u}=Mt(b),h={recoveryMethod:n.recoveryMethod,connectingWalletAddress:n.address,onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,isUnifiedWallet:a,entropyIdVerifier:u,onFailure:e=>{Fa(ye,r,"onError",$.UNKNOWN_CONNECT_WALLET_ERROR),o(e)}};oe({setWalletPassword:{onSuccess:e=>{Fa(ye,r,"onSuccess",{method:"user-passcode",wallet:e}),i(e)},onFailure:e=>{Fa(ye,r,"onError",$.USER_EXITED_SET_PASSWORD_FLOW),o(e)},callAuthOnSuccessOnClose:!1},recoverWallet:{entropyId:c,entropyIdVerifier:u,onFailure:o},connectWallet:h,recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s,shouldCreateEth:!1,shouldCreateSol:!1}}),be(Dn)}))}async function qe({appId:e,action:t}){let r=await Kc();if("link"===t&&!r)throw Fa(ye,"linkAccount","onError",$.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new R("User must be authenticated before linking an account.");if("login"===t&&r)throw Fa(ye,"login","onError",$.UNKNOWN_AUTH_ERROR),new R("Attempted to log in, but user is already logged in. Use a `link` helper instead.");ve.current=`privy:${e}`,Ce.current=t;let a=gr();return n.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,i)=>{let{name:o,logoUrl:s}=await ml({api:n.api,providerAppId:e,requesterAppId:d.id});oe({crossAppAuth:{appId:e,name:o,logoUrl:s,action:t,popup:a,onSuccess:r,onError:i}}),be(Ll)}))}let ze={ready:y,authenticated:f,user:b,walletConnectors:n.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),oe({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,walletChainType:e?.walletChainType,description:e?.description}}),be($n)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),xe("siwe"),ve.current="siwe",Ce.current="link",oe({...ae,externalConnectWallet:{...ae.externalConnectWallet,walletList:e?.walletList,walletChainType:e?.walletChainType,description:e?.description||`Link a wallet to your ${d?.name} account`}}),be(Vn)},startCrossAppAuthFlow:qe,linkEmail:()=>{xe("email"),Le("email"),ve.current="email",Ce.current="link",be(tc)},linkPhone:()=>{xe("sms"),Le("phone"),ve.current="sms",Ce.current="link",be(nc)},linkGoogle:async()=>{xe("google"),Le("google_oauth"),Ce.current="link",await Be.initLoginWithOAuth("google")},linkTwitter:async()=>{xe("twitter"),Le("twitter_oauth"),Ce.current="link",await Be.initLoginWithOAuth("twitter")},linkTwitch:async()=>{xe("twitch"),Le("twitch_oauth"),Ce.current="link",await Be.initLoginWithOAuth("twitch")},linkDiscord:async()=>{xe("discord"),Le("discord_oauth"),Ce.current="link",await Be.initLoginWithOAuth("discord")},linkGithub:async()=>{xe("github"),Le("github_oauth"),Ce.current="link",await Be.initLoginWithOAuth("github")},linkSpotify:async()=>{xe("spotify"),Le("spotify_oauth"),Ce.current="link",await Be.initLoginWithOAuth("spotify")},linkInstagram:async()=>{xe("instagram"),Le("instagram_oauth"),Ce.current="link",await Be.initLoginWithOAuth("instagram")},linkTiktok:async()=>{xe("tiktok"),Le("tiktok_oauth"),Ce.current="link",await Be.initLoginWithOAuth("tiktok")},linkLine:async()=>{xe("line"),Le("line_oauth"),Ce.current="link",await Be.initLoginWithOAuth("line")},linkLinkedIn:async()=>{xe("linkedin"),Le("linkedin_oauth"),Ce.current="link",await Be.initLoginWithOAuth("linkedin")},linkApple:async()=>{xe("apple"),Le("apple_oauth"),Ce.current="link",await Be.initLoginWithOAuth("apple")},linkPasskey:async()=>{xe("passkey"),Le("passkey"),await Be.initLinkWithPasskey(),be(Al)},linkTelegram:async e=>{if(xe("telegram"),Le("telegram"),Ce.current="link",ve.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new En;n.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=jn(e.launchParams.initDataRaw),oe({telegramAuthModalData:{seamlessAuth:!0}}),be(On)}else Fa(ye,"linkAccount","onError",$.INVALID_DATA,{linkMethod:"telegram"});else await Be.initLoginWithTelegram();be(On)},linkFarcaster:async()=>{xe("farcaster"),Le("farcaster"),await Be.initLoginWithFarcaster(),Ce.current="link",ve.current="farcaster",be(Hn)},updateEmail:()=>{if(xe("email"),!b?.email)throw new R("User does not have an email linked to their account.");Ce.current="update",ve.current="email",be(Wc)},updatePhone:()=>{if(xe("sms"),!b?.phone)throw new R("User does not have a phone number linked to their account.");Ce.current="update",ve.current="sms",be(Nc)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!y){let e=await new Promise((e=>{le((t=>e.bind(t)))}));if(le(null),e)return void console.warn(t)}!b||b.isGuest?(Ce.current="login",oe({login:e}),be(Br)):console.warn(t)},connectOrCreateWallet:async()=>{y||(await new Promise((e=>{le((()=>e))})),le(null)),f?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(Ce.current="connect-or-create",be(Bn))},logout:async()=>{if(Ce.current=null,ve.current=null,b&&n.clearProviderAcccessTokens(b),O(null),await n.logout(),b&&te)try{await te.clearMfa({userId:b.id})}catch(e){}E(null),v(!1),j({status:"initial"}),K({status:"initial"}),B({status:"initial"}),Z({status:"initial"}),X({status:"initial"}),ee({status:"initial"}),Fa(ye,"logout","onSuccess"),m(!1),et.del(Ia),et.del(ma(d.id))},getAccessToken:p((async()=>{let e=await n.getCustomerAccessToken();return e&&!f&&v(!0),e}),[n,f]),unlinkWallet:async e=>{let t;return E(t=e.startsWith("0x")?await n.unlinkEthereumWallet(e):await n.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await n.unlinkEmail(e);return E(t),t},unlinkPhone:async e=>{let t=await n.unlinkPhone(e);return E(t),t},unlinkGoogle:async e=>{let t=await n.unlinkOAuth("google",e);return E(t),t},unlinkTwitter:async e=>{let t=await n.unlinkOAuth("twitter",e);return E(t),t},unlinkTwitch:async e=>{let t=await n.unlinkOAuth("twitch",e);return E(t),t},unlinkDiscord:async e=>{let t=await n.unlinkOAuth("discord",e);return E(t),t},unlinkGithub:async e=>{let t=await n.unlinkOAuth("github",e);return E(t),t},unlinkSpotify:async e=>{let t=await n.unlinkOAuth("spotify",e);return E(t),t},unlinkInstagram:async e=>{let t=await n.unlinkOAuth("instagram",e);return E(t),t},unlinkTiktok:async e=>{let t=await n.unlinkOAuth("tiktok",e);return E(t),t},unlinkLine:async e=>{let t=await n.unlinkOAuth("line",e);return E(t),t},unlinkLinkedIn:async e=>{let t=await n.unlinkOAuth("linkedin",e);return E(t),t},unlinkApple:async e=>{let t=await n.unlinkOAuth("apple",e);return E(t),t},unlinkFarcaster:async e=>{let t=await n.unlinkFarcaster(e);return E(t),t},unlinkTelegram:async e=>{let t=await n.unlinkTelegram(e);return E(t),t},unlinkPasskey:async e=>{let t=await Kc();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!te)throw Error("Wallet proxy not initialized.");let r=d.passkeys.shouldUnenrollMfaOnUnlink;await te.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let a=await n.getAuthenticatedUser();return E(a),a},unlinkCrossAppAccount:async({subject:e})=>{let t=b?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new R("Invalid subject");n.storeProviderAccessToken(t.id,null);let r=await n.unlinkOAuth(`privy:${t.id}`,e);return E(r),r},setWalletRecovery:async e=>De({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>De({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:o}=t?.uiOptions||{},s=e.message,l=t?.address?kn(b,t.address):pn(b);if(!l&&void 0!==t?.address){let e=qn(Rc(),t.address);if(e)try{let t=await e.getEthereumProvider(),n=await t.request({method:"personal_sign",params:[s,e.address]});return Fa(ye,"signMessage","onSuccess",{signature:n}),void r({signature:n})}catch(e){return Fa(ye,"signMessage","onError",$.UNABLE_TO_SIGN),void a(e??new zn("Unable to sign message"))}}if(!l)throw new R("No embedded or connected wallet found for address.");if(!f||!b)return Fa(ye,"signMessage","onError",$.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let c=l.address,d=l.walletIndex??0,{entropyId:u,entropyIdVerifier:h}=Mt(b,l),p=Et(l);if("string"!=typeof s||s.length<1)return Fa(ye,"signMessage","onError",$.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));let m=async()=>{let t;if(!f)throw Error("User must be authenticated before signing with a Privy wallet");let r=await Kc();if(!te||!r||!await Be.recoverEmbeddedWallet({address:c}))throw Error("Unable to connect to wallet");if(n.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:c,requesterAppId:o}}),p){let n=_(e.message,{strict:!0}),a=await U(i,(async({message:e})=>await te.signWithUserSigner({accessToken:r,requesterAppId:o,message:e})),{chain_type:"ethereum",method:"personal_sign",params:n?{message:s.slice(2),encoding:"hex"}:{message:s,encoding:"utf-8"},wallet_id:l.id});if(!a.data||!("signature"in a.data))throw new zn("Unable to sign message");t=a.data.signature}else{let{response:e}=await te.rpc({accessToken:r,entropyId:u,entropyIdVerifier:h,chainType:"ethereum",hdWalletIndex:d,requesterAppId:o,request:{method:"personal_sign",params:[s,c]}});t=e.data}return n.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:c,requesterAppId:o}}),t};if(Ae({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await m();Fa(ye,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){Fa(ye,"signMessage","onError",$.UNABLE_TO_SIGN),a(e??new zn("Unable to sign message"))}else oe({signMessage:{method:"personal_sign",data:s,confirmAndSign:m,onSuccess:e=>{Fa(ye,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{Fa(ye,"signMessage","onError",$.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:l.recoveryMethod,connectingWalletAddress:c,entropyId:u,entropyIdVerifier:h,onCompleteNavigateTo:Ui,isUnifiedWallet:p,onFailure:e=>{Fa(ye,"signMessage","onError",$.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),be(Dn)})),signTypedData:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:o}=t?.uiOptions||{},s=t?.address?kn(b,t.address):pn(b);if(!s&&t?.address){let n=qn(Rc(),t.address);if(n)try{let t=await n.getEthereumProvider(),a=_t(e),i=await t.request({method:"eth_signTypedData_v4",params:[n.address,a]});return Fa(ye,"signTypedData","onSuccess",{signature:i}),void r({signature:i})}catch(e){return Fa(ye,"signTypedData","onError",$.UNABLE_TO_SIGN),void a(e??new zn("Unable to sign typed data "+e))}}if(!s)throw new R("No embedded or connected wallet found for address.");if(!f||!b)return Fa(ye,"signTypedData","onError",$.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let l=s.address,c=s.walletIndex??0,{entropyId:d,entropyIdVerifier:u}=Mt(b,s),h=Et(s),p=_t(e),m=async()=>{let e;if(!f)throw Error("User must be authenticated before signing with a Privy wallet");let t=await Kc();if(!te||!t||!await Be.recoverEmbeddedWallet({address:l}))throw Error("Unable to connect to wallet");if(n.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:l,requesterAppId:o}}),h){let{domain:r,types:n,primaryType:a,message:l}=p,c=await U(i,(async({message:e})=>await te.signWithUserSigner({accessToken:t,requesterAppId:o,message:e})),{chain_type:"ethereum",method:"eth_signTypedData_v4",params:{typed_data:{domain:r,types:n,primary_type:a,message:l}},wallet_id:s.id});if(!c.data||!("signature"in c.data))throw new zn("Unable to sign message");e=c.data.signature}else{let{response:r}=await te.rpc({accessToken:t,entropyId:d,entropyIdVerifier:u,chainType:"ethereum",hdWalletIndex:c,requesterAppId:o,request:{method:"eth_signTypedData_v4",params:[l,p]}});e=r.data}return n.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:l,requesterAppId:o}}),e};if(Ae({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await m();Fa(ye,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){Fa(ye,"signTypedData","onError",$.UNABLE_TO_SIGN),a(e??new zn("Unable to sign message"))}else oe({signMessage:{method:"eth_signTypedData_v4",data:p,confirmAndSign:m,onSuccess:e=>{Fa(ye,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{Fa(ye,"signTypedData","onError",$.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:s.recoveryMethod,connectingWalletAddress:s.address,entropyId:d,isUnifiedWallet:h,entropyIdVerifier:u,onCompleteNavigateTo:Ui,onFailure:e=>{Fa(ye,"signMessage","onError",$.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),be(Dn)})),sendTransaction:async(e,t)=>await Re({transaction:e,sponsor:t?.sponsor,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await Re({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:t=>new Promise((async(r,a)=>{if(!f||!b)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?kn(b,t.address):pn(b);if(!i)return void a(new R("User must have an embedded wallet."));let o=i.address,{entropyId:s,entropyIdVerifier:l}=Mt(b,i),c=Et(i);if(!o)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(o))return void a(Error("Must provide a valid Ethereum address."));let d={recoveryMethod:i.recoveryMethod,connectingWalletAddress:i.address,isUnifiedWallet:c,entropyId:s,entropyIdVerifier:l,onCompleteNavigateTo:Ln,onFailure:a,shouldForceMFA:!0};oe(ae),await Kc()&&te?te?pi(i)?(oe({keyExport:{appId:e.appId,appClientId:e.clientId,origin:n.apiUrl,address:i.address,entropyId:s,entropyIdVerifier:l,hdWalletIndex:i.walletIndex,chainType:i.chainType,walletId:i.id,isUnifiedWallet:c,imported:i.imported,onSuccess:r,onFailure:a},connectWallet:d}),be(Dn)):a(Error(`Export is not supported for ${i.chainType} wallets`)):a(Error("Must have a Privy wallet before exporting")):a(Error("Must have valid access token to enroll in MFA"))})),promptMfa:Me,async init(e){switch(e){case"sms":return void await n.initMfaSmsVerification();case"passkey":return await n.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 R("Invalid MFA code");me.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{we.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new R("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=Ml(await r.startAuthentication({optionsJSON:t}));me.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{we.current={resolve:e,reject:t}}));break;default:throw me.current?.reject(new R("Unsupported MFA method")),new R(`Unsupported MFA method: ${e}`)}},cancel(){me.current?.reject(new R("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Kc();if(!t||!te)throw Error("Must have valid access token to enroll in MFA");await te.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return Be.closePrivyModal(),void t();d.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."),oe({mfaEnrollmentFlow:{mfaMethods:d.mfa.methods,shouldUnlinkOnUnenrollMfa:d.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),be(Tc)})),async initEnrollmentWithTotp(){let e=await Kc();if(!e||!te)throw Error("Must have valid access token to enroll in MFA");let t=await te.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Kc();if(!t||!te)throw Error("Must have valid access token to enroll in MFA");await te.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),E(await n.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Kc();if(!t||!te)throw Error("Must have valid access token to enroll in MFA");await te.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),E(await n.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await Kc();if(!r||!te)throw Error("Must have valid access token to enroll in MFA");await te.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),E(await n.getAuthenticatedUser())},async unenroll(e,t={}){let r=await Kc();if(!r||!te)throw Error("Must have valid access token to remove MFA");"passkey"===e?await te.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await te.unenrollMfa({method:e,accessToken:r}),E(await n.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Kc(),t=b?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!te||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(Et(t))throw new R("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!b?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedWallet({address:t.address}))throw Error("Unable to connect to wallet");let r=await te.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&E(await n.getAuthenticatedUser()||b||null),oe({farcasterSigner:r}),be(Jl)},getFarcasterSignerPublicKey:async()=>{let e,t=await Kc(),r=b?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!te||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(Et(r))throw new R("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!b?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!b.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=b.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Kc(),r=b?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!te||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(Et(r))throw new R("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!b?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Be.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!b.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),a=await te.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(b.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(a.signature))},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let a=b?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return wl({user:b,client:n,address:t,requesterAppId:d.id,request:{method:a?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:qe})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let a=b?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),i=_t(e);return wl({user:b,client:n,address:t,requesterAppId:d.id,request:{method:a?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,i],chainId:r},reconnect:qe})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=b?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return wl({user:b,client:n,address:t,requesterAppId:d.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:qe})},signTransactionWithCrossAppWallet(e,{address:t}){let r=b?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return wl({user:b,client:n,address:t,requesterAppId:d.id,request:{method:r?"privy_signSmartWalletTx":"eth_signTransaction",params:[e],chainId:e.chainId},reconnect:qe})},isModalOpen:h||!!w,mfaMethods:d.mfa.methods};zc=ze.signMessage,Bc=ze.signTypedData,jc=async(e,t)=>await Re({transaction:e,...t,signOnly:!1}),Hc=async(e,t)=>({signature:(await Re({transaction:e,...t,signOnly:!0})).hash});let Be={privy:i,setAuthenticated:v,setUser:E,setIsNewUser:x,isNewUserThisSession:W,pendingTransaction:null,walletConnectionStatus:D,setWalletConnectionStatus:q,connectors:n.connectors?.walletConnectors??[],rpcConfig:d.rpcConfig,chains:d.chains,appId:e.appId,showFiatPrices:"native-token"!==d.embeddedWallets.priceDisplay.primary,clientAnalyticsId:n.clientAnalyticsId,onCustomAuthAuthenticated:Te,hideWalletUIs:ke,isHeadlessSigning:p(Ae,[d.embeddedWallets.showWalletUIs]),emailOtpState:H,setEmailOtpState:j,smsOtpState:V,setSmsOtpState:K,oAuthState:J,setOAuthState:X,telegramAuthState:Q,setTelegramAuthState:ee,siweState:Y,setSiweState:Z,isHeadlessOAuthLoading:M,baseAccountSdk:S,setBaseAccountSdk:P,nativeTokenSymbolForChainId:e=>d.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(te)return te;let t=new Promise((e=>{ce.current=e})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return ce.current=null,n},getAuthFlow:()=>n.authFlow,getAuthMeta:()=>n.authFlow?.meta,client:n,closePrivyModal:async(t={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let r,a=y&&f&&b;if(a&&ve.current&&(r=Fe(b)),"login"===Ce.current)t.shouldCallAuthOnSuccess&&a&&ve.current?Fa(ye,"login","onComplete",{user:b,isNewUser:W,wasAlreadyAuthenticated:!1,loginMethod:ve.current,loginAccount:r??null}):Fa(ye,"login","onError",$.USER_EXITED_AUTH_FLOW);else if("link"===Ce.current&&r)t.isSuccess&&a&&ve.current?Fa(ye,"linkAccount","onSuccess",{user:b,linkMethod:ve.current,linkedAccount:r}):ve.current&&Fa(ye,"linkAccount","onError",$.USER_EXITED_LINK_FLOW,{linkMethod:ve.current});else if("update"===Ce.current&&r)t.isSuccess&&a&&ve.current?Fa(ye,"update","onSuccess",{user:b,updateMethod:ve.current,updatedAccount:r}):ve.current&&Fa(ye,"update","onError",$.USER_EXITED_UPDATE_FLOW,{linkMethod:ve.current});else if("connect-or-create"===Ce.current){let e=Rc();e[0]?Fa(ye,"connectOrCreateWallet","onSuccess",{wallet:e[0]}):Fa(ye,"connectOrCreateWallet","onError",$.USER_EXITED_AUTH_FLOW)}let i=N&&Nl.has(N),o=N===zr&&ae.errorModalData&&Nl.has(ae.errorModalData.previousScreen);if((i||o)&&ae.funding){let t,r=Nl.get(N)??null;if("solana"===ae.funding.chainType){let e=d.solanaRpcs[ae.funding.chain];if(!e)return void console.warn("Unable to load solana rpc, skipping balance");if(c(Sn))try{t=await Un({rpc:e.rpc,address:ae.funding.address})}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");Fa(ye,"fundSolanaWallet","onUserExited",{address:ae.funding.address,fundingMethod:r,chain:ae.funding.chain,balance:t})}else{let n=Tt(ae.funding.chain.id,d.chains,d.rpcConfig,{appId:e.appId});try{t=await n.getBalance({address:ae.funding.address})}catch{console.error("Unable to pull wallet balance")}Fa(ye,"fundWallet","onUserExited",{address:ae.funding.address,chain:ae.funding.chain,fundingMethod:r,balance:t})}}oe((e=>({...e,externalConnectWallet:{}}))),Ce.current=null,ve.current=null,x(!1),m(!1),setTimeout((()=>{n.authFlow=void 0}),200)},openPrivyModal:be,connectWallet:Se,initLoginWithWallet:async(e,t,r,n)=>{fn(e)?(ve.current="siwe",Ue(e,t,r)):(ve.current="siws",Pe(e,t,r,n))},loginWithWallet:async()=>{let e,t,r;if(!y)throw new Ye;if(n.authFlow instanceof Bt?e="siwe":n.authFlow instanceof In&&(e="siws"),!e)throw new R("Must initialize SIWE/SIWS flow first.");if(null!==await n.getAccessToken())try{({user:t}=await n.link()),ve.current=e}catch(t){throw Fa(ye,"linkAccount","onError",t.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await n.authenticate()),ve.current=e}catch(e){throw Fa(ye,"login","onError",e.privyErrorCode||$.GENERIC_CONNECT_WALLET_ERROR),e}E(t||b||null),x(r||!1),v(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,a)=>{let i=await Kc();if(!f||!b||!i)throw new R("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new R("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let o=Be.walletProxy??await Be.initializeWalletProxy(15e3);if(!o)throw new R("Wallet proxy not initialized.");if((({address:e,user:t})=>!!dl(t).find((t=>t.address===e)))({address:e,user:b}))return n();let s=kn(b,e);if(!s)throw new R("Address to delegate is not associated with current user.");if(Et(s))throw new R("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let l=ll({address:e,user:b}),c=cl({address:e,user:b}),d=async()=>{await o.createDelegatedAction({accessToken:i,rootWallet:c,delegatedWallets:[l]}),await Be.refreshSessionAndUser()};if(await Be.recoverEmbeddedWallet({address:e}),r)oe({delegatedActions:{consent:{address:e,onDelegate:d,onSuccess:async()=>{n()},onError:async e=>{a(e)}}}}),be(ql);else try{await d(),n()}catch(e){a(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!f||!b)throw new R("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");let a=dl(b);if(0===a.length)throw new R("User has no delegated wallets to revoke.");if(a.some(Et))throw new R("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let i=async()=>{await n.revokeDelegatedWallet(),await Be.refreshSessionAndUser()};if(e)oe({delegatedActions:{revoke:{onRevoke:i,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),be(Bl);else try{await i(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new eo(e,t);n.startAuthFlow(r);try{ve.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===Ce.current?Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR):"link"===Ce.current&&Fa(ye,"linkAccount","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!y)throw new Ye;if(!(n.authFlow instanceof eo))throw new R("Must initialize Farcaster flow first.");if(null!==await n.getAccessToken())try{({user:e}=await n.link()),ve.current="farcaster"}catch(e){throw Fa(ye,"linkAccount","onError",e.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await n.authenticate()),ve.current="farcaster"}catch(e){throw Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}E(e||null),x(t||!1),v(!0)},async crossAppAuthFlow({appId:e,popup:t,action:r}){let a=`privy:${e}`;ve.current=a;let{url:i,stateCode:o,codeVerifier:s}=await async function({api:e,appId:t}){let r=tt(),n=rt(),a=await nt(r);try{let{url:i}=await e.post(G,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:a,state_code:n});return{url:i,stateCode:n,codeVerifier:r}}catch(e){throw F(e)}}({api:n.api,appId:e});if(!i)throw n.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new R("No authorization URL returned for cross-app auth.");try{let l=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,a=setTimeout((()=>{r(new R("Authorization request timed out after 2 minutes.")),i()}),12e4);function i(){t?.close(),window.removeEventListener("message",s)}let o=setInterval((()=>{t?.closed&&!n&&(i(),clearInterval(o),clearTimeout(a),r(new R("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),r(new R(t.data.error)),i()),t.data.type===hl&&((n=new BroadcastChannel(ul)).onmessage=s))}window.addEventListener("message",s)}))}({url:i,popup:t,provider:a}),c=l.stateCode,d=l.authorizationCode;if(c!==o)throw n.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:o??"",returnedStateCode:c??""}}),new R("Unexpected auth flow. This may be a phishing attempt.",void 0,$.OAUTH_UNEXPECTED);let u=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:a,client:i}){if(!n||!t)throw new R("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new R("User denied confirmation during cross-app auth flow");try{let o=new pl({authorizationCode:n,stateCode:t,codeVerifier:r,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=F(e);if(t.privyErrorCode===$.ACCOUNT_TRANSFER_REQUIRED)throw t;if(t.privyErrorCode)throw new R(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 R("Invalid code during cross-app auth flow.",void 0,$.OAUTH_USER_DENIED);throw new R("Invalid code during cross-app auth flow.",void 0,$.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:s,stateCode:c,authorizationCode:d,action:r,client:n});u&&n.storeProviderAccessToken(e,u);let h=await Be.refreshSessionAndUser();if(!h)throw new R("Unable to update user");return n.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),h}catch(e){throw n.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,r){if(ve.current=e,!qt())return void be(Ql);if("google"===e&&!d.allowOAuthInEmbeddedBrowsers&&_n(window.navigator.userAgent))return void be(Ql);"twitter"===e&&window.opener&&window.opener.postMessage({type:hl},"*"),et.del(da),et.del(ua);let a=new io({provider:e,disableSignup:!!r,withPrivyUi:!0,customOAuthRedirectUrl:d.customOAuthRedirectUrl});t&&a.addCaptchaToken(t),n.startAuthFlow(a);let i=await n.authFlow.getAuthorizationUrl();if(i&&i.url)if("twitter"===e&&C&&(i.url=i.url.replace("x.com","twitter.com")),"chrome-extension:"===window.location.protocol&&no())try{let{privyOAuthCode:e,privyOAuthState:t}=await ao(i.url);be(Ec),a.meta.stateCode=t,a.meta.authorizationCode=e}catch(e){throw console.error("OAuth in chrome extension flow failed:",e),e}else window.location.assign(i.url)},async initLoginWithTelegram(e,t){if(!y)throw new Ye;ve.current="telegram";let r=new En(e,t);n.startAuthFlow(r),ee({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>d.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:d.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):("link"===Ce.current?Fa(ye,"linkAccount","onError",$.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}):"login"===Ce.current?Fa(ye,"login","onError",$.INVALID_CREDENTIALS):"update"===Ce.current&&Fa(ye,"login","onError",$.FAILED_TO_UPDATE_ACCOUNT),t(new R("Telegram auth failed or was canceled by the client"))))):t(new R("Telegram was not initialized")):t(new R("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(n.authFlow instanceof En))throw new R("Must initialize Telegram flow before calling loginWithTelegram");n.authFlow.meta.captchaToken||=e?.captchaToken;let a=await Kc(),i=e?.intent||Ce.current;if("login"===i)try{let e=await n.authenticate();t=e.user,r=e.isNewUser,ve.current="telegram"}catch(e){throw Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}else{if("link"!==i)throw new R("Unknown auth intent");try{t=(await n.link()).user,ve.current="telegram"}catch(e){throw Fa(ye,"linkAccount","onError",e.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}E(t),x(r||!1),v(!0),ee({status:"done"});let o=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,loginAccount:o}},async loginWithOAuth(e){let t,r,a;if(!(n.authFlow instanceof io))throw new R("Must initialize OAuth flow before calling loginWithOAuth");let i=et.get(ha),o=n.authFlow.meta.stateCode;if(i!==o)throw n.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:i??"",returnedStateCode:o??""}}),new R("Unexpected auth flow. This may be a phishing attempt.",void 0,$.OAUTH_UNEXPECTED);if(null!==await n.getAccessToken())try{let r=await n.link();t=r.user,a=r.oAuthTokens,ve.current=e}catch(t){throw Fa(ye,"linkAccount","onError",t.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let i=await n.authenticate();t=i.user,r=i.isNewUser,a=i.oAuthTokens,ve.current=e}catch(t){throw"login"===Ce.current?Fa(ye,"login","onError",t.privyErrorCode||$.UNKNOWN_AUTH_ERROR):"link"===Ce.current&&Fa(ye,"linkAccount","onError",t.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return E(t),x(r||!1),v(!0),a&&t&&Fa(ye,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),a},passkeyAuthState:z,setPasskeyAuthState:B,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new ho({captchaToken:e,setPasskeyAuthState:B,hints:d.passkeys.registration?.hints});n.startAuthFlow(r),Ce.current="login";try{ve.current="passkey",B({status:"generating-challenge"}),await r.initRegisterFlow(t),B({status:"awaiting-passkey"})}catch(e){throw B({status:"error",error:e}),Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!y)throw new Ye;if(!(n.authFlow instanceof ho))throw new R("Must initialize Passkey flow first.");if("passkey"!==ve.current){let e=new R("Must init login with Passkey flow first.");throw B({status:"error",error:e}),e}let r=await Kc();try{ve.current="passkey",B({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await n.authenticate())}catch(e){throw B({status:"error",error:e}),Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}E(e),x(t||!1),v(!0),B({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:a}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new ho({captchaToken:e,setPasskeyAuthState:B,hints:void 0});n.startAuthFlow(r),Ce.current="login";try{ve.current="passkey",B({status:"generating-challenge"}),await r.initAuthenticationFlow(t),B({status:"awaiting-passkey"})}catch(e){throw B({status:"error",error:e}),Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!y)throw new Ye;if(!(n.authFlow instanceof ho))throw new R("Must initialize Passkey flow first.");if(e?.credentialIds&&(n.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==ve.current){let e=new R("Must init login with Passkey flow first.");throw B({status:"error",error:e}),e}let a=await Kc();try{ve.current="passkey",B({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await n.authenticate())}catch(e){throw B({status:"error",error:e}),Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}E(t),x(r||!1),v(!0),B({status:"done"});let i=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,loginAccount:i}},async initLinkWithPasskey(e){let t=new ho({captchaToken:e,hints:d.passkeys.registration?.hints});n.startAuthFlow(t),Ce.current="link",ve.current="passkey",B({status:"generating-challenge"});try{await t.initLinkFlow(),B({status:"awaiting-passkey"})}catch(e){throw Fa(ye,"linkAccount","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),B({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!y)throw new Ye;if(!(n.authFlow instanceof ho))throw new R("Must initialize Passkey flow first.");if("passkey"!==ve.current)throw new R("Must init login with Passkey flow first.");try{ve.current="passkey",({user:e}=await n.link())}catch(e){throw Fa(ye,"linkAccount","onError",e.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return E(e||b||null),B({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!qt())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&&!d.allowOAuthInEmbeddedBrowsers&&_n(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 io({provider:e,withPrivyUi:!1,disableSignup:r??!1,customOAuthRedirectUrl:d.customOAuthRedirectUrl});t&&a.addCaptchaToken(t),X({status:"loading"});let i=await n.startAuthFlow(a).getAuthorizationUrl();if(i?.url)if("chrome-extension:"===window.location.protocol&&no())try{let{privyOAuthCode:e,privyOAuthState:t}=await ao(i.url);a.meta.stateCode=t,a.meta.authorizationCode=e,await this.loginWithHeadlessOAuth(a.meta)}catch(e){throw X({status:"error",error:e}),e}else window.location.assign(i.url)},async loginWithHeadlessOAuth(e){let t,r,a;L(!0),X({status:"loading"}),n.startAuthFlow(new io({...e,customOAuthRedirectUrl:d.customOAuthRedirectUrl}));let i=et.get(ha),o=e.stateCode;if(i!==o)throw n.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:i??"",returnedStateCode:o??""}}),L(!1),new R("Unexpected auth flow. This may be a phishing attempt.",void 0,$.OAUTH_UNEXPECTED);if(null!==await n.getAccessToken())try{({user:t,oAuthTokens:a}=await n.link()),ve.current=e.provider;let r=Fe(t);t&&r&&Fa(ye,"linkAccount","onSuccess",{user:t,linkMethod:ve.current,linkedAccount:r})}catch(t){throw L(!1),Fa(ye,"linkAccount","onError",t.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:a}=await n.authenticate()),ve.current=e.provider;let i=Fe(t);t&&i&&void 0!==r&&Fa(ye,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:ve.current,loginAccount:i})}catch(e){throw L(!1),X({status:"error",error:e}),Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}return E(t),x(r||!1),v(!0),L(!1),X({status:"done"}),a&&t&&Fa(ye,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{let i=new Xi({email:e,captchaToken:t,disableSignup:r});n.startAuthFlow(i);try{ve.current="email",j({status:"sending-code"});let e=await i.sendCodeEmail({withPrivyUi:a});if(e?.ssoRedirectUrl)return void(window.location.href=e.ssoRedirectUrl);j({status:"awaiting-code-input"})}catch(e){throw j({status:"error",error:e}),"login"===Ce.current?Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR):"link"===Ce.current&&Fa(ye,"linkAccount","onError",e.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async({oldAddress:e,newAddress:t,captchaToken:r})=>{let a=new Qi(e,t,r);n.startAuthFlow(a);try{await a.sendCodeEmail({withPrivyUi:!0})}catch(e){throw Fa(ye,"update","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:ve.current}),e}},initUpdatePhone:async(e,t,r)=>{let a=new mo(e,t,r);n.startAuthFlow(a);try{await a.sendSmsCode({withPrivyUi:!0})}catch(e){Fa(ye,"update","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:ve.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{K({status:"sending-code"});let i=new po({phoneNumber:e,captchaToken:t,disableSignup:r});n.startAuthFlow(i);try{ve.current="sms",await i.sendSmsCode({withPrivyUi:a}),K({status:"awaiting-code-input"})}catch(e){throw K({status:"error",error:e}),"login"===Ce.current?Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR):"link"===Ce.current&&Fa(ye,"linkAccount","onError",e.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(n.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(n.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function a(e){n.authFlow instanceof Xi?j(e):n.authFlow instanceof po&&K(e)}if(a({status:"submitting-code"}),!y){let e=new Ye;throw a({status:"error",error:e}),e}if(n.authFlow instanceof Xi)n.authFlow.meta.emailCode=e.trim();else{if(!(n.authFlow instanceof po)){let e=new R("Must initialize a passwordless code flow first");throw a({status:"error",error:e}),e}n.authFlow.meta.smsCode=e.trim()}let i=await Kc();if("link"===Ce.current)try{({user:t}=await n.link())}catch(e){throw a({status:"error",error:e}),Fa(ye,"linkAccount","onError",e.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:ve.current}),e}else if("update"===Ce.current)try{({user:t}=await n.link())}catch(e){throw a({status:"error",error:e}),Fa(ye,"update","onError",e.privyErrorCode||$.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:ve.current}),e}else try{({user:t,isNewUser:r}=await n.authenticate())}catch(e){throw a({status:"error",error:e}),Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}let o=t||b;E(o||null),x(r||!1),v(!0),a({status:"done"});let s=null;return n.authFlow instanceof Xi?s=o?.linkedAccounts.find((({type:e})=>"email"===e))||null:n.authFlow instanceof po&&(s=o?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:o,isNewUser:r||!1,wasAlreadyAuthenticated:!!i,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{Ce.current=f?"link":"login",ve.current="siwe",Z({status:"generating-message"});let a=await n.generateSiweNonce({address:e,captchaToken:r});return Z({status:"awaiting-signature"}),Tn({address:e,chainId:t.replace("eip155:",""),nonce:a})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await n.generateSiweNonce({address:e});return Tn({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r,smartWalletVersion:a})=>{let i;i=await n.linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:a}),E((i=await Be.refreshSessionAndUser()??i)||b||null)},loginWithSiwe:async({message:e,signature:t,captchaToken:r,disableSignup:a,walletClientType:i,connectorType:o})=>{let s,l=null;try{if(b)throw Error("User already authenticated");let c=new Bt(n,void 0,r,a,{message:e,signature:t,walletClientType:i,connectorType:o});n.startAuthFlow(c),ve.current="siwe",Ce.current="login",Z({status:"submitting-signature"});let d=await n.authenticate();if(({user:l,isNewUser:s}=d),!l)throw Error("Authentication failed - no user returned")}catch(e){throw Fa(ye,"login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),Z({status:"error",error:e}),e}return E(l),x(s||!1),v(!0),Z({status:"done"}),Ce.current=null,ve.current=null,{user:l,isNewUser:s||!1}},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:a,connectorType:i})=>{let o;xe("siwe");let s=null;try{Z({status:"submitting-signature"}),o=await n.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:i}),o=await Be.refreshSessionAndUser()??o,Z({status:"done"}),(s=Fe(o)||null)&&Fa(ye,"linkAccount","onSuccess",{user:o,linkMethod:"siwe",linkedAccount:s})}catch(e){throw Fa(ye,"linkAccount","onError",e.privyErrorCode||$.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),Ce.current=null,ve.current=null,Z({status:"error",error:e}),e}let l=o||b;return E(l||null),Ce.current=null,ve.current=null,{user:l,linkedAccount:s}},refreshSessionAndUser:async()=>{let e=await n.getAuthenticatedUser();return v(!!e),E(e),e},walletProxy:te,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>n.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await n.acceptTerms();return E(e),e},getUsdTokenPrice:e=>n.getUsdTokenPrice(e),getUsdPriceForSol:()=>n.getUsdPriceForSol(),getSplTokenMetadata:e=>n.getSplTokenMetadata(e),recoverEmbeddedWallet:async e=>new Promise((async(t,r)=>{if(!b)return void t(!0);let a=e?.address?kn(b,e.address):yr(b)||wn(b).at(0)||An(b).at(0);if(!a||Et(a))return void t(!0);let i=await Kc();if(!i||!te||!a)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));let{entropyId:o,entropyIdVerifier:s}=Mt(b,a);try{await te.connect({accessToken:i,entropyId:o,entropyIdVerifier:s}),t(!0)}catch(e){if(Sr(e)&&"privy"===a.recoveryMethod){let e;n.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:a.address}});try{e=await te.recover({entropyId:o,entropyIdVerifier:s,accessToken:i})}catch(e){return void r(e)}e.entropyId||r(Error("Unable to recover wallet")),n.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:a.address}}),t(!0)}else Sr(e)&&"privy"!==a.recoveryMethod&&"privy-v2"!==a.recoveryMethod?(oe({recoverWallet:{entropyId:o,entropyIdVerifier:s,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:a.recoveryMethod,action:"recover",shouldCreateEth:!1,shouldCreateSol:!1}}),be(bn(a.recoveryMethod))):r(e)}})),setReadyToTrue:e=>{g(!0),se?.(e)},updateWallets:()=>Oe(),fundWallet:async(e,t)=>{oe({funding:yi({address:e,appConfig:d,fundWalletConfig:t,methodScreen:kr})}),be(kr)},openModal:be,requestFarcasterSignerStatus:async e=>{let t=await Kc(),r=b?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!te||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!b?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let a=await n.requestFarcasterSignerStatus(e);return"approved"===a.status&&E(await n.getAuthenticatedUser()||b||null),a},connectCoinbaseSmartWallet:async()=>{d.externalWallets.coinbaseWallet.config.preference={...d.externalWallets.coinbaseWallet.config.preference,options:"smartWalletOnly"};let e=n.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||n.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Se(e);await Ie("coinbase_wallet","coinbase_smart_wallet")},connectBaseAccount:async()=>{let e=n.connectors?.findWalletConnector("base_account","base_account");if(e)return Se(e);await Ie("base_account","base_account")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:i,telegramWebAppData:o,farcasterEmbeddedAddress:s,oAuthUserInfo:l})=>{let c=await n.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:i,telegramWebAppData:o,farcasterEmbeddedAddress:s,oAuthUserInfo:l});return E(c),c},inProgressAuthFlowRef:Ce,inProgressLoginOrLinkMethodRef:ve};Vc=Be.recoverEmbeddedWallet,Be.recoverEmbeddedWallet;let He=o((()=>({wallets:I,ready:de&&ge})),[I,de,ge]),je=n.authFlow instanceof En,Ve=!d.headless&&d.captchaEnabled&&!f&&(y||je);/*#__PURE__*/return t(Dc.Provider,{value:!0,children:/*#__PURE__*/t(cr.Provider,{value:ze,children:/*#__PURE__*/t(La.Provider,{value:ye,children:/*#__PURE__*/t(Pn.Provider,{value:He,children:/*#__PURE__*/t(Wn,{...d,children:/*#__PURE__*/r(Ze.Provider,{value:Be,children:[/*#__PURE__*/t(xn,{children:/*#__PURE__*/r(Nn,{data:ae,setModalData:oe,setInitialScreen:O,initialScreen:N,authenticated:f,open:h,children:[e.children,/*#__PURE__*/t(Lc,{customAuth:d.customAuth}),Ve&&/*#__PURE__*/t(Xo,{delayedExecution:!1}),/*#__PURE__*/t(Xs,{}),/*#__PURE__*/t(Rl,{disabled:d.embeddedWallets.disableAutomaticMigration}),/*#__PURE__*/t(Fs,{palette:d.appearance.palette||{}}),!d.render.standalone&&/*#__PURE__*/t(Gs,{open:h})]})}),/*#__PURE__*/t(sl,{appId:e.appId,appClientId:e.clientId,clientAnalyticsId:n.clientAnalyticsId,origin:n.apiUrl,mfaMethods:b?.mfaMethods,mfaPromise:me,mfaSubmitPromise:we,onLoad:re,onLoadFailed:()=>null}),d.loginConfig.telegramAuthConfiguration&&
|
|
6
|
-
/*#__PURE__*/t(pr,{$if:!0,children:/*#__PURE__*/t(Js,{scriptHost:e.apiUrl||_a,botUsername:d.loginConfig.telegramAuthConfiguration.botName})})]})})})})})})};const td=()=>{let{user:e}=sr(),{walletProxy:t}=Ve();return{recover:p((async r=>{if(!t)throw Error("Wallet proxy is not ready");let n=await Kc();if(!e||!n)throw new R("User must be logged in before attempting to modify the recovery method.");let{entropyId:a,entropyIdVerifier:i}=Mt(e);try{await t.recover({entropyId:a,entropyIdVerifier:i,accessToken:n,...r})}catch{throw new R("Unable to recover wallets")}}),[t,e])}},rd=()=>{let{client:e,setAuthenticated:t,setUser:r}=Ve();return o((()=>({init:async()=>{if(!e)throw new R("Must initialize Privy client first.");let t=new zi;return e.startAuthFlow(t),await t.init()},login:async({fid:n,message:a,signature:i})=>{if(!e)throw new R("Must initialize Privy client first.");if(!(e.authFlow instanceof zi))throw new R("Must initialize Farcaster Mini App flow first.");e.authFlow.setAuthData({message:a,signature:i,fid:n});let{user:o}=await e.authenticate();if(!o)throw new R("Failed to login with Farcaster V2");return r(o),t(!0),{user:o}}})),[e,r,t])},nd=()=>o((()=>({getAccessTokenForProvider:({appId:e})=>{try{let t=et.get(fa(e));if("string"!=typeof t)return{token:null};{let r=new wo(t);return r.isExpired()?(et.del(fa(e)),{token:null}):{token:r.value}}}catch(e){return console.error(e),{token:null}}}})),[]),ad=e=>{Sa("login",e);let t=jt(),r=Wa(),{ready:n,user:a}=sr(),{initLoginWithHeadlessOAuth:i,loginWithHeadlessOAuth:o,oAuthState:l,setOAuthState:c,isHeadlessOAuthLoading:d}=Ve(),u=p((async e=>{try{if(t.enabled&&"success"!==t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);return await i(e.provider,t.token,e.disableSignup)}catch(e){throw c({status:"error",error:e}),e}}),[i,t]),h=p((async()=>{let e=uo();try{if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");let t=e.provider;if(wt(t)){if(a&&a.linkedAccounts.some((e=>e.type===t)))return console.warn("User is already logged in with this OAuth provider"),a}else if(a&&t in a&&a[t])return console.warn("User is already logged in with this OAuth provider"),a;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{tn()}}),[o]);return s((()=>{let e=uo();n&&r&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&h().catch((()=>{}))}),[n,r]),{initOAuth:u,loading:d,state:l}},id=e=>{let t=jt(),{emailOtpState:r,setEmailOtpState:n,initLoginWithEmail:a,loginWithCode:i}=Ve();return{sendCode:p((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 Qn(t.error,null,$.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({email:r,captchaToken:e,disableSignup:i,withPrivyUi:!1})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:p((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);let{user:n,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:s}=await i(r);e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"email",loginAccount:s})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR),r}}),[i,t.status]),state:r}},od=e=>{let t=jt(),{initSignupWithPasskey:r,signupWithPasskey:n,passkeyAuthState:a,setPasskeyAuthState:i}=Ve();return{signupWithPasskey:p((async()=>{try{let a;if(t.enabled&&"error"===t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),a=await t.waitForResult()),await r({captchaToken:a,withPrivyUi:!1});let{user:i,isNewUser:o,wasAlreadyAuthenticated:s,loginAccount:l}=await n();e?.onComplete?.({user:i,isNewUser:o,wasAlreadyAuthenticated:s,loginMethod:"passkey",loginAccount:l})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||$.UNKNOWN_AUTH_ERROR),t}}),[n,t.status]),state:a}},sd=e=>{let t=jt(),{initLoginWithPasskey:r,loginWithPasskey:n,passkeyAuthState:a,setPasskeyAuthState:i}=Ve();return{loginWithPasskey:p((async a=>{try{let i;if(t.enabled&&"error"===t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult()),await r({captchaToken:i,withPrivyUi:!1});let{user:o,isNewUser:s,wasAlreadyAuthenticated:l,loginAccount:c}=await n(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||$.UNKNOWN_AUTH_ERROR),a}}),[n,t.status]),state:a}},ld=e=>{let{initLinkWithPasskey:t,linkWithPasskey:r,passkeyAuthState:n,setPasskeyAuthState:a}=Ve();return{linkWithPasskey:p((async()=>{try{await t();let n=await r();if(!n)throw Error("Error, user not found");let a=n.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:n,linkMethod:"passkey",linkedAccount:a})}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[r]),state:n}},cd=e=>{let t=jt(),{smsOtpState:r,setSmsOtpState:n,initLoginWithSms:a,loginWithCode:i}=Ve();return{sendCode:p((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 Qn(t.error,null,$.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({phoneNumber:r,captchaToken:e,disableSignup:i,withPrivyUi:!1})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:p((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);let{user:n,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:s}=await i(r);e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"sms",loginAccount:s})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR),r}}),[i,t.status]),state:r}},dd=e=>{let{connectOrCreateWallet:t}=sr();return Sa("connectOrCreateWallet",e),{connectOrCreateWallet:t}},ud=e=>{let t=jt(),{siweState:r,setSiweState:n,linkWithSiwe:a,generateSiweMessage:i}=Ve();return{generateSiweMessage:p((async({address:t,chainId:r})=>{try{if(!t||!r)throw Error("wallet address and chainId required to generate nonce");return await i({address:t,chainId:r}).then((e=>e))}catch(t){throw n({status:"error",error:t}),e?.onError?.(t.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[i]),linkWithSiwe:p((async({signature:r,message:i,chainId:o,walletClientType:s,connectorType:l})=>{try{if(t.enabled&&"success"!==t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);let{user:n,linkedAccount:c}=await a({message:i,signature:r,chainId:o,walletClientType:s,connectorType:l});c&&e?.onSuccess?.({user:n,linkMethod:"siwe",linkedAccount:c})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[a,t.status]),state:r}},hd=e=>{let t=jt(),{siweState:r,setSiweState:n,client:a,generateSiweMessage:i,loginWithSiwe:o}=Ve();return{generateSiweNonce:p((async r=>{try{let e;if(t.enabled&&"error"===t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),n({status:"generating-message"});let i=await a.generateSiweNonce({address:r?.address,captchaToken:e});return n({status:"awaiting-signature"}),i}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR),r}}),[a,t]),generateSiweMessage:p((async({address:r,chainId:a})=>{try{let e;if(t.enabled&&"error"===t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await i({address:r,chainId:a,captchaToken:e})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR),r}}),[i,t]),loginWithSiwe:p((async({message:r,signature:a,disableSignup:i,walletClientType:s,connectorType:l})=>{try{let n;if(t.enabled&&"error"===t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),n=await t.waitForResult());let{user:c,isNewUser:d}=await o({message:r,signature:a,captchaToken:n,disableSignup:i,walletClientType:s,connectorType:l});return e?.onComplete?.({user:c,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"siwe",loginAccount:null}),c}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR),r}}),[o,t.status]),state:r}},pd=()=>{let e=jt(),{client:t,setAuthenticated:r,setUser:n,setIsNewUser:a}=Ve(),{authenticated:i}=wi();return{generateSiwsMessage:p((async({address:r})=>{let n;if(e.enabled&&"error"===e.status)throw new Qn(e.error,null,$.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let a=await t.generateSiwsNonce({address:r,captchaToken:n});return ea({address:r,nonce:a})}),[e,t]),loginWithSiws:p((async({message:o,signature:s,disableSignup:l,walletClientType:c,connectorType:d})=>{if(i)throw Error("User already authenticated");if(e.enabled&&"error"===e.status)throw new Qn(e.error,null,$.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),await e.waitForResult());let{user:u,isNewUser:h}=await t.authenticateWithSiws({message:o,signature:s,walletClientType:c,connectorType:d,mode:l?"no-signup":"login-or-sign-up",messageType:"plain"});if(!u)throw Error("Authentication failed - no user returned");return n(u),a(h||!1),r(!0),u}),[i,e,t,r,n,a])}},md=()=>{let e=jt(),{client:t,setUser:r,refreshSessionAndUser:n}=Ve(),{authenticated:a}=wi();return{generateSiwsMessage:p((async({address:r})=>{let n;if(e.enabled&&"error"===e.status)throw new Qn(e.error,null,$.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let a=await t.generateSiwsNonce({address:r,captchaToken:n});return ea({address:r,nonce:a})}),[e,t]),linkWithSiws:p((async({signature:i,message:o,walletClientType:s,connectorType:l})=>{if(!a)throw Error("User must be authenticated before linking");if(e.enabled&&"error"===e.status)throw new Qn(e.error,null,$.CAPTCHA_FAILURE);let c=await t.linkWithSiws({message:o,signature:i,walletClientType:s,connectorType:l,messageType:"plain"}),d=(e=>{if(!e)return;let t=e.linkedAccounts;return t&&0!==t.length?t[t.length-1]:void 0})(c=await n()??c)||null;return r(c||null),{user:c,linkedAccount:d}}),[a,e,t,n,r])}};function wd(){let{signTransaction:e}=h(cr);return{signTransaction:e}}function yd(e){let{linkEmail:t,linkPhone:r,linkWallet:n,linkGoogle:a,linkApple:i,linkTwitter:o,linkTwitch:s,linkDiscord:l,linkGithub:c,linkLinkedIn:d,linkTiktok:u,linkLine:p,linkSpotify:m,linkInstagram:w,linkTelegram:y,linkFarcaster:g,linkPasskey:f}=h(cr);return Sa("linkAccount",e),{linkEmail:t,linkPhone:r,linkWallet:n,linkGoogle:a,linkApple:i,linkTwitter:o,linkTwitch:s,linkDiscord:l,linkGithub:c,linkLinkedIn:d,linkTiktok:u,linkLine:p,linkSpotify:m,linkInstagram:w,linkFarcaster:g,linkTelegram:y,linkPasskey:f}}function gd(e){let{updateEmail:t,updatePhone:r}=h(cr);return Sa("update",e),{updateEmail:t,updatePhone:r}}const fd=e=>{let{user:t}=sr(),{loginWithCode:r,emailOtpState:n,setEmailOtpState:a,client:i,inProgressAuthFlowRef:o,inProgressLoginOrLinkMethodRef:s}=Ve();return{state:n,sendCode:p((async({newEmailAddress:r})=>{try{if(!t?.email)throw Error("User is required to have an email address to update it.");let e=new Qi(t.email.address,r);i.startAuthFlow(e),await e.sendCodeEmail({withPrivyUi:!1})}catch(r){a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[t?.email]),verifyCode:p((async({code:n})=>{try{if(!t?.email)throw Error("User is required to have an email address to update it.");o.current="update",s.current="email";let{user:a,linkedAccount:i}=await r(n);return e?.onSuccess?.({user:a,updateMethod:"email",updatedAccount:i}),{user:a}}catch(n){a({status:"error",error:n}),e?.onError?.(n.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[t?.email])}},vd=()=>{let{connectCoinbaseSmartWallet:e}=Ve();return{connectCoinbaseSmartWallet:e}},Cd=()=>{let{connectBaseAccount:e}=Ve();return{connectBaseAccount:e}},kd=()=>{let{baseAccountSdk:e}=Ve();return{baseAccountSdk:e}},Ad=()=>{let{setModalData:e}=lr(),{openModal:t,privy:r,closePrivyModal:n}=Ve(),{user:a}=sr();return o((()=>({verify:async({standalone:i=!0}={standalone:!0})=>new Promise(((o,s)=>a?0===a.mfaMethods.length?o():(e((e=>({...e,mfaVerify:{onSuccess:async()=>{i?await n({shouldCallAuthOnSuccess:!1,isSuccess:!0}):Ms.setState({inProgressMfaFlow:void 0}),o()},onFailure:async e=>{i?await n({shouldCallAuthOnSuccess:!1,isSuccess:!1}):Ms.setState({inProgressMfaFlow:void 0}),s(e)},sendSmsCode:async()=>{throw Error("Not enabled")},verifySmsCode:async()=>{throw Error("Not enabled")},verifyTotpCode:async e=>{await r.fetchPrivyRoute(ji,{body:{code:e}})},generateOptions:async()=>Lo((await r.fetchPrivyRoute(Hi,{body:{}})).options),verifyPasskey:async e=>{let t=await import("@simplewebauthn/browser"),n=await t.startAuthentication({optionsJSON:e});await r.fetchPrivyRoute(Bi,{body:{authenticator_response:Ml(n)}})}}}))),void(i?t(Ns):Ms.setState({inProgressMfaFlow:"auth"}))):s(Error("Must be logged in to verify MFA"))))})),[r,e,t,n])},bd={component:()=>{let{user:e,ready:a}=sr(),{data:i,onUserCloseViaDialogOrKeybindRef:o}=lr(),s=Ua(),[c,d]=l(null),[u,h]=l(null),[p,m]=l(null),[w,y]=l(!1),[g,f]=l(!1),[v,C]=l(),k=async()=>{v?A(v):e?await b({user:e}):A(Error("Must be logged in to manage MFA")),setTimeout((()=>{d(null),h(null)}),500)};if(o.current=k,!i?.mfaEnroll)throw Error("Missing modal data for MFA enrollment screen.");let{onFailure:A,onSuccess:b,onBack:T,mfaMethods:_,verify:E,generateTotpSecret:I,enrollTotp:S,unenrollTotp:U,enrollPasskey:P}=i.mfaEnroll,W=e?.mfaMethods.includes("sms"),x=e?.mfaMethods.includes("totp"),N=e?.mfaMethods.includes("passkey"),O=!!e?.phone,R=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function M(){d(null),h(null),C(void 0)}async function F(e=R){try{C(void 0),f(!0);let t=await P(e);return await b({user:t})}catch(e){C(e)}finally{f(!1),y(!1)}}if(!a||!e||!s)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{onClose:k,backFn:T},"header"),/*#__PURE__*/t(es,{children:/*#__PURE__*/t(sc,{})}),/*#__PURE__*/t(ns,{children:/*#__PURE__*/t(ur,{})}),/*#__PURE__*/t(Gt,{})]});if("sms"===c)return null;if("totp"===c)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{backFn:M,onClose:k},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Wi,{})}),/*#__PURE__*/t(ts,{children:"Remove authenticator app verification?"}),/*#__PURE__*/r(rs,{children:["MFA adds an extra layer of security to your ",s?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/t(ss,{children:/*#__PURE__*/t(rr,{$warn:!0,onClick:async function(){try{C(void 0),f(!0);let e=await U();return await b({user:e})}catch(e){C(e)}finally{f(!1),d(null)}},loading:g,children:"Remove"})}),/*#__PURE__*/t(Gt,{})]});if("passkey"===c){let e=i.mfaEnroll.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(Qt,{backFn:M,onClose:k},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Wi,{})}),/*#__PURE__*/t(ts,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/t(rs,{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(ss,{children:/*#__PURE__*/t(rr,{$warn:!0,onClick:async function(){try{C(void 0),f(!0);let e=await P([]);return await b({user:e})}catch(e){C(e)}finally{f(!1),d(null)}},loading:g,children:"Remove"})}),/*#__PURE__*/t(Gt,{})]})}return 0!==_.length||W||x||N?"sms"===u?null:"totp"===u&&p?/*#__PURE__*/t(bc,{onClose:k,onReset:M,submitEnrollmentWithTotp:e=>async function(e){try{C(void 0),f(!0);let t=await S(e);return await b({user:t})}catch(e){C(e)}finally{f(!1),d(null)}}(e.mfaCode),error:v,totpInfo:{...p,appName:s?.name||"Privy"}}):"passkey"===u?/*#__PURE__*/t(pc,{onReset:M,onClose:k,submitEnrollmentWithPasskey:F}):/*#__PURE__*/t(cc,{showIntro:!0,userMfaMethods:e.mfaMethods,appMfaMethods:s.mfa.methods,userHasAuthSms:O,backFn:T,handleSelectMethod:async function(e){C(void 0);try{await E()}catch(e){return void C(e)}return"totp"===e?(h(e),m(null),void I().then((({totpSecret:e,totpAuthUrl:t})=>{m({authUrl:t,secret:e})})).catch((()=>{m(null),M()}))):"passkey"===e&&1===R.length?await F():void h(e)},isTotpLoading:"totp"===u&&!p,isPasskeyLoading:w,error:v,onClose:k,setRemovingMfaMethod:async function(e){C(void 0);try{await E()}catch(e){return void C(e)}d(e)}}):/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(Qt,{onClose:k,backFn:T},"header"),/*#__PURE__*/t(ys,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Qa,{})}),/*#__PURE__*/t(ts,{children:"Add more security"}),/*#__PURE__*/r(rs,{children:[s?.name," does not have any verification methods enabled."]}),/*#__PURE__*/t(ss,{children:/*#__PURE__*/t(rr,{onClick:k,children:"Close"})}),/*#__PURE__*/t(Gt,{})]})}},Td=()=>{let e=Ua(),{setModalData:t}=lr(),{verify:r}=Ad(),{openModal:n,privy:a,closePrivyModal:i,refreshSessionAndUser:s,setUser:l}=Ve();return o((()=>({enroll:async o=>new Promise(((c,d)=>{t({mfaEnroll:{onSuccess:async e=>{await i({shouldCallAuthOnSuccess:!1,isSuccess:!0}),c(e)},onFailure:async e=>{await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}),d(e)},onBack:o?.onBack?async()=>{await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}),d(Error("User canceled MFA enrollment flow.")),o.onBack?.()}:void 0,verify:()=>r({standalone:!1}),shouldUnlinkOnUnenrollMfa:!0,mfaMethods:e.mfa.methods,sendSmsCode:async()=>{throw Error("Not enabled")},enrollSms:async()=>{throw Error("Not enabled")},unenrollSms:async()=>{throw Error("Not enabled")},generateTotpSecret:async()=>await a.fetchPrivyRoute(Gi,{body:{}}),enrollTotp:async e=>{await a.fetchPrivyRoute(Ki,{body:{code:e}});let t=await s();return l(t),t},unenrollTotp:async()=>{await a.fetchPrivyRoute($i,{body:{}});let e=await s();return l(e),e},enrollPasskey:async e=>{await a.fetchPrivyRoute(Vi,{body:{credential_ids:e,remove_for_login:!0}});let t=await s();return l(t),t}}}),n(bd)}))})),[a,t,n,i])},_d=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:a,signTransactionWithCrossAppWallet:i}=sr();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:n,sendTransaction:a,signTransaction:i}};function Ed(e){let{sendTransaction:t}=h(cr);return Sa("sendTransaction",e),{sendTransaction:t}}function Id(){let e=Ua(),t=xa(),{client:r,setUser:n,setAuthenticated:a,setIsNewUser:i,initializeWalletProxy:o}=Ve(),{create:s}=fi();return{createGuestAccount:async()=>{if(!e.id||!r)throw Error("SDK not yet ready");r.startAuthFlow(new qo(e.id));try{let l=await r.authenticate(),c=l.user,d=l.isNewUser??!1;if(!c)throw new R("Unable to authenticate guest account");let u=await r.getAccessToken(),h=await o(Da);if(u&&h)try{let t=yn(c,e.embeddedWallets.ethereum.createOnLogin),r=gn(c,e.embeddedWallets.solana.createOnLogin);t&&r?(c=(await s({chainType:"ethereum",latestUser:c})).user,c=(await s({chainType:"solana",latestUser:c})).user):r?c=(await s({chainType:"solana",latestUser:c})).user:t?c=(await s({chainType:"ethereum",latestUser:c})).user:n(c)}catch(e){n(c),console.warn("Unable to create embedded wallet for guest account")}return i(d),a(!0),t("login","onComplete",{user:c,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),c}catch(e){throw t("login","onError",e.privyErrorCode||$.UNKNOWN_AUTH_ERROR),e}}}}function Sd(e){let{setWalletRecovery:t}=h(cr);return Sa("setWalletRecovery",e),{setWalletRecovery:t}}function Ud(e){let{signMessage:t}=h(cr);return Sa("signMessage",e),{signMessage:t}}const Pd=()=>{let{ready:e,wallets:t}=Yt(),{user:r}=sr(),{rpcConfig:n,chains:a,appId:i}=Ve();return{signAuthorization:p((async(o,s)=>{let l;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??pn(r)?.address??ni,d=t.find((e=>ai(e.address)===ai(c)));if(!d)throw Error("Signing wallet not found.");let u=o.chainId??Number(d.chainId.split(":")[1]);if(0===u)l={chainId:0,address:o.contractAddress,nonce:o.nonce??0};else{let e=a.find((e=>e.id===u));if(!e)throw Error("Error, chain not configured in PrivyProvider config");let t=ii({account:c,chain:e,transport:oi(ta(e,n,i))});l=await t.prepareAuthorization({...o})}let h=await d.getEthereumProvider(),p=await h.request({method:"secp256k1_sign",params:[E(l)]});return{...l,...si(p)}}),[e,t,r,a])}};function Wd(e){let{signTypedData:t}=h(cr);return Sa("signTypedData",e),{signTypedData:t}}const xd=()=>{let{isModalOpen:e}=h(cr);return{isOpen:e}};function Nd(e){let{getAccessToken:t}=h(cr);return Sa("accessToken",e),{getAccessToken:t}}function Od(e){let{authenticated:t,user:r}=sr(),{initLoginWithOAuth:n}=Ve(),a=xa();return Sa("oAuthAuthorization",e),{reauthorize:e=>Rd(t,r,n,a,e.provider)}}let Rd=async(e,t,r,n,a)=>{if(!e)throw n("linkAccount","onError",$.MUST_BE_AUTHENTICATED,{linkMethod:a}),new R("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(a))))throw new R(`OAuth account of type ${a} not linked to the account.`);await r(a)};function Md(e){let{client:t}=Ve(),[r,n]=l({status:"initial"});return{linkWithCustomJwt:p((async r=>{try{n({status:"initial"}),t.startAuthFlow(new Do(r)),n({status:"loading"});let{user:a}=await t.link();if(!a)throw Error("Error, user not found");let i=a.linkedAccounts.filter((e=>"custom_auth"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime())).at(0);return n({status:"done"}),e?.onSuccess?.({user:a,linkMethod:"custom",linkedAccount:i}),{user:a}}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||$.UNKNOWN_AUTH_ERROR,{linkMethod:"custom"}),r}}),[t.startAuthFlow,t.link]),state:r}}const Fd=e=>{let t=Fc((e=>e.jwtAuthFlowState));return Sa("customAuth",e),{status:t}};function Ld({isAuthenticated:e,isLoading:t,...r}){let n=u();s((()=>{t||n.current?.()}),[e,t]);let a=p((e=>(n.current=e,()=>{n.current=void 0})),[]);return Mc({...r,subscribe:a})}function Dd(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=sr();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}}const qd=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=Ve();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},zd=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=(()=>{let{user:e}=sr(),t=Ve(),{signWithUserSigner:r}=Yi(),n=async({wallet:n,additional_signers:a})=>{let i=await t.client.getAccessToken();if(!e||!i)throw new R("User must be authenticated and have an embedded wallet to delegate actions.");if(!n.id)throw new R("Wallet to add signers to must have ID on server");if(!t.walletProxy)throw new R("Wallet proxy not initialized.");await x(t.privy,{wallet_id:n.id},r,{additional_signers:a})};return{addSessionSignersInternal:async({address:r,signers:a})=>{let i=await t.client.getAccessToken();if(!e||!i)throw new R("User must be authenticated and have an embedded wallet to add a session signer.");let o=t.walletProxy??await t.initializeWalletProxy(15e3);if(!o)throw new R("Wallet proxy not initialized.");let s=kn(e,r);if(!s)throw new R("Address to add signers too is not associated with current user.");if(Et(s)){if(0===a.length)throw new R("Must specify at least one signer to add.");let e=[...(await W(t.privy,{wallet_id:s.id})).additional_signers,...ra(a)];await n({wallet:s,additional_signers:e})}else{if(s.delegated)return{user:e};if(a.length>0)throw new R("Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let n=ll({address:r,user:e}),l=cl({address:r,user:e});await t.recoverEmbeddedWallet({address:r}),await o.createDelegatedAction({accessToken:i,rootWallet:l,delegatedWallets:[n]})}let l=await t.refreshSessionAndUser();if(!l)throw Error("Could not refresh user");return{user:l}},removeSessionSignersInternal:async({address:r})=>{let a=await t.client.getAccessToken();if(!e||!a)throw new R("User must be authenticated and have an embedded wallet to delegate actions.");if(!(t.walletProxy??await t.initializeWalletProxy(15e3)))throw new R("Wallet proxy not initialized.");let i=kn(e,r);if(!i)throw new R("Address to remove signers from is not associated with current user.");Et(i)?await n({wallet:i,additional_signers:[]}):await t.client.revokeDelegatedWallet();let o=await t.refreshSessionAndUser();if(!o)throw Error("Could not refresh user");return{user:o}}}})();return{addSessionSigners:async({address:t,signers:r})=>e({address:t,signers:r}),removeSessionSigners:async({address:e})=>t({address:e})}},Bd=()=>{let{signWithUserSigner:e}=Yi();return o((()=>({async generateAuthorizationSignature(t){let{targetAppId:r,...n}=t,{signature:a}=await N((async({message:t})=>e({message:t,targetAppId:r})),n);return{signature:a}}})),[e])},Hd=()=>{let{setUser:e,client:t}=h(Ze),{user:r}=h(cr);return{user:r,refreshUser:p((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}},jd=e=>{let t=jt(),{initLoginWithTelegram:r,loginWithTelegram:n,telegramAuthState:a,setTelegramAuthState:i}=Ve();return{login:p((async a=>{try{if(t.enabled&&"success"!==t.status)throw new Qn(t.error,null,$.CAPTCHA_FAILURE);await r(t.token,a?.disableSignup);let{user:i,isNewUser:o,loginAccount:s,wasAlreadyAuthenticated:l}=await n({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||$.UNKNOWN_AUTH_ERROR),a}}),[r,n,t]),state:a}},Vd=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=Ve();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}},$d=async({wallet:e})=>{let t=await e.getEthereumProvider();return Zi({address:e.address,sign:async({hash:r})=>{if("privy"!==e.walletClientType)throw new O({error:"Unprefixed signing is not supported by external wallets.",code:"unsupported_wallet_type"});return await t.request({method:"secp256k1_sign",params:[r]})},signMessage:async({message:r})=>await t.request({method:"personal_sign",params:[r,e.address]}),signTypedData:async r=>await t.request({method:"eth_signTypedData_v4",params:[e.address,r]}),signTransaction:async e=>await t.request({method:"eth_signTransaction",params:[e]})})};export{Xo as Captcha,xo as ConnectorManager,gt as EthereumWalletConnector,Gs as LoginModal,Zo as PrivyClient,Qc as PrivyProvider,pa as VERSION,ar as errorIndicatesMaxMfaRetries,or as errorIndicatesMfaTimeout,ir as errorIndicatesMfaVerificationFailed,$c as getAccessToken,$d as toViemAccount,Ad as useAuthMfa,Td as useAuthMfaEnrollment,Bd as useAuthorizationSignature,kd as useBaseAccountSdk,Cd as useConnectBaseAccount,vd as useConnectCoinbaseSmartWallet,dd as useConnectOrCreateWallet,_d as useCrossAppAccounts,Fd as useCustomAuth,qd as useDelegatedActions,Dd as useFarcasterSigner,nd as useGetAccessTokenForProvider,Id as useGuestAccounts,Vd as useHeadlessDelegatedActions,Ho as useIdentityToken,yd as useLinkAccount,Md as useLinkJwtAccount,ld as useLinkWithPasskey,ud as useLinkWithSiwe,md as useLinkWithSiws,id as useLoginWithEmail,rd as useLoginWithFarcasterV2,ad as useLoginWithOAuth,sd as useLoginWithPasskey,hd as useLoginWithSiwe,pd as useLoginWithSiws,cd as useLoginWithSms,jd as useLoginWithTelegram,Ga as useLogout,Os as useMfa,oc as useMfaEnrollment,Ol as useMigrateWallets,xd as useModalStatus,Od as useOAuthTokens,wi as usePrivy,td as useRecoverEmbeddedWallet,Qo as useRegisterMfaListener,Ed as useSendTransaction,zd as useSessionSigners,Sd as useSetWalletRecovery,Pd as useSign7702Authorization,Ud as useSignMessage,wd as useSignTransaction,Wd as useSignTypedData,od as useSignupWithPasskey,Ld as useSubscribeToJwtAuthWithFlag,Mc as useSyncJwtBasedAuthState,Nd as useToken,gd as useUpdateAccount,fd as useUpdateEmail,Hd as useUser,Yt as useWallets};
|
|
1
|
+
import{jsx as t,jsxs as r,Fragment as n}from"react/jsx-runtime";import{createStore as a}from"mipd";import i,{useMemo as o,useEffect as s,useState as l,useRef as u,useContext as h,useCallback as p,forwardRef as m,createContext as w}from"react";import{isMobile as y,isIOS as f,isSafari as v,isAndroid as C}from"react-device-detect";import{toHex as k,isAddress as A,getAddress as T,isHex as _,hashAuthorization as E}from"viem/utils";import I,{DEFAULT_SUPPORTED_CHAIN_IDS as S,rpc as U,lastFourDigits as P,PrivyClientError as x,getWallet as W,updateWallet as N,generateAuthorizationSignature as R}from"@privy-io/js-sdk-core";export{DEFAULT_SUPPORTED_CHAINS as SUPPORTED_CHAINS,addPrivyRpcToChain,addRpcUrlOverrideToChain}from"@privy-io/js-sdk-core";import{trigger as O}from"@privy-io/popup";import{P as M,u as F,f as L,p as D,a as q,b as z,c as B,d as H,e as j,g as V,o as $,h as K,i as Y,j as G,k as Z,l as J,m as X,n as Q,q as ee,r as te,s as re,t as ne,v as ae,w as ie,x as oe,y as se,z as le,A as ce,B as de,C as ue,D as he,E as pe,F as me,G as we,H as ye,I as ge,J as fe,K as ve,L as Ce,M as ke,N as Ae,O as be,Q as Te,R as _e,S as Ee,T as Ie,U as Se,V as Ue,W as Pe,X as xe,Y as We,Z as Ne,_ as Re,$ as Oe,a0 as Me,a1 as Fe,a2 as Le,a3 as De,a4 as qe,a5 as ze,a6 as Be,a7 as He,a8 as je,a9 as Ve,aa as $e,ab as Ke,ac as Ye,ad as Ge,ae as Ze,af as Je}from"./internal-context-eGSwROSk.mjs";import{o as Xe,R as Qe,g as et,p as tt,c as rt,a as nt,d as at,A as it,T as ot,L as st,b as lt,I as ct,S as dt,e as ut,f as ht,G as pt,D as mt,h as wt,i as yt,j as gt,E as ft,B as vt,k as Ct,P as kt,C as At,t as bt,l as Tt,m as _t,n as Et,q as It,r as St,s as Ut,M as Pt,u as xt,v as Wt,w as Nt,x as Rt,y as Ot,z as Mt,F as Ft,H as Lt,J as Dt,W as qt,K as zt,N as Bt,O as Ht,Q as jt,U as Vt,V as $t,X as Kt,Y as Yt,Z as Gt,_ as Zt,$ as Jt,a0 as Xt,a1 as Qt,a2 as er,a3 as tr,a4 as rr,a5 as nr,a6 as ar,a7 as ir,a8 as or,a9 as sr,aa as lr,ab as cr,ac as dr,ad as ur,ae as hr,af as pr,ag as mr,ah as wr,ai as yr,aj as gr,ak as fr,al as vr,am as Cr,an as kr,ao as Ar,ap as br,aq as Tr,ar as _r,as as Er,at as Ir,au as Sr,av as Ur,aw as Pr,ax as xr,ay as Wr,az as Nr,aA as Rr,aB as Or,aC as Mr,aD as Fr,aE as Lr,aF as Dr,aG as qr,aH as zr,aI as Br,aJ as Hr,aK as jr,aL as Vr,aM as $r,aN as Kr,aO as Yr,aP as Gr,aQ as Zr,aR as Jr,aS as Xr,aT as Qr,aU as en,aV as tn,aW as rn,aX as nn,aY as an,aZ as on,a_ as sn,a$ as ln,b0 as cn,b1 as dn,b2 as un,b3 as hn,b4 as pn,b5 as mn,b6 as wn,b7 as yn,b8 as gn,b9 as fn,ba as vn,bb as Cn,bc as kn,bd as An,be as bn,bf as Tn,bg as _n,bh as En,bi as In,bj as Sn,bk as Un,bl as Pn,bm as xn,bn as Wn,bo as Nn,bp as Rn,bq as On,br as Mn,bs as Fn,bt as Ln,bu as Dn,bv as qn,bw as zn,bx as Bn,by as Hn,bz as jn,bA as Vn,bB as $n,bC as Kn,bD as Yn,bE as Gn,bF as Zn,bG as Jn,bH as Xn,bI as Qn,bJ as ea,bK as ta,bL as ra,bM as na,bN as aa,bO as ia}from"./EmbeddedWalletConnectingScreen-D50stmJi.mjs";export{bP as WalletConnector}from"./EmbeddedWalletConnectingScreen-D50stmJi.mjs";import{v4 as oa}from"uuid";import*as sa from"jose";import{base64url as la}from"jose";import ca from"eventemitter3";import{createCoinbaseWalletSDK as da}from"@coinbase/wallet-sdk";import{toViemTransactionSerializable as ua}from"@privy-io/ethereum";import{C as ha,H as pa,O as ma,S as wa,V as ya,g as ga,a as fa,P as va,R as Ca,b as ka,c as Aa,D as ba,d as Ta,e as _a,I as Ea,f as Ia,h as Sa,i as Ua,j as Pa,u as xa,k as Wa,l as Na,m as Ra,n as Oa,o as Ma,p as Fa,q as La,r as Da,s as qa,t as za,W as Ba}from"./events-context-ClaboIDc.mjs";import{ofetch as Ha}from"ofetch";import ja from"js-cookie";import{create as Va}from"zustand";import{Turnstile as $a}from"@marsidev/react-turnstile";import{styled as Ka,createGlobalStyle as Ya,css as Ga}from"styled-components";import{u as Za,a as Ja,C as Xa}from"./useActiveWallet-B8DSbnuu.mjs";export{e as useActiveWallet,c as useConnectWallet,d as useFundWallet,b as useLogin}from"./useActiveWallet-B8DSbnuu.mjs";import Qa from"@heroicons/react/24/outline/DevicePhoneMobileIcon";import ei from"@heroicons/react/24/outline/FingerPrintIcon";import ti from"@heroicons/react/24/outline/PhoneIcon";import ri from"@heroicons/react/24/outline/ShieldCheckIcon";import ni from"@heroicons/react/24/outline/CalendarIcon";import ai from"@heroicons/react/24/outline/ExclamationTriangleIcon";import{toHex as ii,zeroAddress as oi,getAddress as si,createWalletClient as li,http as ci,parseSignature as di}from"viem";import{Transition as ui,Dialog as hi,TransitionChild as pi,DialogPanel as mi}from"@headlessui/react";import{constructURL as wi}from"@privy-io/urls";import{i as yi,f as gi,u as fi,p as vi,e as Ci,a as ki}from"./usePrivy-BCcRF869.mjs";export{b as useCreateWallet,c as useImportWallet}from"./usePrivy-BCcRF869.mjs";import{CheckCircle as Ai,FingerprintIcon as bi,Trash2 as Ti,AlertCircle as _i,CloudUpload as Ei,Ban as Ii,ExternalLink as Si,XCircle as Ui,Mail as Pi}from"lucide-react";import{C as xi,S as Wi}from"./SignRequestScreen-D9o7VhNz.mjs";import Ni from"@heroicons/react/24/outline/EnvelopeIcon";import Ri from"@heroicons/react/24/outline/QuestionMarkCircleIcon";import Oi from"@heroicons/react/24/solid/CheckBadgeIcon";import Mi from"@heroicons/react/24/solid/IdentificationIcon";import Fi from"@heroicons/react/24/outline/ChevronRightIcon";import Li from"@heroicons/react/24/outline/MinusCircleIcon";import Di from"@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon";import qi from"@heroicons/react/24/outline/ClockIcon";import zi from"@heroicons/react/24/outline/CheckCircleIcon";import Bi from"@heroicons/react/24/solid/ShieldCheckIcon";import Hi from"@heroicons/react/24/outline/GlobeAltIcon";import{F as ji}from"./frame-Dj70FEYB.mjs";import{MfaAuthPasskeyVerify as Vi,MfaAuthPasskeyInit as $i,MfaAuthTotpVerify as Ki,MfaAuthPasskeyEnrollment as Yi,MfaAuthTotpUnenroll as Gi,MfaAuthTotpEnroll as Zi,MfaAuthTotpInit as Ji}from"@privy-io/routes";import{selectPaymentRequirements as Xi,createPaymentHeader as Qi}from"x402/client";import{InvalidInputError as eo}from"@privy-io/api-base";import{toAccount as to}from"viem/accounts";import{u as ro}from"./use-sign-with-user-signer-DaTvrd5T.mjs";export{g as getEmbeddedConnectedWallet}from"./getEmbeddedConnectedWallet-CM6cDQCS.mjs";import"fast-password-entropy";import"secure-password-utilities";import"secure-password-utilities/wordlists";import"@heroicons/react/24/outline/UserCircleIcon";import"@heroicons/react/24/outline/ArrowLeftIcon";import"@heroicons/react/24/outline/ArrowRightIcon";import"@heroicons/react/24/outline/XMarkIcon";import"@heroicons/react/20/solid/CheckIcon";import"@heroicons/react/24/outline/WalletIcon";import"@heroicons/react/24/outline/ExclamationCircleIcon";import"@heroicons/react/24/outline/Square2StackIcon";import"@heroicons/react/24/outline";import"@tanstack/react-virtual";import"@heroicons/react/24/outline/CheckIcon";import"qrcode";import"@scure/base";import"@walletconnect/ethereum-provider";import"@heroicons/react/24/outline/CreditCardIcon";import"@heroicons/react/24/outline/QrCodeIcon";import"@heroicons/react/24/solid/ArrowsRightLeftIcon";import"@heroicons/react/24/outline/InformationCircleIcon";import"@heroicons/react/24/outline/ClipboardDocumentCheckIcon";import"@heroicons/react/24/outline/ClipboardDocumentIcon";import"@heroicons/react/24/outline/ChevronDownIcon";import"@heroicons/react/24/solid/CheckCircleIcon";import"@heroicons/react/24/outline/LockClosedIcon";import"@heroicons/react/24/outline/PencilSquareIcon";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/DocumentDuplicateIcon";import"@heroicons/react/24/solid/XCircleIcon";import"tinycolor2";function no(e){return e?{"privy-ui":"t"}:void 0}class ao{async authenticate(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new M("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(D,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw L(e)}}async link(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new M("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(q,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw L(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new M("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new M("Email must be set when initialzing authentication.");let n=no(r);try{return await this.api.post(z,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw L(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class io extends ao{async link(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new M("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(F,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw L(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}class oo{get meta(){return this._meta}async authenticate(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.channelToken)throw new M("Auth flow must be initialized first");try{let e=await this.api.post(B,{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 M("No response from authentication");return e}catch(e){throw L(e)}}async link(){if(!this.api)throw new M("Auth flow has no API instance");try{return await this.api.post(H,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw L(e)}}async _startChannelOnce(){if(!this.api)throw new M("Auth flow has no API instance");let e=await this.api.post(j,{token:this.captchaToken});y&&!f&&e.connect_uri&&Xe(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new M("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.channelToken)throw new M("Auth flow must be initialized first");let e=await this.api.get(V,{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 Qe(this._startChannelOnce.bind(this)),this.pollForReady=new Qe(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function so(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function lo(){if(!so())return;let e=window.chrome;return e?.runtime?.id}function co(){if(!so())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function uo(e){return new Promise(((t,r)=>{co()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!so())return;let e=window.chrome;return e?.runtime?.lastError?.message}();if(r||!e){let e=`WebAuthFlow failed: ${r||"Response URI missing"}`;throw Error(e)}let n=new URL(e),a=lo();if(!a)throw Error("Invalid extension context");if("chrome-extension:"===n.protocol){if(n.hostname!==a)throw Error("Invalid responseUri origin")}else{if("https:"!==n.protocol)throw Error("Invalid responseUri protocol");{let e=n.hostname.split(".");if(3!==e.length||"chromiumapp"!==e[1]||"org"!==e[2]||e[0]!==a)throw Error("Invalid responseUri origin")}}let i=n.searchParams.get("privy_oauth_state"),o=n.searchParams.get("privy_oauth_code");if(!i||!o)throw Error("Invalid responseUri - missing required parameters");t({privyOAuthState:i,privyOAuthCode:o})}catch(e){r(e)}})):r(Error("Chrome identity API not available"))}))}class ho{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new M("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new M("User denied confirmation during OAuth flow");let e=et();try{let t=await this.api.post($,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return tt.del(ha),tt.del(pa),tt.del(ma),t}catch(e){let t=L(e);if(t.privyErrorCode)throw new M(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new M("Invalid code during oauth flow.",void 0,K.OAUTH_USER_DENIED);throw new M("Invalid code during OAuth flow.",void 0,K.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new M("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new M("User denied confirmation during OAuth flow");let e=tt.get(ha);if(!e)throw new M("Authentication error.");try{let t=await this.api.post(Y,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return tt.del(ha),t}catch(e){throw L(e)}}async getAuthorizationUrl(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.provider)throw new M("Provider must be set when initializing OAuth authentication.");let e=rt();tt.put(ha,e);let t=nt();tt.put(wa,t);let r=await at(e);this.meta.withPrivyUi||tt.put(pa,!0),this.meta.disableSignup?tt.put(ma,!0):tt.del(ma);let n=no(this.meta.withPrivyUi),a=window.location.href,i=function(){let e=lo();if(e)return`https://${e}.chromiumapp.org`}();i&&(a=i);try{return await this.api.post(G,{provider:this.meta.provider,redirect_to:this.meta.customOAuthRedirectUrl||a,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw L(e)}}constructor(e){this.meta=e}}const po=({style:e})=>/*#__PURE__*/t(Hi,{style:{color:"var(--privy-color-error)",...e}});let mo={google:{name:"Google",component:wt},discord:{name:"Discord",component:mt},github:{name:"Github",component:pt},linkedin:{name:"LinkedIn",component:ht},twitter:{name:"Twitter",component:ut},spotify:{name:"Spotify",component:dt},instagram:{name:"Instagram",component:ct},tiktok:{name:"Tiktok",component:lt},line:{name:"LINE",component:st},twitch:{name:"Twitch",component:ot},apple:{name:"Apple",component:it}},wo=({iconUrl:e,...t})=>i.createElement("svg",{width:"33",height:"32",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t},i.createElement("foreignObject",{x:"2",y:"2",width:"29",height:"28"},i.createElement("img",{src:e,width:"29",height:"28",style:{display:"block",objectFit:"contain",borderRadius:"4px"},alt:"Provider icon"})));const yo=(e,t)=>{if(e in mo)return mo[e];if(yt(e)&&t){let r=t.find((t=>t.provider===e));if(r)return{name:r.provider_display_name,component:e=>i.createElement(wo,{...e,iconUrl:r.provider_icon_url})}}return{name:"Unknown",component:po}};function go(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),n=e.get("privy_oauth_provider");if(!t||!r||!n)return{inProgress:!1};let a=!1;try{a=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:n,withPrivyUi:!tt.get(pa),popupFlow:null!==window.opener&&a,disableSignup:!!tt.get(ma)}}class fo{async initRegisterFlow(e){if(!this.api)throw new M("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 M("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new M("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 M("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new M("WebAuthn is not supported in this browser");this.meta.initRegisterResponse||(this.meta.initRegisterResponse=await this.initRegisterOnce.execute());try{let t=this.meta.initRegisterResponse.options,r=await e.startRegistration({optionsJSON:this._transformInitLinkOptionsToCamelCase(t)});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(Z,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new M("Passkey request timed out or rejected by user.",void 0,K.PASSKEY_NOT_ALLOWED);throw L(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new M("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new M("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 r=await e.startAuthentication({optionsJSON:this._transformInitAuthenticateOptionsToCamelCase({...this.meta.initAuthenticateResponse.options,allow_credentials:t})});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(J,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new M("Passkey request timed out or rejected by user.",void 0,K.PASSKEY_NOT_ALLOWED);throw L(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new M("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new M("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let t=this.meta.initLinkResponse.options,r=await e.startRegistration({optionsJSON:this._transformInitLinkOptionsToCamelCase(t)});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(X,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new M("Passkey request timed out or rejected by user.",void 0,K.PASSKEY_NOT_ALLOWED);throw L(e)}}async _initRegisterOnce(e){if(!this.api)throw new M("Auth flow has no API instance");let t=no(e);return await this.api.post(Q,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new M("Auth flow has no API instance");let t=no(e);return await this.api.post(ee,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new M("Auth flow has no API instance");return await this.api.post(te,{})}_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},hints:this.meta.hints}}_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,hints:r}){this.authenticateForRegistration=!1,this.initRegisterOnce=new Qe(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new Qe(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new Qe(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t,hints:r}}}class vo{async authenticate(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new M("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(re,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw L(e)}}async link(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new M("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(ne,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw L(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new M("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new M("phone nNumber must be set when initialzing authentication.");let n=no(r);try{return await this.api.post(ae,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw L(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class Co extends vo{async link(){if(!this.api)throw new M("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new M("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(ie,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw L(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}class ko{static parse(e){try{return new ko(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return sa.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=sa.decodeJwt(e)}}class Ao extends ko{static parse(e){try{return new Ao(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let bo,To;class _o extends ft{async initialize(){await this.importPromise,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:vt,id:"com.coinbase.wallet"}}async promptConnection(){try{await this.importPromise;let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new oe("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw Ct(e)}}constructor(e,t,r,n,a){super("base_account",e,t,r),this.connectorType="base_account",this.walletClientType="base_account",this.displayName="Base",this.setBaseAccountSdk=a,this.proxyProvider=new kt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},bo?(this.proxyProvider.setWalletProvider(bo.getProvider()),this.setBaseAccountSdk(bo),console.log("Base Account SDK Initialized")):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{bo=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(bo.getProvider()),this.setBaseAccountSdk(bo),console.log("Base Account SDK Initialized")})).catch(console.error)}}let Eo=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class Io extends ft{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:At,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 oe("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw Ct(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",To=da({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(To.getProvider())}constructor(e,t,r,n){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new kt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.coinbaseWalletConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},this.walletClientType="smartWalletOnly"===this.coinbaseWalletConfig.preference?.options?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!To){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!Eo.includes(e))):[];e.length>0&&!e.every((e=>S.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${e.join(", ")}`),To=da(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(To.getProvider())}}class So extends ft{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:[bt(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:Tt,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}constructor({provider:e,chains:t,defaultChain:r,rpcConfig:n,imported:a,walletIndex:i}){super("privy",t,r,n),this.connectorType="embedded",this.proxyProvider=e,this.walletIndex=i,a&&(this.connectorType="embedded_imported"),this.subscribeListeners()}}const Uo=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];class Po extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class xo extends ca{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Po(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Qc()||!this.address)throw new Po("Disconnected",4900);let{hash:r}=await ad(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Po(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Qc()||!this.address)throw new Po("Disconnected",4900);let{signature:r}=await nd(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new Po(`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 Po(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=_t(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],r=e.params[1],{signature:n}=await td({message:t},{address:r});return n}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],r="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1],{signature:n}=await rd(Et(r),{address:t});return n}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:bt(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...ua(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 bt(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=>Uo.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await Qc();if(await id({address:this.address}),!t||!this.address)throw new Po("Disconnected",4900);try{let r={method:e.method,params:e.params},n=this.walletAccount;return n&&It(n)?this.handleWalletApiRequest(r,n,t):(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:r})).response.data}catch(e){throw console.error(e),new Po("Disconnected",4900)}}}async handleWalletApiRequest(e,t,r){let n=this.privyClient;if(!n)throw new Po("Disconnected",4900);if("secp256k1_sign"===e.method){let a=await U(n,(async({message:e})=>this.walletProxy.signWithUserSigner({accessToken:r,message:e})),{chain_type:"ethereum",method:"secp256k1_sign",wallet_id:t.id,params:{hash:e.params[0]}});if("secp256k1_sign"!==a.method)throw new Po(`Invalid params for ${e.method}`,4200);return a.data.signature}throw new Po(`Method not supported: ${e.method}`,4200)}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:a,chains:i,appId:o,chainId:s=1,walletIndex:l,privyClient:c,walletAccount:d}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=s,this.rpcConfig=a,this.chains=i,this.publicClient=_t(s,this.chains,a,{appId:o}),this.rpcTimeoutDuration=St(a,"privy"),this.appId=o,this.walletIndex=l,this.privyClient=c,this.walletAccount=d}}function Wo(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var No=0;class Ro extends ft{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 oe("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw Ct(e)}}constructor(e,t,r,n,a){super(a||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new kt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let i=n.provider;this.proxyProvider.setWalletProvider(i)}}var Oo="__private_"+No+++"__walletBranding";class Mo extends ft{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 Wo(this,Oo)[Oo]??{name:"Browser Extension",icon:Ut,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 oe("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw Ct(e)}}constructor(e,t,r,n,a){super(a??"unknown",e,t,r),Object.defineProperty(this,Oo,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new kt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===a?Wo(this,Oo)[Oo]={name:"MetaMask",icon:Pt,id:"io.metamask"}:"phantom"===a&&(Wo(this,Oo)[Oo]={name:"Phantom",icon:xt,id:"phantom"})}}class Fo extends Ro{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{y||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 oe("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw Ct(e)}}}class Lo extends ca{get wallets(){let e=new Set;return this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(r)&&(e.add(r),!0)}))}async initialize(e){if(this.initialized&&!e||(e&&this.removeAllConnectors(),this.externalWalletConfig.disableAllExternalWallets))return;let t=Wt({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:r}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),this.walletList.includes("base_account")&&this.createEthereumWalletConnector({connectorType:"base_account",walletClientType:"base_account"}),Object.values(Nt)))!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 Rt({id:e.client,name:e.name})));this.externalWalletConfig.walletConnect.enabled&&(this.walletList.includes("wallet_connect_qr")||Ot(this.walletList))&&"solana-only"!==this.walletChainType&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"});let r=this.walletList.includes("wallet_connect_qr_solana"),n=this.externalWalletConfig.solana.connectors?.get()||[],a=async e=>{if(!r)return;let t=e.find((e=>"walletconnect_solana"===e.walletBranding?.id));t&&t.wallet&&await t.wallet.initialize({walletConnectCloudProjectId:this.walletConnectCloudProjectId,privyAppName:this.privyAppName})};a(n),n.filter((e=>r||"walletconnect_solana"!==e.walletBranding?.id)).forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{a(e),e?.filter((e=>r||"walletconnect_solana"!==e.walletBranding?.id)).forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t,r){return"wallet_connect_v2"===e?this.walletConnectors.filter(Mt).find((t=>t.connectorType===e&&(!r||t.wallets.some((e=>e.address===r)))))??null:this.walletConnectors.filter(Mt).find((n=>n.connectorType===e&&n.walletClientType===t&&(!r||n.wallets.some((e=>e.address===r)))))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(Ft).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}findImportedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded_imported"===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.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&this.emit("walletsUpdated")}addEmbeddedWalletConnectors({walletProxy:e,user:t,embeddedWallets:r,defaultChain:n,appId:a,privyClient:i}){let{entropyId:o,entropyIdVerifier:s}=Lt(t);for(let t of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===t.walletIndex));if(r&&Mt(r))r.proxyProvider.walletProxy=e;else{let r=new So({provider:new xo({walletProxy:e,address:t.address,entropyId:o,entropyIdVerifier:s,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:n.id,walletIndex:t.walletIndex,privyClient:i,walletAccount:t}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:t.walletIndex});this.addWalletConnector(r)}}}addImportedWalletConnector(e,t,r,n){let a=this.findWalletConnector("embedded_imported","privy",t);if(a&&Mt(a))a.proxyProvider.walletProxy=e;else{let a=new So({provider:new xo({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(a)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.storedConnections=Dt(),this.emit("walletsUpdated")}removeImportedWalletConnectors(){let e=this.findImportedWalletConnectors();e.length&&(e.forEach((e=>{let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1)})),this.storedConnections=Dt(),this.emit("walletsUpdated"))}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let a=this.findWalletConnector(e,t);if(a&&Mt(a))return a instanceof qt&&a.resetConnection(t),a;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new Io(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new _o(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new qt({walletConnectCloudProjectId:this.walletConnectCloudProjectId,rpcConfig:this.rpcConfig,chains:this.chains,defaultChain:this.defaultChain,shouldEnforceDefaultChainOnConnect:this.shouldEnforceDefaultChainOnConnect,privyAppId:this.privyAppId,privyAppName:this.privyAppName,walletClientType:t}):n?new zt({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new Fo(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Mo(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Mo(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Mo(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Ro(this.chains,this.defaultChain,this.rpcConfig,r?.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)}))}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,r,n,a,i,o,s,l,c,d,u){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.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=a,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=s,this.externalWalletConfig=l,this.privyAppName=c,this.walletChainType=u||"ethereum-only",this.setBaseAccountSdk=d,this.storedConnections=Dt()}}let Do=[le,ce,de];class qo{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw L(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw L(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw L(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=ya,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=Ha.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 r=new Headers(t.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-ca-id",this.clientAnalyticsId||""),r.set("privy-client",`react-auth:${this.sdkVersion}`);let n=Do.includes(e.toString());if(!r.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:n});null!==e&&r.set("authorization",`Bearer ${e}`)}t.headers=r,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new se}})}}let zo=/paymaster\.biconomy\.io\/api/i,Bo={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const Ho=(e,t)=>e&&zo.test(e)?Bo:t&&t.policy_id?{policyId:t.policy_id}:void 0,jo=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});class Vo{async authenticate(){if(!this.api)throw new M("Auth flow has no API instance");try{return await this.api.post(ue,{token:this.meta.token})}catch(e){throw L(e)}}async link(){if(!this.api)throw new M("Auth flow has no API instance");try{return await this.api.post(he,{token:this.meta.token})}catch(e){throw L(e)}}constructor(e){this.meta={token:e}}}class $o{getOrCreateGuestCredential(e){let t=ga(e);if(Bt()){if(tt.get(t))return tt.get(t);{let e=la.encode(Ht(32));return tt.put(t,e),e}}return la.encode(Ht(32))}async authenticate(){if(!this.api)throw new M("Auth flow has no API instance");try{return await this.api.post(pe,{guest_credential:this.meta.guestCredential})}catch(e){throw L(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function Ko(){return!(v&&window.location.origin.startsWith("http://localhost"))}const Yo=Va((()=>({identityToken:null})));function Go(){let{identityToken:e}=Yo();return{identityToken:e}}var Zo,Jo=((Zo={}).PRIVY="privy_access_token",Zo.CUSTOMER="customer_access_token",Zo);class Xo{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(fa)}get privyAccessToken(){return this._getToken(va)}_getToken(e){try{let t=tt.get(e);return"string"==typeof t?ko.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=tt.get(Ca);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=tt.get(ka(e));if("string"!=typeof t)return null;{let r=new ko(t);return r.isExpired()?(tt.del(ka(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=ja.get(Aa);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),r="string"==typeof this.refreshToken&&this.refreshToken!==ba;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=ko.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?tt.put(ka(e),t):tt.del(ka(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:r,is_new_user:n,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,n),{user:Vt(r),isNewUser:n,oAuthTokens:i}}catch(e){throw console.warn("Error authenticating session"),me(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof ao?"email":e instanceof vo?"sms":e instanceof jt?"siwe":e instanceof $o?"guest":e instanceof Vo?"custom_auth":e instanceof ho?e.meta.provider:null}(e);r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:r,isNewUser:t}}),"siwe"===r&&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(),r=t.oauth_tokens,n=r?{provider:r.provider,accessToken:r.access_token,accessTokenExpiresInSeconds:r.access_token_expires_in_seconds,refreshToken:r.refresh_token,refreshTokenExpiresInSeconds:r.refresh_token_expires_in_seconds,scopes:r.scopes}:void 0;return{user:Vt(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),me(e)}}async _refresh(){if(!this.api)throw new M("Session has no API instance");if(!this.client)throw new M("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 r;if(!(e&&t||this.mightHaveServerCookies))return null;{let n={};e&&(n.authorization=`Bearer ${e}`),r=await this.api.post(le,t?{refresh_token:t}:{},{headers:n})}return this.handleTokenResponse(r),Vt(r.user)}catch(e){if(e instanceof we&&e.privyErrorCode===K.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw me(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(ce,{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=tt.get(fa);if(tt.put(fa,e),!this.client?.useServerCookies){let t=ko.parse(e)?.expiration;ja.set(Ta,e,{sameSite:"Strict",secure:Ko(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else tt.del(fa),ja.remove(Ta),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(tt.put(Ca,e),this.client?.useServerCookies||ja.set(Aa,"t",{sameSite:"Strict",secure:Ko(),expires:30})):(tt.del(Ca),ja.remove(_a),ja.remove(Aa))}storePrivyAccessToken(e){"string"==typeof e?tt.put(va,e):tt.del(va)}storeIdentityToken(e){if(Yo.setState({identityToken:e}),this.client?.useServerCookies)return;tt.put(Ea,e);let t=ko.parse(e)?.expiration;ja.set(Ia,e,{sameSite:"Strict",secure:Ko(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){tt.del(Ea),Yo.setState({identityToken:null}),ja.remove(Ia)}constructor(){this.authenticateOnce=new Qe((async e=>this._authenticate(e))),this.linkOnce=new Qe((async e=>this._link(e))),this.refreshOnce=new Qe(this._refresh.bind(this)),this.destroyOnce=new Qe(this._destroy.bind(this))}}let Qo;var es=0,ts="__private_"+es+++"__getOrGenerateClientAnalyticsId";class rs{getAppId(){return this.appId}initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,store:a,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c,setBaseAccountSdk:d}){this.connectors||(this.connectors=new Lo(this.appId,e,t,r,n,a,i,o,s,l,d,c))}generateApi(){let e=new qo({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 M("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new M("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(ye,{action:"verify"})}catch(e){throw L(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(ge,{});return jo(e.options)}catch(e){throw L(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(fe,{});return Vt(e)}catch(e){throw me(e)}}async unlinkEmail(e){try{let t=await this.api.post(ve,{address:e});return await this.getAuthenticatedUser()??Vt(t)}catch(e){throw me(e)}}async unlinkPhone(e){try{let t=await this.api.post(Ce,{phoneNumber:e});return await this.getAuthenticatedUser()??Vt(t)}catch(e){throw me(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(ke,{address:e});return await this.getAuthenticatedUser()??Vt(t)}catch(e){throw me(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(Ae,{address:e});return await this.getAuthenticatedUser()??Vt(t)}catch(e){throw me(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(be,{provider:e,subject:t});return await this.getAuthenticatedUser()??Vt(r)}catch(e){throw me(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(Te,{fid:e});return await this.getAuthenticatedUser()??Vt(t)}catch(e){throw me(e)}}async unlinkTelegram(e){try{let t=await this.api.post(_e,{telegram_user_id:e});return await this.getAuthenticatedUser()??Vt(t)}catch(e){throw me(e)}}async revokeDelegatedWallet(){try{await this.api.post(Ee,{})}catch(e){throw me(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:n}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(de,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:n?.keepAlive??!1})}catch(e){console.log("Unable to submit event. This is not an issue.")}}async signMoonpayOnRampUrl(e){try{return this.api.post(Ie,e)}catch(e){throw me(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(Se,e)}catch(e){throw me(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${Ue}?partnerUserId=${e}`)}catch(e){throw me(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(Jo.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Jo.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?Ao.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 r=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return r.enabled?{enabled:r.enabled,smartWalletVersion:r.smart_wallet_version,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:Ho(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw me(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(r){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(Pe,{address:e,token:t})).nonce}catch(e){throw me(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a,mode:i}){return await this.api.post(xe,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:a,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}){return await this.api.post(We,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:a})}async linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:n}){try{let a=await this.api.post(Ne,{message:e,signature:t,smart_wallet_type:r,smart_wallet_version:n});return Vt(a)}catch(e){throw me(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a});return Vt(i)}catch(e){throw me(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(Re,{address:e,token:t})).nonce}catch(e){throw me(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:a,messageType:i="plain"}){return await this.api.post(Oe,{message:e,signature:t,walletClientType:r,connectorType:n,mode:a,message_type:i})}async authenticateWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,mode:a,messageType:i="plain"}){let o=await this.authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:a,messageType:i});this.session.handleTokenResponse(o);let s=Vt(o.user);if(!s)throw Error("Authentication failed - no user returned");return{user:s,isNewUser:o.is_new_user||!1}}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s}){try{let l,c;switch(r){case"email":l=Be,c={nonce:e,email:t};break;case"sms":l=ze,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=qe,!n)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...n};break;case"farcaster":l=De,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=Le,c={nonce:e,telegram_auth_result:a,telegram_web_app_data:i};break;case"siws":l=Fe,c={nonce:e,address:t,...n};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:l=Me,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??Vt(d)}catch(e){throw me(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:a="plain"}){return await this.api.post(He,{message:e,signature:t,walletClientType:r,connectorType:n,message_type:a})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,messageType:a="plain"}){try{let i=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:a});return Vt(i)}catch(e){throw me(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(je);return this.session.updateIdentityToken(e.identity_token),Vt(e.user)}catch(e){throw me(e)}}async scanTransaction(e){try{return await this.api.post(Ve,e)}catch(e){throw me(e)}}constructor({apiUrl:e=Sa,appId:t,appClientId:r,timeout:n=Ua}){Object.defineProperty(this,ts,{value:ns}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==Sa&&e.startsWith("https://privy."),this.timeout=n,this.appId=t,this.appClientId=r,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,ts)[ts](),Qo||(Qo=new Xo),this.session=Qo,this.api=this.generateApi(),this.session.client=this}}function ns(){if("undefined"==typeof window)return null;try{let e=tt.get(Pa);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=oa();try{return tt.put(Pa,e),e}catch(t){return e}}const as=({delayedExecution:e,...r})=>{let{enabled:n,siteKey:a,appId:i,setError:l,setToken:c,setExecuting:d,ref:u}=$t(),[,h]=o((()=>a?.split("t:")||[]),[a]);if(s((()=>u.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($a,{...r,ref:u,siteKey:h,options:{action:i,size:"invisible",...e?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{r.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:e=>{r.onError?.(e),l("Captcha failed"),d(!1)},onSuccess:e=>{r.onSuccess?.(e),c(e),d(!1)},onExpire:e=>{r.onExpire?.(e);try{u.current?.reset(),l(void 0),c(void 0)}catch(e){l("expired_and_failed_reset")}}})})};function is(e){xa("configureMfa",e)}const os=/*#__PURE__*/Ka.div.withConfig({displayName:"AppLogoContainer",componentId:"sc-ba98f772-0"})(["display:flex;flex-direction:column;align-items:center;padding:0px 0px 30px;@media (max-width:440px){padding:10px 10px 20px;}"]),ss=/*#__PURE__*/Ka.div.withConfig({displayName:"Title",componentId:"sc-ba98f772-1"})(["font-size:18px;line-height:30px;text-align:center;font-weight:600;margin-bottom:10px;"]),ls=/*#__PURE__*/Ka.div.withConfig({displayName:"SubTitle",componentId:"sc-ba98f772-2"})(["font-size:0.875rem;text-align:center;"]),cs=/*#__PURE__*/Ka.div.withConfig({displayName:"Container",componentId:"sc-ba98f772-3"})(["display:flex;flex-direction:column;align-items:center;gap:10px;flex-grow:1;padding:20px 0;@media (max-width:440px){padding:10px 10px 20px;}"]),ds=/*#__PURE__*/Ka.div.withConfig({displayName:"List",componentId:"sc-ba98f772-4"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.75rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),us=/*#__PURE__*/Ka.div.withConfig({displayName:"ListItemIcon",componentId:"sc-ba98f772-5"})(["width:25px;display:flex;align-items:center;justify-content:flex-start;> svg{z-index:2;height:25px !important;width:25px !important;color:var(--privy-color-accent);}"]),hs=/*#__PURE__*/Ka.div.withConfig({displayName:"ListItem",componentId:"sc-ba98f772-6"})(["display:flex;align-items:center;gap:10px;font-size:0.875rem;line-height:1rem;text-align:left;"]),ps=/*#__PURE__*/Ka.div.withConfig({displayName:"BottomSection",componentId:"sc-ba98f772-7"})(["display:flex;flex-direction:column;gap:10px;padding-top:20px;"]),ms=/*#__PURE__*/Ka.div.withConfig({displayName:"MethodList",componentId:"sc-ba98f772-8"})(["display:flex;flex-direction:column;align-items:stretch;gap:1rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),ws=/*#__PURE__*/Ka.div.withConfig({displayName:"MethodListItem",componentId:"sc-ba98f772-9"})(["display:flex;gap:5px;width:100%;position:relative;"]),ys=/*#__PURE__*/Ka.button.withConfig({displayName:"RemoveMethodButton",componentId:"sc-ba98f772-10"})(["&&{background-color:transparent;color:var(--privy-color-foreground-3);padding:0 0.75rem;display:flex;align-items:center;height:100%;> svg{z-index:2;height:20px !important;width:20px !important;}}&&:hover{color:var(--privy-color-error);}"]),gs=/*#__PURE__*/Ka.div.withConfig({displayName:"MethodText",componentId:"sc-ba98f772-11"})(["display:flex;align-items:center;gap:0.5rem;> svg{z-index:2;height:20px !important;width:20px !important;}"]),fs=/*#__PURE__*/Ka.div.withConfig({displayName:"ExtraText",componentId:"sc-ba98f772-12"})(["display:flex;align-items:center;gap:6px;font-weight:400 !important;color:",";> svg{z-index:2;height:18px !important;width:18px !important;display:flex !important;align-items:flex-end;}"],(e=>e.$isAccent?"var(--privy-color-accent)":"var(--privy-color-foreground-3)")),vs=/*#__PURE__*/Ka.div.withConfig({displayName:"SmsInsecureText",componentId:"sc-ba98f772-13"})(["width:100%;display:flex;justify-content:space-between;"]),Cs=/*#__PURE__*/Ka.p.withConfig({displayName:"TermsText",componentId:"sc-ba98f772-14"})(["text-align:left;width:100%;color:var(--privy-color-foreground-3) !important;"]),ks=/*#__PURE__*/Ka.button.withConfig({displayName:"PrimaryTextButton",componentId:"sc-ba98f772-15"})(["display:flex;flex-direction:row;align-items:center;justify-content:center;user-select:none;&{width:100%;cursor:pointer;border-radius:var(--privy-border-radius-md);font-size:0.875rem;line-height:1rem;font-style:normal;font-weight:500;line-height:22px;letter-spacing:-0.016px;}&&{color:",";background-color:transparent;padding:0.5rem 0px;}&:hover{text-decoration:underline;}"],(e=>"dark"===e.theme?"var(--privy-color-foreground-2)":"var(--privy-color-accent)")),As=/*#__PURE__*/Ka.div.withConfig({displayName:"IconWrapper",componentId:"sc-ba98f772-16"})(["display:flex;align-items:center;justify-content:center;color:var(--privy-color-accent);width:100%;> svg{z-index:2;width:3rem;height:3rem;}"]),bs=/*#__PURE__*/Ka.div.withConfig({displayName:"ErrorMessage",componentId:"sc-ba98f772-17"})(["color:var(--privy-color-error);"]),Ts=({handleClose:e,user:n,onSelect:a})=>/*#__PURE__*/r(Kt,{title:"Verify your identity",subtitle:"Choose a verification method",icon:ri,iconVariant:"subtle",onClose:e,showClose:!0,watermark:!0,children:[/*#__PURE__*/r(ms,{children:[n.mfaMethods.includes("totp")&&/*#__PURE__*/r(Yt,{onClick:()=>a("totp"),children:[/*#__PURE__*/t(Gt,{children:/*#__PURE__*/t(Qa,{})}),"Authenticator app"]},"totp"),n.mfaMethods.includes("sms")&&/*#__PURE__*/r(Yt,{onClick:()=>a("sms"),children:[/*#__PURE__*/t(Gt,{children:/*#__PURE__*/t(ti,{})}),"SMS"]},"sms"),n.mfaMethods.includes("passkey")&&/*#__PURE__*/r(Yt,{onClick:()=>a("passkey"),children:[/*#__PURE__*/t(Gt,{children:/*#__PURE__*/t(ei,{})}),"Passkey"]},"passkey")]}),/*#__PURE__*/t(Zt,{})]}),_s=({pendingTransaction:e})=>{let{wallets:r}=Jt(),{walletProxy:n,rpcConfig:a,chains:i,appId:c,nativeTokenSymbolForChainId:d}=$e(),[u,h]=l(null),[p,m]=l(e),{tokenPrice:w}=Xt(p.chainId),y=d(e.chainId)||"ETH",g=o((()=>r.find((e=>"privy"===e.walletClientType))),[r]);return s((()=>{(async function(){if(!n||!g)return p;let e=_t(p.chainId,i,a,{appId:c}),t=await Qt(p,e,g.address);return h(ii(BigInt(t.gas??0))),t})().then(m).catch(console.error)}),[n]),g?/*#__PURE__*/t(Es,{children:/*#__PURE__*/t(er,{from:g.address,to:p.to,txn:p,gas:u??void 0,tokenPrice:w,tokenSymbol:y})}):null};let Es=/*#__PURE__*/Ka.div.withConfig({displayName:"TransactionInfoWrapper",componentId:"sc-8d9a2f57-0"})(["width:100%;padding:1rem 0;"]);const Is=({style:e,...r})=>/*#__PURE__*/t("svg",{x:0,y:0,width:"65",height:"64",viewBox:"0 0 65 64",style:{height:"64px",width:"65px",...e},fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:/*#__PURE__*/t("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M3.71369 17.5625V10.375C3.71369 6.44625 6.85845 3.25 10.7238 3.25H17.7953C18.6783 3.25 19.3941 2.52244 19.3941 1.625C19.3941 0.727562 18.6783 0 17.7953 0H10.7238C5.09529 0 0.516113 4.65419 0.516113 10.375V17.5625C0.516113 18.4599 1.23194 19.1875 2.1149 19.1875C2.99787 19.1875 3.71369 18.4599 3.71369 17.5625ZM17.7953 60.7501C18.6783 60.7501 19.3941 61.4777 19.3941 62.3751C19.3941 63.2726 18.6783 64.0001 17.7953 64.0001H10.7238C5.09529 64.0001 0.516113 59.3459 0.516113 53.6251V46.4376C0.516113 45.5402 1.23194 44.8126 2.1149 44.8126C2.99787 44.8126 3.71369 45.5402 3.71369 46.4376V53.6251C3.71369 57.5538 6.85845 60.7501 10.7238 60.7501H17.7953ZM63.4839 46.4376V53.6251C63.4839 59.3459 58.9048 64.0001 53.2763 64.0001H46.2047C45.3217 64.0001 44.6059 63.2726 44.6059 62.3751C44.6059 61.4777 45.3217 60.7501 46.2047 60.7501H53.2763C57.1416 60.7501 60.2864 57.5538 60.2864 53.6251V46.4376C60.2864 45.5402 61.0022 44.8126 61.8851 44.8126C62.7681 44.8126 63.4839 45.5402 63.4839 46.4376ZM63.4839 10.375V17.5625C63.4839 18.4599 62.7681 19.1875 61.8851 19.1875C61.0022 19.1875 60.2864 18.4599 60.2864 17.5625V10.375C60.2864 6.44625 57.1416 3.25 53.2763 3.25H46.2047C45.3217 3.25 44.6059 2.52244 44.6059 1.625C44.6059 0.727562 45.3217 0 46.2047 0H53.2763C58.9048 0 63.4839 4.65419 63.4839 10.375ZM43.0331 47.3022C43.7067 46.6698 43.7483 45.6022 43.1262 44.9176C42.5039 44.233 41.4536 44.1906 40.78 44.823C38.3832 47.0732 35.265 48.3125 31.9997 48.3125C28.7344 48.3125 25.6162 47.0732 23.2194 44.823C22.5457 44.1906 21.4955 44.233 20.8732 44.9176C20.251 45.6022 20.2927 46.6698 20.9663 47.3022C23.9784 50.1301 27.8968 51.6875 31.9997 51.6875C36.1026 51.6875 40.021 50.1301 43.0331 47.3022ZM35.3207 24.1249V36.1249C35.3207 38.5029 33.4173 40.4374 31.0777 40.4374H29.7249C28.8079 40.4374 28.0646 39.6819 28.0646 38.7499C28.0646 37.8179 28.8079 37.0624 29.7249 37.0624H31.0777C31.5863 37.0624 32.0001 36.6419 32.0001 36.1249V24.1249C32.0001 23.1929 32.7434 22.4374 33.6604 22.4374C34.5774 22.4374 35.3207 23.1929 35.3207 24.1249ZM46.7581 28.8437V24.0312C46.7581 23.151 46.056 22.4374 45.19 22.4374C44.324 22.4374 43.622 23.151 43.622 24.0312V28.8437C43.622 29.7239 44.324 30.4374 45.19 30.4374C46.056 30.4374 46.7581 29.7239 46.7581 28.8437ZM17.6109 28.8437C17.6109 29.7239 18.313 30.4374 19.1789 30.4374C20.0449 30.4374 20.747 29.7239 20.747 28.8437V24.0312C20.747 23.151 20.0449 22.4374 19.1789 22.4374C18.313 22.4374 17.6109 23.151 17.6109 24.0312V28.8437Z"})}),Ss=({hasBlockingError:e,error:a,onClose:i,onBack:o,handleSubmit:s,account:l,submitSuccess:c})=>{let{pendingTransaction:d}=$e();/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{onClose:i},"header"),/*#__PURE__*/t(rr,{children:/*#__PURE__*/r("div",{children:[/*#__PURE__*/t(nr,{success:c,fail:!!a}),/*#__PURE__*/t(a?ai:Is,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/t(ss,{style:{marginTop:"1rem"},children:"Verifying with passkey"}),/*#__PURE__*/r(ds,{children:[/*#__PURE__*/r(hs,{children:[/*#__PURE__*/t(us,{children:/*#__PURE__*/t(ri,{})}),"Approve this action using your touch, face, PIN, or hardware key."]}),/*#__PURE__*/r(hs,{children:[/*#__PURE__*/t(us,{children:/*#__PURE__*/t(ni,{})}),"You last added a passkey on"," ",l?.firstVerifiedAt?.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),"."]})]}),d&&/*#__PURE__*/t(cs,{children:/*#__PURE__*/t(_s,{pendingTransaction:d})}),a&&/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(bs,{style:{marginTop:"1.25rem"},children:a.message}),/*#__PURE__*/t(ar,{disabled:e,onClick:s,style:{margin:"1.25rem auto 0"},children:"Try again"})]}),o&&/*#__PURE__*/t(ks,{style:{marginTop:"1rem"},onClick:o,children:"Choose another method"}),/*#__PURE__*/t(Zt,{})]})};let Us=Array(6).fill("");var Ps,xs=((Ps=xs||{})[Ps.RESET_AFTER_DELAY=0]="RESET_AFTER_DELAY",Ps[Ps.CLEAR_ON_NEXT_VALID_INPUT=1]="CLEAR_ON_NEXT_VALID_INPUT",Ps);function Ws(e){return/^[0-9]{1}$/.test(e)}function Ns(e){return 6===e.length&&e.every(Ws)}const Rs=({onChange:e,disabled:a,errorReasonOverride:i,success:o})=>{let[s,c]=l(Us),[d,u]=l(null),[h,p]=l(null),m=async t=>{t.preventDefault();let r=t.currentTarget.value.replace(/\s+/g,"");if(""===r)return;let n=s.reduce(((e,t)=>e+Number(Ws(t))),0),a=r.split(""),i=!a.every(Ws),o=a.length+n>6;if(i)return u("Passcode can only be numbers"),void p(1);if(o)return u("Passcode must be exactly 6 numbers"),void p(1);u(null),p(null);let l=Number(t.currentTarget.name?.charAt(4)),d=[...r||[""]].slice(0,6-l),h=[...s.slice(0,l),...d,...s.slice(l+d.length)];c(h);let m=Math.min(Math.max(l+d.length,0),5),w=document.querySelector(`input[name=pin-${m}]`);if(w?.focus(),Ns(h))try{await e(h.join(""));let t=document.querySelector(`input[name=pin-${m}]`);t?.blur()}catch(t){p(1),u(t.message)}else try{await e(null)}catch(t){p(1),u(t.message)}},w=o?"success":!(!i&&!d)?"fail":"";/*#__PURE__*/return t(n,{children:/*#__PURE__*/r(Os,{children:[/*#__PURE__*/t("div",{children:s.map(((r,n)=>/*#__PURE__*/t("input",{name:`pin-${n}`,type:"text",value:s[n],onChange:m,onKeyUp:t=>{"Backspace"===t.key&&(t=>{1===h&&(u(null),p(null));let r=[...s.slice(0,t),"",...s.slice(t+1)];if(c(r),t>0){let e=document.querySelector(`input[name=pin-${t-1}]`);e?.focus()}Ns(r)?e(r.join("")):e(null)})(n)},inputMode:"numeric",autoFocus:0===n,pattern:"[0-9]",className:w,autoComplete:y?"one-time-code":"off",disabled:a},n)))}),/*#__PURE__*/t("div",{children:/*#__PURE__*/t(Ms,{$fail:!!i||!!d,children:i||d})})]})})};let Os=/*#__PURE__*/Ka.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);}}"]),Ms=/*#__PURE__*/Ka.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 Fs=({selectedMethod:e,submitSuccess:a,hasBlockingError:i,onClose:o,onBack:s,handleSubmitCode:l})=>{let c=Wa(),{pendingTransaction:d}=$e();switch(e){case"sms":/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{onClose:o},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(ti,{})}),/*#__PURE__*/t(ss,{children:"Enter verification code"}),/*#__PURE__*/r(cs,{children:[/*#__PURE__*/t(Rs,{success:a,disabled:i,onChange:l}),/*#__PURE__*/r(ls,{children:["To continue, please enter the 6-digit code sent to your ",/*#__PURE__*/t("strong",{children:"mobile device"})]}),d&&/*#__PURE__*/t(_s,{pendingTransaction:d})]}),s&&/*#__PURE__*/t(ks,{theme:c?.appearance.palette.colorScheme,onClick:s,children:"Choose another method"}),/*#__PURE__*/t(ir,{onClick:o,children:"Cancel"}),/*#__PURE__*/t(Zt,{})]});case"totp":/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{onClose:o},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Qa,{})}),/*#__PURE__*/t(ss,{children:"Enter verification code"}),/*#__PURE__*/r(cs,{children:[/*#__PURE__*/t(Rs,{success:a,disabled:i,onChange:l}),/*#__PURE__*/r(ls,{children:["To continue, please enter the 6-digit code generated from your"," ",/*#__PURE__*/t("strong",{children:"authenticator app"})]}),d&&/*#__PURE__*/t(_s,{pendingTransaction:d})]}),s&&/*#__PURE__*/t(ks,{theme:c?.appearance.palette.colorScheme,onClick:s,children:"Choose another method"}),/*#__PURE__*/t(ir,{onClick:o,children:"Cancel"}),/*#__PURE__*/t(Zt,{})]});default:return null}},Ls=e=>or(e)?{isBlocking:!0,error:Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.")}:sr(e)?{isBlocking:!1,error:Error("The code you entered is not valid")}:lr(e)?{isBlocking:!0,error:Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.")}:(console.error(e),{isBlocking:!1,error:Error("Something went wrong.")}),Ds={component:()=>{let{user:e}=cr(),{data:r}=dr(),[n,a]=l(e?.mfaMethods[0]),[i,o]=l(!1),[c,d]=l(),[h,p]=l();if(s((()=>{a(e?.mfaMethods[0])}),[e?.mfaMethods]),!r?.mfaVerify)throw Error("Missing modal data for MFA verification screen.");let{onFailure:m,onSuccess:w,generateOptions:y,verifyTotpCode:g,verifyPasskey:f,verifySmsCode:v,sendSmsCode:C}=r.mfaVerify,k=async e=>{if("passkey"!==e)try{a(e),"sms"===e&&(a(e),await C()),"totp"===e&&a(e)}catch(e){console.error(e)}else try{a(e);let t=await y();if(!t)throw Error("something went wrong");d(t),await f(t),o(!0),p(void 0),w()}catch(e){p(Ls(e))}},A=async e=>{p(void 0);try{if(!e||!n)return;if("passkey"===n){if(!c)throw Error("Missing passkey challenge");await f(c)}else"sms"===n?await v(e):"totp"===n&&await g(e);p(void 0),o(!0),w()}catch(e){throw Ls(e).error}},b=()=>{h||!i?m(h?.error??Error("Canceled MFA verification.")):w()},T=u(!1);return s((()=>{!T.current&&n&&(T.current=!0,k(n).finally((()=>{T.current=!1})))}),[open]),e?"passkey"===n?/*#__PURE__*/t(Ss,{account:e.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],submitSuccess:i,hasBlockingError:h?.isBlocking??!1,error:h?.error,onClose:b,onBack:()=>{a(void 0),p(void 0)},handleSubmit:()=>A(c).catch(p)}):"sms"===n||"totp"===n?/*#__PURE__*/t(Fs,{selectedMethod:n,submitSuccess:i,hasBlockingError:h?.isBlocking??!1,handleSubmitCode:A,onClose:b,onBack:e.mfaMethods.length>1?()=>a(void 0):void 0}):/*#__PURE__*/t(Ts,{user:e,onSelect:k,handleClose:b}):null}};function qs(){let{promptMfa:e,init:t,submit:r,cancel:n,mfaMethods:a}=h(ur);return{promptMfa:e,init:t,submit:r,cancel:n,mfaMethods:a}}const zs=({onClose:e})=>{let{user:r}=cr(),[n,a]=l(r?.mfaMethods[0]??null),{init:i,cancel:o,submit:c}=qs(),[d,h]=l(!1),[p,m]=l(null),[w,y]=l();s((()=>{a(r?.mfaMethods[0]??null)}),[r?.mfaMethods]);let g=u(!1);async function f(t){y(void 0);try{if(!t||!n)return;await c(n,t),h(!0),y(void 0),e()}catch(t){throw Ls(t).error}}async function v(t){if("passkey"!==t)try{a(t),await i(t)}catch(t){console.error(t)}else try{a(t);let r=await i(t);if(!r)throw Error("something went wrong");m(r),await c(t,r),h(!0),y(void 0),e()}catch(t){y(Ls(t))}}s((()=>{!g.current&&n&&(g.current=!0,v(n).finally((()=>{g.current=!1})))}),[]);let C=()=>{a(null),y(void 0),o(),e()};return r?"passkey"===n?/*#__PURE__*/t(Ss,{account:r.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],submitSuccess:d,hasBlockingError:w?.isBlocking??!1,error:w?.error,onClose:C,onBack:()=>{a(null),y(void 0)},handleSubmit:()=>f(p).catch(y)}):n?/*#__PURE__*/t(Fs,{submitSuccess:d,hasBlockingError:w?.isBlocking??!1,handleSubmitCode:f,selectedMethod:n,onClose:C,onBack:r.mfaMethods.length>1?()=>a(null):void 0}):/*#__PURE__*/t(Ts,{user:r,onSelect:v,handleClose:C}):null},Bs=Va((()=>({inProgressMfaFlow:void 0})));const Hs=/*#__PURE__*/Ya([":root{","};"],(e=>js(e.palette)));const js=e=>
|
|
2
|
+
/*#__PURE__*/Ga(["",""],Object.entries(function(e){return{"--privy-color-background":e.background,"--privy-color-background-2":e.background2,"--privy-color-background-3":e.background3,"--privy-color-foreground":e.foreground,"--privy-color-foreground-2":e.foreground2,"--privy-color-foreground-3":e.foreground3,"--privy-color-foreground-4":e.foreground4,"--privy-color-foreground-accent":e.foregroundAccent,"--privy-color-accent":e.accent,"--privy-color-accent-light":e.accentLight,"--privy-color-accent-hover":e.accentHover,"--privy-color-accent-dark":e.accentDark,"--privy-color-accent-darkest":e.accentDarkest,"--privy-color-success":e.success,"--privy-color-success-dark":e.successDark,"--privy-color-success-light":e.successLight,"--privy-color-success-bg":e.successBg,"--privy-color-error":e.error,"--privy-color-error-light":e.errorLight,"--privy-color-error-bg":e.errorBg,"--privy-color-error-bg-hover":e.errorBgHover,"--privy-color-warn":e.warn,"--privy-color-warn-light":e.warnLight,"--privy-color-warn-bg":e.warnBg,"--privy-color-warning-dark":e.warningDark,"--privy-color-error-dark":e.errorDark,"--privy-color-info-bg":e.infoBg,"--privy-color-info-bg-hover":e.infoBgHover,"--privy-color-border-default":e.borderDefault,"--privy-color-border-hover":e.borderHover,"--privy-color-border-focus":e.borderFocus,"--privy-color-border-error":e.borderError,"--privy-color-border-success":e.borderSuccess,"--privy-color-border-warning":e.borderWarning,"--privy-color-border-info":e.borderInfo,"--privy-color-border-interactive":e.borderInteractive,"--privy-color-border-interactive-hover":e.borderInteractiveHover,"--privy-color-background-hover":e.backgroundHover,"--privy-color-background-clicked":e.backgroundClicked,"--privy-color-background-disabled":e.backgroundDisabled,"--privy-color-background-interactive":e.backgroundInteractive,"--privy-color-background-interactive-hover":e.backgroundInteractiveHover,"--privy-color-background-interactive-clicked":e.backgroundInteractiveClicked,"--privy-color-background-interactive-disabled":e.backgroundInteractiveDisabled,"--privy-color-foreground-hover":e.foregroundHover,"--privy-color-foreground-clicked":e.foregroundClicked,"--privy-color-foreground-disabled":e.foregroundDisabled,"--privy-color-foreground-interactive":e.foregroundInteractive,"--privy-color-foreground-interactive-hover":e.foregroundInteractiveHover,"--privy-link-navigation-color":e.linkNavigationColor,"--privy-link-navigation-decoration":e.linkNavigationDecoration,"--privy-accent-has-good-contrast":e.accentHasGoodContrast,"--privy-color-icon-default":e.iconDefault,"--privy-color-icon-muted":e.iconMuted,"--privy-color-icon-subtle":e.iconSubtle,"--privy-color-icon-inverse":e.iconInverse,"--privy-color-icon-success":e.iconSuccess,"--privy-color-icon-warning":e.iconWarning,"--privy-color-icon-error":e.iconError,"--privy-color-icon-interactive":e.iconInteractive,"--privy-color-icon-default-hover":e.iconDefaultHover,"--privy-color-icon-muted-hover":e.iconMutedHover,"--privy-color-icon-subtle-hover":e.iconSubtleHover,"--privy-color-icon-default-clicked":e.iconDefaultClicked,"--privy-color-icon-muted-clicked":e.iconMutedClicked,"--privy-color-icon-subtle-clicked":e.iconSubtleClicked,"--privy-color-icon-default-disabled":e.iconDefaultDisabled,"--privy-color-icon-muted-disabled":e.iconMutedDisabled,"--privy-color-icon-subtle-disabled":e.iconSubtleDisabled,"--privy-color-icon-error-hover":e.iconErrorHover,"--privy-color-icon-interactive-hover":e.iconInteractiveHover,"--privy-color-icon-error-clicked":e.iconErrorClicked,"--privy-color-icon-interactive-clicked":e.iconInteractiveClicked,"--privy-color-icon-muted-disabled-alt":e.iconMutedDisabledAlt,"--privy-color-icon-subtle-disabled-alt":e.iconSubtleDisabledAlt,"--privy-border-radius-xs":"6px","--privy-border-radius-sm":"8px","--privy-border-radius-md":"12px","--privy-border-radius-mdlg":"16px","--privy-border-radius-lg":"24px","--privy-border-radius-full":"9999px","--privy-height-modal-full":"620px","--privy-height-modal-compact":"480px"}}(e)).map((([e,t])=>`${e}: ${t};`)).join("\n")),Vs=/*#__PURE__*/Ka.div.withConfig({displayName:"StylesWrapper",componentId:"sc-188229e4-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 3px var(--privy-color-border-focus);}.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"),$s=({children:e,open:n,onClick:a,...o})=>/*#__PURE__*/t(ui,{show:n,as:i.Fragment,children:/*#__PURE__*/r(hi,{onClose:a,...o,as:Ys,children:[/*#__PURE__*/t(pi,{as:i.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/t(Ks,{id:"privy-dialog-backdrop","aria-hidden":"true"})}),/*#__PURE__*/t(Gs,{children:/*#__PURE__*/t(pi,{as:i.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/t(mi,{as:Zs,children:e})})})]})});let Ks=/*#__PURE__*/Ka.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;}"]),Ys=/*#__PURE__*/Ka.div.withConfig({displayName:"DialogWrapper",componentId:"sc-3cfde0b5-1"})(["position:relative;z-index:999999;"]),Gs=/*#__PURE__*/Ka.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 Zs=/*#__PURE__*/Ka.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);}"]),Js=/*#__PURE__*/Ka.div.withConfig({displayName:"CenterItem",componentId:"sc-3cfde0b5-4"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;"]);let Xs=()=>{let{ready:e,isModalOpen:a}=cr(),{headless:i}=Wa(),{currentScreen:o}=dr(),{status:l,execute:c,reset:d,enabled:u}=$t(),h=Bs((e=>e.inProgressMfaFlow)),p=()=>Bs.setState({inProgressMfaFlow:void 0}),m=a&&o&&o.isCaptchaRequired&&!i&&"ready"===l;return s((()=>{m&&c()}),[m]),s((()=>{!a&&u&&d()}),[a,u]),o&&!e&&o.isShownBeforeReady?/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(tr,{}),/*#__PURE__*/t(hr,{}),/*#__PURE__*/t(Js,{children:/*#__PURE__*/t(pr,{})}),/*#__PURE__*/t(mr,{}),/*#__PURE__*/t(Zt,{})]}):o||"txn"!==h?o?
|
|
3
|
+
/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(wr,{$if:!!h,children:/*#__PURE__*/t(o.component,{})}),"txn"===h&&/*#__PURE__*/t(zs,{onClose:p}),"auth"===h&&/*#__PURE__*/t(Ds.component,{})]}):null:/*#__PURE__*/t(zs,{onClose:p})},Qs=()=>{let e=u(null);/*#__PURE__*/return t(rl,{style:{height:Za(e)},id:"privy-modal-content",children:/*#__PURE__*/t("div",{ref:e,children:/*#__PURE__*/t(Xs,{})})})};const el=({open:e})=>{let r=Wa(),{gracefulClosePrivyModal:n}=(()=>{let{closePrivyModal:e}=$e(),{onUserCloseViaDialogOrKeybindRef:t}=dr();return{gracefulClosePrivyModal:p((()=>{if(!t?.current)return e({shouldCallAuthOnSuccess:!1});t.current()}),[e])}})(),a=Bs((e=>e.inProgressMfaFlow));return is({onMfaRequired:()=>{r.mfa.noPromptOnMfaRequired||Bs.setState({inProgressMfaFlow:"txn"})}}),r.render.standalone?/*#__PURE__*/t(Vs,{children:/*#__PURE__*/t(tl,{id:"privy-modal-content",children:/*#__PURE__*/t(Xs,{})})}):/*#__PURE__*/t($s,{open:!(!e&&!a),id:"privy-dialog","aria-label":"log in or sign up","aria-labelledby":"privy-dialog-title",onClick:()=>n(),children:/*#__PURE__*/t(Vs,{children:/*#__PURE__*/t(Qs,{})})})};let tl=/*#__PURE__*/Ka.div.withConfig({displayName:"ContentWrapper",componentId:"sc-c903accd-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;"]),rl=/*#__PURE__*/Ka(tl).withConfig({displayName:"BaseModal",componentId:"sc-c903accd-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 nl(e){let r=u(null),n=u();return s((()=>{n.current?.remove(),n.current=function({botUsername:e,scriptHost:t}){let r=document.createElement("script"),{origin:n}=new URL(t);return r.async=!0,r.src=`${n}/js/telegram-login.js`,r.setAttribute("data-telegram-login",e),r.setAttribute("data-request-access","write"),r.setAttribute("data-lang","en"),r}(e),r.current?.after(n.current)}),[e]),/*#__PURE__*/t("div",{ref:r,hidden:!0})}const al=()=>{let{ready:e}=Jt(),{client:t}=$e();return s((()=>{let r=()=>{if(!t.connectors||!e)return;let r=t.connectors.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt,id:e.meta.id})));tt.put(Na,r)};return t.connectors?.on("walletsUpdated",r),()=>{t.connectors?.off("walletsUpdated",r)}}),[e,t.connectors]),null};async function il(e,t,r,n,a,i=!1){let o=i,s=async s=>{if(o&&t&&t.length>0){s===(i?0:1)?a("configureMfa","onMfaRequired",{mfaMethods:t}):n.current?.reject(new yr("missing_or_invalid_mfa","MFA verification failed, retry."));let o=await new Promise(((e,t)=>{r.current={resolve:e,reject:t},setTimeout((()=>{let e=new yr("mfa_timeout","Timed out waiting for MFA code");n.current?.reject(e),t(e)}),3e5)}));return await e(o)}return await e()},l=null;for(let e=0;e<4;e++)try{l=await s(e),n.current?.resolve(void 0);break}catch(e){if("missing_or_invalid_mfa"!==e.type)throw n.current?.resolve(void 0),e;o=!0}if(null===l){let e=new yr("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return l}var ol;let sl=(ol=0,()=>"id-"+ol++);function ll(e){return void 0!==e.error}let cl=new class{enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let r=this.callbacks[t];if(!r)throw Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:user-signer:sign":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 r;default:throw Error(`invalid wallet event type ${e}`)}}constructor(){this.callbacks={}}},dl=new Map,ul=(e,t)=>"bigint"==typeof t?t.toString():t;function hl(e,t,r,n){let a=r.contentWindow;if(!a)throw Error("iframe not initialized");let i=((e,t)=>`${e}${JSON.stringify(t,ul)}`)(e,t);if("privy:wallet:create"===e){let e=dl.get(i);if(e)return e}let o=new Promise(((r,i)=>{let o=sl();cl.enqueue(o,{resolve:r,reject:i}),a.postMessage({id:o,event:e,data:t},n)})).finally((()=>{dl.delete(i)}));return dl.set(i,o),o}function pl(e){let r=Ra(),n=u(null),a=u(e.mfaMethods),i=Oa(),[o,c]=l(!1);return s((()=>{a.current=e.mfaMethods}),[e.mfaMethods]),s((()=>{if(!o)return;let t=n.current;if(!t)return;function r(t){var r;t&&t.origin===e.origin&&"string"==typeof(r=t.data).event&&/^privy:.+/.test(r.event)&&function(e){switch(e.event){case"privy:iframe:ready":let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data);case"privy:user-signer:sign":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:add":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:set-recovery":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:connect":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:recover":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:rpc":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallet:create":let r=cl.dequeue(e.event,e.id);return ll(e)?r.reject(new yr(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallets:import":let n=cl.dequeue(e.event,e.id);return ll(e)?n.reject(new yr(e.error.type,e.error.message)):n.resolve(e.data);case"privy:mfa:verify":let a=cl.dequeue(e.event,e.id);return ll(e)?a.reject(new yr(e.error.type,e.error.message)):a.resolve(e.data);case"privy:mfa:init-enrollment":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:auth:unlink-passkey":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let i=cl.dequeue(e.event,e.id);return ll(e)?i.reject(new yr(e.error.type,e.error.message)):i.resolve(e.data);case"privy:farcaster:init-signer":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=cl.dequeue(e.event,e.id);return ll(e)?t.reject(new yr(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(t.data)}let s={signWithUserSigner:r=>il((n=>hl("privy:user-signer:sign",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),addWallet:r=>il((n=>hl("privy:wallets:add",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),setRecovery:r=>il((n=>hl("privy:wallets:set-recovery",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),connect:r=>il((n=>hl("privy:wallets:connect",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),recover:r=>il((n=>hl("privy:wallets:recover",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i,!r.recoveryAccessToken&&!r.recoveryPassword&&!r.recoverySecretOverride),rpc:r=>il((n=>hl("privy:wallets:rpc",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),create:r=>hl("privy:wallet:create",r,t,e.origin),importWallet:r=>hl("privy:wallets:import",r,t,e.origin),createSolana:r=>il((n=>hl("privy:solana-wallet:create",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),createDelegatedAction:r=>hl("privy:delegated-actions:consent",r,t,e.origin),verifyMfa:r=>il((n=>hl("privy:mfa:verify",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i,!0),initEnrollMfa:r=>il((n=>hl("privy:mfa:init-enrollment",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),submitEnrollMfa:r=>il((n=>hl("privy:mfa:submit-enrollment",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),unenrollMfa:r=>il((n=>hl("privy:mfa:unenroll",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),clearMfa:r=>hl("privy:mfa:clear",r,t,e.origin),unlinkPasskeyAccount:r=>il((n=>hl("privy:auth:unlink-passkey",{...r,...n},t,e.origin)),a.current,e.mfaPromise,e.mfaSubmitPromise,i),initFarcasterSigner:r=>hl("privy:farcaster:init-signer",r,t,e.origin),signFarcasterMessage:r=>hl("privy:farcaster:sign",r,t,e.origin)};window.addEventListener("message",r);let l=new AbortController;return gr((()=>hl("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",r),l.abort()}}),[o]),r?
|
|
4
|
+
/*#__PURE__*/t("iframe",{ref:n,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>c(!0),src:wi({origin:e.origin,path:`/apps/${e.appId}/embedded-wallets`,query:{caid:e.clientAnalyticsId,client_id:e.appClientId}})}):null}const ml=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new M("Address to delegate is not associated with current user.");if(!yi(r))throw new M(`useDelegatedActions is not supported for ${r.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}},wl=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new M("Address to delegate is not associated with current user.");let n=r.imported?r:fr(t);if(!n)throw new M("Unable to determine root address for delegated address.");if(!yi(n))throw new M(`useDelegatedActions is not supported for ${n.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:n.address,chainType:n.chainType,imported:n.imported}},yl=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));const gl="popup-privy-oauth",fl="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class vl{async authenticate(){if(!this.api)throw new M("Auth flow has no API instance");try{return await this.api.post($,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw L(e)}}async link(){if(!this.api)throw new M("Auth flow has no API instance");try{return await this.api.post(Y,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw L(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}}}async function Cl({api:e,requesterAppId:t,providerAppId:r}){let n=(await e.get(`/api/v1/apps/${t}/cross-app/connections`)).connections.find((e=>e.provider_app_id===r));if(!n)throw new M("Invalid connected app");return{name:n.provider_app_name,logoUrl:n.provider_app_icon_url||void 0,apiUrl:n.provider_app_custom_api_url,readOnly:n.read_only,customAuthAuthorizeUrl:n.provider_app_custom_auth_authorize_url,customAuthTransactUrl:n.provider_app_custom_auth_transact_url}}const kl=async({user:e,address:t,client:r,request:n,requesterAppId:a,reconnect:i})=>{r.createAnalyticsEvent({eventName:"cross_app_request_started",payload:{address:t,method:n.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 r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Cannot request a signature with this wallet address",address:t}}),new M("Cannot request a signature with this wallet address");let s=r.getProviderAccessToken(o.providerApp.id),l=await Cl({api:r.api,requesterAppId:a,providerAppId:o.providerApp.id});if(!s){if(l.readOnly)throw console.error("cannot transact against a read-only provider app"),new M("Cannot transact against a read-only provider app");await i({appId:o.providerApp.id,action:"link"})&&(s=r.getProviderAccessToken(o.providerApp.id))}if(!s)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Transactions require a valid token",address:t}}),new M("Transactions require a valid token");let c=new URL(l.customAuthTransactUrl||`${l.apiUrl}/oauth/transact`);c.searchParams.set("token",s||""),c.searchParams.set("request",Al(n));let d=O({location:c.href});if(!d)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new M("Failed to initialize signature request");return new Promise(((e,a)=>{let i=setTimeout((()=>{c(),a(new M("Request timeout")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),s=setInterval((()=>{d.closed&&(c(),a(new M("User rejected request")),r.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?r.storeProviderAccessToken(o.providerApp.id,i.data.token.value):"clear"===i.data.token?.action&&r.storeProviderAccessToken(o.providerApp.id,null),"PRIVY_CROSS_APP_ACTION_RESPONSE"===i.data.type&&i.data.result&&(c(),e(i.data.result),r.createAnalyticsEvent({eventName:"cross_app_request_success",payload:{address:t,method:n.method}})),"PRIVY_CROSS_APP_ACTION_ERROR"===i.data.type&&i.data.error&&(c(),a(i.data.error),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:i.data.error,address:t}})))};window.addEventListener("message",l);let c=()=>{d.close(),clearInterval(s),clearTimeout(i),window.removeEventListener("message",l)}}))};let Al=e=>JSON.stringify({content:{request:{request:bl(e,ii)}},timestamp:Date.now(),callbackUrl:window.origin});const bl=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>bl(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,bl(r,t)]))):e,Tl=({passkeys:e,isLoading:r,errorReason:n,success:a,expanded:i,onLinkPasskey:o,onUnlinkPasskey:s,onExpand:l,onBack:c,onClose:d})=>/*#__PURE__*/t(Kt,a?{title:"Passkeys updated",icon:Ai,iconVariant:"success",primaryCta:{label:"Done",onClick:d},onClose:d,watermark:!0}:i?{icon:bi,title:"Your passkeys",onBack:c,onClose:d,watermark:!0,children:/*#__PURE__*/t(El,{passkeys:e,expanded:i,onUnlink:s,onExpand:l})}:{icon:bi,title:"Set up passkey verification",subtitle:"Verify with passkey",primaryCta:{label:"Add new passkey",onClick:o,loading:r},onClose:d,watermark:!0,helpText:n||void 0,children:0===e.length?/*#__PURE__*/t(Il,{}):/*#__PURE__*/t(_l,{children:/*#__PURE__*/t(El,{passkeys:e,expanded:i,onUnlink:s,onExpand:l})})});let _l=/*#__PURE__*/Ka.div.withConfig({displayName:"ContentContainer",componentId:"sc-d4c46a0c-0"})(["margin-bottom:12px;"]),El=({passkeys:e,expanded:n,onUnlink:a,onExpand:i})=>{let[o,s]=l([]),c=n?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 r("div",{children:[/*#__PURE__*/t(Nl,{children:"Your passkeys"}),/*#__PURE__*/r(Wl,{children:[e.slice(0,c).map((e=>/*#__PURE__*/r(Ml,{children:[/*#__PURE__*/r("div",{children:[/*#__PURE__*/t(Rl,{children:d(e)}),/*#__PURE__*/r(Ol,{children:["Last used:"," ",(e.latestVerifiedAt??e.firstVerifiedAt)?.toLocaleString()??"N/A"]})]}),/*#__PURE__*/t(Ll,{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(vr,{}):/*#__PURE__*/t(Ti,{size:16})})]},e.credentialId))),e.length>2&&!n&&/*#__PURE__*/t(xl,{onClick:i,children:"View all"})]})]})},Il=()=>/*#__PURE__*/r(Cr,{style:{color:"var(--privy-color-foreground)"},children:[/*#__PURE__*/t(kr,{children:"Verify with Touch ID, Face ID, PIN, or hardware key"}),/*#__PURE__*/t(kr,{children:"Takes seconds to set up and use"}),/*#__PURE__*/t(kr,{children:"Use your passkey to verify transactions and login to your account"})]});const Sl={component:()=>{let{user:e,unlinkPasskey:r}=cr(),{linkWithPasskey:n,closePrivyModal:a}=$e(),i=e?.linkedAccounts.filter((e=>"passkey"===e.type)),[o,c]=l(!1),[d,u]=l(""),[h,p]=l(!1),[m,w]=l(!1);return s((()=>{0===i.length&&w(!1)}),[i.length]),/*#__PURE__*/t(Tl,{passkeys:i,isLoading:o,errorReason:d,success:h,expanded:m,onLinkPasskey:()=>{c(!0),n().then((()=>p(!0))).catch((e=>{if(e instanceof Ke){if(e.privyErrorCode===K.CANNOT_LINK_MORE_OF_TYPE)return void u("Cannot link more passkeys to account.");if(e.privyErrorCode===K.PASSKEY_NOT_ALLOWED)return void u("Passkey request timed out or rejected by user.")}u("Unknown error occurred.")})).finally((()=>{c(!1)}))},onUnlinkPasskey:async e=>(c(!0),await r(e).then((()=>p(!0))).catch((e=>{e instanceof Ke&&e.privyErrorCode===K.MISSING_MFA_CREDENTIALS?u("Cannot unlink a passkey enrolled in MFA"):u("Unknown error occurred.")})).finally((()=>{c(!1)}))),onExpand:()=>w(!0),onBack:()=>w(!1),onClose:()=>a()})}},Ul=/*#__PURE__*/Ka.div.withConfig({displayName:"DoubleIconWrapper",componentId:"sc-d4c46a0c-1"})(["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 Pl=/*#__PURE__*/Ga(["&&{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 xl=/*#__PURE__*/Ka.button.withConfig({displayName:"LinkButton",componentId:"sc-d4c46a0c-2"})(["",""],Pl);let Wl=/*#__PURE__*/Ka.div.withConfig({displayName:"List",componentId:"sc-d4c46a0c-3"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.8rem;padding:0.5rem 0rem 0rem;flex-grow:1;width:100%;"]),Nl=/*#__PURE__*/Ka.div.withConfig({displayName:"PasskeyListTitle",componentId:"sc-d4c46a0c-4"})(["line-height:20px;height:20px;font-size:1em;font-weight:450;display:flex;justify-content:flex-beginning;width:100%;"]),Rl=/*#__PURE__*/Ka.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-d4c46a0c-5"})(["font-size:1em;line-height:1.3em;font-weight:500;color:var(--privy-color-foreground-2);padding:0.2em 0;"]),Ol=/*#__PURE__*/Ka.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-d4c46a0c-6"})(["font-size:0.875rem;line-height:1rem;color:#64668b;padding:0.2em 0;"]),Ml=/*#__PURE__*/Ka.div.withConfig({displayName:"PasskeyListItem",componentId:"sc-d4c46a0c-7"})(["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;"]),Fl=/*#__PURE__*/Ga([":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);}"]),Ll=/*#__PURE__*/Ka.button.withConfig({displayName:"PasskeyItemUnlinkButton",componentId:"sc-d4c46a0c-8"})(["",""],Fl);const Dl=new Map([[Ar,null],[br,"external"],[Tr,"external"],[_r,"external"],[Er,"external"],[Ir,"manual"],[Sr,"moonpay"]]),ql=()=>{let e=Wa(),{user:t}=cr(),{client:r,refreshSessionAndUser:n,walletProxy:a}=$e();return{migrate:p((async()=>{if("legacy-embedded-wallets-only"===e.embeddedWallets.mode)return{success:!0};if(!t)throw new M("User must be authenticated before migrating wallets",K.MUST_BE_AUTHENTICATED);if(!a)throw new M("Cannot connect to wallet proxy");let i=await r.getAccessToken();if(!i)throw new M("User must be authenticated before migrating wallets",K.MUST_BE_AUTHENTICATED);let o=t.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&yi(e)&&!It(e)));if(0===o.length)return{success:!0};let s=o.filter((e=>e.imported)),l=o.filter((e=>!e.imported));if(l.length>0){let e=l.find((e=>"ethereum"===e.chainType&&0===e.walletIndex))??l.find((e=>"solana"===e.chainType&&0===e.walletIndex))??null;if(!e)throw new M("Primary wallet not found");let{entropyId:t,entropyIdVerifier:r}=Ur(e);try{await a.connect({accessToken:i,entropyId:t,entropyIdVerifier:r})}catch(n){if(!Pr(n)||"privy"!==e.recoveryMethod)throw n;await a.recover({accessToken:i,entropyId:t,entropyIdVerifier:r})}await a.createDelegatedAction({accessToken:i,rootWallet:{address:e.address,chainType:e.chainType,imported:!1},delegatedWallets:l.map((e=>({address:e.address,chainType:e.chainType,walletIndex:e.walletIndex??0})))})}for(let e of s){let{entropyId:t,entropyIdVerifier:r}=Ur(e);try{await a.connect({accessToken:i,entropyId:t,entropyIdVerifier:r})}catch(s){if(!Pr(s)||"privy"!==e.recoveryMethod)throw s;await a.recover({accessToken:i,entropyId:t,entropyIdVerifier:r})}await a.createDelegatedAction({accessToken:i,rootWallet:{address:e.address,chainType:e.chainType,imported:!0},delegatedWallets:[{address:e.address,chainType:e.chainType,walletIndex:e.walletIndex??0}]})}return await n(),{success:!0}}),[e.embeddedWallets.mode,t,a,r,n])}},zl=({disabled:e})=>{let{migrate:t}=ql(),{user:r}=cr(),{walletProxy:n}=$e();return s((()=>{!e&&r&&n&&t().catch((e=>{console.debug("Unable to migrate wallets: ",e)}))}),[r,n,e,t]),null},Bl=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}),Hl=({providerApp:e,success:r,error:n,onClose:a})=>{let{title:i,subtitle:s}=o((()=>r?{title:`Successfully connected with ${e.name}`,subtitle:"You're good to go!"}:n?{title:"Authentication failed",subtitle:n.message}:{title:`Connecting to ${e.name}`,subtitle:`Please check the pop-up from ${e.name} to continue`}),[r,n,e.name]);/*#__PURE__*/return t(Kt,{title:i,subtitle:s,icon:e.logoUrl,iconVariant:"loading",iconLoadingStatus:{success:r,fail:!!n},onBack:a,watermark:!0})},jl={component:()=>{let e=Wa(),{data:r,navigate:n,setModalData:a,onUserCloseViaDialogOrKeybindRef:i}=dr(),{crossAppAuthFlow:o,updateWallets:c,closePrivyModal:d,createAnalyticsEvent:u}=$e(),{logout:h}=Ja(),[p,m]=l({}),w=r?.crossAppAuth,y={id:w.appId,name:w.name,logoUrl:w.logoUrl},g=new M(`There was an issue connecting your ${y.name} account. Please try again.`),f=new Qe((async e=>{if(w.popup)try{let t=await o({appId:e,popup:w.popup,action:w.action});m({data:t})}catch(e){if(e instanceof M)m({error:e});else if(e instanceof we){if(e.privyErrorCode===K.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return a({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:`privy:${y.id}`,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void n(Rr);w.popup&&w.popup.close(),m({error:g})}else m({error:g})}else m({error:g})})),v=()=>{p.data&&(c(),w.onSuccess(p.data),d({shouldCallAuthOnSuccess:!0,isSuccess:!0})),w.onError(p.error??new M("User canceled flow")),d({shouldCallAuthOnSuccess:!1,isSuccess:!1})};return i.current=v,s((()=>{y.id.length&&f.execute(y.id)}),[y.id]),s((()=>{if(!p.data)return;let t=p.data;if(e.legal.requireUsersAcceptTerms&&!t.hasAcceptedTerms){let e=setTimeout((()=>{n(xr)}),Ma);return()=>clearTimeout(e)}if(Wr(t,e.embeddedWallets)){let e=setTimeout((()=>{a({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),u({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:`privy:${y.id}`,screen:"CrossAppAuthScreen"}}),h()},callAuthOnSuccessOnClose:!0}}),n(Nr)}),Ma);return()=>clearTimeout(e)}let r=setTimeout(v,Ma);return()=>clearTimeout(r)}),[p.data]),/*#__PURE__*/t(Hl,{providerApp:y,success:!!p.data,error:p.error,onClose:v})}},Vl=({appName:e,address:r,success:n,error:a,onAccept:i,onDecline:o,onClose:s})=>/*#__PURE__*/t(Kt,n||a?{title:a?"Something went wrong":"Success!",subtitle:a?"Please try again.":`You've successfully granted delegated action permissions to ${e}.`,icon:a?_i:Ai,iconVariant:a?"error":"success",onBack:s,watermark:!0}:{title:"Enable offline access",subtitle:`By confirming, ${e} will be able to use your wallet for you even when you're not around. You can revoke this later.`,icon:Ei,primaryCta:{label:"Accept",onClick:i},secondaryCta:{label:"Not now",onClick:o},onBack:s,watermark:!0,children:/*#__PURE__*/t(Or,{address:r,title:"Wallet"})}),$l={component:()=>{let{data:e}=dr(),r=Wa(),{closePrivyModal:n}=$e(),[a,i]=l(!1),[o,c]=l(),{address:d,onDelegate:u,onSuccess:h,onError:p}=e.delegatedActions.consent,m=async()=>{a?h():p(o??new M("User declined delegating actions.")),n({shouldCallAuthOnSuccess:!1})};return s((()=>{if(!a&&!o)return;let e=setTimeout(m,Fa);return()=>clearTimeout(e)}),[a,o]),/*#__PURE__*/t(Vl,{appName:r.name,address:d,success:a,error:o,onAccept:async()=>{try{await u(),i(!0)}catch(e){c(e)}},onDecline:()=>{m()},onClose:m})}},Kl=({appName:e,success:r,error:n,onRevoke:a,onDeny:i,onClose:o})=>/*#__PURE__*/t(Kt,r||n?{title:n?"Something went wrong":"Success!",subtitle:n?"Please try again.":"You've successfully revoked permissions.",icon:n?_i:Ai,iconVariant:n?"error":"success",onBack:o,watermark:!0}:{title:"Revoke offline access to wallet",subtitle:`By confirming, ${e} will no longer be able to use this wallet on your behalf when you are not online.`,icon:Ii,primaryCta:{label:"Confirm",onClick:a},secondaryCta:{label:"Deny",onClick:i},onBack:o,watermark:!0}),Yl={component:()=>{let{data:e}=dr(),r=Wa(),{closePrivyModal:n}=$e(),[a,i]=l(!1),[o,c]=l(),{onRevoke:d,onSuccess:u,onError:h}=e.delegatedActions.revoke,p=async()=>{a?u():h(o??new M("User declined revoking access to their delegated wallet.")),n({shouldCallAuthOnSuccess:!1})};return s((()=>{if(!a&&!o)return;let e=setTimeout(p,Fa);return()=>clearTimeout(e)}),[a,o]),/*#__PURE__*/t(Kl,{appName:r.name,success:a,error:o,onRevoke:async()=>{try{await d(),i(!0)}catch(e){c(e)}},onDeny:()=>{p()},onClose:p})}};let Gl="#8a63d2";const Zl=({appName:e,loading:n,success:a,errorMessage:i,connectUri:o,onBack:s,onClose:l,onOpenFarcaster:c})=>/*#__PURE__*/t(Kt,y||n?f?{title:i?i.message:"Add a signer to Farcaster",subtitle:i?i.detail:`This will allow ${e} to add casts, likes, follows, and more on your behalf.`,icon:Mr,iconVariant:"loading",iconLoadingStatus:{success:a,fail:!!i},primaryCta:o&&c?{label:"Open Farcaster app",onClick:c}:void 0,onBack:s,onClose:l,watermark:!0}:{title:i?i.message:"Requesting signer from Farcaster",subtitle:i?i.detail:"This should only take a moment",icon:Mr,iconVariant:"loading",iconLoadingStatus:{success:a,fail:!!i},onBack:s,onClose:l,watermark:!0,children:o&&y&&/*#__PURE__*/t(Jl,{children:/*#__PURE__*/t(Fr,{text:"Take me to Farcaster",url:o,color:Gl})})}:{title:"Add a signer to Farcaster",subtitle:`This will allow ${e} to add casts, likes, follows, and more on your behalf.`,onBack:s,onClose:l,watermark:!0,children:/*#__PURE__*/r(Xl,{children:[/*#__PURE__*/t(Ql,{children:o?/*#__PURE__*/t(Lr,{url:o,size:275,squareLogoElement:Mr}):/*#__PURE__*/t(rc,{children:/*#__PURE__*/t(pr,{})})}),/*#__PURE__*/r(ec,{children:[/*#__PURE__*/t(tc,{children:"Or copy this link and paste it into a phone browser to open the Farcaster app."}),o&&/*#__PURE__*/t(xi,{text:o,itemName:"link",color:Gl})]})]})});let Jl=/*#__PURE__*/Ka.div.withConfig({displayName:"MobileLinkContainer",componentId:"sc-75c99bb6-0"})(["margin-top:24px;"]),Xl=/*#__PURE__*/Ka.div.withConfig({displayName:"ContentContainer",componentId:"sc-75c99bb6-1"})(["display:flex;flex-direction:column;align-items:center;gap:24px;"]),Ql=/*#__PURE__*/Ka.div.withConfig({displayName:"QrContainer",componentId:"sc-75c99bb6-2"})(["padding:24px;position:relative;display:flex;align-items:center;justify-content:center;min-height:275px;"]),ec=/*#__PURE__*/Ka.div.withConfig({displayName:"InstructionsContainer",componentId:"sc-75c99bb6-3"})(["display:flex;flex-direction:column;align-items:center;gap:16px;"]),tc=/*#__PURE__*/Ka.div.withConfig({displayName:"InstructionText",componentId:"sc-75c99bb6-4"})(["font-size:0.875rem;text-align:center;color:var(--privy-color-foreground-2);"]),rc=/*#__PURE__*/Ka.div.withConfig({displayName:"LoaderWrapper",componentId:"sc-75c99bb6-5"})(["position:relative;width:82px;height:82px;"]);const nc={component:()=>{let{lastScreen:e,navigateBack:r,data:n}=dr(),a=Wa(),{requestFarcasterSignerStatus:i,closePrivyModal:o}=$e(),[c,d]=l(void 0),[h,p]=l(!1),[m,w]=l(!1),y=u([]),g=n?.farcasterSigner;s((()=>{let e=Date.now(),t=setInterval((async()=>{if(!g?.public_key)return clearInterval(t),void d({retryable:!0,message:"Connect failed",detail:"Something went wrong. Please try again."});"approved"===g.status&&(clearInterval(t),p(!1),w(!0),y.current.push(setTimeout((()=>o({shouldCallAuthOnSuccess:!1,isSuccess:!0})),Ma)));let r=await i(g?.public_key),n=Date.now()-e;"approved"===r.status?(clearInterval(t),p(!1),w(!0),y.current.push(setTimeout((()=>o({shouldCallAuthOnSuccess:!1,isSuccess:!0})),Ma))):n>3e5?(clearInterval(t),d({retryable:!0,message:"Connect failed",detail:"The request timed out. Try again."})):"revoked"===r.status&&(clearInterval(t),d({retryable:!0,message:"Request rejected",detail:"The request was rejected. Please try again."}))}),2e3);return()=>{clearInterval(t),y.current.forEach((e=>clearTimeout(e)))}}),[]);let f="pending_approval"===g?.status?g.signer_approval_url:void 0;/*#__PURE__*/return t(Zl,{appName:a.name,loading:h,success:m,errorMessage:c,connectUri:f,onBack:e?r:void 0,onClose:o,onOpenFarcaster:()=>{f&&(window.location.href=f)}})}},ac=({onClose:e})=>/*#__PURE__*/t(Kt,{title:"Could not log in with provider",subtitle:"It looks like you're using an in-app browser. To log in, please try again using an external browser.",icon:Si,primaryCta:{label:"Close",onClick:e},watermark:!0}),ic={component:()=>{let{closePrivyModal:e}=$e();/*#__PURE__*/return t(ac,{onClose:()=>e()})}},oc=({title:e="Connect your email",subtitle:r="Add your email to your account"})=>/*#__PURE__*/t(Kt,{title:e,subtitle:r,icon:Ni,watermark:!0,children:/*#__PURE__*/t(Dr,{children:/*#__PURE__*/t(qr,{stacked:!0})})}),sc={component:()=>{let e=Wa();/*#__PURE__*/return t(oc,{subtitle:`Add your email to your ${e?.name} account`})}},lc=({title:e="Connect your phone",subtitle:r="Add your number to your account",onSubmit:n,isSubmitting:a=!1})=>{let[i,o]=l(null),s=async()=>{i?.qualifiedPhoneNumber&&await n(i)};/*#__PURE__*/return t(Kt,{title:e,subtitle:r,icon:ti,primaryCta:{label:a?"Submitting":"Submit",onClick:s,disabled:!i?.isValid||a},watermark:!0,children:/*#__PURE__*/t(zr,{onChange:e=>{o(e)},onSubmit:s,noIncludeSubmitButton:!0,hideRecent:!0})})},cc={component:()=>{let{currentScreen:e,data:r,navigate:n,setModalData:a}=dr(),i=Wa(),{initLoginWithSms:o}=$e(),[s,c]=l(!1);/*#__PURE__*/return t(lc,{subtitle:`Add your number to your ${i?.name} account`,onSubmit:async t=>{c(!0);try{await o({phoneNumber:t.qualifiedPhoneNumber,withPrivyUi:!0}),n(Br)}catch(t){a({errorModalData:{error:t,previousScreen:r?.errorModalData?.previousScreen||e||cc}}),n(Hr)}finally{c(!1)}},isSubmitting:s})}},dc=({title:e="Could not connect with wallet",subtitle:r="Please check that Phantom multichain is enabled and try again.",primaryCtaText:n="Try again",secondaryCtaText:a="Cancel",onTryAgain:i,onCancel:o})=>/*#__PURE__*/t(Kt,{title:e,subtitle:r,icon:Ui,iconVariant:"error",primaryCta:{label:n,onClick:i},secondaryCta:{label:a,onClick:o},watermark:!0}),uc={component:()=>{let{closePrivyModal:e}=$e(),{navigate:r}=dr();/*#__PURE__*/return t(dc,{onTryAgain:()=>{r(jr)},onCancel:async()=>{await e()}})}};function hc(){let{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:r,submitEnrollmentWithSms:n,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:i,unenroll:o,enrollInMfa:s}=h(ur);return{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:r,submitEnrollmentWithSms:n,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:i,unenrollWithSms:()=>o("sms"),unenrollWithTotp:()=>o("totp"),unenrollWithPasskey:e=>o("passkey",e),showMfaEnrollmentModal:()=>s(!0),closeMfaEnrollmentModal:()=>s(!1)}}const pc=e=>/*#__PURE__*/r(mc,{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 mc=/*#__PURE__*/Ka.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 wc=({showIntro:e,userMfaMethods:a,appMfaMethods:i,userHasAuthSms:o,isTotpLoading:s,isPasskeyLoading:l,error:c,onClose:d,backFn:u,handleSelectMethod:h,setRemovingMfaMethod:p})=>{let m=a.reduce(((e,t)=>({...e,[t]:!0})),{}),w=i.reduce(((e,t)=>({...e,[t]:!0})),{});/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{backFn:e?u:void 0,onClose:d},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(ri,{})}),/*#__PURE__*/t(ss,{children:"Choose a verification method"}),a.length>0?/*#__PURE__*/t(ls,{children:"To add or delete verification methods, verification is required."}):/*#__PURE__*/t(ls,{children:"How would you like to verify your identity?"}),c&&/*#__PURE__*/t(bs,{style:{marginTop:"1.25rem"},children:c.message}),/*#__PURE__*/r(ms,{children:[(w.passkey||m.passkey)&&/*#__PURE__*/r(ws,{children:[/*#__PURE__*/t(Yt,{style:{justifyContent:"center"},onClick:()=>h("passkey"),disabled:m.passkey||l,children:l?/*#__PURE__*/t(pr,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/r(vs,{children:[/*#__PURE__*/r(gs,{children:[/*#__PURE__*/t(ei,{}),"Passkey"]}),m.passkey?/*#__PURE__*/t(yc,{color:"green",children:"Enabled"}):/*#__PURE__*/t(fs,{$isAccent:!0,children:/*#__PURE__*/t(Fi,{})})]})}),m.passkey&&/*#__PURE__*/t(ys,{style:{position:"absolute",right:0},onClick:()=>p("passkey"),children:/*#__PURE__*/t(Li,{})})]},"passkey"),(w.totp||m.totp)&&/*#__PURE__*/r(ws,{children:[/*#__PURE__*/t(Yt,{style:{justifyContent:"center"},disabled:m.totp||s,onClick:()=>h("totp"),children:s?/*#__PURE__*/t(pr,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/r(vs,{children:[/*#__PURE__*/r(gs,{children:[/*#__PURE__*/t(Qa,{}),"Authenticator app"]}),m.totp&&/*#__PURE__*/t(yc,{color:"green",children:"Enabled"})]})}),m.totp&&/*#__PURE__*/t(ys,{style:{position:"absolute",right:0},onClick:()=>p("totp"),children:/*#__PURE__*/t(Li,{})})]},"totp"),(w.sms||m.sms)&&/*#__PURE__*/r(ws,{children:[/*#__PURE__*/t(Yt,{disabled:m.sms||o,onClick:()=>h("sms"),children:/*#__PURE__*/r(vs,{children:[/*#__PURE__*/r(gs,{children:[/*#__PURE__*/t(ti,{}),"SMS"]}),m.sms&&/*#__PURE__*/t(yc,{color:"green",children:"Enabled"}),o&&/*#__PURE__*/t(fs,{children:"Disabled"})]})}),m.sms&&/*#__PURE__*/t(ys,{style:{position:"absolute",right:0},onClick:()=>p("sms"),children:/*#__PURE__*/t(Li,{})})]},"sms")]}),/*#__PURE__*/t(gc,{children:"You can always change your selection later"}),/*#__PURE__*/t(Zt,{})]})};let yc=/*#__PURE__*/Ka(Vr).withConfig({displayName:"StyledChip",componentId:"sc-5f06df7f-0"})(["margin-right:1.5rem;"]),gc=/*#__PURE__*/Ka(Cs).withConfig({displayName:"StyledTerms",componentId:"sc-5f06df7f-1"})(["&&{margin-top:1rem;}text-align:center;"]);const fc=({style:e,...n})=>/*#__PURE__*/r("svg",{x:0,y:0,width:"65",height:"64",viewBox:"0 0 65 64",style:{height:"64px",width:"65px",...e},xmlns:"http://www.w3.org/2000/svg",...n,children:[/*#__PURE__*/r("g",{clipPath:"url(#clip0_113_33841)",children:[/*#__PURE__*/t("path",{d:"M39.1193 0.943398C34.636 -0.174912 29.9185 -0.334713 25.328 0.656273C24.9732 0.732859 24.7477 1.08253 24.8243 1.43729C24.9009 1.79205 25.2506 2.01756 25.6053 1.94097C30.0015 0.991934 34.53 1.14842 38.8375 2.22802C49.1385 4.80983 57.7129 12.5548 60.9786 22.6718C62.2416 26.5843 62.7781 30.7505 62.8855 35.1167C62.8945 35.4795 63.1958 35.7664 63.5586 35.7575C63.9215 35.7485 64.2083 35.4472 64.1994 35.0843C64.0905 30.6582 63.5477 26.3849 62.2536 22.3432C58.8621 11.7515 49.9005 3.63265 39.1193 0.943398Z"}),/*#__PURE__*/t("path",{d:"M21.9931 2.93163C22.343 2.83511 22.5484 2.47325 22.4518 2.12339C22.3553 1.77352 21.9935 1.56815 21.6436 1.66466C16.8429 2.98903 10.0898 7.56519 5.91628 13.6786C5.91465 13.681 5.91304 13.6834 5.91145 13.6858C2.24684 19.2083 -0.0503572 26.1484 0.591012 32.8828C0.591623 32.8892 0.592328 32.8956 0.593127 32.902C0.746837 34.1317 1.00488 35.3591 1.26323 36.5879C1.80735 39.1761 2.35282 41.7706 1.92765 44.4064C1.86986 44.7647 2.11347 45.102 2.47177 45.1598C2.83007 45.2176 3.16738 44.974 3.22518 44.6157C3.66961 41.8605 3.11776 39.173 2.56581 36.4851C2.31054 35.2419 2.05525 33.9987 1.89847 32.7486C1.29525 26.3851 3.46802 19.7466 7.00418 14.416C11.0189 8.5373 17.5201 4.16562 21.9931 2.93163Z"}),/*#__PURE__*/t("path",{d:"M30.6166 4.39985C38.8671 3.89603 47.1159 7.26314 52.6556 13.7139C52.8921 13.9893 52.8605 14.4042 52.5852 14.6406C52.3099 14.8771 51.895 14.8455 51.6585 14.5702C46.3904 8.43576 38.541 5.23144 30.6927 5.71195C30.6899 5.71212 30.6871 5.71227 30.6843 5.71241C20.7592 6.19265 11.4643 12.9257 8.04547 22.3603C7.92183 22.7016 7.54498 22.8779 7.20375 22.7543C6.86253 22.6306 6.68616 22.2538 6.80981 21.9126C10.4114 11.9735 20.1717 4.90702 30.6166 4.39985Z"}),/*#__PURE__*/t("path",{d:"M54.6576 16.5848C54.4553 16.2836 54.047 16.2033 53.7457 16.4057C53.4444 16.608 53.3642 17.0163 53.5665 17.3176C56.6376 21.8904 57.9074 26.8665 58.4094 32.7717C58.4401 33.1333 58.7582 33.4016 59.1199 33.3708C59.4815 33.3401 59.7497 33.022 59.719 32.6604C59.206 26.6261 57.8965 21.4076 54.6576 16.5848Z"}),/*#__PURE__*/t("path",{d:"M59.2796 35.4504C59.6419 35.4277 59.9539 35.703 59.9765 36.0653C60.2242 40.0279 60.2265 44.5112 59.7881 47.8243C59.7405 48.1841 59.4102 48.4372 59.0504 48.3896C58.6906 48.342 58.4376 48.0117 58.4852 47.6519C58.9077 44.4586 58.91 40.0704 58.6648 36.1473C58.6421 35.785 58.9174 35.473 59.2796 35.4504Z"}),/*#__PURE__*/t("path",{d:"M7.05311 25.5432C7.13829 25.1904 6.92135 24.8354 6.56855 24.7502C6.21576 24.665 5.86071 24.882 5.77553 25.2348C5.2932 27.2325 5.0428 29.2847 5.03288 31.3388C5.02266 33.4559 5.41742 35.5225 5.81234 37.5899C6.1354 39.2811 6.45855 40.9728 6.5602 42.6932C6.69373 44.9531 6.21839 47.2163 5.39698 49.3703C5.26766 49.7094 5.43774 50.0891 5.77685 50.2184C6.11596 50.3477 6.4957 50.1777 6.62502 49.8386C7.49325 47.5617 8.01954 45.1092 7.87221 42.6157C7.77126 40.9071 7.44813 39.2252 7.12512 37.5439C6.73099 35.4925 6.33704 33.442 6.34716 31.3451C6.35659 29.3933 6.59455 27.4425 7.05311 25.5432Z"}),/*#__PURE__*/t("path",{d:"M24.2964 10.94C24.4317 11.2768 24.2683 11.6595 23.9315 11.7947C17.1187 14.5307 12.0027 20.7047 10.959 27.9852C10.523 31.0269 10.9941 34.0398 11.465 37.052C11.7303 38.7483 11.9954 40.4443 12.0985 42.1451C12.3221 45.833 11.902 49.8839 9.50192 53.5696C9.30387 53.8737 8.89677 53.9597 8.59264 53.7617C8.28851 53.5636 8.20251 53.1565 8.40056 52.8524C10.5873 49.4944 11.0012 45.7644 10.7867 42.2246C10.6821 40.499 10.4185 38.7833 10.1552 37.0686C9.68265 33.9923 9.21067 30.9195 9.65804 27.7987C10.7724 20.025 16.221 13.4748 23.4417 10.5751C23.7785 10.4399 24.1612 10.6032 24.2964 10.94Z"}),/*#__PURE__*/t("path",{d:"M47.3662 14.6814C41.9915 9.64741 34.2017 7.89046 27.122 9.4433C26.7675 9.52105 26.5432 9.87147 26.6209 10.226C26.6987 10.5805 27.0491 10.8048 27.4036 10.7271C34.1075 9.25665 41.4426 10.934 46.4677 15.6406C50.7033 19.6077 53.1628 25.38 53.8066 31.6779C53.8435 32.0389 54.1661 32.3017 54.5272 32.2648C54.8883 32.2279 55.151 31.9053 55.1141 31.5442C54.4456 25.0047 51.8822 18.9111 47.3662 14.6814Z"}),/*#__PURE__*/t("path",{d:"M54.9766 34.6738C55.3376 34.6368 55.6604 34.8994 55.6975 35.2604C56.3216 41.337 56.0526 47.9003 55.1104 54.2496C55.0571 54.6086 54.7229 54.8565 54.3639 54.8032C54.0049 54.7499 53.7571 54.4157 53.8103 54.0567C54.7394 47.7957 55.001 41.3439 54.39 35.3947C54.353 35.0336 54.6156 34.7109 54.9766 34.6738Z"}),/*#__PURE__*/t("path",{d:"M32.0659 13.3553C21.9959 13.3553 13.814 21.3892 13.814 31.3219C13.814 32.3829 13.9081 33.4225 14.0876 34.4334C14.1511 34.7907 14.4922 35.029 14.8495 34.9655C15.2069 34.9021 15.4451 34.561 15.3817 34.2036C15.2155 33.2677 15.1283 32.305 15.1283 31.3219C15.1283 22.1352 22.7014 14.6696 32.0659 14.6696C36.2978 14.6696 40.1642 16.1949 43.1319 18.7152C43.4086 18.9501 43.8233 18.9163 44.0582 18.6396C44.2931 18.363 44.2593 17.9483 43.9827 17.7134C40.7847 14.9975 36.6188 13.3553 32.0659 13.3553Z"}),/*#__PURE__*/t("path",{d:"M45.455 20.1635C45.717 19.9123 46.133 19.921 46.3842 20.183C49.2843 23.2072 50.2126 27.9605 50.8269 31.9494C51.5188 36.4426 51.6244 40.826 51.6244 42.8585C51.6244 43.2214 51.3302 43.5156 50.9673 43.5156C50.6044 43.5156 50.3101 43.2214 50.3101 42.8585C50.3101 40.8589 50.2055 36.5497 49.5279 32.1494C48.9577 28.4462 48.1356 23.9082 45.4356 21.0927C45.1844 20.8307 45.1931 20.4147 45.455 20.1635Z"}),/*#__PURE__*/t("path",{d:"M51.4576 46.6219C51.4864 46.2601 51.2165 45.9435 50.8547 45.9146C50.493 45.8858 50.1763 46.1557 50.1474 46.5175C49.8247 50.5654 49.403 54.6088 48.5474 58.3439C48.4663 58.6977 48.6874 59.0502 49.0412 59.1312C49.3949 59.2123 49.7474 58.9912 49.8285 58.6374C50.7067 54.8039 51.134 50.6806 51.4576 46.6219Z"}),/*#__PURE__*/t("path",{d:"M15.1454 36.852C15.5015 36.7819 15.847 37.0137 15.9171 37.3698C17.3066 44.4257 16.3467 50.8355 12.6672 56.4502C12.4682 56.7537 12.0609 56.8385 11.7573 56.6396C11.4538 56.4407 11.369 56.0333 11.5679 55.7298C15.0299 50.4469 15.9617 44.3985 14.6276 37.6238C14.5575 37.2677 14.7893 36.9221 15.1454 36.852Z"}),/*#__PURE__*/t("path",{d:"M32.0659 17.631C25.5291 17.631 19.1165 22.691 18.462 29.0504C18.1754 31.8345 18.578 34.5769 18.9807 37.3204C19.3323 39.7159 19.684 42.1124 19.5772 44.5381C19.3328 50.0898 17.7039 54.6726 14.905 58.4471C14.6888 58.7386 14.7499 59.1502 15.0414 59.3663C15.333 59.5825 15.7445 59.5214 15.9607 59.2299C18.9293 55.2266 20.6354 50.386 20.8903 44.5959C20.9966 42.1811 20.6438 39.7923 20.2912 37.4051C19.888 34.6752 19.4851 31.9473 19.7694 29.1849C20.3444 23.5983 26.0946 18.9453 32.0659 18.9453C34.851 18.9453 42.057 20.4534 44.3492 27.9205C45.7856 32.5998 46.1774 38.9326 45.8295 45.0849C45.4816 51.2364 44.3994 57.12 42.9442 60.8928C42.8136 61.2314 42.9822 61.6118 43.3208 61.7424C43.6594 61.873 44.0398 61.7044 44.1704 61.3658C45.6929 57.4186 46.7895 51.386 47.1417 45.1591C47.4938 38.9329 47.1068 32.4249 45.6056 27.5348C43.0612 19.2461 35.0851 17.631 32.0659 17.631Z"}),/*#__PURE__*/t("path",{d:"M21.9529 56.4512C22.2569 56.6494 22.3426 57.0566 22.1444 57.3606C21.7369 57.9854 21.3784 58.6391 21.0199 59.2928C20.6614 59.9465 20.3028 60.6004 19.8953 61.2253C19.697 61.5293 19.2898 61.615 18.9858 61.4167C18.6819 61.2184 18.5962 60.8113 18.7944 60.5073C19.2019 59.8825 19.5604 59.2288 19.9189 58.5751C20.2774 57.9213 20.636 57.2675 21.0435 56.6426C21.2418 56.3386 21.649 56.2529 21.9529 56.4512Z"}),/*#__PURE__*/t("path",{d:"M27.5799 24.4525C27.8816 24.2508 27.9625 23.8426 27.7608 23.541C27.559 23.2393 27.1509 23.1583 26.8492 23.3601C24.247 25.1006 22.6505 27.494 22.6505 31.0002C22.6505 33.088 23.0203 34.7946 23.3997 36.5449C23.9674 39.1641 24.3524 41.7777 24.2832 44.468C24.1992 47.7349 23.56 50.7201 22.3313 53.564C22.1873 53.8971 22.3407 54.2839 22.6739 54.4278C23.0071 54.5718 23.3938 54.4184 23.5378 54.0852C24.8369 51.0784 25.509 47.9266 25.5971 44.5018C25.6689 41.7062 25.2732 38.9892 24.6845 36.267C24.3042 34.509 23.9648 32.9394 23.9648 31.0002C23.9648 27.9961 25.2863 25.9866 27.5799 24.4525Z"}),/*#__PURE__*/t("path",{d:"M30.1447 22.1436C32.8717 21.5877 35.8061 22.2746 37.966 24.0228C41.8241 27.1455 42.3372 32.8403 42.753 37.4549L42.7742 37.69C43.3115 43.6385 42.6964 49.4163 41.4575 55.2186C41.3817 55.5736 41.0326 55.7999 40.6776 55.7241C40.3227 55.6483 40.0964 55.2991 40.1722 54.9442C41.3926 49.2288 41.9873 43.5885 41.4652 37.8082C41.4479 37.6169 41.4307 37.4228 41.4133 37.2264L41.4131 37.2235C41.0438 33.0534 40.5812 27.8304 37.1392 25.0444C35.2926 23.5498 32.7599 22.9518 30.4073 23.4314C30.0517 23.5039 29.7046 23.2744 29.6321 22.9188C29.5596 22.5632 29.7891 22.2161 30.1447 22.1436Z"}),/*#__PURE__*/t("path",{d:"M40.5287 58.4885C40.6183 58.1368 40.4057 57.7791 40.054 57.6896C39.7023 57.6 39.3446 57.8126 39.2551 58.1643C38.8578 59.7247 38.2456 61.1333 37.4695 62.4301C37.2831 62.7415 37.3844 63.145 37.6958 63.3314C38.0072 63.5178 38.4108 63.4165 38.5972 63.1051C39.4336 61.7075 40.0977 60.1816 40.5287 58.4885Z"}),/*#__PURE__*/t("path",{d:"M37.3152 48.9521C37.6756 48.9948 37.9332 49.3215 37.8906 49.682C37.2699 54.9267 35.8688 59.6042 33.6205 63.6613C33.4446 63.9787 33.0446 64.0934 32.7272 63.9175C32.4097 63.7416 32.295 63.3417 32.4709 63.0242C34.6226 59.1416 35.9811 54.6339 36.5854 49.5275C36.6281 49.1671 36.9548 48.9095 37.3152 48.9521Z"}),/*#__PURE__*/t("path",{d:"M37.1798 30.6556C36.7242 28.2212 34.6349 26.3591 32.0985 26.3591C28.6638 26.3591 26.254 29.8212 27.1032 33.0422C28.54 38.7279 28.7759 44.2077 27.8032 49.4855L27.8025 49.4893C26.9584 54.228 25.3374 58.4908 23.1263 62.1031C22.9368 62.4127 23.0342 62.8172 23.3437 63.0067C23.6533 63.1962 24.0578 63.0988 24.2473 62.7893C26.5488 59.0292 28.2249 54.6109 29.0961 49.7218C30.106 44.2403 29.8558 38.5684 28.3765 32.7168L28.3748 32.7099C27.7378 30.3005 29.5133 27.6734 32.0985 27.6734C33.9641 27.6734 35.5393 29.0459 35.8871 30.8929C36.8436 36.4411 37.3418 41.5862 36.9871 46.016C36.9581 46.3778 37.2279 46.6945 37.5897 46.7235C37.9515 46.7525 38.2682 46.4827 38.2972 46.1209C38.6649 41.5294 38.1459 36.2576 37.1815 30.6648C37.1809 30.6617 37.1804 30.6586 37.1798 30.6556Z"}),/*#__PURE__*/t("path",{d:"M30.1376 59.1171C30.4604 59.283 30.5876 59.6792 30.4217 60.002L28.6804 63.3906C28.5145 63.7134 28.1184 63.8406 27.7956 63.6747C27.4728 63.5088 27.3456 63.1127 27.5114 62.7899L29.2527 59.4013C29.4186 59.0785 29.8147 58.9513 30.1376 59.1171Z"}),/*#__PURE__*/t("path",{d:"M32.5872 31.2892C32.5042 30.9359 32.1505 30.7168 31.7972 30.7998C31.4439 30.8828 31.2247 31.2365 31.3077 31.5898C33.5238 41.0232 33.2194 49.3066 30.5201 56.363C30.3905 56.702 30.5602 57.0819 30.8991 57.2115C31.2381 57.3412 31.618 57.1715 31.7477 56.8326C34.5622 49.475 34.8483 40.9141 32.5872 31.2892Z"})]}),/*#__PURE__*/t("defs",{children:/*#__PURE__*/t("clipPath",{id:"clip0_113_33841",children:/*#__PURE__*/t("rect",{width:"64",height:"64",fill:"white",transform:"translate(0.483887)"})})})]}),vc=({onClose:e,onReset:r,submitEnrollmentWithPasskey:n})=>{let{user:a}=cr(),{initLinkWithPasskey:i,linkWithPasskey:s}=$e(),c=Wa(),[d,u]=l(!1),[h,p]=l(!1),[m,w]=l(null),y=o((()=>a?.linkedAccounts.filter((e=>"passkey"===e.type))??[]),[a]),g=async e=>{u(!0);try{await n(e)}catch(e){w(e)}finally{u(!1)}},f=async()=>{p(!0),w(null);try{await i();let e=await s(),t=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];await g(t)}catch(e){w(e)}finally{p(!1)}};return 0===y.length||h?/*#__PURE__*/t(Cc,{onReset:r,onClose:e,onClick:f,isCreating:h}):m?/*#__PURE__*/t($r,{allowlistConfig:c.allowlistConfig,error:m,onBack:()=>w(null),onRetry:()=>w(null)}):/*#__PURE__*/t(kc,{passkeys:y,isSubmitting:d,isCreating:h,onReset:r,onClose:e,onSubmitEnrollment:()=>g(y.map((e=>e.credentialId))),onAddPasskey:f})};let Cc=({onReset:e,onClose:a,onClick:i,isCreating:o})=>/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(tr,{backFn:e,onClose:a},"header"),/*#__PURE__*/t(os,{children:/*#__PURE__*/r(Ul,{children:[/*#__PURE__*/t(Is,{}),/*#__PURE__*/t(fc,{})]})}),/*#__PURE__*/t(ss,{children:"Set up passkey verification"}),/*#__PURE__*/r(ds,{children:[/*#__PURE__*/r(hs,{children:[/*#__PURE__*/t(us,{children:/*#__PURE__*/t(ri,{})}),"Verify with Touch ID, Face ID, PIN, or hardware key"]}),/*#__PURE__*/r(hs,{children:[/*#__PURE__*/t(us,{children:/*#__PURE__*/t(qi,{})}),"Takes seconds to set up and use"]}),/*#__PURE__*/r(hs,{children:[/*#__PURE__*/t(us,{children:/*#__PURE__*/t(Di,{})}),"Use your passkey to verify transactions and login to your account"]})]}),/*#__PURE__*/t(ar,{style:{marginTop:"2.25rem"},onClick:i,loading:o,children:"Add a new passkey"}),/*#__PURE__*/t(Zt,{})]}),kc=({onReset:e,onClose:a,onAddPasskey:i,onSubmitEnrollment:o,passkeys:s,isSubmitting:c,isCreating:d})=>{let[u,h]=l(!1),p=u?s.length:s.length>3?2:3;/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{backFn:u?()=>h(!1):e,onClose:a},"header"),!u&&/*#__PURE__*/t(os,{children:/*#__PURE__*/r(Ul,{children:[/*#__PURE__*/t(Is,{}),/*#__PURE__*/t(fc,{})]})}),/*#__PURE__*/t(ss,{children:"Enable your passkeys for verification"}),/*#__PURE__*/r(ds,{children:[s.slice(0,p).map((e=>/*#__PURE__*/r(Ac,{children:[/*#__PURE__*/t(bc,{children:_c(e)}),/*#__PURE__*/r(Tc,{children:["Last used: ",e.latestVerifiedAt?.toLocaleString()]})]},e.credentialId))),!u&&s.length>3&&/*#__PURE__*/t(Ec,{onClick:()=>h(!0),children:"View All"})]}),/*#__PURE__*/t(ar,{style:{marginTop:"1.5rem"},onClick:o,loading:c,children:"Enable passkeys"}),s.length<5&&/*#__PURE__*/t(Ec,{style:{marginTop:"0.5rem"},onClick:i,disabled:d,children:d?/*#__PURE__*/t(pr,{style:{height:"1rem",width:"1rem",borderWidth:2}}):"Add new passkey"}),/*#__PURE__*/t(Zt,{})]})},Ac=/*#__PURE__*/Ka.div.withConfig({displayName:"PasskeyItem",componentId:"sc-23451ce2-0"})(["&&{padding:0.75rem 1rem;text-align:left;border-radius:0.5rem;border:1px solid var(--privy-color-foreground-4);width:100%;}"]),bc=/*#__PURE__*/Ka.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-23451ce2-1"})(["font-size:0.875rem;line-height:1.375rem;font-weight:500;color:var(--privy-color-foreground-1);"]),Tc=/*#__PURE__*/Ka.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-23451ce2-2"})(["font-size:0.75rem;font-weight:400;line-height:1.125rem;color:var(--privy-color-foreground-2);"]),_c=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 Ec=/*#__PURE__*/Ka.button.withConfig({displayName:"StyledLink",componentId:"sc-23451ce2-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;}}"]),Ic=({appName:e,onComplete:a,onReset:i,onClose:o})=>{let[s,c]=l(""),[d,u]=l(!1),[h,p]=l(null),[m,w]=l("enroll"),{initEnrollmentWithSms:y,submitEnrollmentWithSms:g}=hc(),{data:f}=dr(),v=Wa();function C(){f?.mfaEnrollmentFlow?.onSuccess(),a()}return h?/*#__PURE__*/t($r,{allowlistConfig:v.allowlistConfig,error:h,onBack:()=>p(null),onRetry:()=>p(null)}):/*#__PURE__*/r(n,"enroll"===m?{children:[/*#__PURE__*/t(tr,{backFn:i,onClose:o},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(ti,{})}),/*#__PURE__*/t(ss,{children:"Set up SMS verification"}),/*#__PURE__*/r(ls,{children:["We'll text a verification code to this mobile device whenever you use your ",e," ","wallet."]}),/*#__PURE__*/r(cs,{children:[/*#__PURE__*/t(zr,{onSubmit:async function({qualifiedPhoneNumber:e}){try{await y({phoneNumber:e}),c(e),w("verify")}catch(e){p(e)}},hideRecent:!0}),/*#__PURE__*/r(Cs,{children:["By providing your mobile number, you agree to receive text messages from ",v?.name,". Some carrier charges may apply"]})]}),/*#__PURE__*/t(Zt,{})]}:d?{children:[/*#__PURE__*/t(tr,{onClose:C},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(zi,{})}),/*#__PURE__*/t(ss,{children:"SMS verification added"}),/*#__PURE__*/r(ls,{children:["From now on, you'll enter the verification code sent to your mobile device whenever you use your ",e," wallet."]}),/*#__PURE__*/t(ps,{children:/*#__PURE__*/t(ar,{onClick:C,children:"Done"})}),/*#__PURE__*/t(Zt,{})]}:{children:[/*#__PURE__*/t(tr,{backFn:function(){"verify"===m?w("enroll"):i()},onClose:o},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(ti,{})}),/*#__PURE__*/t(ss,{children:"Enter enrollment code"}),/*#__PURE__*/r(cs,{children:[/*#__PURE__*/t(Rs,{onChange:async function(e){try{if(!e)return;await g({phoneNumber:s,mfaCode:e}),u(!0)}catch(e){if(Kr(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(sr(e))throw Error("The code you entered is not valid");if(lr(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw Yr(e)?Error("Verification canceled"):Error("Unknown error")}}}),/*#__PURE__*/r(ls,{children:["To continue, enter the 6-digit code sent to ",/*#__PURE__*/t("strong",{children:P(s)})]})]}),/*#__PURE__*/t(Zt,{})]})},Sc=({size:e,authUrl:r})=>/*#__PURE__*/t(Lr,{url:r,squareLogoElement:Bi,size:e,fgColor:"#1F1F1F"}),Uc=({onClose:e,onReset:a,totpInfo:i,submitEnrollmentWithTotp:o,error:s})=>{let[c,d]=l("enroll");/*#__PURE__*/return r(n,"enroll"===c?{children:[/*#__PURE__*/t(tr,{backFn:a,onClose:e},"header"),/*#__PURE__*/t(Gr,{children:"Scan QR code"}),/*#__PURE__*/t(Zr,{children:"Open your authenticator app and scan this code to continue"}),/*#__PURE__*/t(Jr,{children:/*#__PURE__*/t(Sc,{authUrl:i.authUrl,size:240})}),/*#__PURE__*/t(Xr,{style:{textAlign:"left"},children:"Setup key"}),/*#__PURE__*/r(Qr,{style:{marginTop:"0.25rem"},children:[/*#__PURE__*/t(Xa,{children:"•".repeat(16)}),/*#__PURE__*/t(xi,{itemName:" ",text:i.secret})]}),/*#__PURE__*/t(ar,{style:{marginTop:"1rem"},onClick:function(){d("verify")},children:"Continue"}),/*#__PURE__*/t(Zt,{})]}:{children:[/*#__PURE__*/t(tr,{backFn:function(){"verify"===c?d("enroll"):a()},onClose:e},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Qa,{})}),/*#__PURE__*/t(Gr,{children:"Enter enrollment code"}),/*#__PURE__*/t(Zr,{children:"To continue, enter the 6-digit code generated from your authenticator app"}),/*#__PURE__*/t(cs,{children:/*#__PURE__*/t(Rs,{onChange:async function(e){try{if(!e)return;await o({mfaCode:e})}catch(e){if(Kr(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(sr(e))throw Error("The code you entered is not valid");if(lr(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw Yr(e)?Error("Verification canceled"):Error("Unknown error")}},errorReasonOverride:s?.message})}),/*#__PURE__*/t(Zt,{})]})},Pc={component:()=>{let{user:e,enrollInMfa:a,ready:i}=cr(),[o,c]=l(null),{unenrollWithSms:d,unenrollWithTotp:u,unenrollWithPasskey:h,submitEnrollmentWithTotp:p,initEnrollmentWithPasskey:m,submitEnrollmentWithPasskey:w,initEnrollmentWithTotp:y}=hc(),{data:g,onUserCloseViaDialogOrKeybindRef:f}=dr(),v=Wa(),{closePrivyModal:C}=$e(),{promptMfa:k}=qs(),[A,b]=l(!1),[T,_]=l(null),[E,I]=l(null),S=()=>{C({shouldCallAuthOnSuccess:!0}),a(!1),setTimeout((()=>{c(null),_(null)}),500)},[U,P]=l(!1),[x,W]=l();f.current=S;let N=e?.mfaMethods.includes("sms"),R=!!e?.phone,O=e?.mfaMethods.includes("totp"),M=e?.mfaMethods.includes("passkey"),F=N||O||M,L=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function D(){c(null),_(null)}async function q(e=L){P(!0);try{return await m(),await w({credentialIds:e},{removeForLogin:g?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa}),g?.mfaEnrollmentFlow?.onSuccess(),S()}catch(e){W(e)}finally{P(!1)}}if(s((()=>{F&&b(!0)}),[F]),!i||!e||!v/*#__PURE__*/)return r(n,{children:[/*#__PURE__*/t(tr,{onClose:S},"header"),/*#__PURE__*/t(os,{children:/*#__PURE__*/t(pc,{})}),/*#__PURE__*/t(cs,{children:/*#__PURE__*/t(pr,{})}),/*#__PURE__*/t(Zt,{})]});if("sms"===o)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{backFn:D,onClose:S},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ri,{})}),/*#__PURE__*/t(ss,{children:"Remove SMS verification?"}),/*#__PURE__*/r(ls,{children:["MFA adds an extra layer of security to your ",v?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/t(ps,{children:/*#__PURE__*/t(ar,{$warn:!0,onClick:async function(){c(null);try{await d()}catch(e){c(null)}},children:"Remove"})}),/*#__PURE__*/t(Zt,{})]});if("totp"===o)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{backFn:D,onClose:S},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ri,{})}),/*#__PURE__*/t(ss,{children:"Remove authenticator app verification?"}),/*#__PURE__*/r(ls,{children:["MFA adds an extra layer of security to your ",v?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/t(ps,{children:/*#__PURE__*/t(ar,{$warn:!0,onClick:async function(){c(null);try{await u()}catch(e){c(null)}},children:"Remove"})}),/*#__PURE__*/t(Zt,{})]});if("passkey"===o){let e=g?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{backFn:D,onClose:S},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ri,{})}),/*#__PURE__*/t(ss,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/t(ls,{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(ps,{children:/*#__PURE__*/t(ar,{$warn:!0,onClick:async function(){c(null);try{await h({removeForLogin:g?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){c(null)}},children:"Remove"})}),/*#__PURE__*/t(Zt,{})]})}if(0===g.mfaEnrollmentFlow.mfaMethods.length&&!F)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{onClose:S},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(ri,{})}),/*#__PURE__*/t(ss,{children:"Add more security"}),/*#__PURE__*/r(ls,{children:[v?.name," does not have any verification methods enabled."]}),/*#__PURE__*/t(ps,{children:/*#__PURE__*/t(ar,{onClick:S,children:"Close"})}),/*#__PURE__*/t(Zt,{})]});let z=!F&&!A;return z?/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(tr,{onClose:S},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(ri,{})}),/*#__PURE__*/t(ss,{children:"Transaction Protection"}),/*#__PURE__*/t(ls,{children:"Set up transaction protection to add an extra layer of security to your account"}),/*#__PURE__*/r(ds,{children:[/*#__PURE__*/r(hs,{children:[/*#__PURE__*/t(us,{children:/*#__PURE__*/t(Oi,{})}),"Enable 2-Step verification for your ",v?.name," wallet."]}),/*#__PURE__*/r(hs,{children:[/*#__PURE__*/t(us,{children:/*#__PURE__*/t(Mi,{})}),"You'll be prompted to authenticate to complete transactions."]})]}),/*#__PURE__*/r(ps,{children:[/*#__PURE__*/t(ar,{onClick:()=>b(!0),children:"Continue"}),/*#__PURE__*/t(ir,{onClick:S,children:"Not now"})]}),/*#__PURE__*/t(Zt,{})]}):"sms"===T?/*#__PURE__*/t(Ic,{appName:v?.name||"Privy",onComplete:S,onReset:D,onClose:S}):"totp"===T&&E?/*#__PURE__*/t(Uc,{onClose:S,onReset:D,submitEnrollmentWithTotp:({mfaCode:e})=>async function(e){try{return W(void 0),await p({mfaCode:e}),g?.mfaEnrollmentFlow?.onSuccess(),S()}catch(e){W(e)}finally{c(null)}}(e),totpInfo:{...E,appName:v?.name||"Privy"}}):"passkey"===T?/*#__PURE__*/t(vc,{onReset:D,onClose:S,submitEnrollmentWithPasskey:q}):/*#__PURE__*/t(wc,{showIntro:z,userMfaMethods:e.mfaMethods,appMfaMethods:v.mfa.methods,userHasAuthSms:R,backFn:function(){b(!1)},handleSelectMethod:async function(e){try{await k()}catch(e){return void W(e)}return"totp"===e?(_(e),I(null),void y().then((e=>{I(e)})).catch((()=>{I(null),D()}))):"passkey"===e&&1===L.length?await q():void _(e)},isTotpLoading:"totp"===T&&!E,isPasskeyLoading:U,error:x,onClose:S,setRemovingMfaMethod:async e=>{try{await k()}catch(e){return void W(e)}c(e)}})}},xc=({providerName:e,ProviderLogo:r,success:n,errorMessage:a,onRetry:i})=>{let o=n?`Successfully connected with ${e}`:a?a.message:`Verifying connection to ${e}`;/*#__PURE__*/return t(Kt,{title:o,subtitle:n?"You're good to go!":a?a.detail:"Just a few moments more",icon:r,iconVariant:"loading",iconLoadingStatus:{success:n,fail:!!a},secondaryCta:a?.retryable&&i?{label:"Retry",onClick:i}:void 0,watermark:!0})},Wc={component:()=>{let{authenticated:e,logout:r,ready:n,user:a}=cr(),{setModalData:i,navigate:o,resetNavigation:c}=dr(),d=Wa(),{getAuthMeta:u,initLoginWithOAuth:h,loginWithOAuth:p,updateWallets:m,setReadyToTrue:w,closePrivyModal:y,createAnalyticsEvent:g}=$e(),[f,v]=l(!1),[C,k]=l(void 0),A=u()?.provider||"google",{name:b,component:T}=yo(A,d.customOAuthProviders);return s((()=>{p(A).then((()=>{v(!0),w(!0)})).catch((e=>{if(w(!1),e?.privyErrorCode===K.ALLOWLIST_REJECTED)return k(void 0),c(),void o(en);if(e?.privyErrorCode===K.USER_LIMIT_REACHED)return console.error(new Ye(e).toString()),k(void 0),c(),void o(tn);if(e?.privyErrorCode===K.USER_DOES_NOT_EXIST)return k(void 0),c(),void o(rn);if(e?.privyErrorCode===K.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return k(void 0),c(),i({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:u()?.provider,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void o(Rr);let{retryable:t,detail:r}=function(e,t,r){let n={detail:"",retryable:!1},a=gt(t);if(e?.privyErrorCode===K.LINKED_TO_ANOTHER_USER&&(n.detail="This account has already been linked to another user."),e?.privyErrorCode===K.INVALID_CREDENTIALS&&(n.retryable=!0,n.detail="Something went wrong. Try again."),e.privyErrorCode===K.OAUTH_USER_DENIED&&(n.detail=`Retry and check ${a} to finish connecting your account.`,n.retryable=!0),e?.privyErrorCode===K.TOO_MANY_REQUESTS&&(n.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===K.TOO_MANY_REQUESTS&&e.message.includes("provider rate limit")){let e=yo(t,r).name;n.detail=`Request limit reached for ${e}. Please wait a moment and try again.`}if(e?.privyErrorCode===K.OAUTH_ACCOUNT_SUSPENDED){let e=yo(t,r).name;n.detail=`Your ${e} account is suspended. Please try another login method.`}return e?.privyErrorCode===K.CANNOT_LINK_MORE_OF_TYPE&&(n.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode===K.OAUTH_UNEXPECTED&&t.startsWith("privy:")&&(n.detail="Something went wrong. Please try again."),n}(e,A,d.customOAuthProviders);k({retryable:t,detail:r,message:"Authentication failed"})})).finally((()=>{nn()}))}),[b,A]),s((()=>{if(n&&e&&f&&a){if(d?.legal.requireUsersAcceptTerms&&!a.hasAcceptedTerms){let e=setTimeout((()=>{o(xr)}),Ma);return()=>clearTimeout(e)}if(Wr(a,d.embeddedWallets)){let e=setTimeout((()=>{i({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),g({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:A,screen:"OAuthStatusScreen"}}),r()},callAuthOnSuccessOnClose:!0}}),o(Nr)}),Ma);return()=>clearTimeout(e)}{let e=setTimeout((()=>y({shouldCallAuthOnSuccess:!0,isSuccess:!0})),Ma);return m(),()=>clearTimeout(e)}}}),[n,e,f,a]),/*#__PURE__*/t(xc,{providerName:b,ProviderLogo:T,success:f,errorMessage:C,onRetry:C?.retryable?()=>{nn(),h(A),k(void 0)}:void 0})}},Nc=/*#__PURE__*/m(((e,a)=>{let[i,o]=l(""),[s,c]=l(""),[d,u]=l(!1),{authenticated:h,user:p}=cr(),{initUpdateEmail:m}=$e(),{navigate:w,setModalData:y,currentScreen:g}=dr(),{enabled:f,token:v}=$t(),C=Wa(),k=an(i)&&(C.disablePlusEmails&&i.includes("+")?(s||c("Please enter a valid email address without a '+'."),!1):(s&&c(""),!0)),A=d||!k,b=()=>{!f||v||h?(async e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");u(!0);try{await m({oldAddress:p.email.address,newAddress:i,captchaToken:e}),w(Br)}catch(e){y({errorModalData:{error:e,previousScreen:g||jr}}),w(Hr)}u(!1)})(v):(y({captchaModalData:{callback:e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");return m({oldAddress:p.email.address,newAddress:i,captchaToken:e})},userIntentRequired:!1,onSuccessNavigateTo:Br,onErrorNavigateTo:Hr}}),w(dn))};/*#__PURE__*/return r(n,{children:[/*#__PURE__*/r(Rc,{children:[s&&/*#__PURE__*/t(sn,{style:{marginTop:"0.25rem",textAlign:"left"},children:s}),/*#__PURE__*/r(Oc,{$error:!!s,children:[/*#__PURE__*/t(Gt,{children:/*#__PURE__*/t(Pi,{})}),/*#__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&&b()},value:i,autoComplete:"email"}),e.stacked?null:/*#__PURE__*/t(cn,{isSubmitting:d,onClick:b,disabled:A,children:"Submit"})]})]}),e.stacked?/*#__PURE__*/t(ar,{loadingText:null,loading:d,disabled:A,onClick:b,style:{width:"100%"},children:"Submit"}):null]})}));let Rc=on,Oc=ln;const Mc=({title:e="Update your email",subtitle:r="Add the email address you'd like to use going forward. We'll send you a confirmation code"})=>/*#__PURE__*/t(Kt,{title:e,subtitle:r,icon:Ni,watermark:!0,children:/*#__PURE__*/t(Dr,{children:/*#__PURE__*/t(Nc,{stacked:!0})})}),Fc={component:()=>/*#__PURE__*/t(Mc,{})},Lc=({title:e="Update your phone number",subtitle:r="Add the phone number you'd like to use going forward. We'll send you a confirmation code",onSubmit:n,isSubmitting:a=!1})=>{let[i,o]=l(null);/*#__PURE__*/return t(Kt,{title:e,subtitle:r,icon:ti,primaryCta:{label:a?"Submitting":"Update",onClick:async()=>{i?.qualifiedPhoneNumber&&await n(i)},disabled:!i?.isValid||a},watermark:!0,children:/*#__PURE__*/t(zr,{onChange:e=>{o(e)},onSubmit:async()=>{},noIncludeSubmitButton:!0,hideRecent:!0})})},Dc={component:()=>{let{currentScreen:e,data:r,navigate:n,setModalData:a}=dr(),{user:i}=cr(),{initUpdatePhone:o}=$e(),[s,c]=l(!1);/*#__PURE__*/return t(Lc,{onSubmit:async t=>{c(!0);try{if(!i?.phone?.number)throw Error("User is required to have an phone number to update it.");await o(i?.phone?.number,t.qualifiedPhoneNumber),n(Br)}catch(t){a({errorModalData:{error:t,previousScreen:r?.errorModalData?.previousScreen||e||cc}}),n(Hr)}finally{c(!1)}},isSubmitting:s})}},qc=Va((()=>({ethereum:[]}))),zc=()=>qc.getState().ethereum;function Bc({subscribe:e,getExternalJwt:t,enabled:r=!0,onAuthenticated:n,onUnauthenticated:a,onError:i}){let{client:o,onCustomAuthAuthenticated:c}=$e(),{logout:d,authenticated:h,ready:p}=fi();if(!o)throw new M("`useSyncJwtBasedAuthState` must be used within a `PrivyProvider`");let[m,w]=l({status:"initial"}),y=u(),g=u(!1),f=u(t);s((()=>{f.current=t}),[t]);let v=u(n);s((()=>{v.current=n}),[n]);let C=u(a);s((()=>{C.current=a}),[a]);let k=u(i);return s((()=>{k.current=i}),[i]),s((()=>{if(!r||!p)return;let t=async()=>{if(!g.current){g.current=!0;try{w({status:"loading"});let e=await f.current();if(void 0!==y.current&&y.current===e)return void w({status:"done"});if(!e)return h&&(await d(),C.current?.()),y.current=e,void w({status:"done"});o.startAuthFlow(new Vo(e));let{user:t,isNewUser:r=!1}=await o.authenticate();if(!t)throw new M("Failed to sync with custom auth provider");v.current?.({user:t,isNewUser:r}),c(t,r),y.current=e,w({status:"done"})}catch(e){if(console.warn(e),await d().catch((()=>{})),C.current?.(),e instanceof we&&e.privyErrorCode===K.LINKED_TO_ANOTHER_USER)return w({status:"initial"}),void setTimeout((()=>{t()}),0);k.current?.(e),w({status:"error",error:e})}finally{g.current=!1}}};return t(),e(t)}),[e,o,c,h,d,r,p]),r?{state:m}:{state:{status:"not-enabled"}}}let Hc=Va((()=>({jwtAuthFlowState:{status:"not-enabled"}})));function jc({customAuth:e}){let{jwtAuthFlowState:t}=function({customAuth:e}){let t=Oa(),r=u(),n=p((e=>(r.current=e,()=>{r.current=void 0})),[]),a=e?.getCustomAccessToken??(()=>Promise.resolve(void 0)),{state:i}=Bc({enabled:!0===e?.enabled,subscribe:n,getExternalJwt:a,onAuthenticated:({user:e,isNewUser:r})=>{t("login","onComplete",{user:e,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),t("customAuth","onAuthenticated",{user:e})},onUnauthenticated:()=>{t("customAuth","onUnauthenticated")},onError:e=>{t("login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR)}});return s((()=>{(async()=>{e&&!e.isLoading&&r.current?.()})()}),[e?.enabled,e?.getCustomAccessToken,e?.isLoading]),{jwtAuthFlowState:i}}({customAuth:e});return s((()=>{Hc.setState({jwtAuthFlowState:t})}),[t]),null}const Vc=/*#__PURE__*/w(!1);let $c,Kc,Yc,Gc,Zc,Jc;function Xc(){return $c?$c.getCustomerAccessToken():Promise.resolve(tt.get(fa)||null)}async function Qc(){return $c?$c.getAccessToken():Promise.resolve(tt.get(va)||tt.get(fa)||null)}async function ed(){return await($c?.updateUserAndIdToken()),$c?.useServerCookies?Yo.getState().identityToken:Promise.resolve(tt.get(Ea)||null)}const td=(e,t)=>Kc(e,t),rd=(e,t)=>Yc(e,t),nd=(e,t)=>Gc(e,t),ad=(e,t)=>Zc(e,t),id=e=>Jc(e),od=({config:e,...r})=>{(()=>{if(h(Vc))throw new M("Multiple PrivyProvider instances found","Found multiple instances of PrivyProvider, ensure there is only one mounted in your application tree.")})(),function(){if("undefined"==typeof window)return;let e=["localhost","127.0.0.1"].includes(window.location.hostname),t="https:"===window.location.protocol||"chrome-extension:"===window.location.protocol;if(!e&&!t)throw new M("Embedded wallet is only available over HTTPS")}(),function(e){if("string"!=typeof e||25!==e.length)throw new M("Cannot initialize the Privy provider with an invalid Privy app ID")}(r.appId),$c||($c=new rs({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let n=Object.assign({},e),a=o((()=>new I({appId:r.appId,clientId:r.clientId,storage:tt,baseUrl:r.apiUrl,sdkVersion:"react-auth:3.7.0"})),[]);/*#__PURE__*/return t(La,{client:a,legacyClient:$c,appClientId:r.clientId,clientConfig:n,children:/*#__PURE__*/t(un,{children:/*#__PURE__*/t(sd,{...r,client:$c,privy:a})})})};let sd=e=>{let n=e.client,i=e.privy,c=hn(),d=Wa();pn(Ot(d?.appearance.walletList??[]));let[h,m]=l(!1),w=Bs((e=>e.inProgressMfaFlow)),[y,g]=l(!1),[f,v]=l(!1),[b,E]=l(null),I=qc((e=>e.ethereum)),[S,P]=l(void 0),[x,W]=l(!1),[N,R]=l(null),[F,D]=l(!1),[q,z]=l({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:Ge}),[B,H]=l({status:"initial"}),[j,V]=l({status:"initial"}),[$,Y]=l({status:"initial"}),[Z,J]=l({status:"initial"}),[X,Q]=l({status:"initial"}),[ee,te]=l({status:"initial"}),[re,ne]=l(null),ae=Ra(),[ie,se]=l({}),[le,ce]=l(null),de=u(null),[ue,he]=l(!1),[pe,me]=l(!1),we=u(null),ye=u(null),ge=u(Da),[fe,ve]=l(!1);n.onStoreCustomerAccessToken=e=>{e&&qa(ge,"accessToken","onAccessTokenGranted",{accessToken:e})},n.onDeleteCustomerAccessToken=()=>{E(null),v(!1),qa(ge,"accessToken","onAccessTokenRemoved")};let Ce=u(null),ke=u(null),Ae=u(!1),be=({showWalletUIs:e})=>Ae.current?Ae.current:void 0!==e?!e:!d.embeddedWallets.showWalletUIs,Te=e=>{R(e),setTimeout((()=>{m(!0)}),15)};s((()=>{if(!b)return void n.connectors?.removeEmbeddedWalletConnectors();let t=mn(b),r=wn(b),a=yn(b);t&&r.length||n.connectors?.removeEmbeddedWalletConnectors(),a.length||n.connectors?.removeImportedWalletConnectors(),n.connectors?re?(t&&n.connectors.addEmbeddedWalletConnectors({walletProxy:re,user:b,embeddedWallets:r,defaultChain:d.defaultChain,appId:e.appId,privyClient:i}),a.forEach((t=>n.connectors?.addImportedWalletConnector(re,t.address,d.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")}),[re,b]),s((()=>{re&&de.current?.(re)}),[re]);let _e=p(((e,t)=>{E(e),W(t),v(!0),me(!0)}),[]);s((()=>{pe&&re&&b&&(async()=>{let e=gn(b,d.embeddedWallets.ethereum.createOnLogin),t=fn(b,d.embeddedWallets.solana.createOnLogin),r=await Qc();if(r){if(e&&t){let e=await re.create({accessToken:r});return await re.createSolana({accessToken:r,ethereumAddress:e?.address}),void me(!1)}if(t)return await re.createSolana({accessToken:r,ethereumAddress:mn(b)?.address}),await He.refreshSessionAndUser(),void me(!1);if(e)return await re.create({accessToken:r}),void me(!1)}})().catch(console.error)}),[pe&&re&&b]),s((()=>{if(d.externalWallets.solana.connectors)return d.externalWallets.solana.connectors.onMount(),()=>d.externalWallets.solana.connectors?.onUnmount()}),[d.externalWallets.solana.connectors]),s((()=>{!y&&ae&&async function(){let e,t=Ee(),r=Ie(),i=a();n.initializeConnectorManager({walletConnectCloudProjectId:d.walletConnectCloudProjectId,rpcConfig:d.rpcConfig,chains:d.chains,defaultChain:d.defaultChain,store:i,walletList:d.appearance.walletList,shouldEnforceDefaultChainOnConnect:d.shouldEnforceDefaultChainOnConnect,externalWalletConfig:d.externalWallets,appName:d.name??"Privy",walletChainType:d.appearance.walletChainType,setBaseAccountSdk:P}),n.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=n.connectors.walletConnectors.length,r=n.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?ve(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),ve(!0)}),1500)})),n.connectors?.initialize().then((()=>{We()}));let o=await n.getAuthenticatedUser(),s=!!o;d.legal.requireUsersAcceptTerms&&o&&!o.hasAcceptedTerms?(await n.logout(),He.setReadyToTrue(!0),qa(ge,"logout","onSuccess")):(d.customAuth?.enabled||(v(!!o),o&&qa(ge,"login","onComplete",{user:o,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),E(o)),t?ke.current=s?"link":"login":r&&!s?(ke.current="login",se({telegramAuthModalData:{seamlessAuth:!0}}),Te(Mn)):He.setReadyToTrue(!!o))}()}),[n,le,y,ae]),s((()=>{if(y){if(!b||!b.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void he(!!re);if([...I].some((e=>"privy"===e.walletClientType)))return void he(!0);he(!!re)}}),[y,b,I,re]),s((()=>{n.connectors?.setWalletList(d.appearance.walletList)}),[d.appearance.walletList.join()]);let Ee=()=>{let e=go();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(gl).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(n.startAuthFlow(new ho({...e,customOAuthRedirectUrl:d.customOAuthRedirectUrl})),Te(Wc),!0))},Ie=()=>{let e=Jn();if(!e||!d.loginMethods.telegram||!d.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new Sn;return n.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,r,a)=>{if("solana_adapter"!==e)Ue(await(n.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,a);else{let e=n.connectors?.findSolanaWalletConnector(t);if(!e)return;Ue(e,t,r,a)}};async function Ue(e,t,r,n){if(!e)return z({status:"disconnected",connectedWallet:null,connectError:new oe("Unable to connect to wallet."),connector:null,connectRetry:Ge}),n?.(null,r);z({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:Ge}),e instanceof qt&&t&&await e.resetConnection(t),z({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Ue(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||vn(t))&&d.shouldEnforceDefaultChainOnConnect&&!d.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){z((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:Ge})));try{await(t?.switchChain(d.defaultChain.id)),t&&(t.chainId=Cn(k(d.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${d.defaultChain.id}`)}}return z((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:Ge}))),t&&qa(ge,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof Ke?(console.warn(e.cause?e.cause:e.message),qa(ge,"connectWallet","onError",e.privyErrorCode||K.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),qa(ge,"connectWallet","onError",K.UNKNOWN_CONNECT_WALLET_ERROR)),z((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Pe=async(e,t,r)=>{if(null===e||!vn(e))return;let a=new jt(n,e,t,r);n.startAuthFlow(a)},xe=async(e,t,r,a="plain")=>{let i=c(Ln);if("transaction"===a&&!i)throw new M("useSolanaLedger plugin hook must be mounted");if(null===e||!Dn(e))return;let o=new Un(e,n,t,r,a,i);n.startAuthFlow(o)},We=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),a="true"===e.get("privy_connect_only");if(!t||!r)return;let i=Xn({connectorType:t,walletClientType:r});if(!i||!i.isInstalled)return Te(uc);if(!n.connectors)throw new M("Connector not initialized");Te(a?Qn:Fn);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,r,void 0,a?void 0:"solana_adapter"===t?xe:Pe)};s((()=>{y&&f&&null===b&&n.getAuthenticatedUser().then(E)}),[y,f,b,n]);let Ne=e=>{if(!f)throw qa(ge,"linkAccount","onError",K.MUST_BE_AUTHENTICATED,{linkMethod:e}),new M("User must be authenticated before linking an account.")},Re=e=>{if(!f||!b)return!1;if("privy"===e.walletClientType)return!0;for(let t of b.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Oe=()=>{qc.setState((e=>{let t=n.connectors?.wallets.filter(vn).map((e=>({...e,linked:Re(e),loginOrLink:async()=>{if(!await e.isConnected())throw new M("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new M("Cannot link or login with embedded wallet");(async e=>{let t;if(!n.connectors)throw new M("Connector not initialized");t="ethereum"===e.type?n.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:n.connectors.findSolanaWalletConnector(e.walletClientType)||null,z((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:Ge}))),d.captchaEnabled&&!f?(se({captchaModalData:{callback:t=>vn(e)?Pe(e,t):xe(e,t),userIntentRequired:!1,onSuccessNavigateTo:Fn,onErrorNavigateTo:Hr}}),Te(dn)):(vn(e)?await Pe(e):await xe(e),Te(Fn))})(e)},fund:async t=>{await He.fundWallet(e.address,t)},unlink:async()=>{if(!f)throw new M("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new M("Cannot unlink an embedded wallet");E(await n.unlinkEthereumWallet(e.address))}})))||[];return kn(e.ethereum,t)?{}:{ethereum:t}}))};s((()=>{Oe()}),[b?.linkedAccounts,f,y]),s((()=>{if(y){if(!n.connectors)throw new M("Connector not initialized");Oe(),n.connectors.on("walletsUpdated",Oe)}}),[y]),s((()=>{[...d.loginMethodsAndOrder?.primary??[],...d.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>n.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!n]);let Me=({transaction:t,sponsor:r,uiOptions:a,fundWalletConfig:o,address:s,signOnly:l})=>new Promise((async(c,u)=>{let{requesterAppId:h}=a||{},p=l?"signTransaction":"sendTransaction",m=s?An(b,s):mn(b);if(!m&&s){let e=Bn(zc(),s);if(e){if(r)throw new M("Cannot sponsor transactions for externally connected wallet.");try{let r=await e.getEthereumProvider(),n={...t,from:s,chainId:t.chainId||Number(e.chainId.replace("eip155:","")),value:void 0!==t.value?k(t.value):void 0},a=await r.request({method:"sendTransaction"===p?"eth_sendTransaction":"eth_signTransaction",params:[n]});return qa(ge,p,"onSuccess",{hash:a}),void c({hash:a})}catch(e){return qa(ge,p,"onError",K.TRANSACTION_FAILURE),void u(e??new Hn("Unable to "+p+e))}}}if(!m)return qa(ge,p,"onError",K.EMBEDDED_WALLET_NOT_FOUND),void u(new M("No embedded or connected wallet found for address."));if(!f||!b)return qa(ge,p,"onError",K.MUST_BE_AUTHENTICATED),void u(Error("User must be authenticated before signing with a Privy wallet"));let w=m.address,y=m.walletIndex??0,{entropyId:g,entropyIdVerifier:v}=Lt(b,m),C=je.wallets.find((e=>"privy"===e.walletClientType&&T(e.address)===T(w)));if(!C)return qa(ge,p,"onError",K.EMBEDDED_WALLET_NOT_FOUND),void u(Error("Must have a Privy wallet before signing"));let A=await C.getEthereumProvider(),E=await A.request({method:"eth_chainId"}),I=t.chainId?Number(t.chainId):Ci(E);(e=>{if(!d.chains.map((e=>e.id)).includes(e))throw new oe(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,K.UNSUPPORTED_CHAIN_ID)})(I);let S={...t,from:t.from??w,chainId:I},P=await Qc();if(!P||!re)return qa(ge,p,"onError",K.EMBEDDED_WALLET_NOT_FOUND),void u(Error("Must have valid access token and Privy wallet to send transaction"));let x=_t(S.chainId,d.chains,d.rpcConfig,{appId:e.appId}),W=It(m),N=async({transactionRequest:e})=>{try{let t;if(!await He.recoverEmbeddedWallet({address:w}))throw qa(ge,p,"onError",K.UNKNOWN_CONNECT_WALLET_ERROR),u(Error("Unable to connect to wallet")),Error("Unable to connect to wallet");if(r){let t=await(async({transactionRequest:e})=>{if(!W)throw new M("Sponsoring is only supported for wallets on the TEE stack");if(l)throw new M("Cannot sponsor a sign transaction request");let t=e=>null==e?void 0:k(e),r=await U(i,(async({message:e})=>await re.signWithUserSigner({accessToken:P,requesterAppId:h,message:e})),{chain_type:"ethereum",method:"eth_sendTransaction",caip2:Cn(k(e.chainId)),sponsor:!0,params:{transaction:{from:e.from,to:e.to,chain_id:t(e.chainId),data:_(e.data)?e.data?e.data:k(Uint8Array.from(e.data)):void 0,value:t(e.value)}},wallet_id:m.id});if(r.data&&"hash"in r.data)return r.data.hash;throw new Hn("Unable to sign transaction")})({transactionRequest:e});return qa(ge,"sendTransaction","onSuccess",{hash:t}),t}if(W){let r=e=>null==e?void 0:k(e),n=await U(i,(async({message:e})=>await re.signWithUserSigner({accessToken:P,requesterAppId:h,message:e})),{chain_type:"ethereum",method:"eth_signTransaction",params:{transaction:{from:e.from,to:e.to,nonce:r(e.nonce),chain_id:r(e.chainId),data:_(e.data)?e.data?e.data:k(Uint8Array.from(e.data)):void 0,value:r(e.value),type:e.type,gas_limit:r(e.gasLimit??e.gas),gas_price:r(e.gasPrice??e.gas),max_fee_per_gas:r(e.maxFeePerGas),max_priority_fee_per_gas:r(e.maxPriorityFeePerGas)}},wallet_id:m.id});if(!n.data||!("signed_transaction"in n.data))throw new Hn("Unable to sign transaction");t=n.data.signed_transaction}else t=await async function({accessToken:e,entropyId:t,entropyIdVerifier:r,transactingWalletIndex:n,walletProxy:a,transactionRequest:i,requesterAppId:o}){return(await a.rpc({entropyId:t,entropyIdVerifier:r,hdWalletIndex:n??0,chainType:"ethereum",accessToken:e,requesterAppId:o,request:{method:"eth_signTransaction",params:[i]}})).response.data}({accessToken:P,entropyId:g,entropyIdVerifier:v,transactingWalletIndex:y,walletProxy:re,transactionRequest:e,requesterAppId:h});if(l)return qa(ge,"signTransaction","onSuccess",{signature:t}),t;{let e=await x.sendRawTransaction({serializedTransaction:t});return qa(ge,"sendTransaction","onSuccess",{hash:e}),e}}catch(e){throw qa(ge,p,"onError",K.TRANSACTION_FAILURE),e}};if(be({showWalletUIs:a?.showWalletUIs})){let e=l||r?S:await Qt(S,x,S.from);try{let t=await N({transactionRequest:e});l?qa(ge,"signTransaction","onSuccess",{signature:t}):qa(ge,"sendTransaction","onSuccess",{hash:t}),c({hash:t})}catch(e){qa(ge,p,"onError",K.TRANSACTION_FAILURE),u(e)}}else{let e={connectingWalletAddress:w,recoveryMethod:m.recoveryMethod,entropyId:g,entropyIdVerifier:v,onCompleteNavigateTo:Gn,isUnifiedWallet:W,onFailure:e=>{qa(ge,p,"onError",K.UNKNOWN_CONNECT_WALLET_ERROR),u(e)}},t=(e=>!!e.fundingConfig&&gi(e.fundingConfig.options).length>=1)(d)?vi({address:w,appConfig:d,fundWalletConfig:o,methodScreen:Ar,chainIdOverride:S.chainId,comingFromSendTransactionScreen:!0}):void 0;se({connectWallet:e,sendTransaction:{transactionRequest:S,transactingWalletIndex:y,transactingWalletAddress:w,entropyId:g,entropyIdVerifier:v,signOnly:l,scanTransaction:async()=>{let e=await Qt(S,x,S.from);return await n.scanTransaction({metadata:{domain:d.embeddedWallets.transactionScanning.domain},chain_id:e.chainId.toString(),request:{method:"eth_sendTransaction",params:[{from:e.from,to:e.to,value:e.value?.toString(),gas:e.gas?.toString(),gasPrice:e.gasPrice?.toString(),nonce:e.nonce?.toString(),data:e.data}]}})},getIsSponsored:async()=>!!r,onConfirm:({transactionRequest:e})=>N({transactionRequest:e}),onSuccess:e=>{l?qa(ge,"signTransaction","onSuccess",{signature:e.hash}):qa(ge,"sendTransaction","onSuccess",{hash:e.hash}),c(e)},onFailure:e=>{qa(ge,p,"onError",K.TRANSACTION_FAILURE),u(e)},uiOptions:a||{},fundWalletConfig:o,requesterAppId:h},funding:t}),Te(zn)}}));function Fe(){return new Promise((async(e,t)=>{let r=await Qc();if(!r||!re)throw Error("Must have valid access token to enroll in MFA");try{await re.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let Le=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],De=e=>{let t=b?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=ea(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw qa(ge,"linkAccount","onError",K.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new M(`User already has an account of type ${r} linked.`)};async function qe({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){R(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!f||!b)throw qa(ge,r,"onError",K.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=fr(b);if(!n||!re)throw qa(ge,r,"onError",K.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");let a=It(n);if(a)throw qa(ge,r,"onError",K.UNSUPPORTED_WALLET_TYPE),new M("User owned wallet recovery is only supported for on-device execution and this app uses TEE execution. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");try{await Fe()}catch(e){throw qa(ge,r,"onError",K.MISSING_MFA_CREDENTIALS),e}return new Promise(((i,o)=>{let s="user-passcode"===n.recoveryMethod,l=Zn({walletAction:"update",availableRecoveryMethods:d.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:u}=Lt(b),h={recoveryMethod:n.recoveryMethod,connectingWalletAddress:n.address,onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,isUnifiedWallet:a,entropyIdVerifier:u,onFailure:e=>{qa(ge,r,"onError",K.UNKNOWN_CONNECT_WALLET_ERROR),o(e)}};se({setWalletPassword:{onSuccess:e=>{qa(ge,r,"onSuccess",{method:"user-passcode",wallet:e}),i(e)},onFailure:e=>{qa(ge,r,"onError",K.USER_EXITED_SET_PASSWORD_FLOW),o(e)},callAuthOnSuccessOnClose:!1},recoverWallet:{entropyId:c,entropyIdVerifier:u,onFailure:o},connectWallet:h,recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s,shouldCreateEth:!1,shouldCreateSol:!1}}),Te(zn)}))}async function ze({appId:e,action:t}){let r=await Qc();if("link"===t&&!r)throw qa(ge,"linkAccount","onError",K.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new M("User must be authenticated before linking an account.");if("login"===t&&r)throw qa(ge,"login","onError",K.UNKNOWN_AUTH_ERROR),new M("Attempted to log in, but user is already logged in. Use a `link` helper instead.");Ce.current=`privy:${e}`,ke.current=t;let a=O();return n.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,i)=>{let{name:o,logoUrl:s}=await Cl({api:n.api,providerAppId:e,requesterAppId:d.id});se({crossAppAuth:{appId:e,name:o,logoUrl:s,action:t,popup:a,onSuccess:r,onError:i}}),Te(jl)}))}let Be={ready:y,authenticated:f,user:b,walletConnectors:n.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),se({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,walletChainType:e?.walletChainType,description:e?.description,hideHeader:e?.hideHeader}}),Te(Yn)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),Ne("siwe"),Ce.current="siwe",ke.current="link",se({...ie,externalConnectWallet:{...ie.externalConnectWallet,walletList:e?.walletList,walletChainType:e?.walletChainType,description:e?.description||`Link a wallet to your ${d?.name} account`}}),Te(Kn)},startCrossAppAuthFlow:ze,linkEmail:()=>{Ne("email"),De("email"),Ce.current="email",ke.current="link",Te(sc)},linkPhone:()=>{Ne("sms"),De("phone"),Ce.current="sms",ke.current="link",Te(cc)},linkGoogle:async()=>{Ne("google"),De("google_oauth"),ke.current="link",await He.initLoginWithOAuth("google")},linkTwitter:async()=>{Ne("twitter"),De("twitter_oauth"),ke.current="link",await He.initLoginWithOAuth("twitter")},linkTwitch:async()=>{Ne("twitch"),De("twitch_oauth"),ke.current="link",await He.initLoginWithOAuth("twitch")},linkDiscord:async()=>{Ne("discord"),De("discord_oauth"),ke.current="link",await He.initLoginWithOAuth("discord")},linkGithub:async()=>{Ne("github"),De("github_oauth"),ke.current="link",await He.initLoginWithOAuth("github")},linkSpotify:async()=>{Ne("spotify"),De("spotify_oauth"),ke.current="link",await He.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Ne("instagram"),De("instagram_oauth"),ke.current="link",await He.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Ne("tiktok"),De("tiktok_oauth"),ke.current="link",await He.initLoginWithOAuth("tiktok")},linkLine:async()=>{Ne("line"),De("line_oauth"),ke.current="link",await He.initLoginWithOAuth("line")},linkLinkedIn:async()=>{Ne("linkedin"),De("linkedin_oauth"),ke.current="link",await He.initLoginWithOAuth("linkedin")},linkApple:async()=>{Ne("apple"),De("apple_oauth"),ke.current="link",await He.initLoginWithOAuth("apple")},linkPasskey:async()=>{Ne("passkey"),De("passkey"),await He.initLinkWithPasskey(),Te(Sl)},linkTelegram:async e=>{if(Ne("telegram"),De("telegram"),ke.current="link",Ce.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new Sn;n.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=$n(e.launchParams.initDataRaw),se({telegramAuthModalData:{seamlessAuth:!0}}),Te(Mn)}else qa(ge,"linkAccount","onError",K.INVALID_DATA,{linkMethod:"telegram"});else await He.initLoginWithTelegram();Te(Mn)},linkFarcaster:async()=>{Ne("farcaster"),De("farcaster"),await He.initLoginWithFarcaster(),ke.current="link",Ce.current="farcaster",Te(Vn)},updateEmail:()=>{if(Ne("email"),!b?.email)throw new M("User does not have an email linked to their account.");ke.current="update",Ce.current="email",Te(Fc)},updatePhone:()=>{if(Ne("sms"),!b?.phone)throw new M("User does not have a phone number linked to their account.");ke.current="update",Ce.current="sms",Te(Dc)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!y){let e=await new Promise((e=>{ce((t=>e.bind(t)))}));if(ce(null),e)return void console.warn(t)}!b||b.isGuest?(ke.current="login",se({login:e}),Te(jr)):console.warn(t)},connectOrCreateWallet:async()=>{y||(await new Promise((e=>{ce((()=>e))})),ce(null)),f?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(ke.current="connect-or-create",Te(jn))},logout:async()=>{if(ke.current=null,Ce.current=null,b&&n.clearProviderAcccessTokens(b),R(null),await n.logout(),b&&re)try{await re.clearMfa({userId:b.id})}catch(e){}E(null),v(!1),V({status:"initial"}),Y({status:"initial"}),H({status:"initial"}),J({status:"initial"}),Q({status:"initial"}),te({status:"initial"}),qa(ge,"logout","onSuccess"),m(!1),tt.del(Pa),tt.del(ga(d.id))},getAccessToken:p((async()=>{let e=await n.getCustomerAccessToken();return e&&!f&&v(!0),e}),[n,f]),unlinkWallet:async e=>{let t;return E(t=e.startsWith("0x")?await n.unlinkEthereumWallet(e):await n.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await n.unlinkEmail(e);return E(t),t},unlinkPhone:async e=>{let t=await n.unlinkPhone(e);return E(t),t},unlinkGoogle:async e=>{let t=await n.unlinkOAuth("google",e);return E(t),t},unlinkTwitter:async e=>{let t=await n.unlinkOAuth("twitter",e);return E(t),t},unlinkTwitch:async e=>{let t=await n.unlinkOAuth("twitch",e);return E(t),t},unlinkDiscord:async e=>{let t=await n.unlinkOAuth("discord",e);return E(t),t},unlinkGithub:async e=>{let t=await n.unlinkOAuth("github",e);return E(t),t},unlinkSpotify:async e=>{let t=await n.unlinkOAuth("spotify",e);return E(t),t},unlinkInstagram:async e=>{let t=await n.unlinkOAuth("instagram",e);return E(t),t},unlinkTiktok:async e=>{let t=await n.unlinkOAuth("tiktok",e);return E(t),t},unlinkLine:async e=>{let t=await n.unlinkOAuth("line",e);return E(t),t},unlinkLinkedIn:async e=>{let t=await n.unlinkOAuth("linkedin",e);return E(t),t},unlinkApple:async e=>{let t=await n.unlinkOAuth("apple",e);return E(t),t},unlinkFarcaster:async e=>{let t=await n.unlinkFarcaster(e);return E(t),t},unlinkTelegram:async e=>{let t=await n.unlinkTelegram(e);return E(t),t},unlinkPasskey:async e=>{let t=await Qc();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!re)throw Error("Wallet proxy not initialized.");let r=d.passkeys.shouldUnenrollMfaOnUnlink;await re.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let a=await n.getAuthenticatedUser();return E(a),a},unlinkCrossAppAccount:async({subject:e})=>{let t=b?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new M("Invalid subject");n.storeProviderAccessToken(t.id,null);let r=await n.unlinkOAuth(`privy:${t.id}`,e);return E(r),r},setWalletRecovery:async e=>qe({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>qe({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:o}=t?.uiOptions||{},s=e.message,l=t?.address?An(b,t.address):mn(b);if(!l&&void 0!==t?.address){let e=Bn(zc(),t.address);if(e)try{let t=await e.getEthereumProvider(),n=await t.request({method:"personal_sign",params:[s,e.address]});return qa(ge,"signMessage","onSuccess",{signature:n}),void r({signature:n})}catch(e){return qa(ge,"signMessage","onError",K.UNABLE_TO_SIGN),void a(e??new Hn("Unable to sign message"))}}if(!l)throw new M("No embedded or connected wallet found for address.");if(!f||!b)return qa(ge,"signMessage","onError",K.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let c=l.address,d=l.walletIndex??0,{entropyId:u,entropyIdVerifier:h}=Lt(b,l),p=It(l);if("string"!=typeof s||s.length<1)return qa(ge,"signMessage","onError",K.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));let m=async()=>{let t;if(!f)throw Error("User must be authenticated before signing with a Privy wallet");let r=await Qc();if(!re||!r||!await He.recoverEmbeddedWallet({address:c}))throw Error("Unable to connect to wallet");if(n.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:c,requesterAppId:o}}),p){let n=_(e.message,{strict:!0}),a=await U(i,(async({message:e})=>await re.signWithUserSigner({accessToken:r,requesterAppId:o,message:e})),{chain_type:"ethereum",method:"personal_sign",params:n?{message:s.slice(2),encoding:"hex"}:{message:s,encoding:"utf-8"},wallet_id:l.id});if(!a.data||!("signature"in a.data))throw new Hn("Unable to sign message");t=a.data.signature}else{let{response:e}=await re.rpc({accessToken:r,entropyId:u,entropyIdVerifier:h,chainType:"ethereum",hdWalletIndex:d,requesterAppId:o,request:{method:"personal_sign",params:[s,c]}});t=e.data}return n.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:c,requesterAppId:o}}),t};if(be({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await m();qa(ge,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){qa(ge,"signMessage","onError",K.UNABLE_TO_SIGN),a(e??new Hn("Unable to sign message"))}else se({signMessage:{method:"personal_sign",data:s,confirmAndSign:m,onSuccess:e=>{qa(ge,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{qa(ge,"signMessage","onError",K.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:l.recoveryMethod,connectingWalletAddress:c,entropyId:u,entropyIdVerifier:h,onCompleteNavigateTo:Wi,isUnifiedWallet:p,onFailure:e=>{qa(ge,"signMessage","onError",K.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Te(zn)})),signTypedData:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:o}=t?.uiOptions||{},s=t?.address?An(b,t.address):mn(b);if(!s&&t?.address){let n=Bn(zc(),t.address);if(n)try{let t=await n.getEthereumProvider(),a=Et(e),i=await t.request({method:"eth_signTypedData_v4",params:[n.address,a]});return qa(ge,"signTypedData","onSuccess",{signature:i}),void r({signature:i})}catch(e){return qa(ge,"signTypedData","onError",K.UNABLE_TO_SIGN),void a(e??new Hn("Unable to sign typed data "+e))}}if(!s)throw new M("No embedded or connected wallet found for address.");if(!f||!b)return qa(ge,"signTypedData","onError",K.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let l=s.address,c=s.walletIndex??0,{entropyId:d,entropyIdVerifier:u}=Lt(b,s),h=It(s),p=Et(e),m=async()=>{let e;if(!f)throw Error("User must be authenticated before signing with a Privy wallet");let t=await Qc();if(!re||!t||!await He.recoverEmbeddedWallet({address:l}))throw Error("Unable to connect to wallet");if(n.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:l,requesterAppId:o}}),h){let{domain:r,types:n,primaryType:a,message:l}=p,c=await U(i,(async({message:e})=>await re.signWithUserSigner({accessToken:t,requesterAppId:o,message:e})),{chain_type:"ethereum",method:"eth_signTypedData_v4",params:{typed_data:{domain:r,types:n,primary_type:a,message:l}},wallet_id:s.id});if(!c.data||!("signature"in c.data))throw new Hn("Unable to sign message");e=c.data.signature}else{let{response:r}=await re.rpc({accessToken:t,entropyId:d,entropyIdVerifier:u,chainType:"ethereum",hdWalletIndex:c,requesterAppId:o,request:{method:"eth_signTypedData_v4",params:[l,p]}});e=r.data}return n.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:l,requesterAppId:o}}),e};if(be({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await m();qa(ge,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){qa(ge,"signTypedData","onError",K.UNABLE_TO_SIGN),a(e??new Hn("Unable to sign message"))}else se({signMessage:{method:"eth_signTypedData_v4",data:p,confirmAndSign:m,onSuccess:e=>{qa(ge,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{qa(ge,"signTypedData","onError",K.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:s.recoveryMethod,connectingWalletAddress:s.address,entropyId:d,isUnifiedWallet:h,entropyIdVerifier:u,onCompleteNavigateTo:Wi,onFailure:e=>{qa(ge,"signMessage","onError",K.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Te(zn)})),sendTransaction:async(e,t)=>await Me({transaction:e,sponsor:t?.sponsor,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await Me({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:t=>new Promise((async(r,a)=>{if(!f||!b)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?An(b,t.address):mn(b);if(!i)return void a(new M("User must have an embedded wallet."));let o=i.address,{entropyId:s,entropyIdVerifier:l}=Lt(b,i),c=It(i);if(!o)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(o))return void a(Error("Must provide a valid Ethereum address."));let d={recoveryMethod:i.recoveryMethod,connectingWalletAddress:i.address,isUnifiedWallet:c,entropyId:s,entropyIdVerifier:l,onCompleteNavigateTo:qn,onFailure:a,shouldForceMFA:!0};se(ie),await Qc()&&re?re?yi(i)?(se({keyExport:{appId:e.appId,appClientId:e.clientId,origin:n.apiUrl,address:i.address,entropyId:s,entropyIdVerifier:l,hdWalletIndex:i.walletIndex,chainType:i.chainType,walletId:i.id,isUnifiedWallet:c,imported:i.imported,onSuccess:r,onFailure:a},connectWallet:d}),Te(zn)):a(Error(`Export is not supported for ${i.chainType} wallets`)):a(Error("Must have a Privy wallet before exporting")):a(Error("Must have valid access token to enroll in MFA"))})),promptMfa:Fe,async init(e){switch(e){case"sms":return void await n.initMfaSmsVerification();case"passkey":return await n.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 M("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 M("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=Bl(await r.startAuthentication({optionsJSON:t}));we.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{ye.current={resolve:e,reject:t}}));break;default:throw we.current?.reject(new M("Unsupported MFA method")),new M(`Unsupported MFA method: ${e}`)}},cancel(){we.current?.reject(new M("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Qc();if(!t||!re)throw Error("Must have valid access token to enroll in MFA");await re.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return He.closePrivyModal(),void t();d.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."),se({mfaEnrollmentFlow:{mfaMethods:d.mfa.methods,shouldUnlinkOnUnenrollMfa:d.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),Te(Pc)})),async initEnrollmentWithTotp(){let e=await Qc();if(!e||!re)throw Error("Must have valid access token to enroll in MFA");let t=await re.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Qc();if(!t||!re)throw Error("Must have valid access token to enroll in MFA");await re.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),E(await n.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Qc();if(!t||!re)throw Error("Must have valid access token to enroll in MFA");await re.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),E(await n.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await Qc();if(!r||!re)throw Error("Must have valid access token to enroll in MFA");await re.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),E(await n.getAuthenticatedUser())},async unenroll(e,t={}){let r=await Qc();if(!r||!re)throw Error("Must have valid access token to remove MFA");"passkey"===e?await re.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await re.unenrollMfa({method:e,accessToken:r}),E(await n.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Qc(),t=b?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!re||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(It(t))throw new M("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!b?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await He.recoverEmbeddedWallet({address:t.address}))throw Error("Unable to connect to wallet");let r=await re.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&E(await n.getAuthenticatedUser()||b||null),se({farcasterSigner:r}),Te(nc)},getFarcasterSignerPublicKey:async()=>{let e,t=await Qc(),r=b?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!re||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(It(r))throw new M("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!b?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await He.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!b.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=b.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Qc(),r=b?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!re||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(It(r))throw new M("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!b?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await He.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!b.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),a=await re.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(b.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(a.signature))},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let a=b?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return kl({user:b,client:n,address:t,requesterAppId:d.id,request:{method:a?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:ze})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let a=b?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),i=Et(e);return kl({user:b,client:n,address:t,requesterAppId:d.id,request:{method:a?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,i],chainId:r},reconnect:ze})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=b?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return kl({user:b,client:n,address:t,requesterAppId:d.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:ze})},signTransactionWithCrossAppWallet(e,{address:t}){let r=b?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return kl({user:b,client:n,address:t,requesterAppId:d.id,request:{method:r?"privy_signSmartWalletTx":"eth_signTransaction",params:[e],chainId:e.chainId},reconnect:ze})},isModalOpen:h||!!w,mfaMethods:d.mfa.methods};Kc=Be.signMessage,Yc=Be.signTypedData,Zc=async(e,t)=>await Me({transaction:e,...t,signOnly:!1}),Gc=async(e,t)=>({signature:(await Me({transaction:e,...t,signOnly:!0})).hash});let He={privy:i,setAuthenticated:v,setUser:E,setIsNewUser:W,isNewUserThisSession:x,pendingTransaction:null,walletConnectionStatus:q,setWalletConnectionStatus:z,connectors:n.connectors?.walletConnectors??[],rpcConfig:d.rpcConfig,chains:d.chains,appId:e.appId,showFiatPrices:"native-token"!==d.embeddedWallets.priceDisplay.primary,clientAnalyticsId:n.clientAnalyticsId,onCustomAuthAuthenticated:_e,hideWalletUIs:Ae,isHeadlessSigning:p(be,[d.embeddedWallets.showWalletUIs]),emailOtpState:j,setEmailOtpState:V,smsOtpState:$,setSmsOtpState:Y,oAuthState:X,setOAuthState:Q,telegramAuthState:ee,setTelegramAuthState:te,siweState:Z,setSiweState:J,isHeadlessOAuthLoading:F,baseAccountSdk:S,setBaseAccountSdk:P,nativeTokenSymbolForChainId:e=>d.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(re)return re;let t=new Promise((e=>{de.current=e})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return de.current=null,n},getAuthFlow:()=>n.authFlow,getAuthMeta:()=>n.authFlow?.meta,client:n,closePrivyModal:async(t={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let r,a=y&&f&&b;if(a&&Ce.current&&(r=Le(b)),"login"===ke.current)t.shouldCallAuthOnSuccess&&a&&Ce.current?qa(ge,"login","onComplete",{user:b,isNewUser:x,wasAlreadyAuthenticated:!1,loginMethod:Ce.current,loginAccount:r??null}):qa(ge,"login","onError",K.USER_EXITED_AUTH_FLOW);else if("link"===ke.current&&r)t.isSuccess&&a&&Ce.current?qa(ge,"linkAccount","onSuccess",{user:b,linkMethod:Ce.current,linkedAccount:r}):Ce.current&&qa(ge,"linkAccount","onError",K.USER_EXITED_LINK_FLOW,{linkMethod:Ce.current});else if("update"===ke.current&&r)t.isSuccess&&a&&Ce.current?qa(ge,"update","onSuccess",{user:b,updateMethod:Ce.current,updatedAccount:r}):Ce.current&&qa(ge,"update","onError",K.USER_EXITED_UPDATE_FLOW,{linkMethod:Ce.current});else if("connect-or-create"===ke.current){let e=zc();e[0]?qa(ge,"connectOrCreateWallet","onSuccess",{wallet:e[0]}):qa(ge,"connectOrCreateWallet","onError",K.USER_EXITED_AUTH_FLOW)}let i=N&&Dl.has(N),o=N===Hr&&ie.errorModalData&&Dl.has(ie.errorModalData.previousScreen);if((i||o)&&ie.funding){let t,r=Dl.get(N)??null;if("solana"===ie.funding.chainType){let e=d.solanaRpcs[ie.funding.chain];if(!e)return void console.warn("Unable to load solana rpc, skipping balance");if(c(Pn))try{t=await xn({rpc:e.rpc,address:ie.funding.address})}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");qa(ge,"fundSolanaWallet","onUserExited",{address:ie.funding.address,fundingMethod:r,chain:ie.funding.chain,balance:t})}else{let n=_t(ie.funding.chain.id,d.chains,d.rpcConfig,{appId:e.appId});try{t=await n.getBalance({address:ie.funding.address})}catch{console.error("Unable to pull wallet balance")}qa(ge,"fundWallet","onUserExited",{address:ie.funding.address,chain:ie.funding.chain,fundingMethod:r,balance:t})}}se((e=>({...e,externalConnectWallet:{}}))),ke.current=null,Ce.current=null,W(!1),m(!1),z({status:"disconnected",connectedWallet:null,connector:null,connectError:null,connectRetry:()=>{}}),setTimeout((()=>{n.authFlow=void 0}),200)},openPrivyModal:Te,connectWallet:Ue,initLoginWithWallet:async(e,t,r,n)=>{vn(e)?(Ce.current="siwe",Pe(e,t,r)):(Ce.current="siws",xe(e,t,r,n))},loginWithWallet:async()=>{let e,t,r;if(!y)throw new Ze;if(n.authFlow instanceof jt?e="siwe":n.authFlow instanceof Un&&(e="siws"),!e)throw new M("Must initialize SIWE/SIWS flow first.");if(null!==await n.getAccessToken())try{({user:t}=await n.link()),Ce.current=e}catch(t){throw qa(ge,"linkAccount","onError",t.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await n.authenticate()),Ce.current=e}catch(e){throw qa(ge,"login","onError",e.privyErrorCode||K.GENERIC_CONNECT_WALLET_ERROR),e}E(t||b||null),W(r||!1),v(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,a)=>{let i=await Qc();if(!f||!b||!i)throw new M("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new M("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let o=He.walletProxy??await He.initializeWalletProxy(15e3);if(!o)throw new M("Wallet proxy not initialized.");if((({address:e,user:t})=>!!yl(t).find((t=>t.address===e)))({address:e,user:b}))return n();let s=An(b,e);if(!s)throw new M("Address to delegate is not associated with current user.");if(It(s))throw new M("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let l=ml({address:e,user:b}),c=wl({address:e,user:b}),d=async()=>{await o.createDelegatedAction({accessToken:i,rootWallet:c,delegatedWallets:[l]}),await He.refreshSessionAndUser()};if(await He.recoverEmbeddedWallet({address:e}),r)se({delegatedActions:{consent:{address:e,onDelegate:d,onSuccess:async()=>{n()},onError:async e=>{a(e)}}}}),Te($l);else try{await d(),n()}catch(e){a(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!f||!b)throw new M("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");let a=yl(b);if(0===a.length)throw new M("User has no delegated wallets to revoke.");if(a.some(It))throw new M("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let i=async()=>{await n.revokeDelegatedWallet(),await He.refreshSessionAndUser()};if(e)se({delegatedActions:{revoke:{onRevoke:i,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),Te(Yl);else try{await i(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new oo(e,t);n.startAuthFlow(r);try{Ce.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===ke.current?qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR):"link"===ke.current&&qa(ge,"linkAccount","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!y)throw new Ze;if(!(n.authFlow instanceof oo))throw new M("Must initialize Farcaster flow first.");if(null!==await n.getAccessToken())try{({user:e}=await n.link()),Ce.current="farcaster"}catch(e){throw qa(ge,"linkAccount","onError",e.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await n.authenticate()),Ce.current="farcaster"}catch(e){throw qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}E(e||null),W(t||!1),v(!0)},async crossAppAuthFlow({appId:e,popup:t,action:r}){let a=`privy:${e}`;Ce.current=a;let{url:i,stateCode:o,codeVerifier:s}=await async function({api:e,appId:t}){let r=rt(),n=nt(),a=await at(r);try{let{url:i}=await e.post(G,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:a,state_code:n});return{url:i,stateCode:n,codeVerifier:r}}catch(e){throw L(e)}}({api:n.api,appId:e});if(!i)throw n.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new M("No authorization URL returned for cross-app auth.");try{let l=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,a=setTimeout((()=>{r(new M("Authorization request timed out after 2 minutes.")),i()}),12e4);function i(){t?.close(),window.removeEventListener("message",s)}let o=setInterval((()=>{t?.closed&&!n&&(i(),clearInterval(o),clearTimeout(a),r(new M("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),r(new M(t.data.error)),i()),t.data.type===fl&&((n=new BroadcastChannel(gl)).onmessage=s))}window.addEventListener("message",s)}))}({url:i,popup:t,provider:a}),c=l.stateCode,d=l.authorizationCode;if(c!==o)throw n.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:o??"",returnedStateCode:c??""}}),new M("Unexpected auth flow. This may be a phishing attempt.",void 0,K.OAUTH_UNEXPECTED);let u=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:a,client:i}){if(!n||!t)throw new M("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new M("User denied confirmation during cross-app auth flow");try{let o=new vl({authorizationCode:n,stateCode:t,codeVerifier:r,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=L(e);if(t.privyErrorCode===K.ACCOUNT_TRANSFER_REQUIRED)throw t;if(t.privyErrorCode)throw new M(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 M("Invalid code during cross-app auth flow.",void 0,K.OAUTH_USER_DENIED);throw new M("Invalid code during cross-app auth flow.",void 0,K.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:s,stateCode:c,authorizationCode:d,action:r,client:n});u&&n.storeProviderAccessToken(e,u);let h=await He.refreshSessionAndUser();if(!h)throw new M("Unable to update user");return n.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),h}catch(e){throw n.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,r){if(Ce.current=e,!Bt())return void Te(ic);if("google"===e&&!d.allowOAuthInEmbeddedBrowsers&&In(window.navigator.userAgent))return void Te(ic);"twitter"===e&&window.opener&&window.opener.postMessage({type:fl},"*"),tt.del(pa),tt.del(ma);let a=new ho({provider:e,disableSignup:!!r,withPrivyUi:!0,customOAuthRedirectUrl:d.customOAuthRedirectUrl});t&&a.addCaptchaToken(t),n.startAuthFlow(a);let i=await n.authFlow.getAuthorizationUrl();if(i&&i.url)if("twitter"===e&&C&&(i.url=i.url.replace("x.com","twitter.com")),"chrome-extension:"===window.location.protocol&&co())try{let{privyOAuthCode:e,privyOAuthState:t}=await uo(i.url);Te(Wc),a.meta.stateCode=t,a.meta.authorizationCode=e}catch(e){throw console.error("OAuth in chrome extension flow failed:",e),e}else window.location.assign(i.url)},async initLoginWithTelegram(e,t){if(!y)throw new Ze;Ce.current="telegram";let r=new Sn(e,t);n.startAuthFlow(r),te({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>d.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:d.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):("link"===ke.current?qa(ge,"linkAccount","onError",K.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}):"login"===ke.current?qa(ge,"login","onError",K.INVALID_CREDENTIALS):"update"===ke.current&&qa(ge,"login","onError",K.FAILED_TO_UPDATE_ACCOUNT),t(new M("Telegram auth failed or was canceled by the client"))))):t(new M("Telegram was not initialized")):t(new M("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(n.authFlow instanceof Sn))throw new M("Must initialize Telegram flow before calling loginWithTelegram");n.authFlow.meta.captchaToken||=e?.captchaToken;let a=await Qc(),i=e?.intent||ke.current;if("login"===i)try{let e=await n.authenticate();t=e.user,r=e.isNewUser,Ce.current="telegram"}catch(e){throw qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}else{if("link"!==i)throw new M("Unknown auth intent");try{t=(await n.link()).user,Ce.current="telegram"}catch(e){throw qa(ge,"linkAccount","onError",e.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}E(t),W(r||!1),v(!0),te({status:"done"});let o=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,loginAccount:o}},async loginWithOAuth(e){let t,r,a;if(!(n.authFlow instanceof ho))throw new M("Must initialize OAuth flow before calling loginWithOAuth");let i=tt.get(wa),o=n.authFlow.meta.stateCode;if(i!==o)throw n.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:i??"",returnedStateCode:o??""}}),new M("Unexpected auth flow. This may be a phishing attempt.",void 0,K.OAUTH_UNEXPECTED);if(null!==await n.getAccessToken())try{let r=await n.link();t=r.user,a=r.oAuthTokens,Ce.current=e}catch(t){throw qa(ge,"linkAccount","onError",t.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let i=await n.authenticate();t=i.user,r=i.isNewUser,a=i.oAuthTokens,Ce.current=e}catch(t){throw"login"===ke.current?qa(ge,"login","onError",t.privyErrorCode||K.UNKNOWN_AUTH_ERROR):"link"===ke.current&&qa(ge,"linkAccount","onError",t.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return E(t),W(r||!1),v(!0),a&&t&&qa(ge,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),a},passkeyAuthState:B,setPasskeyAuthState:H,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new fo({captchaToken:e,setPasskeyAuthState:H,hints:d.passkeys.registration?.hints});n.startAuthFlow(r),ke.current="login";try{Ce.current="passkey",H({status:"generating-challenge"}),await r.initRegisterFlow(t),H({status:"awaiting-passkey"})}catch(e){throw H({status:"error",error:e}),qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!y)throw new Ze;if(!(n.authFlow instanceof fo))throw new M("Must initialize Passkey flow first.");if("passkey"!==Ce.current){let e=new M("Must init login with Passkey flow first.");throw H({status:"error",error:e}),e}let r=await Qc();try{Ce.current="passkey",H({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await n.authenticate())}catch(e){throw H({status:"error",error:e}),qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}E(e),W(t||!1),v(!0),H({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:a}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new fo({captchaToken:e,setPasskeyAuthState:H,hints:void 0});n.startAuthFlow(r),ke.current="login";try{Ce.current="passkey",H({status:"generating-challenge"}),await r.initAuthenticationFlow(t),H({status:"awaiting-passkey"})}catch(e){throw H({status:"error",error:e}),qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!y)throw new Ze;if(!(n.authFlow instanceof fo))throw new M("Must initialize Passkey flow first.");if(e?.credentialIds&&(n.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==Ce.current){let e=new M("Must init login with Passkey flow first.");throw H({status:"error",error:e}),e}let a=await Qc();try{Ce.current="passkey",H({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await n.authenticate())}catch(e){throw H({status:"error",error:e}),qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}E(t),W(r||!1),v(!0),H({status:"done"});let i=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,loginAccount:i}},async initLinkWithPasskey(e){let t=new fo({captchaToken:e,hints:d.passkeys.registration?.hints});n.startAuthFlow(t),ke.current="link",Ce.current="passkey",H({status:"generating-challenge"});try{await t.initLinkFlow(),H({status:"awaiting-passkey"})}catch(e){throw qa(ge,"linkAccount","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),H({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!y)throw new Ze;if(!(n.authFlow instanceof fo))throw new M("Must initialize Passkey flow first.");if("passkey"!==Ce.current)throw new M("Must init login with Passkey flow first.");try{Ce.current="passkey",({user:e}=await n.link())}catch(e){throw qa(ge,"linkAccount","onError",e.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return E(e||b||null),H({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!Bt())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&&!d.allowOAuthInEmbeddedBrowsers&&In(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 ho({provider:e,withPrivyUi:!1,disableSignup:r??!1,customOAuthRedirectUrl:d.customOAuthRedirectUrl});t&&a.addCaptchaToken(t),Q({status:"loading"});let i=await n.startAuthFlow(a).getAuthorizationUrl();if(i?.url)if("chrome-extension:"===window.location.protocol&&co())try{let{privyOAuthCode:e,privyOAuthState:t}=await uo(i.url);a.meta.stateCode=t,a.meta.authorizationCode=e,await this.loginWithHeadlessOAuth(a.meta)}catch(e){throw Q({status:"error",error:e}),e}else window.location.assign(i.url)},async loginWithHeadlessOAuth(e){let t,r,a;D(!0),Q({status:"loading"}),n.startAuthFlow(new ho({...e,customOAuthRedirectUrl:d.customOAuthRedirectUrl}));let i=tt.get(wa),o=e.stateCode;if(i!==o)throw n.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:i??"",returnedStateCode:o??""}}),D(!1),new M("Unexpected auth flow. This may be a phishing attempt.",void 0,K.OAUTH_UNEXPECTED);if(null!==await n.getAccessToken())try{({user:t,oAuthTokens:a}=await n.link()),Ce.current=e.provider;let r=Le(t);t&&r&&qa(ge,"linkAccount","onSuccess",{user:t,linkMethod:Ce.current,linkedAccount:r})}catch(t){throw D(!1),qa(ge,"linkAccount","onError",t.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:a}=await n.authenticate()),Ce.current=e.provider;let i=Le(t);t&&i&&void 0!==r&&qa(ge,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:Ce.current,loginAccount:i})}catch(e){throw D(!1),Q({status:"error",error:e}),qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}return E(t),W(r||!1),v(!0),D(!1),Q({status:"done"}),a&&t&&qa(ge,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{let i=new ao({email:e,captchaToken:t,disableSignup:r});n.startAuthFlow(i);try{Ce.current="email",V({status:"sending-code"});let e=await i.sendCodeEmail({withPrivyUi:a});if(e?.ssoRedirectUrl)return window.location.href=e.ssoRedirectUrl,void await En(1e4);V({status:"awaiting-code-input"})}catch(e){throw V({status:"error",error:e}),"login"===ke.current?qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR):"link"===ke.current&&qa(ge,"linkAccount","onError",e.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async({oldAddress:e,newAddress:t,captchaToken:r})=>{let a=new io(e,t,r);n.startAuthFlow(a);try{await a.sendCodeEmail({withPrivyUi:!0})}catch(e){throw qa(ge,"update","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:Ce.current}),e}},initUpdatePhone:async(e,t,r)=>{let a=new Co(e,t,r);n.startAuthFlow(a);try{await a.sendSmsCode({withPrivyUi:!0})}catch(e){qa(ge,"update","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:Ce.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{Y({status:"sending-code"});let i=new vo({phoneNumber:e,captchaToken:t,disableSignup:r});n.startAuthFlow(i);try{Ce.current="sms",await i.sendSmsCode({withPrivyUi:a}),Y({status:"awaiting-code-input"})}catch(e){throw Y({status:"error",error:e}),"login"===ke.current?qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR):"link"===ke.current&&qa(ge,"linkAccount","onError",e.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(n.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(n.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function a(e){n.authFlow instanceof ao?V(e):n.authFlow instanceof vo&&Y(e)}if(a({status:"submitting-code"}),!y){let e=new Ze;throw a({status:"error",error:e}),e}if(n.authFlow instanceof ao)n.authFlow.meta.emailCode=e.trim();else{if(!(n.authFlow instanceof vo)){let e=new M("Must initialize a passwordless code flow first");throw a({status:"error",error:e}),e}n.authFlow.meta.smsCode=e.trim()}let i=await Qc();if("link"===ke.current)try{({user:t}=await n.link())}catch(e){throw a({status:"error",error:e}),qa(ge,"linkAccount","onError",e.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:Ce.current}),e}else if("update"===ke.current)try{({user:t}=await n.link())}catch(e){throw a({status:"error",error:e}),qa(ge,"update","onError",e.privyErrorCode||K.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:Ce.current}),e}else try{({user:t,isNewUser:r}=await n.authenticate())}catch(e){throw a({status:"error",error:e}),qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}let o=t||b;E(o||null),W(r||!1),v(!0),a({status:"done"});let s=null;return n.authFlow instanceof ao?s=o?.linkedAccounts.find((({type:e})=>"email"===e))||null:n.authFlow instanceof vo&&(s=o?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:o,isNewUser:r||!1,wasAlreadyAuthenticated:!!i,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{ke.current=f?"link":"login",Ce.current="siwe",J({status:"generating-message"});let a=await n.generateSiweNonce({address:e,captchaToken:r});return J({status:"awaiting-signature"}),_n({address:e,chainId:t.replace("eip155:",""),nonce:a})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await n.generateSiweNonce({address:e});return _n({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r,smartWalletVersion:a})=>{let i;i=await n.linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:a}),E((i=await He.refreshSessionAndUser()??i)||b||null)},loginWithSiwe:async({message:e,signature:t,captchaToken:r,disableSignup:a,walletClientType:i,connectorType:o})=>{let s,l=null;try{if(b)throw Error("User already authenticated");let c=new jt(n,void 0,r,a,{message:e,signature:t,walletClientType:i,connectorType:o});n.startAuthFlow(c),Ce.current="siwe",ke.current="login",J({status:"submitting-signature"});let d=await n.authenticate();if(({user:l,isNewUser:s}=d),!l)throw Error("Authentication failed - no user returned")}catch(e){throw qa(ge,"login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),J({status:"error",error:e}),e}return E(l),W(s||!1),v(!0),J({status:"done"}),ke.current=null,Ce.current=null,{user:l,isNewUser:s||!1}},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:a,connectorType:i})=>{let o;Ne("siwe");let s=null;try{J({status:"submitting-signature"}),o=await n.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:i}),o=await He.refreshSessionAndUser()??o,J({status:"done"}),(s=Le(o)||null)&&qa(ge,"linkAccount","onSuccess",{user:o,linkMethod:"siwe",linkedAccount:s})}catch(e){throw qa(ge,"linkAccount","onError",e.privyErrorCode||K.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),ke.current=null,Ce.current=null,J({status:"error",error:e}),e}let l=o||b;return E(l||null),ke.current=null,Ce.current=null,{user:l,linkedAccount:s}},refreshSessionAndUser:async()=>{let e=await n.getAuthenticatedUser();return v(!!e),E(e),e},walletProxy:re,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>n.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await n.acceptTerms();return E(e),e},getUsdTokenPrice:e=>n.getUsdTokenPrice(e),getUsdPriceForSol:()=>n.getUsdPriceForSol(),getSplTokenMetadata:e=>n.getSplTokenMetadata(e),recoverEmbeddedWallet:async e=>new Promise((async(t,r)=>{if(!b)return void t(!0);let a=e?.address?An(b,e.address):fr(b)||yn(b).at(0)||bn(b).at(0);if(!a||It(a))return void t(!0);let i=await Qc();if(!i||!re||!a)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));let{entropyId:o,entropyIdVerifier:s}=Lt(b,a);try{await re.connect({accessToken:i,entropyId:o,entropyIdVerifier:s}),t(!0)}catch(e){if(Pr(e)&&"privy"===a.recoveryMethod){let e;n.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:a.address}});try{e=await re.recover({entropyId:o,entropyIdVerifier:s,accessToken:i})}catch(e){return void r(e)}e.entropyId||r(Error("Unable to recover wallet")),n.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:a.address}}),t(!0)}else Pr(e)&&"privy"!==a.recoveryMethod&&"privy-v2"!==a.recoveryMethod?(se({recoverWallet:{entropyId:o,entropyIdVerifier:s,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:a.recoveryMethod,action:"recover",shouldCreateEth:!1,shouldCreateSol:!1}}),Te(Tn(a.recoveryMethod))):r(e)}})),setReadyToTrue:e=>{g(!0),le?.(e)},updateWallets:()=>Oe(),fundWallet:async(e,t)=>{se({funding:vi({address:e,appConfig:d,fundWalletConfig:t,methodScreen:Ar})}),Te(Ar)},openModal:Te,requestFarcasterSignerStatus:async e=>{let t=await Qc(),r=b?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!re||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!b?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let a=await n.requestFarcasterSignerStatus(e);return"approved"===a.status&&E(await n.getAuthenticatedUser()||b||null),a},connectCoinbaseSmartWallet:async()=>{d.externalWallets.coinbaseWallet.config.preference={...d.externalWallets.coinbaseWallet.config.preference,options:"smartWalletOnly"};let e=n.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||n.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Ue(e);await Se("coinbase_wallet","coinbase_smart_wallet")},connectBaseAccount:async()=>{let e=n.connectors?.findWalletConnector("base_account","base_account");if(e)return Ue(e);await Se("base_account","base_account")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:i,telegramWebAppData:o,farcasterEmbeddedAddress:s,oAuthUserInfo:l})=>{let c=await n.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:i,telegramWebAppData:o,farcasterEmbeddedAddress:s,oAuthUserInfo:l});return E(c),c},inProgressAuthFlowRef:ke,inProgressLoginOrLinkMethodRef:Ce};Jc=He.recoverEmbeddedWallet,He.recoverEmbeddedWallet;let je=o((()=>({wallets:I,ready:ue&&fe})),[I,ue,fe]),Ve=n.authFlow instanceof Sn,$e=!d.headless&&d.captchaEnabled&&!f&&(y||Ve);/*#__PURE__*/return t(Vc.Provider,{value:!0,children:/*#__PURE__*/t(ur.Provider,{value:Be,children:/*#__PURE__*/t(za.Provider,{value:ge,children:/*#__PURE__*/t(Wn.Provider,{value:je,children:/*#__PURE__*/t(Nn,{...d,children:/*#__PURE__*/r(Je.Provider,{value:He,children:[/*#__PURE__*/t(Rn,{children:/*#__PURE__*/r(On,{data:ie,setModalData:se,setInitialScreen:R,initialScreen:N,authenticated:f,open:h,children:[e.children,/*#__PURE__*/t(jc,{customAuth:d.customAuth}),$e&&/*#__PURE__*/t(as,{delayedExecution:!1}),/*#__PURE__*/t(al,{}),/*#__PURE__*/t(zl,{disabled:d.embeddedWallets.disableAutomaticMigration}),/*#__PURE__*/t(Hs,{palette:d.appearance.palette||{}}),!d.render.standalone&&/*#__PURE__*/t(el,{open:h})]})}),/*#__PURE__*/t(pl,{appId:e.appId,appClientId:e.clientId,clientAnalyticsId:n.clientAnalyticsId,origin:n.apiUrl,mfaMethods:b?.mfaMethods,mfaPromise:we,mfaSubmitPromise:ye,onLoad:ne,onLoadFailed:()=>null}),d.loginConfig.telegramAuthConfiguration&&
|
|
5
|
+
/*#__PURE__*/t(wr,{$if:!0,children:/*#__PURE__*/t(nl,{scriptHost:e.apiUrl||Sa,botUsername:d.loginConfig.telegramAuthConfiguration.botName})})]})})})})})})};const ld=()=>{let{user:e}=cr(),{walletProxy:t}=$e();return{recover:p((async r=>{if(!t)throw Error("Wallet proxy is not ready");let n=await Qc();if(!e||!n)throw new M("User must be logged in before attempting to modify the recovery method.");let{entropyId:a,entropyIdVerifier:i}=Lt(e);try{await t.recover({entropyId:a,entropyIdVerifier:i,accessToken:n,...r})}catch{throw new M("Unable to recover wallets")}}),[t,e])}},cd=()=>{let{client:e,setAuthenticated:t,setUser:r}=$e();return o((()=>({init:async()=>{if(!e)throw new M("Must initialize Privy client first.");let t=new ji;return e.startAuthFlow(t),await t.init()},login:async({fid:n,message:a,signature:i})=>{if(!e)throw new M("Must initialize Privy client first.");if(!(e.authFlow instanceof ji))throw new M("Must initialize Farcaster Mini App flow first.");e.authFlow.setAuthData({message:a,signature:i,fid:n});let{user:o}=await e.authenticate();if(!o)throw new M("Failed to login with Farcaster V2");return r(o),t(!0),{user:o}}})),[e,r,t])},dd=()=>o((()=>({getAccessTokenForProvider:({appId:e})=>{try{let t=tt.get(ka(e));if("string"!=typeof t)return{token:null};{let r=new ko(t);return r.isExpired()?(tt.del(ka(e)),{token:null}):{token:r.value}}}catch(e){return console.error(e),{token:null}}}})),[]),ud=e=>{xa("login",e);let t=$t(),r=Ra(),{ready:n,user:a}=cr(),{initLoginWithHeadlessOAuth:i,loginWithHeadlessOAuth:o,oAuthState:l,setOAuthState:c,isHeadlessOAuthLoading:d}=$e(),u=p((async e=>{try{if(t.enabled&&"success"!==t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);return await i(e.provider,t.token,e.disableSignup)}catch(e){throw c({status:"error",error:e}),e}}),[i,t]),h=p((async()=>{let e=go();try{if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");let t=e.provider;if(yt(t)){if(a&&a.linkedAccounts.some((e=>e.type===t)))return console.warn("User is already logged in with this OAuth provider"),a}else if(a&&t in a&&a[t])return console.warn("User is already logged in with this OAuth provider"),a;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{nn()}}),[o]);return s((()=>{let e=go();n&&r&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&h().catch((()=>{}))}),[n,r]),{initOAuth:u,loading:d,state:l}},hd=e=>{let t=$t(),{emailOtpState:r,setEmailOtpState:n,initLoginWithEmail:a,loginWithCode:i}=$e();return{sendCode:p((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 ta(t.error,null,K.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({email:r,captchaToken:e,disableSignup:i,withPrivyUi:!1})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:p((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);let{user:n,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:s}=await i(r);e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"email",loginAccount:s})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR),r}}),[i,t.status]),state:r}},pd=e=>{let t=$t(),{initSignupWithPasskey:r,signupWithPasskey:n,passkeyAuthState:a,setPasskeyAuthState:i}=$e();return{signupWithPasskey:p((async()=>{try{let a;if(t.enabled&&"error"===t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),a=await t.waitForResult()),await r({captchaToken:a,withPrivyUi:!1});let{user:i,isNewUser:o,wasAlreadyAuthenticated:s,loginAccount:l}=await n();e?.onComplete?.({user:i,isNewUser:o,wasAlreadyAuthenticated:s,loginMethod:"passkey",loginAccount:l})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||K.UNKNOWN_AUTH_ERROR),t}}),[n,t.status]),state:a}},md=e=>{let t=$t(),{initLoginWithPasskey:r,loginWithPasskey:n,passkeyAuthState:a,setPasskeyAuthState:i}=$e();return{loginWithPasskey:p((async a=>{try{let i;if(t.enabled&&"error"===t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult()),await r({captchaToken:i,withPrivyUi:!1});let{user:o,isNewUser:s,wasAlreadyAuthenticated:l,loginAccount:c}=await n(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||K.UNKNOWN_AUTH_ERROR),a}}),[n,t.status]),state:a}},wd=e=>{let{initLinkWithPasskey:t,linkWithPasskey:r,passkeyAuthState:n,setPasskeyAuthState:a}=$e();return{linkWithPasskey:p((async()=>{try{await t();let n=await r();if(!n)throw Error("Error, user not found");let a=n.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:n,linkMethod:"passkey",linkedAccount:a})}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[r]),state:n}},yd=e=>{let t=$t(),{smsOtpState:r,setSmsOtpState:n,initLoginWithSms:a,loginWithCode:i}=$e();return{sendCode:p((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 ta(t.error,null,K.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({phoneNumber:r,captchaToken:e,disableSignup:i,withPrivyUi:!1})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:p((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);let{user:n,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:s}=await i(r);e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"sms",loginAccount:s})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR),r}}),[i,t.status]),state:r}},gd=e=>{let{connectOrCreateWallet:t}=cr();return xa("connectOrCreateWallet",e),{connectOrCreateWallet:t}},fd=e=>{let t=$t(),{siweState:r,setSiweState:n,linkWithSiwe:a,generateSiweMessage:i}=$e();return{generateSiweMessage:p((async({address:t,chainId:r})=>{try{if(!t||!r)throw Error("wallet address and chainId required to generate nonce");return await i({address:t,chainId:r}).then((e=>e))}catch(t){throw n({status:"error",error:t}),e?.onError?.(t.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[i]),linkWithSiwe:p((async({signature:r,message:i,chainId:o,walletClientType:s,connectorType:l})=>{try{if(t.enabled&&"success"!==t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);let{user:n,linkedAccount:c}=await a({message:i,signature:r,chainId:o,walletClientType:s,connectorType:l});c&&e?.onSuccess?.({user:n,linkMethod:"siwe",linkedAccount:c})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[a,t.status]),state:r}},vd=e=>{let t=$t(),{siweState:r,setSiweState:n,client:a,generateSiweMessage:i,loginWithSiwe:o}=$e();return{generateSiweNonce:p((async r=>{try{let e;if(t.enabled&&"error"===t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),n({status:"generating-message"});let i=await a.generateSiweNonce({address:r?.address,captchaToken:e});return n({status:"awaiting-signature"}),i}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR),r}}),[a,t]),generateSiweMessage:p((async({address:r,chainId:a})=>{try{let e;if(t.enabled&&"error"===t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await i({address:r,chainId:a,captchaToken:e})}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR),r}}),[i,t]),loginWithSiwe:p((async({message:r,signature:a,disableSignup:i,walletClientType:s,connectorType:l})=>{try{let n;if(t.enabled&&"error"===t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),n=await t.waitForResult());let{user:c,isNewUser:d}=await o({message:r,signature:a,captchaToken:n,disableSignup:i,walletClientType:s,connectorType:l});return e?.onComplete?.({user:c,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"siwe",loginAccount:null}),c}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR),r}}),[o,t.status]),state:r}},Cd=()=>{let e=$t(),{client:t,setAuthenticated:r,setUser:n,setIsNewUser:a}=$e(),{authenticated:i}=fi();return{generateSiwsMessage:p((async({address:r})=>{let n;if(e.enabled&&"error"===e.status)throw new ta(e.error,null,K.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let a=await t.generateSiwsNonce({address:r,captchaToken:n});return ra({address:r,nonce:a})}),[e,t]),loginWithSiws:p((async({message:o,signature:s,disableSignup:l,walletClientType:c,connectorType:d})=>{if(i)throw Error("User already authenticated");if(e.enabled&&"error"===e.status)throw new ta(e.error,null,K.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),await e.waitForResult());let{user:u,isNewUser:h}=await t.authenticateWithSiws({message:o,signature:s,walletClientType:c,connectorType:d,mode:l?"no-signup":"login-or-sign-up",messageType:"plain"});if(!u)throw Error("Authentication failed - no user returned");return n(u),a(h||!1),r(!0),u}),[i,e,t,r,n,a])}},kd=()=>{let e=$t(),{client:t,setUser:r,refreshSessionAndUser:n}=$e(),{authenticated:a}=fi();return{generateSiwsMessage:p((async({address:r})=>{let n;if(e.enabled&&"error"===e.status)throw new ta(e.error,null,K.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let a=await t.generateSiwsNonce({address:r,captchaToken:n});return ra({address:r,nonce:a})}),[e,t]),linkWithSiws:p((async({signature:i,message:o,walletClientType:s,connectorType:l})=>{if(!a)throw Error("User must be authenticated before linking");if(e.enabled&&"error"===e.status)throw new ta(e.error,null,K.CAPTCHA_FAILURE);let c=await t.linkWithSiws({message:o,signature:i,walletClientType:s,connectorType:l,messageType:"plain"}),d=(e=>{if(!e)return;let t=e.linkedAccounts;return t&&0!==t.length?t[t.length-1]:void 0})(c=await n()??c)||null;return r(c||null),{user:c,linkedAccount:d}}),[a,e,t,n,r])}};function Ad(){let{signTransaction:e}=h(ur);return{signTransaction:e}}function bd(e){let{linkEmail:t,linkPhone:r,linkWallet:n,linkGoogle:a,linkApple:i,linkTwitter:o,linkTwitch:s,linkDiscord:l,linkGithub:c,linkLinkedIn:d,linkTiktok:u,linkLine:p,linkSpotify:m,linkInstagram:w,linkTelegram:y,linkFarcaster:g,linkPasskey:f}=h(ur);return xa("linkAccount",e),{linkEmail:t,linkPhone:r,linkWallet:n,linkGoogle:a,linkApple:i,linkTwitter:o,linkTwitch:s,linkDiscord:l,linkGithub:c,linkLinkedIn:d,linkTiktok:u,linkLine:p,linkSpotify:m,linkInstagram:w,linkFarcaster:g,linkTelegram:y,linkPasskey:f}}function Td(e){let{updateEmail:t,updatePhone:r}=h(ur);return xa("update",e),{updateEmail:t,updatePhone:r}}const _d=e=>{let{user:t}=cr(),{loginWithCode:r,emailOtpState:n,setEmailOtpState:a,client:i,inProgressAuthFlowRef:o,inProgressLoginOrLinkMethodRef:s}=$e();return{state:n,sendCode:p((async({newEmailAddress:r})=>{try{if(!t?.email)throw Error("User is required to have an email address to update it.");let e=new io(t.email.address,r);i.startAuthFlow(e),await e.sendCodeEmail({withPrivyUi:!1})}catch(r){a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[t?.email]),verifyCode:p((async({code:n})=>{try{if(!t?.email)throw Error("User is required to have an email address to update it.");o.current="update",s.current="email";let{user:a,linkedAccount:i}=await r(n);return e?.onSuccess?.({user:a,updateMethod:"email",updatedAccount:i}),{user:a}}catch(n){a({status:"error",error:n}),e?.onError?.(n.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[t?.email])}},Ed=()=>{let{connectCoinbaseSmartWallet:e}=$e();return{connectCoinbaseSmartWallet:e}},Id=()=>{let{connectBaseAccount:e}=$e();return{connectBaseAccount:e}},Sd=()=>{let{baseAccountSdk:e}=$e();return{baseAccountSdk:e}},Ud=()=>{let{setModalData:e}=dr(),{openModal:t,privy:r,closePrivyModal:n}=$e(),{user:a}=cr();return o((()=>({verify:async({standalone:i=!0}={standalone:!0})=>new Promise(((o,s)=>a?0===a.mfaMethods.length?o():(e((e=>({...e,mfaVerify:{onSuccess:async()=>{i?await n({shouldCallAuthOnSuccess:!1,isSuccess:!0}):Bs.setState({inProgressMfaFlow:void 0}),o()},onFailure:async e=>{i?await n({shouldCallAuthOnSuccess:!1,isSuccess:!1}):Bs.setState({inProgressMfaFlow:void 0}),s(e)},sendSmsCode:async()=>{throw Error("Not enabled")},verifySmsCode:async()=>{throw Error("Not enabled")},verifyTotpCode:async e=>{await r.fetchPrivyRoute(Ki,{body:{code:e}})},generateOptions:async()=>jo((await r.fetchPrivyRoute($i,{body:{}})).options),verifyPasskey:async e=>{let t=await import("@simplewebauthn/browser"),n=await t.startAuthentication({optionsJSON:e});await r.fetchPrivyRoute(Vi,{body:{authenticator_response:Bl(n)}})}}}))),void(i?t(Ds):Bs.setState({inProgressMfaFlow:"auth"}))):s(Error("Must be logged in to verify MFA"))))})),[r,e,t,n])},Pd={component:()=>{let{user:e,ready:a}=cr(),{data:i,onUserCloseViaDialogOrKeybindRef:o}=dr(),s=Wa(),[c,d]=l(null),[u,h]=l(null),[p,m]=l(null),[w,y]=l(!1),[g,f]=l(!1),[v,C]=l(),k=async()=>{v?A(v):e?await b({user:e}):A(Error("Must be logged in to manage MFA")),setTimeout((()=>{d(null),h(null)}),500)};if(o.current=k,!i?.mfaEnroll)throw Error("Missing modal data for MFA enrollment screen.");let{onFailure:A,onSuccess:b,onBack:T,mfaMethods:_,verify:E,generateTotpSecret:I,enrollTotp:S,unenrollTotp:U,enrollPasskey:P}=i.mfaEnroll,x=e?.mfaMethods.includes("sms"),W=e?.mfaMethods.includes("totp"),N=e?.mfaMethods.includes("passkey"),R=!!e?.phone,O=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function M(){d(null),h(null),C(void 0)}async function F(e=O){try{C(void 0),f(!0);let t=await P(e);return await b({user:t})}catch(e){C(e)}finally{f(!1),y(!1)}}if(!a||!e||!s)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{onClose:k,backFn:T},"header"),/*#__PURE__*/t(os,{children:/*#__PURE__*/t(pc,{})}),/*#__PURE__*/t(cs,{children:/*#__PURE__*/t(pr,{})}),/*#__PURE__*/t(Zt,{})]});if("sms"===c)return null;if("totp"===c)/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{backFn:M,onClose:k},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ri,{})}),/*#__PURE__*/t(ss,{children:"Remove authenticator app verification?"}),/*#__PURE__*/r(ls,{children:["MFA adds an extra layer of security to your ",s?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/t(ps,{children:/*#__PURE__*/t(ar,{$warn:!0,onClick:async function(){try{C(void 0),f(!0);let e=await U();return await b({user:e})}catch(e){C(e)}finally{f(!1),d(null)}},loading:g,children:"Remove"})}),/*#__PURE__*/t(Zt,{})]});if("passkey"===c){let e=i.mfaEnroll.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return r(n,{children:[/*#__PURE__*/t(tr,{backFn:M,onClose:k},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(Ri,{})}),/*#__PURE__*/t(ss,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/t(ls,{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(ps,{children:/*#__PURE__*/t(ar,{$warn:!0,onClick:async function(){try{C(void 0),f(!0);let e=await P([]);return await b({user:e})}catch(e){C(e)}finally{f(!1),d(null)}},loading:g,children:"Remove"})}),/*#__PURE__*/t(Zt,{})]})}return 0!==_.length||x||W||N?"sms"===u?null:"totp"===u&&p?/*#__PURE__*/t(Uc,{onClose:k,onReset:M,submitEnrollmentWithTotp:e=>async function(e){try{C(void 0),f(!0);let t=await S(e);return await b({user:t})}catch(e){C(e)}finally{f(!1),d(null)}}(e.mfaCode),error:v,totpInfo:{...p,appName:s?.name||"Privy"}}):"passkey"===u?/*#__PURE__*/t(vc,{onReset:M,onClose:k,submitEnrollmentWithPasskey:F}):/*#__PURE__*/t(wc,{showIntro:!0,userMfaMethods:e.mfaMethods,appMfaMethods:s.mfa.methods,userHasAuthSms:R,backFn:T,handleSelectMethod:async function(e){C(void 0);try{await E()}catch(e){return void C(e)}return"totp"===e?(h(e),m(null),void I().then((({totpSecret:e,totpAuthUrl:t})=>{m({authUrl:t,secret:e})})).catch((()=>{m(null),M()}))):"passkey"===e&&1===O.length?await F():void h(e)},isTotpLoading:"totp"===u&&!p,isPasskeyLoading:w,error:v,onClose:k,setRemovingMfaMethod:async function(e){C(void 0);try{await E()}catch(e){return void C(e)}d(e)}}):/*#__PURE__*/r(n,{children:[/*#__PURE__*/t(tr,{onClose:k,backFn:T},"header"),/*#__PURE__*/t(As,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/t(ri,{})}),/*#__PURE__*/t(ss,{children:"Add more security"}),/*#__PURE__*/r(ls,{children:[s?.name," does not have any verification methods enabled."]}),/*#__PURE__*/t(ps,{children:/*#__PURE__*/t(ar,{onClick:k,children:"Close"})}),/*#__PURE__*/t(Zt,{})]})}},xd=()=>{let e=Wa(),{setModalData:t}=dr(),{verify:r}=Ud(),{openModal:n,privy:a,closePrivyModal:i,refreshSessionAndUser:s,setUser:l}=$e();return o((()=>({enroll:async o=>new Promise(((c,d)=>{t({mfaEnroll:{onSuccess:async e=>{await i({shouldCallAuthOnSuccess:!1,isSuccess:!0}),c(e)},onFailure:async e=>{await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}),d(e)},onBack:o?.onBack?async()=>{await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}),d(Error("User canceled MFA enrollment flow.")),o.onBack?.()}:void 0,verify:()=>r({standalone:!1}),shouldUnlinkOnUnenrollMfa:!0,mfaMethods:e.mfa.methods,sendSmsCode:async()=>{throw Error("Not enabled")},enrollSms:async()=>{throw Error("Not enabled")},unenrollSms:async()=>{throw Error("Not enabled")},generateTotpSecret:async()=>await a.fetchPrivyRoute(Ji,{body:{}}),enrollTotp:async e=>{await a.fetchPrivyRoute(Zi,{body:{code:e}});let t=await s();return l(t),t},unenrollTotp:async()=>{await a.fetchPrivyRoute(Gi,{body:{}});let e=await s();return l(e),e},enrollPasskey:async e=>{await a.fetchPrivyRoute(Yi,{body:{credential_ids:e,remove_for_login:!0}});let t=await s();return l(t),t}}}),n(Pd)}))})),[a,t,n,i])},Wd=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:a,signTransactionWithCrossAppWallet:i}=cr();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:n,sendTransaction:a,signTransaction:i}};function Nd(e){let{sendTransaction:t}=h(ur);return xa("sendTransaction",e),{sendTransaction:t}}function Rd(){let e=Wa(),t=Oa(),{client:r,setUser:n,setAuthenticated:a,setIsNewUser:i,initializeWalletProxy:o}=$e(),{create:s}=ki();return{createGuestAccount:async()=>{if(!e.id||!r)throw Error("SDK not yet ready");r.startAuthFlow(new $o(e.id));try{let l=await r.authenticate(),c=l.user,d=l.isNewUser??!1;if(!c)throw new M("Unable to authenticate guest account");let u=await r.getAccessToken(),h=await o(Ba);if(u&&h)try{let t=gn(c,e.embeddedWallets.ethereum.createOnLogin),r=fn(c,e.embeddedWallets.solana.createOnLogin);t&&r?(c=(await s({chainType:"ethereum",latestUser:c})).user,c=(await s({chainType:"solana",latestUser:c})).user):r?c=(await s({chainType:"solana",latestUser:c})).user:t?c=(await s({chainType:"ethereum",latestUser:c})).user:n(c)}catch(e){n(c),console.warn("Unable to create embedded wallet for guest account")}return i(d),a(!0),t("login","onComplete",{user:c,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),c}catch(e){throw t("login","onError",e.privyErrorCode||K.UNKNOWN_AUTH_ERROR),e}}}}function Od(e){let{setWalletRecovery:t}=h(ur);return xa("setWalletRecovery",e),{setWalletRecovery:t}}function Md(e){let{signMessage:t}=h(ur);return xa("signMessage",e),{signMessage:t}}const Fd=()=>{let{ready:e,wallets:t}=Jt(),{user:r}=cr(),{rpcConfig:n,chains:a,appId:i}=$e();return{signAuthorization:p((async(o,s)=>{let l;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??mn(r)?.address??oi,d=t.find((e=>si(e.address)===si(c)));if(!d)throw Error("Signing wallet not found.");let u=o.chainId??Number(d.chainId.split(":")[1]);if(0===u)l={chainId:0,address:o.contractAddress,nonce:o.nonce??0};else{let e=a.find((e=>e.id===u));if(!e)throw Error("Error, chain not configured in PrivyProvider config");let t=li({account:c,chain:e,transport:ci(na(e,n,i))});l=await t.prepareAuthorization({...o})}let h=await d.getEthereumProvider(),p=await h.request({method:"secp256k1_sign",params:[E(l)]});return{...l,...di(p)}}),[e,t,r,a])}};function Ld(e){let{signTypedData:t}=h(ur);return xa("signTypedData",e),{signTypedData:t}}const Dd=async({wallet:e})=>{let t=await e.getEthereumProvider();return to({address:e.address,sign:async({hash:r})=>{if("privy"!==e.walletClientType)throw new x({error:"Unprefixed signing is not supported by external wallets.",code:"unsupported_wallet_type"});return await t.request({method:"secp256k1_sign",params:[r]})},signMessage:async({message:r})=>await t.request({method:"personal_sign",params:[r,e.address]}),signTypedData:async r=>await t.request({method:"eth_signTypedData_v4",params:[e.address,r]}),signTransaction:async e=>await t.request({method:"eth_signTransaction",params:[e]})})},qd=()=>{let{wallets:e}=Jt();return o((()=>({wrapFetchWithPayment:({walletAddress:t,fetch:r,maxValue:n=BigInt(1e5),paymentRequirementsSelector:a=Xi,config:i})=>{let o=t||e[0]?.address;if(!o)throw new eo("No wallet available for payment");let s=e.find((e=>aa(e.address,o)));if(!s)throw new eo(`Wallet ${o} not found in connected wallets`);return async(e,t)=>{let o=await r(e,t);if(402!==o.status)return o;if(t?.__is402Retry)throw Error("Payment already attempted for this request");let{x402Version:l,accepts:c}=await o.json(),d=a(c,void 0,"exact");if(BigInt(d.maxAmountRequired)>n)throw new eo("Payment amount exceeds maximum allowed");let u=await Dd({wallet:s}),h=await Qi(u,l,d,i),p={...t,headers:{...t?.headers||{},"X-PAYMENT":h,"Access-Control-Expose-Headers":"X-PAYMENT-RESPONSE"},__is402Retry:!0};return await r(e,p)}}})),[e])},zd=()=>{let{isModalOpen:e}=h(ur);return{isOpen:e}};function Bd(e){let{getAccessToken:t}=h(ur);return xa("accessToken",e),{getAccessToken:t}}function Hd(e){let{authenticated:t,user:r}=cr(),{initLoginWithOAuth:n}=$e(),a=Oa();return xa("oAuthAuthorization",e),{reauthorize:e=>jd(t,r,n,a,e.provider)}}let jd=async(e,t,r,n,a)=>{if(!e)throw n("linkAccount","onError",K.MUST_BE_AUTHENTICATED,{linkMethod:a}),new M("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(a))))throw new M(`OAuth account of type ${a} not linked to the account.`);await r(a)};function Vd(e){let{client:t}=$e(),[r,n]=l({status:"initial"});return{linkWithCustomJwt:p((async r=>{try{n({status:"initial"}),t.startAuthFlow(new Vo(r)),n({status:"loading"});let{user:a}=await t.link();if(!a)throw Error("Error, user not found");let i=a.linkedAccounts.filter((e=>"custom_auth"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime())).at(0);return n({status:"done"}),e?.onSuccess?.({user:a,linkMethod:"custom",linkedAccount:i}),{user:a}}catch(r){throw n({status:"error",error:r}),e?.onError?.(r.privyErrorCode||K.UNKNOWN_AUTH_ERROR,{linkMethod:"custom"}),r}}),[t.startAuthFlow,t.link]),state:r}}const $d=e=>{let t=Hc((e=>e.jwtAuthFlowState));return xa("customAuth",e),{status:t}};function Kd({isAuthenticated:e,isLoading:t,...r}){let n=u();s((()=>{t||n.current?.()}),[e,t]);let a=p((e=>(n.current=e,()=>{n.current=void 0})),[]);return Bc({...r,subscribe:a})}function Yd(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=cr();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}}const Gd=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=$e();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},Zd=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=(()=>{let{user:e}=cr(),t=$e(),{signWithUserSigner:r}=ro(),n=async({wallet:n,additional_signers:a})=>{let i=await t.client.getAccessToken();if(!e||!i)throw new M("User must be authenticated and have an embedded wallet to delegate actions.");if(!n.id)throw new M("Wallet to add signers to must have ID on server");if(!t.walletProxy)throw new M("Wallet proxy not initialized.");await N(t.privy,{wallet_id:n.id},r,{additional_signers:a})};return{addSessionSignersInternal:async({address:r,signers:a})=>{let i=await t.client.getAccessToken();if(!e||!i)throw new M("User must be authenticated and have an embedded wallet to add a session signer.");let o=t.walletProxy??await t.initializeWalletProxy(15e3);if(!o)throw new M("Wallet proxy not initialized.");let s=An(e,r);if(!s)throw new M("Address to add signers too is not associated with current user.");if(It(s)){if(0===a.length)throw new M("Must specify at least one signer to add.");let e=[...(await W(t.privy,{wallet_id:s.id})).additional_signers,...ia(a)];await n({wallet:s,additional_signers:e})}else{if(s.delegated)return{user:e};if(a.length>0)throw new M("Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let n=ml({address:r,user:e}),l=wl({address:r,user:e});await t.recoverEmbeddedWallet({address:r}),await o.createDelegatedAction({accessToken:i,rootWallet:l,delegatedWallets:[n]})}let l=await t.refreshSessionAndUser();if(!l)throw Error("Could not refresh user");return{user:l}},removeSessionSignersInternal:async({address:r})=>{let a=await t.client.getAccessToken();if(!e||!a)throw new M("User must be authenticated and have an embedded wallet to delegate actions.");if(!(t.walletProxy??await t.initializeWalletProxy(15e3)))throw new M("Wallet proxy not initialized.");let i=An(e,r);if(!i)throw new M("Address to remove signers from is not associated with current user.");It(i)?await n({wallet:i,additional_signers:[]}):await t.client.revokeDelegatedWallet();let o=await t.refreshSessionAndUser();if(!o)throw Error("Could not refresh user");return{user:o}}}})();return{addSessionSigners:async({address:t,signers:r})=>e({address:t,signers:r}),removeSessionSigners:async({address:e})=>t({address:e})}},Jd=()=>{let{signWithUserSigner:e}=ro();return o((()=>({async generateAuthorizationSignature(t){let{targetAppId:r,...n}=t,{signature:a}=await R((async({message:t})=>e({message:t,targetAppId:r})),n);return{signature:a}}})),[e])},Xd=()=>{let{setUser:e,client:t}=h(Je),{user:r}=h(ur);return{user:r,refreshUser:p((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}},Qd=e=>{let t=$t(),{initLoginWithTelegram:r,loginWithTelegram:n,telegramAuthState:a,setTelegramAuthState:i}=$e();return{login:p((async a=>{try{if(t.enabled&&"success"!==t.status)throw new ta(t.error,null,K.CAPTCHA_FAILURE);await r(t.token,a?.disableSignup);let{user:i,isNewUser:o,loginAccount:s,wasAlreadyAuthenticated:l}=await n({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||K.UNKNOWN_AUTH_ERROR),a}}),[r,n,t]),state:a}},eu=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=$e();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}},tu=el;export{as as Captcha,Lo as ConnectorManager,ft as EthereumWalletConnector,tu as LoginModal,rs as PrivyClient,el as PrivyModal,od as PrivyProvider,ya as VERSION,or as errorIndicatesMaxMfaRetries,lr as errorIndicatesMfaTimeout,sr as errorIndicatesMfaVerificationFailed,Xc as getAccessToken,ed as getIdentityToken,Dd as toViemAccount,Ud as useAuthMfa,xd as useAuthMfaEnrollment,Jd as useAuthorizationSignature,Sd as useBaseAccountSdk,Id as useConnectBaseAccount,Ed as useConnectCoinbaseSmartWallet,gd as useConnectOrCreateWallet,Wd as useCrossAppAccounts,$d as useCustomAuth,Gd as useDelegatedActions,Yd as useFarcasterSigner,dd as useGetAccessTokenForProvider,Rd as useGuestAccounts,eu as useHeadlessDelegatedActions,Go as useIdentityToken,bd as useLinkAccount,Vd as useLinkJwtAccount,wd as useLinkWithPasskey,fd as useLinkWithSiwe,kd as useLinkWithSiws,hd as useLoginWithEmail,cd as useLoginWithFarcasterV2,ud as useLoginWithOAuth,md as useLoginWithPasskey,vd as useLoginWithSiwe,Cd as useLoginWithSiws,yd as useLoginWithSms,Qd as useLoginWithTelegram,Ja as useLogout,qs as useMfa,hc as useMfaEnrollment,ql as useMigrateWallets,zd as useModalStatus,Hd as useOAuthTokens,fi as usePrivy,ld as useRecoverEmbeddedWallet,is as useRegisterMfaListener,Nd as useSendTransaction,Zd as useSessionSigners,Od as useSetWalletRecovery,Fd as useSign7702Authorization,Md as useSignMessage,Ad as useSignTransaction,Ld as useSignTypedData,pd as useSignupWithPasskey,Kd as useSubscribeToJwtAuthWithFlag,Bc as useSyncJwtBasedAuthState,Bd as useToken,Td as useUpdateAccount,_d as useUpdateEmail,Xd as useUser,Jt as useWallets,qd as useX402Fetch};
|