UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

1 lines • 260 kB
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