UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

2 lines (1 loc) • 10.2 kB
import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{useRef as o,useEffect as i,useState as a,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-CCyaupaz.mjs";import{L as g}from"./Link-DwjLfHwW.mjs";import{u as w,q as h}from"./context-Bycd1SKV.mjs";import{u as S}from"./useI18n-BtdAZuQ8.mjs";import{C as y,P as f,d as C}from"./prepareFundingModalData-CIgFwA7s.mjs";import{Q as b,k as v,T}from"./useActiveWallet-Bsy5GTCV.mjs";import{isHex as _,getAddress as E}from"viem";import{b as R,u as k,k as A}from"./internal-context-e-Eni5bG.mjs";import{u as W,a as I}from"./get-is-unified-wallet-DvKS5IUO.mjs";import{s as L}from"./shouldProceedtoEmbeddedWalletCreationFlow-Djgu4xiS.mjs";import{c as j,e as U}from"./usePrivy-BaiIHGte.mjs";import{S as O}from"./ScreenLayout-CddsD3Of.mjs";import"@privy-io/js-sdk-core";import"uuid";import"jose";import"eventemitter3";import"./useWallets-D0lpBS44.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"./getPublicClient-A9RSftUZ.mjs";import"ofetch";import"js-cookie";import"./frame-CwE9r3cT.mjs";import"@privy-io/routes";import"x402/client";import"@privy-io/api-base";import"viem/accounts";import"./use-sign-with-user-signer-eEm9Olt_.mjs";import"./getEmbeddedConnectedWallet-CM6cDQCS.mjs";import"tinycolor2";import"./Button-B8mqatRx.mjs";import"./Screen-BTyXgDrd.mjs";import"./ModalHeader-BLGC-7ev.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"./index-CJMgUOnw.mjs";const N=e=>{let t=localStorage.getItem("-walletlink:https://www.walletlink.org:Addresses")?.split(" ").filter((e=>_(e,{strict:!0}))).map((e=>E(e)));return!!t?.length&&!!e?.linkedAccounts.filter((e=>"wallet"==e.type&&t.includes(e.address))).length};const M=e=>e?.privyErrorCode===R.LINKED_TO_ANOTHER_USER?y.ERROR_USER_EXISTS:e instanceof f&&!e.details.default?e.details:e instanceof C?y.ERROR_TIMED_OUT:e?.privyErrorCode===R.CANNOT_LINK_MORE_OF_TYPE?y.ERROR_USER_LIMIT_REACHED:y.ERROR_WALLET_CONNECTION,x=({walletLogo:o,title:i,subtitle:a,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:b,onCoinbaseReset:v,onDifferentWallet:T})=>{let{t:_}=S(),E=w?{label:"Use a different wallet",onClick:v,disabled:r}:c===y.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:b,disabled:!1}:r||c?void 0:{label:_("connectionStatus.connecting"),onClick:()=>{},disabled:!0};/*#__PURE__*/return e(O,{title:i,subtitle:a,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]=a(!1),[g,f]=a(!1),[C,_]=a(void 0),{authenticated:E,logout:O}=W(),{navigate:D,navigateBack:B,lastScreen:F,currentScreen:P,setModalData:q,data:H}=I(),X=w(),{t:z}=S(),{getAuthFlow:Q,walletConnectionStatus:Y,closePrivyModal:J,initLoginWithWallet:K,loginWithWallet:V,updateWallets:$,createAnalyticsEvent:G}=k(),{walletConnectors:Z}=W(),[ee,te]=a(0),{user:ne}=W(),oe=j(),[ie]=a(ne?.linkedAccounts.length||0),[ae,re]=a(""),[ce,le]=a(""),[se,de]=a(!1),{hasTabbedAway:me}=function(){let[e,t]=a(!1),n=r((()=>{document.hidden&&t(!0)}),[]);return i((()=>(document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n))),[n]),{hasTabbedAway:e,reset:()=>t(!1)}}(),{enabled:ue,token:pe}=s(),ge=b(Y?.connector?.walletClientType||"unknown"),we=c&&"wallet_connect_v2"===Y?.connector?.connectorType||c&&"coinbase_wallet"===Y?.connector?.connectorType||c&&"base_account"===Y?.connector?.connectorType||c&&"injected"===Y?.connector?.connectorType&&"phantom"===Y?.connector?.walletClientType||c&&"solana_adapter"===Y?.connector?.connectorType&&"mobile_wallet_adapter"===Y.connector.walletClientType,he="connected"===Y?.status,Se="switching_to_supported_chain"===Y?.status;i((()=>{let e=Q(),t=e instanceof p||e instanceof d?e:void 0;he&&"solana"===Y.connector?.chainType&&"phantom"===Y.connector?.walletClientType&&oe(U)&&void 0===H?.login?.isSigningInWithLedgerSolana?D("ConnectLedgerScreen",!1):(he&&!t&&(!ue||pe||E?K(Y.connectedWallet,pe,H?.login?.disableSignup,H?.login?.isSigningInWithLedgerSolana?"transaction":"plain").then((()=>{de(!0)})):(q({captchaModalData:{callback:e=>K(Y.connectedWallet,e,H?.login?.disableSignup,H?.login?.isSigningInWithLedgerSolana?"transaction":"plain").then((()=>{de(!0)})),userIntentRequired:!1,onSuccessNavigateTo:"ConnectionStatusScreen",onErrorNavigateTo:"ErrorScreen"}}),D("CaptchaScreen",!1))),t instanceof d&&H?.login?.isSigningInWithLedgerSolana&&(t.messageType="transaction"),t&&we&&he&&!t.preparedMessage?t.buildMessage():t&&!we&&he&&(g||(async()=>{f(!0),_(void 0);try{"wallet_connect_v2"===Y?.connector?.connectorType&&"metamask"===Y?.connector?.walletClientType&&await v(2500),await fe()}catch(e){console.warn("Auto-prompted signature failed",e)}finally{f(!1)}})()))}),[ee,he,se]),i((()=>{if(ne&&n){let e=h-500;if(X?.legal.requireUsersAcceptTerms&&!ne.hasAcceptedTerms){let t=setTimeout((()=>{D("AffirmativeConsentScreen")}),e);return()=>clearTimeout(t)}if(L(ne,X.embeddedWallets)){let t=setTimeout((()=>{q({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),G({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"ConnectionStatusScreen"}}),O()},callAuthOnSuccessOnClose:!0}}),D("EmbeddedWalletOnAccountCreateScreen")}),e);return()=>clearTimeout(t)}$();let t=setTimeout((()=>J({shouldCallAuthOnSuccess:!0,isSuccess:!0})),h);return()=>clearTimeout(t)}}),[ne,n]);let ye=e=>{if(e?.privyErrorCode!==R.ALLOWLIST_REJECTED){if(e?.privyErrorCode===R.USER_LIMIT_REACHED)return console.error(new A(e).toString()),void D("UserLimitReachedScreen");if(e?.privyErrorCode!==R.USER_DOES_NOT_EXIST)return e?.privyErrorCode===R.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce?(q({accountTransfer:{nonce:e.data?.data?.nonce,account:Q()?.meta.address,displayName:e.data?.data?.account?.displayName,externalWalletMetadata:{walletClientType:Q()?.meta.walletClientType,chainId:Q()?.meta.chainId,connectorType:Q()?.meta.connectorType},linkMethod:Q()instanceof p?"siwe":"siws",embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress}}),void D("LinkConflictScreen")):void _(M(e));D("AccountNotFoundScreen")}else D("AllowlistRejectionScreen")};async function fe(){try{await V(),l(!0)}catch(e){ye(e)}finally{f(!1)}}i((()=>{Y?.connectError&&ye(Y?.connectError)}),[Y]),((e,t)=>{let n=o((()=>{}));i((()=>{n.current=e})),i((()=>{if(null!==t){let e=setInterval((()=>n.current()),t||0);return()=>clearInterval(e)}}),[t])})((()=>{let e="wallet_connect_v2"===Ce&&Y?.connector instanceof m?Y.connector.redirectUri:void 0;e&&re(e);let t="wallet_connect_v2"===Ce&&Y?.connector instanceof m?Y.connector.fallbackUniversalRedirectUri:void 0;t&&le(t)}),Y?.connector instanceof m&&!ae?500:null);let Ce=Y?.connector?.connectorType||"injected",be=Y?.connector?.walletClientType||"unknown",ve=ge?.metadata?.shortName||ge?.name||Y?.connector?.walletBranding.name||"Browser Extension",Te=ge?.image_url?.md||Y?.connector?.walletBranding.icon||(t=>/*#__PURE__*/e(u,{...t})),_e="Browser Extension"===ve?ve.toLowerCase():ve;t=n?z("connectionStatus.successfullyConnected",{walletName:_e}):C?z("connectionStatus.errorTitle",{errorMessage:C.message}):Se?"Switching networks":he?g&&we?"Signing":"Sign to verify":`Waiting for ${_e}`;let Ee=z("connectionStatus.checkOtherWindows");n?Ee=ie===(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:Se?Ee="Switch your wallet to the requested network.":he&&we?Ee="Sign the message in your wallet to verify it belongs to you.":"metamask"===be&&c?Ee="Click continue to open and connect MetaMask.":"metamask"===be?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?T()||(Ee=N(ne)?"Continue with the Coinbase app. Not the right wallet? Reset your connection below.":"Confirm in the Coinbase app/popup to continue."):H?.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"===be&&(N(ne)||C===y.ERROR_USER_EXISTS);/*#__PURE__*/return e(x,{walletLogo:Te,title:t,subtitle:Ee,signSuccess:n,errorMessage:C,connectSuccess:he,separateConnectAndSign:we,signing:g,walletConnectRedirectUri:ae,walletConnectFallbackUniversalUri:ce,hasTabbedAway:me,showCoinbaseWalletResetCta:ke,numRetries:ee,onBack:F&&P!==F?B:void 0,onSign:()=>{f(!0),fe()},onRetry:()=>{te(ee+1),_(void 0),he?(f(!0),fe()):Y?.connectRetry()},onCoinbaseReset:()=>{Re&&Re?.disconnect()},onDifferentWallet:B})}};let B=/*#__PURE__*/l.p.withConfig({displayName:"RedirectLinksContainer",componentId:"sc-2a867557-0"})(["text-align:center;color:var(--privy-color-foreground-2);font-size:14px;line-height:22px;margin:16px 0;"]);export{D as ConnectionStatusScreen,x as ConnectionStatusView,D as default,M as getErrorDetails};