UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

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