UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

8 lines (7 loc) • 10.1 kB
import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{useRef as o,useEffect as a,useState as i,useCallback as r}from"react";import{isMobile as c}from"react-device-detect";import{styled as l}from"styled-components";import{a as s,S as d,W as m,B as u,b as p}from"./index-YDEix4mU.mjs";import{L as g}from"./Link-DJ5gq9Di.mjs";import{u as w,q as h}from"./context-DLtU3JQy.mjs";import{u as y}from"./useI18n-C4fmUAf3.mjs";import{C as S,P as f,w as C,k as v,y as b}from"./use-export-wallet-_wu5ex5t.mjs";import{isHex as T,getAddress as _}from"viem";import{b as E,u as R,k}from"./internal-context-Z-fyxadS.mjs";import{z as A}from"./useActiveWallet-CvP7iYvj.mjs";import{u as W,a as L}from"./privy-context-DrMxzgOR.mjs";import{s as I}from"./shouldProceedtoEmbeddedWalletCreationFlow-D2ZT5lW9.mjs";import{u as j}from"./PrivyPluginContext-2QN2dVUw.mjs";import{e as U}from"./usePrivy-C_sY2Duk.mjs";import{S as O}from"./ScreenLayout-D1p_ntex.mjs";import"@privy-io/js-sdk-core";import"uuid";import"jose";import"eventemitter3";import"./useWallets-BzNCTucF.mjs";import"@coinbase/wallet-sdk";import"@privy-io/ethereum";import"mipd";import"viem/utils";import"@privy-io/popup";import"./paths-3HW55qZg.mjs";import"@scure/base";import"./events-context-CI0iqAXA.mjs";import"zustand";import"@headlessui/react";import"@walletconnect/ethereum-provider";import"@privy-io/urls";import"./getEmbeddedConnectedWallet-JzK4iD-L.mjs";import"ofetch";import"js-cookie";import"./frame-uzTmvtww.mjs";import"@privy-io/routes";import"x402/client";import"@privy-io/api-base";import"@privy-io/are-addresses-equal";import"viem/accounts";import"./use-sign-with-user-signer-Do5Oi_rb.mjs";import"tinycolor2";import"./ModalHeader-BnVmXtvG.mjs";import"@heroicons/react/24/outline/ArrowLeftIcon";import"@heroicons/react/24/outline/ArrowRightIcon";import"@heroicons/react/24/outline/QuestionMarkCircleIcon";import"@heroicons/react/24/outline/XMarkIcon";import"./Screen-Cycy3IzT.mjs";import"./index-Dq_xe9dz.mjs";const N=e=>{let t=localStorage.getItem("-walletlink:https://www.walletlink.org:Addresses")?.split(" ").filter((e=>T(e,{strict:!0}))).map((e=>_(e)));return!!t?.length&&!!e?.linkedAccounts.filter((e=>"wallet"==e.type&&t.includes(e.address))).length};const x=e=>e?.privyErrorCode===E.LINKED_TO_ANOTHER_USER?S.ERROR_USER_EXISTS:e instanceof f&&!e.details.default?e.details:e instanceof C?S.ERROR_TIMED_OUT:e?.privyErrorCode===E.CANNOT_LINK_MORE_OF_TYPE?S.ERROR_USER_LIMIT_REACHED:S.ERROR_WALLET_CONNECTION,M=({walletLogo:o,title:a,subtitle:i,signSuccess:r,errorMessage:c,connectSuccess:l,separateConnectAndSign:s,signing:d,walletConnectRedirectUri:m,walletConnectFallbackUniversalUri:u,hasTabbedAway:p,showCoinbaseWalletResetCta:w,numRetries:h,onBack:f,onSign:C,onRetry:v,onCoinbaseReset:b,onDifferentWallet:T})=>{let{t:_}=y(),E=w?{label:"Use a different wallet",onClick:b,disabled:r}:c===S.ERROR_USER_EXISTS&&f?{label:"Use a different wallet",onClick:T}:l&&!r&&s?{label:d?"Signing":"Sign with your wallet",onClick:C,disabled:d}:!r&&c?.retryable&&h<2?{label:"Retry",onClick:v,disabled:!1}:r||c?void 0:{label:_("connectionStatus.connecting"),onClick:()=>{},disabled:!0};/*#__PURE__*/return e(O,{title:a,subtitle:i,icon:o,iconVariant:"loading",iconLoadingStatus:{success:r,fail:!!c},primaryCta:E,onBack:f,watermark:!0,children:!l&&m&&!p&&/*#__PURE__*/t(B,{children:[_("connectionStatus.stillHere")," ",/*#__PURE__*/e(g,{href:m,target:"_blank",variant:"underlined",size:"sm",children:_("connectionStatus.tryConnectingAgain")}),u&&/*#__PURE__*/t(n,{children:[" ",_("connectionStatus.or")," ",/*#__PURE__*/e(g,{href:u,target:"_blank",variant:"underlined",size:"sm",children:_("connectionStatus.useDifferentLink")})]})]})})},D={component:()=>{let t,[n,l]=i(!1),[g,f]=i(!1),[C,T]=i(void 0),{authenticated:_,logout:O}=W(),{navigate:D,navigateBack:B,lastScreen:F,currentScreen:P,setModalData:q,data:z}=L(),H=w(),{t:X}=y(),{getAuthFlow:Y,walletConnectionStatus:K,closePrivyModal:Q,initLoginWithWallet:V,loginWithWallet:G,updateWallets:J,createAnalyticsEvent:$}=R(),{walletConnectors:Z}=W(),[ee,te]=i(0),{user:ne}=W(),oe=j(),[ae]=i(ne?.linkedAccounts.length||0),[ie,re]=i(""),[ce,le]=i(""),[se,de]=i(!1),{hasTabbedAway:me}=function(){let[e,t]=i(!1),n=r((()=>{document.hidden&&t(!0)}),[]);return a((()=>(document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n))),[n]),{hasTabbedAway:e,reset:()=>t(!1)}}(),{enabled:ue,token:pe}=s(),ge=A(K?.connector?.walletClientType||"unknown"),we=c&&"wallet_connect_v2"===K?.connector?.connectorType||c&&"coinbase_wallet"===K?.connector?.connectorType||c&&"base_account"===K?.connector?.connectorType||c&&"injected"===K?.connector?.connectorType&&"phantom"===K?.connector?.walletClientType||c&&"solana_adapter"===K?.connector?.connectorType&&"mobile_wallet_adapter"===K.connector.walletClientType,he="connected"===K?.status,ye="switching_to_supported_chain"===K?.status;a((()=>{let e=Y(),t=e instanceof p||e instanceof d?e:void 0;he&&"solana"===K.connector?.chainType&&"phantom"===K.connector?.walletClientType&&oe(U)&&void 0===z?.login?.isSigningInWithLedgerSolana?D("ConnectLedgerScreen",!1):(he&&!t&&(!ue||pe||_?V(K.connectedWallet,pe,z?.login?.disableSignup,z?.login?.isSigningInWithLedgerSolana?"transaction":"plain").then((()=>{de(!0)})):(q({captchaModalData:{callback:e=>V(K.connectedWallet,e,z?.login?.disableSignup,z?.login?.isSigningInWithLedgerSolana?"transaction":"plain").then((()=>{de(!0)})),userIntentRequired:!1,onSuccessNavigateTo:"ConnectionStatusScreen",onErrorNavigateTo:"ErrorScreen"}}),D("CaptchaScreen",!1))),t instanceof d&&z?.login?.isSigningInWithLedgerSolana&&(t.messageType="transaction"),t&&we&&he&&!t.preparedMessage?t.buildMessage():t&&!we&&he&&(g||(async()=>{f(!0),T(void 0);try{"wallet_connect_v2"===K?.connector?.connectorType&&"metamask"===K?.connector?.walletClientType&&await v(2500),await fe()}catch(e){console.warn("Auto-prompted signature failed",e)}finally{f(!1)}})()))}),[ee,he,se]),a((()=>{if(ne&&n){let e=h-500;if(H?.legal.requireUsersAcceptTerms&&!ne.hasAcceptedTerms){let t=setTimeout((()=>{D("AffirmativeConsentScreen")}),e);return()=>clearTimeout(t)}if(I(ne,H.embeddedWallets)){let t=setTimeout((()=>{q({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),$({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"ConnectionStatusScreen"}}),O()},callAuthOnSuccessOnClose:!0}}),D("EmbeddedWalletOnAccountCreateScreen")}),e);return()=>clearTimeout(t)}J();let t=setTimeout((()=>Q({shouldCallAuthOnSuccess:!0,isSuccess:!0})),h);return()=>clearTimeout(t)}}),[ne,n]);let Se=e=>{if(e?.privyErrorCode!==E.ALLOWLIST_REJECTED){if(e?.privyErrorCode===E.USER_LIMIT_REACHED)return console.error(new k(e).toString()),void D("UserLimitReachedScreen");if(e?.privyErrorCode!==E.USER_DOES_NOT_EXIST)return e?.privyErrorCode===E.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce?(q({accountTransfer:{nonce:e.data?.data?.nonce,account:Y()?.meta.address,displayName:e.data?.data?.account?.displayName,externalWalletMetadata:{walletClientType:Y()?.meta.walletClientType,chainId:Y()?.meta.chainId,connectorType:Y()?.meta.connectorType},linkMethod:Y()instanceof p?"siwe":"siws",embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress}}),void D("LinkConflictScreen")):void T(x(e));D("AccountNotFoundScreen")}else D("AllowlistRejectionScreen")};async function fe(){try{await G(),l(!0)}catch(e){Se(e)}finally{f(!1)}}a((()=>{K?.connectError&&Se(K?.connectError)}),[K]),((e,t)=>{let n=o((()=>{}));a((()=>{n.current=e})),a((()=>{if(null!==t){let e=setInterval((()=>n.current()),t||0);return()=>clearInterval(e)}}),[t])})((()=>{let e="wallet_connect_v2"===Ce&&K?.connector instanceof m?K.connector.redirectUri:void 0;e&&re(e);let t="wallet_connect_v2"===Ce&&K?.connector instanceof m?K.connector.fallbackUniversalRedirectUri:void 0;t&&le(t)}),K?.connector instanceof m&&!ie?500:null);let Ce=K?.connector?.connectorType||"injected",ve=K?.connector?.walletClientType||"unknown",be=ge?.metadata?.shortName||ge?.name||K?.connector?.walletBranding.name||"Browser Extension",Te=ge?.image_url?.md||K?.connector?.walletBranding.icon||(t=>/*#__PURE__*/e(u,{...t})),_e="Browser Extension"===be?be.toLowerCase():be;t=n?X("connectionStatus.successfullyConnected",{walletName:_e}):C?X("connectionStatus.errorTitle",{errorMessage:C.message}):ye?"Switching networks":he?g&&we?"Signing":"Sign to verify":`Waiting for ${_e}`;let Ee=X("connectionStatus.checkOtherWindows");n?Ee=ae===(ne?.linkedAccounts.length||0)?"Wallet was already linked.":"You're good to go!":ee>=2&&C?Ee="Unable to connect wallet":C?Ee=C.detail:ye?Ee="Switch your wallet to the requested network.":he&&we?Ee="Sign the message in your wallet to verify it belongs to you.":"metamask"===ve&&c?Ee="Click continue to open and connect MetaMask.":"metamask"===ve?Ee="For the best experience, connect only one wallet at a time.":"wallet_connect"===Ce?Ee="Open your mobile wallet app to continue":"coinbase_wallet"===Ce?b()||(Ee=N(ne)?"Continue with the Coinbase app. Not the right wallet? Reset your connection below.":"Confirm in the Coinbase app/popup to continue."):z?.login?.isSigningInWithLedgerSolana&&(Ee="Ledger requires a transaction to verify your identity. You'll sign a transaction that performs no onchain action.");let Re=Z?.walletConnectors?.find((e=>"coinbase_wallet"===e.walletClientType)),ke="coinbase_wallet"===ve&&(N(ne)||C===S.ERROR_USER_EXISTS);/*#__PURE__*/return e(M,{walletLogo:Te,title:t,subtitle:Ee,signSuccess:n,errorMessage:C,connectSuccess:he,separateConnectAndSign:we,signing:g,walletConnectRedirectUri:ie,walletConnectFallbackUniversalUri:ce,hasTabbedAway:me,showCoinbaseWalletResetCta:ke,numRetries:ee,onBack:F&&P!==F?B:void 0,onSign:()=>{f(!0),fe()},onRetry:()=>{te(ee+1),T(void 0),he?(f(!0),fe()):K?.connectRetry()},onCoinbaseReset:()=>{Re&&Re?.disconnect()},onDifferentWallet:B})}};let B=l.p` text-align: center; color: var(--privy-color-foreground-2); font-size: 14px; line-height: 22px; margin: 16px 0; `;export{D as ConnectionStatusScreen,M as ConnectionStatusView,D as default,x as getErrorDetails};