> ## Documentation Index
> Fetch the complete documentation index at: https://docs.0xmonaco.com/llms.txt
> Use this file to discover all available pages before exploring further.

# useAuth

> Wallet-based authentication with state management

```tsx theme={null}
import { useAuth } from "@0xmonaco/react";

const {
  authenticationStatus,
  login,
  logout,
  refreshAuth,
  refreshSession,
  revokeSession,
  authenticate,
  signChallenge,
  createChallenge
} = useAuth();
```

`useAuth` wraps the SDK's wallet-authorized session-key flow. `login()` generates a session key, prompts the wallet once, and (via the provider) persists the session; every subsequent request is signed automatically. There are no access or refresh tokens. See [TypeScript authentication](/sdk/typescript/auth) for the lower-level SDK model.

## Authentication State

<ResponseField name="authenticationStatus" type="AuthenticationStatus">
  Current authentication state:

  * `"unauthenticated"` - Not logged in
  * `"authenticating"` - Login in progress
  * `"authenticated"` - Session active
</ResponseField>

## Core Actions

<ResponseField name="login" type="(options?: { connectWebSocket?: boolean }) => Promise<AuthState>">
  Authenticate the user with a wallet signature, using the address and `clientId` from context. Returns an `AuthState` (with the session keypair).

  **Options:**

  * `connectWebSocket`: Auto-connect authenticated WebSocket channels after login (default: `false`). Public channels (OHLCV, Orderbook, Trades) don't require authentication.

  ```tsx theme={null}
  const authState = await login();
  const withSockets = await login({ connectWebSocket: true });
  ```
</ResponseField>

<ResponseField name="logout" type="() => Promise<void>">
  Revoke the session on the server and clear local auth state.
</ResponseField>

<ResponseField name="refreshAuth" type="() => Promise<AuthState>">
  Extend the current session's expiry. The keypair is unchanged; returns the updated `AuthState`.
</ResponseField>

## Session Actions

<ResponseField name="refreshSession" type="() => Promise<SessionRefreshResponse>">
  Lower-level refresh that returns just the new `expiresAt`. `refreshAuth()` wraps this and updates the stored `AuthState`.
</ResponseField>

<ResponseField name="revokeSession" type="() => Promise<void>">
  Revoke the current session on the server without clearing local React state (`logout()` does both).
</ResponseField>

## Advanced Building Blocks

`login` / `authenticate` run these internally and manage the session keypair for you. Use them directly only for custom flows.

<ResponseField name="authenticate" type="() => Promise<AuthState>">
  The programmatic equivalent of `login()` — generates the session key, prompts the wallet, verifies, and returns the `AuthState`.
</ResponseField>

<ResponseField name="signChallenge" type="(message: string) => Promise<string>">
  Ask the connected wallet to authorize a challenge message. Returns a hex signature — EIP-191 from an EOA, or an EIP-1271 contract signature from a smart-contract wallet such as a Safe. Submit it unchanged; do not assume the 65-byte EOA shape. Server-side EIP-1271 verification is deliberately narrow: it is offered only to a wallet holding a BuilderCodes payout bucket, on a deployment with the contract-wallet flag on and a chain RPC endpoint configured. An ordinary smart-contract trading account is NOT covered — it still takes the recovery path and cannot authenticate.
</ResponseField>

<ResponseField name="createChallenge" type="(address: string, sessionPublicKey: string) => Promise<ChallengeResponse>">
  Create a single-use challenge whose message embeds the given session public key. Returns `nonce`, `message`, and `expiresAt`.
</ResponseField>

## Example: Login Button

```tsx theme={null}
import { useAuth } from "@0xmonaco/react";

function LoginButton() {
  const { login, authenticationStatus } = useAuth();

  const handleLogin = async () => {
    try {
      const authState = await login();
      console.log('Logged in:', authState.user);
    } catch (error) {
      if (error.message.includes('SDK not available')) {
        alert('SDK is still loading, please wait');
      } else if (error.message.includes('Wallet not connected')) {
        alert('Please connect your wallet first');
      } else {
        console.error('Login failed:', error);
      }
    }
  };

  return (
    <button
      onClick={handleLogin}
      disabled={authenticationStatus === 'authenticating'}
    >
      {authenticationStatus === 'authenticating' ? 'Logging in...' : 'Login'}
    </button>
  );
}
```

<Note>
  Auth actions validate SDK availability, wallet connection, and required parameters before running, throwing a descriptive `Error` (e.g. `"SDK not available"`, `"Wallet not connected"`, `"Client ID is required"`) when a precondition is missing.
</Note>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.