@privy-io/react-auth
Version:
React client for the Privy Auth API
2 lines (1 loc) • 35.3 kB
JavaScript
"use strict";var e=require("./privy-provider-DEKIIG0u.js"),r=require("react"),t=require("./paths-B00ZrFQm.js"),o=require("./internal-context-B_aIJuQh.js"),s=require("./use-sign-with-user-signer-gh4MDT3P.js"),n=require("./useActiveWallet-B16YB4iX.js"),i=require("./frame-8JZCzmCf.js"),a=require("@privy-io/public-api"),l=require("react/jsx-runtime"),u=require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),c=require("@heroicons/react/24/outline/ShieldCheckIcon"),d=require("viem"),h=require("viem/utils"),y=require("@privy-io/js-sdk-core"),p=require("./getEmbeddedConnectedWallet-DTU4T9TJ.js"),w=require("viem/accounts");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("mipd"),require("react-device-detect"),require("uuid"),require("jose"),require("eventemitter3"),require("@coinbase/wallet-sdk"),require("@privy-io/ethereum"),require("@marsidev/react-turnstile"),require("styled-components"),require("tinycolor2"),require("@heroicons/react/24/outline/DevicePhoneMobileIcon"),require("@heroicons/react/24/outline/FingerPrintIcon"),require("@heroicons/react/24/outline/PhoneIcon"),require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@heroicons/react/24/outline/CalendarIcon"),require("@heroicons/react/24/outline/ExclamationTriangleIcon"),require("@heroicons/react/24/outline/ChevronDownIcon"),require("zustand"),require("@headlessui/react"),require("@heroicons/react/24/outline/CheckIcon"),require("@heroicons/react/24/outline/Square2StackIcon"),require("@walletconnect/ethereum-provider"),require("fast-password-entropy"),require("secure-password-utilities"),require("secure-password-utilities/wordlists"),require("@heroicons/react/24/outline/UserCircleIcon"),require("@heroicons/react/24/outline/EnvelopeIcon"),require("@heroicons/react/20/solid/CheckIcon"),require("@heroicons/react/24/outline/WalletIcon"),require("@heroicons/react/24/outline/ExclamationCircleIcon"),require("@heroicons/react/24/outline/ArrowTopRightOnSquareIcon"),require("@heroicons/react/24/solid/DocumentCheckIcon"),require("@heroicons/react/24/solid/XCircleIcon"),require("@heroicons/react/24/solid/CheckCircleIcon"),require("@heroicons/react/24/outline"),require("@tanstack/react-virtual"),require("qrcode"),require("@heroicons/react/24/solid/ArrowsRightLeftIcon"),require("@heroicons/react/24/outline/ChevronRightIcon"),require("@heroicons/react/24/outline/LockClosedIcon"),require("@heroicons/react/24/outline/PencilSquareIcon"),require("@heroicons/react/24/outline/ArrowPathIcon"),require("@heroicons/react/24/outline/EyeIcon"),require("@heroicons/react/24/outline/EyeSlashIcon"),require("@heroicons/react/24/outline/KeyIcon"),require("@heroicons/react/24/outline/ArrowDownTrayIcon"),require("@heroicons/react/24/outline/ClipboardDocumentCheckIcon"),require("@heroicons/react/24/outline/DocumentDuplicateIcon"),require("@heroicons/react/24/solid/LockClosedIcon"),require("@heroicons/react/24/outline/CheckCircleIcon"),require("@heroicons/react/24/outline/InformationCircleIcon"),require("@heroicons/react/24/outline/CreditCardIcon"),require("@heroicons/react/24/outline/QrCodeIcon"),require("@heroicons/react/24/outline/GlobeAltIcon"),require("ofetch"),require("@heroicons/react/24/outline/ClipboardDocumentIcon"),require("@heroicons/react/24/outline/CloudArrowUpIcon"),require("@heroicons/react/24/outline/NoSymbolIcon"),require("@heroicons/react/24/outline/ClockIcon"),require("@heroicons/react/24/outline/TrashIcon"),require("@heroicons/react/24/solid/CheckBadgeIcon"),require("@heroicons/react/24/solid/IdentificationIcon"),require("@heroicons/react/24/outline/MinusCircleIcon"),require("@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon"),require("@heroicons/react/24/solid/ShieldCheckIcon"),require("js-cookie");var C=/*#__PURE__*/g(u),v=/*#__PURE__*/g(c);const A=()=>{let{setModalData:t}=e.usePrivyModal(),{openModal:n,privy:i,closePrivyModal:l}=o.usePrivyInternal(),{user:u}=s.usePrivyContext();return r.useMemo((()=>({verify:async({standalone:r=!0}={standalone:!0})=>new Promise(((o,s)=>u?0===u.mfaMethods.length?o():(t((t=>({...t,mfaVerify:{onSuccess:async()=>{r?await l({shouldCallAuthOnSuccess:!1,isSuccess:!0}):e.useCorePrivyStateStore.setState({inProgressMfaFlow:void 0}),o()},onFailure:async t=>{r?await l({shouldCallAuthOnSuccess:!1,isSuccess:!1}):e.useCorePrivyStateStore.setState({inProgressMfaFlow:void 0}),s(t)},sendSmsCode:async()=>{throw Error("Not enabled")},verifySmsCode:async()=>{throw Error("Not enabled")},verifyTotpCode:async e=>{await i.fetchPrivyRoute(a.MfaAuthTotpVerify,{body:{code:e}})},generateOptions:async()=>e.transformOptionsToCamelCase((await i.fetchPrivyRoute(a.MfaAuthPasskeyInit,{body:{}})).options),verifyPasskey:async r=>{let t=await import("@simplewebauthn/browser"),o=await t.startAuthentication(r);await i.fetchPrivyRoute(a.MfaAuthPasskeyVerify,{body:{authenticator_response:e.transformResponseToSnakeCase(o)}})}}}))),void(r?n(e.MfaAuthVerifyFlowScreen):e.useCorePrivyStateStore.setState({inProgressMfaFlow:"auth"}))):s(Error("Must be logged in to verify MFA"))))})),[i,t,n,l])},m={component:()=>{let{user:t,ready:o}=s.usePrivyContext(),{app:n,data:i,onUserCloseViaDialogOrKeybindRef:a}=e.usePrivyModal(),[u,c]=r.useState(null),[d,h]=r.useState(null),[y,p]=r.useState(null),[w,g]=r.useState(!1),[A,m]=r.useState(!1),[f,P]=r.useState(),E=async()=>{f?k(f):t?await S({user:t}):k(Error("Must be logged in to manage MFA")),setTimeout((()=>{c(null),h(null)}),500)};if(a.current=E,!i?.mfaEnroll)throw Error("Missing modal data for MFA enrollment screen.");let{onFailure:k,onSuccess:S,mfaMethods:x,verify:W,generateTotpSecret:I,enrollTotp:T,unenrollTotp:b,enrollPasskey:M}=i.mfaEnroll,U=t?.mfaMethods.includes("sms"),R=t?.mfaMethods.includes("totp"),q=t?.mfaMethods.includes("passkey"),O=!!t?.phone,F=t?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function N(){c(null),h(null),P(void 0)}async function _(e=F){try{P(void 0),m(!0);let r=await M(e);return await S({user:r})}catch(e){P(e)}finally{m(!1),g(!1)}}if(!o||!t||!n)/*#__PURE__*/return l.jsxs(l.Fragment,{children:[/*#__PURE__*/l.jsx(e.ModalHeader,{onClose:E},"header"),/*#__PURE__*/l.jsx(e.AppLogoContainer,{children:/*#__PURE__*/l.jsx(e.MfaShieldIcon,{})}),/*#__PURE__*/l.jsx(e.Container,{children:/*#__PURE__*/l.jsx(e.Loader,{})}),/*#__PURE__*/l.jsx(e.ModalFooter,{})]});if("sms"===u)return null;if("totp"===u)/*#__PURE__*/return l.jsxs(l.Fragment,{children:[/*#__PURE__*/l.jsx(e.ModalHeader,{backFn:N,onClose:E},"header"),/*#__PURE__*/l.jsx(e.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/l.jsx(C.default,{})}),/*#__PURE__*/l.jsx(e.Title,{children:"Remove authenticator app verification?"}),/*#__PURE__*/l.jsxs(e.SubTitle,{children:["MFA adds an extra layer of security to your ",n?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/l.jsx(e.BottomSection,{children:/*#__PURE__*/l.jsx(e.PrimaryButton,{$warn:!0,onClick:async function(){try{P(void 0),m(!0);let e=await b();return await S({user:e})}catch(e){P(e)}finally{m(!1),c(null)}},loading:A,children:"Remove"})}),/*#__PURE__*/l.jsx(e.ModalFooter,{})]});if("passkey"===u){let r=i.mfaEnroll.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return l.jsxs(l.Fragment,{children:[/*#__PURE__*/l.jsx(e.ModalHeader,{backFn:N,onClose:E},"header"),/*#__PURE__*/l.jsx(e.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/l.jsx(C.default,{})}),/*#__PURE__*/l.jsx(e.Title,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/l.jsx(e.SubTitle,{children:r?"Removing your passkey will remove as both a verification method and a login method.":"Removing your passkey will remove as a verification method."}),/*#__PURE__*/l.jsx(e.BottomSection,{children:/*#__PURE__*/l.jsx(e.PrimaryButton,{$warn:!0,onClick:async function(){try{P(void 0),m(!0);let e=await M([]);return await S({user:e})}catch(e){P(e)}finally{m(!1),c(null)}},loading:A,children:"Remove"})}),/*#__PURE__*/l.jsx(e.ModalFooter,{})]})}return 0!==x.length||U||R||q?"sms"===d?null:"totp"===d&&y?/*#__PURE__*/l.jsx(e.EnrollTotp,{onClose:E,onReset:N,submitEnrollmentWithTotp:e=>async function(e){try{P(void 0),m(!0);let r=await T(e);return await S({user:r})}catch(e){P(e)}finally{m(!1),c(null)}}(e.mfaCode),error:f,totpInfo:{...y,appName:n?.name||"Privy"}}):"passkey"===d?/*#__PURE__*/l.jsx(e.EnrollPasskey,{onReset:N,onClose:E,submitEnrollmentWithPasskey:_}):/*#__PURE__*/l.jsx(e.EnrollLandingScreen,{showIntro:!1,userMfaMethods:t.mfaMethods,appMfaMethods:n.mfa.methods,userHasAuthSms:O,onBackToIntro:()=>{},handleSelectMethod:async function(e){P(void 0);try{await W()}catch(e){return void P(e)}return"totp"===e?(h(e),p(null),void I().then((({totpSecret:e,totpAuthUrl:r})=>{p({authUrl:r,secret:e})})).catch((()=>{p(null),N()}))):"passkey"===e&&1===F.length?await _():void h(e)},isTotpLoading:"totp"===d&&!y,isPasskeyLoading:w,error:f,onClose:E,setRemovingMfaMethod:async function(e){P(void 0);try{await W()}catch(e){return void P(e)}c(e)}}):/*#__PURE__*/l.jsxs(l.Fragment,{children:[/*#__PURE__*/l.jsx(e.ModalHeader,{onClose:E},"header"),/*#__PURE__*/l.jsx(e.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/l.jsx(v.default,{})}),/*#__PURE__*/l.jsx(e.Title,{children:"Add more security"}),/*#__PURE__*/l.jsxs(e.SubTitle,{children:[n?.name," does not have any verification methods enabled."]}),/*#__PURE__*/l.jsx(e.BottomSection,{children:/*#__PURE__*/l.jsx(e.PrimaryButton,{onClick:E,children:"Close"})}),/*#__PURE__*/l.jsx(e.ModalFooter,{})]})}};const f=()=>{let{ready:t,wallets:n}=e.useWallets(),{user:i}=s.usePrivyContext(),{rpcConfig:a,chains:l,appId:u}=o.usePrivyInternal();return{signAuthorization:r.useCallback((async(r,o)=>{let c;if(!i)throw Error("User must be authenticated before signing with a Privy wallet");if(!t)throw Error("Wallets are not ready");let y=o?.address??s.getPrivyEthereumWallet(i)?.address??d.zeroAddress,p=n.find((e=>d.getAddress(e.address)===d.getAddress(y)));if(!p)throw Error("Signing wallet not found.");let w=r.chainId??Number(p.chainId.split(":")[1]);if(0===w)c={chainId:0,address:r.contractAddress,nonce:r.nonce??0};else{let t=l.find((e=>e.id===w));if(!t)throw Error("Error, chain not configured in PrivyProvider config");let o=d.createWalletClient({account:y,chain:t,transport:d.http(e.getJsonRpcEndpointFromChain(t,a,u))});c=await o.prepareAuthorization({...r})}let g=await p.getEthereumProvider(),C=await g.request({method:"secp256k1_sign",params:[h.hashAuthorization(c)]});return{...c,...d.parseSignature(C)}}),[t,n,i,l])}},P=f;let E=async(e,r,o,s,n)=>{if(!e)throw s("linkAccount","onError",t.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:n}),new t.PrivyClientError("User must be authenticated before linking an account.");if(!r?.linkedAccounts.some((e=>e.type.includes(n))))throw new t.PrivyClientError(`OAuth account of type ${n} not linked to the account.`);await o(n)};exports.Captcha=e.Captcha,exports.ConnectorManager=e.ConnectorManager,exports.EthereumWalletConnector=e.EthereumWalletConnector,exports.LoginModal=e.LoginModal,exports.PrivyClient=e.PrivyClient,exports.PrivyProvider=e.PrivyProvider,exports.VERSION=e.VERSION,exports.WalletConnector=e.WalletConnector,exports.errorIndicatesMaxMfaRetries=e.errorIndicatesMaxMfaRetries,exports.errorIndicatesMfaTimeout=e.errorIndicatesMfaTimeout,exports.errorIndicatesMfaVerificationFailed=e.errorIndicatesMfaVerificationFailed,exports.getAccessToken=e.getCustomerAccessToken,exports.useCreateWallet=e.useCreateWallet,exports.useIdentityToken=e.useIdentityToken,exports.useImportWallet=e.useImportWallet,exports.useLogout=e.useLogout,exports.useMfa=e.useMfa,exports.useMfaEnrollment=e.useMfaEnrollment,exports.useMigrateWallets=e.useMigrateWallets,exports.usePrivy=e.usePrivy,exports.useRegisterMfaListener=e.useRegisterMfaListener,exports.useSolanaWallets=e.useSolanaWallets,exports.useSyncJwtBasedAuthState=e.useSyncJwtBasedAuthState,exports.useWallets=e.useWallets,exports.useActiveWallet=n.useActiveWallet,exports.useConnectWallet=n.useConnectWallet,exports.useFundWallet=n.useFundWallet,exports.useLogin=n.useLogin,Object.defineProperty(exports,"SUPPORTED_CHAINS",{enumerable:!0,get:function(){return y.DEFAULT_SUPPORTED_CHAINS}}),Object.defineProperty(exports,"addPrivyRpcToChain",{enumerable:!0,get:function(){return y.addPrivyRpcToChain}}),Object.defineProperty(exports,"addRpcUrlOverrideToChain",{enumerable:!0,get:function(){return y.addRpcUrlOverrideToChain}}),exports.getEmbeddedConnectedWallet=p.getEmbeddedConnectedWallet,exports.toViemAccount=async({wallet:e})=>{let r=await e.getEthereumProvider();return w.toAccount({address:e.address,sign:async({hash:t})=>{if("privy"!==e.walletClientType)throw new y.PrivyClientError({error:"Unprefixed signing is not supported by external wallets.",code:"unsupported_wallet_type"});return await r.request({method:"secp256k1_sign",params:[t]})},signMessage:async({message:t})=>await r.request({method:"personal_sign",params:[t,e.address]}),signTypedData:async t=>await r.request({method:"eth_signTypedData_v4",params:[e.address,t]}),signTransaction:async e=>await r.request({method:"eth_signTransaction",params:[e]})})},exports.useAuthMfa=A,exports.useAuthMfaEnrollment=()=>{let t=e.useAppConfig(),{setModalData:s}=e.usePrivyModal(),{verify:n}=A(),{openModal:i,privy:l,closePrivyModal:u,refreshSessionAndUser:c,setUser:d}=o.usePrivyInternal();return r.useMemo((()=>({enroll:async()=>new Promise(((e,r)=>{s({mfaEnroll:{onSuccess:async r=>{await u({shouldCallAuthOnSuccess:!1,isSuccess:!0}),e(r)},onFailure:async e=>{await u({shouldCallAuthOnSuccess:!1,isSuccess:!1}),r(e)},verify:()=>n({standalone:!1}),shouldUnlinkOnUnenrollMfa:!0,mfaMethods:t.mfa.methods,sendSmsCode:async()=>{throw Error("Not enabled")},enrollSms:async()=>{throw Error("Not enabled")},unenrollSms:async()=>{throw Error("Not enabled")},generateTotpSecret:async()=>await l.fetchPrivyRoute(a.MfaAuthTotpInit,{body:{}}),enrollTotp:async e=>{await l.fetchPrivyRoute(a.MfaAuthTotpEnroll,{body:{code:e}});let r=await c();return d(r),r},unenrollTotp:async()=>{await l.fetchPrivyRoute(a.MfaAuthTotpUnenroll,{body:{}});let e=await c();return d(e),e},enrollPasskey:async e=>{await l.fetchPrivyRoute(a.MfaAuthPasskeyEnrollment,{body:{credential_ids:e,remove_for_login:!0}});let r=await c();return d(r),r}}}),i(m)}))})),[l,s,i,u])},exports.useAuthorizationSignature=()=>{let{signWithUserSigner:e}=s.useSignWithUserSigner();return r.useMemo((()=>({async generateAuthorizationSignature(r){let{signature:t}=await y.generateAuthorizationSignature(e,r);return{signature:t}}})),[e])},exports.useBaseAccountSdk=()=>{let{baseAccountSdk:e}=o.usePrivyInternal();return{baseAccountSdk:e}},exports.useConnectBaseAccount=()=>{let{connectBaseAccount:e}=o.usePrivyInternal();return{connectBaseAccount:e}},exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=o.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useConnectOrCreateWallet=r=>{let{connectOrCreateWallet:t}=s.usePrivyContext();return e.usePrivyEventSubscription("connectOrCreateWallet",r),{connectOrCreateWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:r,signMessageWithCrossAppWallet:t,signTypedDataWithCrossAppWallet:o,sendTransactionWithCrossAppWallet:n}=s.usePrivyContext();return{loginWithCrossAppAccount:({appId:r})=>e({appId:r,action:"login"}),linkCrossAppAccount:({appId:r})=>e({appId:r,action:"link"}),unlinkCrossAppAccount:r,signMessage:t,signTypedData:o,sendTransaction:n}},exports.useCustomAuth=r=>{let t=e.useJwtAuthFlowState();return e.usePrivyEventSubscription("customAuth",r),{status:t}},exports.useDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:r}=o.usePrivyInternal();return{delegateWallet:async({address:e,chainType:t})=>await r({address:e,chainType:t,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},exports.useFarcasterSigner=function(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:r,requestFarcasterSignerFromWarpcast:t}=s.usePrivyContext();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:r,requestFarcasterSignerFromWarpcast:t}},exports.useGuestAccounts=function(){let r=e.useAppConfig(),s=e.useEmitPrivyEvent(),{client:n,setUser:i,setAuthenticated:a,setIsNewUser:l,initializeWalletProxy:u}=o.usePrivyInternal(),{create:c}=e.useCreateWalletInternal();return{createGuestAccount:async()=>{if(!r.id||!n)throw Error("SDK not yet ready");n.startAuthFlow(new e.GuestFlow(r.id));try{let o=await n.authenticate(),d=o.user,h=o.isNewUser??!1;if(!d)throw new t.PrivyClientError("Unable to authenticate guest account");let y=await n.getAccessToken(),p=await u(e.WALLET_PROXY_TIMEOUT);if(y&&p)try{let t=e.shouldCreateEmbeddedEthWallet(d,r.embeddedWallets.ethereum.createOnLogin),o=e.shouldCreateEmbeddedSolWallet(d,r.embeddedWallets.solana.createOnLogin);t&&o?(d=(await c({chainType:"ethereum",latestUser:d})).user,d=(await c({chainType:"solana",latestUser:d})).user):o?d=(await c({chainType:"solana",latestUser:d})).user:t?d=(await c({chainType:"ethereum",latestUser:d})).user:i(d)}catch(e){i(d),console.warn("Unable to create embedded wallet for guest account")}return l(h),a(!0),s("login","onComplete",{user:d,isNewUser:h,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),d}catch(e){throw s("login","onError",e.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}}}},exports.useHeadlessDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:r}=o.usePrivyInternal();return{delegateWallet:async({address:e,chainType:t})=>await r({address:e,chainType:t,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}},exports.useLinkAccount=function(t){let{linkEmail:o,linkPhone:n,linkWallet:i,linkGoogle:a,linkApple:l,linkTwitter:u,linkDiscord:c,linkGithub:d,linkLinkedIn:h,linkTiktok:y,linkLine:p,linkSpotify:w,linkInstagram:g,linkTelegram:C,linkFarcaster:v,linkPasskey:A}=r.useContext(s.PrivyContext);return e.usePrivyEventSubscription("linkAccount",t),{linkEmail:o,linkPhone:n,linkWallet:i,linkGoogle:a,linkApple:l,linkTwitter:u,linkDiscord:c,linkGithub:d,linkLinkedIn:h,linkTiktok:y,linkLine:p,linkSpotify:w,linkInstagram:g,linkFarcaster:v,linkTelegram:C,linkPasskey:A}},exports.useLinkJwtAccount=function(s){let{client:n}=o.usePrivyInternal(),[i,a]=r.useState({status:"initial"});return{linkWithCustomJwt:r.useCallback((async r=>{try{a({status:"initial"}),n.startAuthFlow(new e.CustomJwtAccountFlow(r)),a({status:"loading"});let{user:t}=await n.link();if(!t)throw Error("Error, user not found");let o=t.linkedAccounts.filter((e=>"custom_auth"===e.type)).sort(((e,r)=>r.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime())).at(0);return a({status:"done"}),s?.onSuccess?.({user:t,linkMethod:"custom",linkedAccount:o}),{user:t}}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"custom"}),r}}),[n.startAuthFlow,n.link]),state:i}},exports.useLinkWithPasskey=e=>{let{initLinkWithPasskey:s,linkWithPasskey:n,passkeyAuthState:i,setPasskeyAuthState:a}=o.usePrivyInternal();return{linkWithPasskey:r.useCallback((async()=>{try{await s();let r=await n();if(!r)throw Error("Error, user not found");let t=r.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,r)=>r.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:r,linkMethod:"passkey",linkedAccount:t})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),r}}),[n]),state:i}},exports.useLinkWithSiwe=s=>{let n=e.useCaptcha(),{siweState:i,setSiweState:a,linkWithSiwe:l,generateSiweMessage:u}=o.usePrivyInternal();return{generateSiweMessage:r.useCallback((async({address:e,chainId:r})=>{try{if(!e||!r)throw Error("wallet address and chainId required to generate nonce");return await u({address:e,chainId:r}).then((e=>e))}catch(e){throw a({status:"error",error:e}),s?.onError?.(e.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),e}}),[u]),linkWithSiwe:r.useCallback((async({signature:r,message:o,chainId:i,walletClientType:u,connectorType:c})=>{try{if(n.enabled&&"success"!==n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);let{user:a,linkedAccount:d}=await l({message:o,signature:r,chainId:i,walletClientType:u,connectorType:c});d&&s?.onSuccess?.({user:a,linkMethod:"siwe",linkedAccount:d})}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[l,n.status]),state:i}},exports.useLoginWithEmail=s=>{let n=e.useCaptcha(),{emailOtpState:i,setEmailOtpState:a,initLoginWithEmail:l,loginWithCode:u}=o.usePrivyInternal();return{sendCode:r.useCallback((async({email:r,disableSignup:o})=>{try{let s;if(!r)throw Error("Email required to send OTP code");if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);return n.enabled&&"success"!==n.status&&(n.execute(),s=await n.waitForResult()),await l({email:r,captchaToken:s,disableSignup:o,withPrivyUi:!1})}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l]),loginWithCode:r.useCallback((async({code:r})=>{try{if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);let{user:o,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:l}=await u(r);s?.onComplete?.({user:o,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"email",loginAccount:l})}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[u,n.status]),state:i}},exports.useLoginWithFarcasterV2=()=>{let{client:e,setAuthenticated:s,setUser:n}=o.usePrivyInternal();return r.useMemo((()=>({init:async()=>{if(!e)throw new t.PrivyClientError("Must initialize Privy client first.");let r=new i.FarcasterFramesFlow;return e.startAuthFlow(r),await r.init()},login:async({fid:r,message:o,signature:a})=>{if(!e)throw new t.PrivyClientError("Must initialize Privy client first.");if(!(e.authFlow instanceof i.FarcasterFramesFlow))throw new t.PrivyClientError("Must initialize Farcaster Mini App flow first.");e.authFlow.setAuthData({message:o,signature:a,fid:r});let{user:l}=await e.authenticate();if(!l)throw new t.PrivyClientError("Failed to login with Farcaster V2");return n(l),s(!0),{user:l}}})),[e,n,s])},exports.useLoginWithOAuth=n=>{e.usePrivyEventSubscription("login",n);let i=e.useCaptcha(),a=e.useIsServerConfigLoaded(),{ready:l,user:u}=s.usePrivyContext(),{initLoginWithHeadlessOAuth:c,loginWithHeadlessOAuth:d,oAuthState:h,setOAuthState:y,isHeadlessOAuthLoading:p}=o.usePrivyInternal(),w=r.useCallback((async r=>{try{if(i.enabled&&"success"!==i.status)throw new e.CaptchaError(i.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);return await c(r.provider,i.token,r.disableSignup)}catch(r){throw y({status:"error",error:r}),r}}),[c,i]),g=r.useCallback((async()=>{let r=e.detectCompletingOAuthFlow();try{if(u)return console.warn("Cannot login with OAuth when already logged in"),u;if(!r.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(r.popupFlow)return}catch(r){throw y({status:"error",error:r}),r}try{return await d(r)}catch(r){throw y({status:"error",error:r}),r}finally{e.stripUrlOAuthParamsAndRemoveStateCode()}}),[d]);return r.useEffect((()=>{let r=e.detectCompletingOAuthFlow();l&&a&&r.inProgress&&!r.withPrivyUi&&!r.popupFlow&&g().catch((()=>{}))}),[l,a]),{initOAuth:w,loading:p,state:h}},exports.useLoginWithPasskey=s=>{let n=e.useCaptcha(),{initLoginWithPasskey:i,loginWithPasskey:a,passkeyAuthState:l,setPasskeyAuthState:u}=o.usePrivyInternal();return{loginWithPasskey:r.useCallback((async r=>{try{let o;if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);n.enabled&&"success"!==n.status&&(n.execute(),o=await n.waitForResult()),await i({captchaToken:o,withPrivyUi:!1});let{user:l,isNewUser:u,wasAlreadyAuthenticated:c,loginAccount:d}=await a(r);s?.onComplete?.({user:l,isNewUser:u,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:d})}catch(r){throw u({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a,n.status]),state:l}},exports.useLoginWithSiwe=s=>{let n=e.useCaptcha(),{siweState:i,setSiweState:a,client:l,generateSiweMessage:u,loginWithSiwe:c}=o.usePrivyInternal();return{generateSiweNonce:r.useCallback((async r=>{try{let o;if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);n.enabled&&"success"!==n.status&&(n.execute(),o=await n.waitForResult()),a({status:"generating-message"});let s=await l.generateSiweNonce({address:r?.address,captchaToken:o});return a({status:"awaiting-signature"}),s}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,n]),generateSiweMessage:r.useCallback((async({address:r,chainId:o})=>{try{let s;if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);return n.enabled&&"success"!==n.status&&(n.execute(),s=await n.waitForResult()),await u({address:r,chainId:o,captchaToken:s})}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[u,n]),loginWithSiwe:r.useCallback((async({message:r,signature:o,disableSignup:i})=>{try{let a;if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);n.enabled&&"success"!==n.status&&(n.execute(),a=await n.waitForResult());let l=await c({message:r,signature:o,captchaToken:a,disableSignup:i});return s?.onComplete?.({user:l,isNewUser:!1,wasAlreadyAuthenticated:!1,loginMethod:"siwe",loginAccount:null}),l}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[c,n.status]),state:i}},exports.useLoginWithSms=s=>{let n=e.useCaptcha(),{smsOtpState:i,setSmsOtpState:a,initLoginWithSms:l,loginWithCode:u}=o.usePrivyInternal();return{sendCode:r.useCallback((async({phoneNumber:r,disableSignup:o})=>{try{let s;if(!r)throw Error("SMS required to send OTP code");if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);return n.enabled&&"success"!==n.status&&(n.execute(),s=await n.waitForResult()),await l({phoneNumber:r,captchaToken:s,disableSignup:o,withPrivyUi:!1})}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l]),loginWithCode:r.useCallback((async({code:r})=>{try{if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);let{user:o,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:l}=await u(r);s?.onComplete?.({user:o,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"sms",loginAccount:l})}catch(r){throw a({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[u,n.status]),state:i}},exports.useLoginWithTelegram=s=>{let n=e.useCaptcha(),{initLoginWithTelegram:i,loginWithTelegram:a,telegramAuthState:l,setTelegramAuthState:u}=o.usePrivyInternal();return{login:r.useCallback((async r=>{try{if(n.enabled&&"success"!==n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);await i(n.token,r?.disableSignup);let{user:o,isNewUser:l,loginAccount:u,wasAlreadyAuthenticated:c}=await a({intent:"login"});s?.onComplete?.({user:o,isNewUser:l,wasAlreadyAuthenticated:c,loginMethod:"telegram",loginAccount:u})}catch(r){throw u({status:"error",error:r}),s?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[i,a,n]),state:l}},exports.useModalStatus=()=>{let{isModalOpen:e}=r.useContext(s.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(r){let{authenticated:t,user:n}=s.usePrivyContext(),{initLoginWithOAuth:i}=o.usePrivyInternal(),a=e.useEmitPrivyEvent();return e.usePrivyEventSubscription("oAuthAuthorization",r),{reauthorize:e=>E(t,n,i,a,e.provider)}},exports.useRecoverEmbeddedWallet=()=>{let{user:n}=s.usePrivyContext(),{walletProxy:i}=o.usePrivyInternal();return{recover:r.useCallback((async r=>{if(!i)throw Error("Wallet proxy is not ready");let o=await e.getAccessToken();if(!n||!o)throw new t.PrivyClientError("User must be logged in before attempting to modify the recovery method.");let{entropyId:s,entropyIdVerifier:a}=e.getEntropyDetailsForUser(n);try{await i.recover({entropyId:s,entropyIdVerifier:a,accessToken:o,...r})}catch{throw new t.PrivyClientError("Unable to recover wallets")}}),[i,n])}},exports.useSendTransaction=function(t){let{sendTransaction:o}=r.useContext(s.PrivyContext);return e.usePrivyEventSubscription("sendTransaction",t),{sendTransaction:o}},exports.useSessionSigners=()=>{let{addSessionSignersInternal:r,removeSessionSignersInternal:n}=(()=>{let{user:r}=s.usePrivyContext(),n=o.usePrivyInternal(),{signWithUserSigner:i}=s.useSignWithUserSigner(),a=async({wallet:e,additional_signers:o})=>{let s=await n.client.getAccessToken();if(!r||!s)throw new t.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if(!e.id)throw new t.PrivyClientError("Wallet to add signers to must have ID on server");if(!n.walletProxy)throw new t.PrivyClientError("Wallet proxy not initialized.");await y.updateWallet(n.privy,{wallet_id:e.id},i,{additional_signers:o})};return{addSessionSignersInternal:async({address:o,signers:i})=>{let l=await n.client.getAccessToken();if(!r||!l)throw new t.PrivyClientError("User must be authenticated and have an embedded wallet to add a session signer.");let u=n.walletProxy??await n.initializeWalletProxy(15e3);if(!u)throw new t.PrivyClientError("Wallet proxy not initialized.");let c=s.getPrivyWalletWithAddress(r,o);if(!c)throw new t.PrivyClientError("Address to add signers too is not associated with current user.");if(s.getIsUnifiedWallet(c)){if(0===i.length)throw new t.PrivyClientError("Must specify at least one signer to add.");let r=[...(await y.getWallet(n.privy,{wallet_id:c.id})).additional_signers,...e.parseAdditionalSigners(i)];await a({wallet:c,additional_signers:r})}else{if(c.delegated)return{user:r};if(i.length>0)throw new t.PrivyClientError("Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let s=e.getDelegatedWalletsData({address:o,user:r}),a=e.getRootWalletDataForDelegation({address:o,user:r});await n.recoverEmbeddedWallet({address:o}),await u.createDelegatedAction({accessToken:l,rootWallet:a,delegatedWallets:[s]})}let d=await n.refreshSessionAndUser();if(!d)throw Error("Could not refresh user");return{user:d}},removeSessionSignersInternal:async({address:e})=>{let o=await n.client.getAccessToken();if(!r||!o)throw new t.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if(!(n.walletProxy??await n.initializeWalletProxy(15e3)))throw new t.PrivyClientError("Wallet proxy not initialized.");let i=s.getPrivyWalletWithAddress(r,e);if(!i)throw new t.PrivyClientError("Address to remove signers from is not associated with current user.");s.getIsUnifiedWallet(i)?await a({wallet:i,additional_signers:[]}):await n.client.revokeDelegatedWallet();let l=await n.refreshSessionAndUser();if(!l)throw Error("Could not refresh user");return{user:l}}}})();return{addSessionSigners:async({address:e,signers:t})=>r({address:e,signers:t}),removeSessionSigners:async({address:e})=>n({address:e})}},exports.useSetWalletPassword=function(t){let{setWalletPassword:o}=r.useContext(s.PrivyContext);return e.usePrivyEventSubscription("setWalletPassword",t),{setWalletPassword:o}},exports.useSetWalletRecovery=function(t){let{setWalletRecovery:o}=r.useContext(s.PrivyContext);return e.usePrivyEventSubscription("setWalletRecovery",t),{setWalletRecovery:o}},exports.useSign7702Authorization=f,exports.useSignAuthorization=P,exports.useSignMessage=function(t){let{signMessage:o}=r.useContext(s.PrivyContext);return e.usePrivyEventSubscription("signMessage",t),{signMessage:o}},exports.useSignTransaction=function(){let{signTransaction:e}=r.useContext(s.PrivyContext);return{signTransaction:e}},exports.useSignTypedData=function(t){let{signTypedData:o}=r.useContext(s.PrivyContext);return e.usePrivyEventSubscription("signTypedData",t),{signTypedData:o}},exports.useSignupWithPasskey=s=>{let n=e.useCaptcha(),{initSignupWithPasskey:i,signupWithPasskey:a,passkeyAuthState:l,setPasskeyAuthState:u}=o.usePrivyInternal();return{signupWithPasskey:r.useCallback((async()=>{try{let r;if(n.enabled&&"error"===n.status)throw new e.CaptchaError(n.error,null,t.PrivyErrorCode.CAPTCHA_FAILURE);n.enabled&&"success"!==n.status&&(n.execute(),r=await n.waitForResult()),await i({captchaToken:r,withPrivyUi:!1});let{user:o,isNewUser:l,wasAlreadyAuthenticated:u,loginAccount:c}=await a();s?.onComplete?.({user:o,isNewUser:l,wasAlreadyAuthenticated:u,loginMethod:"passkey",loginAccount:c})}catch(e){throw u({status:"error",error:e}),s?.onError?.(e.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}}),[a,n.status]),state:l}},exports.useSubscribeToJwtAuthWithFlag=function({isAuthenticated:t,isLoading:o,...s}){let n=r.useRef();r.useEffect((()=>{o||n.current?.()}),[t,o]);let i=r.useCallback((e=>(n.current=e,()=>{n.current=void 0})),[]);return e.useSyncJwtBasedAuthState({...s,subscribe:i})},exports.useToken=function(t){let{getAccessToken:o}=r.useContext(s.PrivyContext);return e.usePrivyEventSubscription("accessToken",t),{getAccessToken:o}},exports.useUpdateAccount=function(t){let{updateEmail:o,updatePhone:n}=r.useContext(s.PrivyContext);return e.usePrivyEventSubscription("update",t),{updateEmail:o,updatePhone:n}},exports.useUpdateEmail=n=>{let{user:i}=s.usePrivyContext(),{loginWithCode:a,emailOtpState:l,setEmailOtpState:u,client:c,inProgressAuthFlowRef:d,inProgressLoginOrLinkMethodRef:h}=o.usePrivyInternal();return{state:l,sendCode:r.useCallback((async({newEmailAddress:r})=>{try{if(!i?.email)throw Error("User is required to have an email address to update it.");let t=new e.UpdateEmailFlow(i.email.address,r);c.startAuthFlow(t),await t.sendCodeEmail({withPrivyUi:!1})}catch(r){u({status:"error",error:r}),n?.onError?.(r.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[i?.email]),verifyCode:r.useCallback((async({code:e})=>{try{if(!i?.email)throw Error("User is required to have an email address to update it.");d.current="update",h.current="email";let{user:r,linkedAccount:t}=await a(e);return n?.onSuccess?.({user:r,updateMethod:"email",updatedAccount:t}),{user:r}}catch(e){u({status:"error",error:e}),n?.onError?.(e.privyErrorCode||t.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[i?.email])}},exports.useUser=()=>{let{setUser:e,client:t}=r.useContext(o.InternalPrivyContext),{user:n}=r.useContext(s.PrivyContext);return{user:n,refreshUser:r.useCallback((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}};