UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

1 lines • 255 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{isAddress as k,toHex 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 R}from"@privy-io/js-sdk-core";export{DEFAULT_SUPPORTED_CHAINS as SUPPORTED_CHAINS,addPrivyRpcToChain,addRpcUrlOverrideToChain}from"@privy-io/js-sdk-core";import{P as O,p as M,f as F,a as L,b as D,u as q,c as z,d as B,e as j,g as H,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 Re,a0 as Oe,a1 as Me,a2 as Fe,a3 as Le,a4 as De,a5 as qe,a6 as ze,a7 as Be,a8 as je,a9 as He,aa as Ve,ab as $e,ac as Ke}from"./paths-B891YjWw.mjs";import{o as Ge,R as Ye,g as Ze,s as Je,C as Xe,H as Qe,O as et,c as tt,a as rt,S as nt,d as at,G as it,D as ot,b as st,L as lt,T as ct,e as dt,I as ut,f as ht,h as pt,A as mt,i as wt,E as yt,B as gt,j as ft,P as vt,k as Ct,t as kt,l as At,m as bt,n as Tt,p as _t,q as Et,M as It,r as St,u as Ut,v as Pt,w as Wt,x as xt,y as Nt,z as Rt,F as Ot,W as Mt,J as Ft,V as Lt,K as Dt,N as qt,Q as zt,U as Bt,X as jt,Y as Ht,Z as Vt,_ as $t,$ as Kt,a0 as Gt,a1 as Yt,a2 as Zt,a3 as Jt,a4 as Xt,a5 as Qt,a6 as er,a7 as tr,a8 as rr,a9 as nr,aa as ar,ab as ir,ac as or,ad as sr,ae as lr,af as cr,ag as dr,ah as ur,ai as hr,aj as pr,ak as mr,al as wr,am as yr,an as gr,ao as fr,ap as vr,aq as Cr,ar as kr,as as Ar,at as br,au as Tr,av as _r,aw as Er,ax as Ir,ay as Sr,az as Ur,aA as Pr,aB as Wr,aC as xr,aD as Nr,aE as Rr,aF as Or,aG as Mr,aH as Fr,aI as Lr,aJ as Dr,aK as qr,aL as zr,aM as Br,aN as jr,aO as Hr,aP as Vr,aQ as $r,aR as Kr,aS as Gr,aT as Yr,aU as Zr,aV as Jr,aW as Xr,aX as Qr,aY as en,aZ as tn,a_ as rn,a$ as nn,b0 as an,b1 as on,b2 as sn,b3 as ln,b4 as cn,b5 as dn,b6 as un,b7 as hn,b8 as pn,b9 as mn,ba as wn,bb as yn,bc as gn,bd as fn,be as vn,bf as Cn,bg as kn,bh as An,bi as bn,bj as Tn,bk as _n,bl as En,bm as In,bn as Sn,bo as Un,bp as Pn,bq as Wn,br as xn,bs as Nn,bt as Rn,bu as On,bv as Mn,bw as Fn,bx as Ln,by as Dn,bz as qn,bA as zn,bB as Bn,bC as jn,bD as Hn,bE as Vn,bF as $n,bG as Kn,bH as Gn,bI as Yn,bJ as Zn,bK as Jn,bL as Xn,bM as Qn,bN as ea,bO as ta,bP as ra,bQ as na,bR as aa,bS as ia,bT as oa,bU as sa,bV as la,bW as ca,bX as da,bY as ua,bZ as ha,b_ as pa,b$ as ma,c0 as wa,c1 as ya,c2 as ga,c3 as fa,c4 as va}from"./SignRequestScreen-NOqdMm22.mjs";export{c5 as WalletConnector}from"./SignRequestScreen-NOqdMm22.mjs";import{v4 as Ca}from"uuid";import*as ka from"jose";import{base64url as Aa}from"jose";import{g as ba,c as Ta,u as _a,P as Ea,a as Ia,b as Sa,d as Ua,e as Pa,f as Wa,h as xa,i as Na}from"./privy-context-V2csHgUI.mjs";import Ra from"eventemitter3";import{createCoinbaseWalletSDK as Oa}from"@coinbase/wallet-sdk";import{toViemTransactionSerializable as Ma}from"@privy-io/ethereum";import{ofetch as Fa}from"ofetch";import La from"js-cookie";import{create as Da}from"zustand";import{Turnstile as qa}from"@marsidev/react-turnstile";import{styled as za,createGlobalStyle as Ba,css as ja}from"styled-components";import{u as Ha,n as Va,I as $a}from"./internal-context-LlMdpfkb.mjs";import{u as Ka,a as Ga,C as Ya}from"./useActiveWallet-58s-VNmj.mjs";export{e as useActiveWallet,c as useConnectWallet,d as useFundWallet,b as useLogin}from"./useActiveWallet-58s-VNmj.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{i as hi,f as pi,u as mi,p as wi,e as yi,a as gi}from"./usePrivy-ZXeOLg-E.mjs";export{b as useCreateWallet,c as useImportWallet}from"./usePrivy-ZXeOLg-E.mjs";import{CheckCircle as fi,FingerprintIcon as vi,Trash2 as Ci,AlertCircle as ki,CloudUpload as Ai,Ban as bi,ExternalLink as Ti,XCircle as _i}from"lucide-react";import Ei from"@heroicons/react/24/outline/EnvelopeIcon";import Ii from"@heroicons/react/24/outline/QuestionMarkCircleIcon";import Si from"@heroicons/react/24/solid/CheckBadgeIcon";import Ui from"@heroicons/react/24/solid/IdentificationIcon";import Pi from"@heroicons/react/24/outline/ChevronRightIcon";import Wi from"@heroicons/react/24/outline/MinusCircleIcon";import xi from"@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon";import Ni from"@heroicons/react/24/outline/ClockIcon";import Ri from"@heroicons/react/24/outline/CheckCircleIcon";import Oi from"@heroicons/react/24/solid/ShieldCheckIcon";import Mi from"@heroicons/react/24/outline/GlobeAltIcon";import{F as Fi}from"./frame-Dh-xhHMG.mjs";import{MfaAuthTotpVerify as Li,MfaAuthPasskeyInit as Di,MfaAuthPasskeyVerify as qi,MfaAuthTotpInit as zi,MfaAuthTotpEnroll as Bi,MfaAuthTotpUnenroll as ji,MfaAuthPasskeyEnrollment as Hi}from"@privy-io/public-api";import{u as Vi}from"./use-sign-with-user-signer-DwqsbciW.mjs";export{g as getEmbeddedConnectedWallet}from"./getEmbeddedConnectedWallet-CSSBWE2p.mjs";import{toAccount as $i}from"viem/accounts";import"@heroicons/react/24/outline/InformationCircleIcon";import"@heroicons/react/24/outline/CreditCardIcon";import"@heroicons/react/24/outline/QrCodeIcon";import"@heroicons/react/24/solid/ArrowsRightLeftIcon";import"@heroicons/react/24/outline/ExclamationCircleIcon";import"@heroicons/react/24/outline/WalletIcon";import"@heroicons/react/24/outline/ChevronDownIcon";import"@heroicons/react/24/solid/CheckCircleIcon";import"@heroicons/react/24/outline";import"@heroicons/react/24/outline/ClipboardDocumentCheckIcon";import"@heroicons/react/24/outline/ClipboardDocumentIcon";import"@scure/base";import"tinycolor2";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/Square2StackIcon";import"fast-password-entropy";import"secure-password-utilities";import"secure-password-utilities/wordlists";import"@heroicons/react/24/outline/LockClosedIcon";import"@heroicons/react/24/outline/PencilSquareIcon";import"@heroicons/react/24/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"@tanstack/react-virtual";import"@heroicons/react/24/outline/CheckIcon";import"qrcode";import"@walletconnect/ethereum-provider";function Ki(e){return e?{"privy-ui":"t"}:void 0}class Gi{async authenticate(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new O("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(M,{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 O("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new O("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})}catch(e){throw F(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new O("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new O("Email must be set when initialzing authentication.");let n=Ki(r);try{return await this.api.post(D,{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 Yi extends Gi{async link(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new O("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(q,{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 Zi{get meta(){return this._meta}async authenticate(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.channelToken)throw new O("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 O("No response from authentication");return e}catch(e){throw F(e)}}async link(){if(!this.api)throw new O("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 O("Auth flow has no API instance");let e=await this.api.post(j,{token:this.captchaToken});y&&!f&&e.connect_uri&&Ge(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new O("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.channelToken)throw new O("Auth flow must be initialized first");let e=await this.api.get(H,{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 Ye(this._startChannelOnce.bind(this)),this.pollForReady=new Ye(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function Ji(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function Xi(){if(!Ji())return;let e=window.chrome;return e?.runtime?.id}function Qi(){if(!Ji())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function eo(e){return new Promise(((t,r)=>{Qi()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!Ji())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=Xi();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 to{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new O("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new O("User denied confirmation during OAuth flow");let e=Ze();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 Je.del(Xe),Je.del(Qe),Je.del(et),t}catch(e){let t=F(e);if(t.privyErrorCode)throw new O(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new O("Invalid code during oauth flow.",void 0,$.OAUTH_USER_DENIED);throw new O("Invalid code during OAuth flow.",void 0,$.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new O("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new O("User denied confirmation during OAuth flow");let e=Je.get(Xe);if(!e)throw new O("Authentication error.");try{let t=await this.api.post(K,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return Je.del(Xe),t}catch(e){throw F(e)}}async getAuthorizationUrl(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.provider)throw new O("Provider must be set when initializing OAuth authentication.");let e=tt();Je.put(Xe,e);let t=rt();Je.put(nt,t);let r=await at(e);this.meta.withPrivyUi||Je.put(Qe,!0),this.meta.disableSignup?Je.put(et,!0):Je.del(et);let n=Ki(this.meta.withPrivyUi),a=window.location.href,i=function(){let e=Xi();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 ro=({style:e})=>/*#__PURE__*/t(Mi,{style:{color:"var(--privy-color-error)",...e}});let no={google:{name:"Google",component:it},discord:{name:"Discord",component:ot},github:{name:"Github",component:st},linkedin:{name:"LinkedIn",component:lt},twitter:{name:"Twitter",component:ct},spotify:{name:"Spotify",component:dt},instagram:{name:"Instagram",component:ut},tiktok:{name:"Tiktok",component:ht},line:{name:"LINE",component:pt},apple:{name:"Apple",component:mt}};const ao=e=>e in no?no[e]:{name:"Unknown",component:ro};function io(){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:!Je.get(Qe),popupFlow:null!==window.opener&&a,disableSignup:!!Je.get(et)}}class oo{async initRegisterFlow(e){if(!this.api)throw new O("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 O("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new O("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 O("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new O("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(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 O("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 O("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new O("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(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 O("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 O("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new O("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(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 O("Passkey request timed out or rejected by user.",void 0,$.PASSKEY_NOT_ALLOWED);throw F(e)}}async _initRegisterOnce(e){if(!this.api)throw new O("Auth flow has no API instance");let t=Ki(e);return await this.api.post(X,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new O("Auth flow has no API instance");let t=Ki(e);return await this.api.post(Q,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new O("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}}}_transformRegistrationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}_transformInitAuthenticateOptionsToCamelCase(e){return{rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}}_transformAuthenticationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}constructor({captchaToken:e,setPasskeyAuthState:t}){this.authenticateForRegistration=!1,this.initRegisterOnce=new Ye(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new Ye(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new Ye(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t}}}class so{async authenticate(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new O("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 O("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new O("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 O("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new O("phone nNumber must be set when initialzing authentication.");let n=Ki(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 lo extends so{async link(){if(!this.api)throw new O("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new O("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 co{static parse(e){try{return new co(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return ka.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=ka.decodeJwt(e)}}class uo extends co{static parse(e){try{return new uo(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let ho,po;class mo extends yt{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:gt,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 ft(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 vt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},ho?(this.proxyProvider.setWalletProvider(ho.getProvider()),this.setBaseAccountSdk(ho),console.log("Base Account SDK Initialized")):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{ho=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(ho.getProvider()),this.setBaseAccountSdk(ho),console.log("Base Account SDK Initialized")})).catch(console.error)}}let wo=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class yo extends yt{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:Ct,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 ft(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",po=Oa({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(po.getProvider())}constructor(e,t,r,n){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new vt(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"),!po){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!wo.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(", ")}`),po=Oa(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(po.getProvider())}}class go extends yt{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:[kt(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:At,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 fo=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];class vo extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class Co extends Ra{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new vo(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await zc()||!this.address)throw new vo("Disconnected",4900);let{hash:r}=await Vc(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new vo(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await zc()||!this.address)throw new vo("Disconnected",4900);let{signature:r}=await Hc(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new vo(`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 vo(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=bt(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 Bc({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 jc(Tt(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:kt(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...Ma(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 kt(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=>fo.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await zc();if(await $c({address:this.address}),!t||!this.address)throw new vo("Disconnected",4900);try{let r={method:e.method,params:e.params},n=this.walletAccount;return n&&ba(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 vo("Disconnected",4900)}}}async handleWalletApiRequest(e,t,r){let n=this.privyClient;if(!n)throw new vo("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 vo(`Invalid params for ${e.method}`,4200);return a.data.signature}throw new vo(`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=bt(s,this.chains,a,{appId:o}),this.rpcTimeoutDuration=_t(a,"privy"),this.appId=o,this.walletIndex=l,this.privyClient=c,this.walletAccount=d}}function ko(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var Ao=0;class bo extends yt{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 ft(e)}}constructor(e,t,r,n,a){super(a||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new vt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let i=n.provider;this.proxyProvider.setWalletProvider(i)}}var To="__private_"+Ao+++"__walletBranding";class _o extends yt{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 ko(this,To)[To]??{name:"Browser Extension",icon:Et,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 ft(e)}}constructor(e,t,r,n,a){super(a??"unknown",e,t,r),Object.defineProperty(this,To,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new vt(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===a?ko(this,To)[To]={name:"MetaMask",icon:It,id:"io.metamask"}:"phantom"===a&&(ko(this,To)[To]={name:"Phantom",icon:St,id:"phantom"})}}class Eo extends bo{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 ft(e)}}}class Io extends Ra{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=Ut({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(Pt)))!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 Wt({id:e.client,name:e.name})));this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"}),this.externalWalletConfig.solana.connectors?.get().forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{e?.forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(xt).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(xt).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(Nt).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id:t.walletClientType===e.walletClientType)));t&&(e.connectedAt=t.connectedAt)})),this.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}=Rt(t);for(let t of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===t.walletIndex));if(r&&xt(r))r.proxyProvider.walletProxy=e;else{let r=new go({provider:new Co({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");if(a&&xt(a))a.proxyProvider.walletProxy=e;else{let a=new go({provider:new Co({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=Ot(),this.emit("walletsUpdated")}removeImportedWalletConnector(){let e=this.findWalletConnector("embedded_imported","privy");if(e){let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1),this.storedConnections=Ot(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let a=this.findWalletConnector(e,t);if(a&&xt(a))return a instanceof Mt&&a.resetConnection(t),a;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new yo(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new mo(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new Mt({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 Ft({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new Eo(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new _o(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new _o(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new _o(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new bo(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=Ot()}}let So=[se,le,ce];class Uo{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=Lt,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=Fa.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=So.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 Po=/paymaster\.biconomy\.io\/api/i,Wo={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const xo=(e,t)=>e&&Po.test(e)?Wo:t&&t.policy_id?{policyId:t.policy_id}:void 0,No=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 Ro{async authenticate(){if(!this.api)throw new O("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 O("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 Oo{getOrCreateGuestCredential(e){let t=zt(e);if(Dt()){if(Je.get(t))return Je.get(t);{let e=Aa.encode(qt(32));return Je.put(t,e),e}}return Aa.encode(qt(32))}async authenticate(){if(!this.api)throw new O("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 Mo(){return!(v&&window.location.origin.startsWith("http://localhost"))}const Fo=Da((()=>({identityToken:null})));function Lo(){let{identityToken:e}=Fo();return{identityToken:e}}var Do,qo=((Do={}).PRIVY="privy_access_token",Do.CUSTOMER="customer_access_token",Do);class zo{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(jt)}get privyAccessToken(){return this._getToken(Ht)}_getToken(e){try{let t=Je.get(e);return"string"==typeof t?co.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=Je.get(Vt);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=Je.get($t(e));if("string"!=typeof t)return null;{let r=new co(t);return r.isExpired()?(Je.del($t(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=La.get(Kt);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!==Gt;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=co.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?Je.put($t(e),t):Je.del($t(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:Ta(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 Gi?"email":e instanceof so?"sms":e instanceof Bt?"siwe":e instanceof Oo?"guest":e instanceof Ro?"custom_auth":e instanceof to?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:Ta(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),pe(e)}}async _refresh(){if(!this.api)throw new O("Session has no API instance");if(!this.client)throw new O("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),Ta(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=Je.get(jt);if(Je.put(jt,e),!this.client?.useServerCookies){let t=co.parse(e)?.expiration;La.set(Yt,e,{sameSite:"Strict",secure:Mo(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else Je.del(jt),La.remove(Yt),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(Je.put(Vt,e),this.client?.useServerCookies||La.set(Kt,"t",{sameSite:"Strict",secure:Mo(),expires:30})):(Je.del(Vt),La.remove(Zt),La.remove(Kt))}storePrivyAccessToken(e){"string"==typeof e?Je.put(Ht,e):Je.del(Ht)}storeIdentityTo