Skip to main content

useAuth Hook

The useAuth hook provides wallet connection and authentication functionality.

Basic Usage

import { useAuth } from '@testinprod-io/privacy-boost-react';

function WalletButton() {
  const {
    isConnected,
    isAuthenticated,
    address,
    privacyAddress,
    connect,
    login,
    logout,
  } = useAuth();

  // ...
}

Return Value

interface UseAuthResult {
  // State
  isConnected: boolean;
  isAuthenticated: boolean;
  isWalletAvailable: boolean;
  address: string | null;
  privacyAddress: string | null;
  mpk: string | null;

  // Separate operations
  connect(adapter: WalletAdapter): Promise<{ address: string; chainId: number }>;
  connectInjected(): Promise<{ address: string; chainId: number }>;
  disconnect(): Promise<void>;
  login(): Promise<LoginResult>;
  logout(): Promise<void>;

  // Combined operations
  authenticate(adapter: WalletAdapter): Promise<LoginResult>;
  authenticateInjected(): Promise<LoginResult>;
}

State Properties

PropertyTypeDescription
isConnectedbooleanWallet is connected
isAuthenticatedbooleanPrivacy keys are derived
isWalletAvailablebooleanBrowser wallet detected
addressstring | nullWallet address
privacyAddressstring | nullPrivacy address
mpkstring | nullMaster public key

Connect Methods

connectInjected()

Connect using the browser’s injected wallet (MetaMask, etc.):
const { connectInjected, isWalletAvailable } = useAuth();

<button
  onClick={connectInjected}
  disabled={!isWalletAvailable}
>
  Connect MetaMask
</button>

connect(adapter)

Connect with a specific wallet adapter:
import { createWalletRegistry } from '@testinprod-io/privacy-boost';

const { connect } = useAuth();

const handleWalletConnect = async () => {
  const registry = createWalletRegistry({
    chains: [1],
    walletConnect: { projectId: 'your-project-id' },
  });
  const adapter = registry.getAdapter('walletconnect');
  await connect(adapter);
};

Authentication Methods

authenticateInjected()

Connect and login in one step:
const { authenticateInjected, isAuthenticated } = useAuth();

if (!isAuthenticated) {
  return <button onClick={authenticateInjected}>Login</button>;
}

authenticate(adapter)

Authenticate with specific adapter:
const { authenticate } = useAuth();

const handleAuth = async (adapter: WalletAdapter) => {
  const { privacyAddress } = await authenticate(adapter);
  console.log('Logged in:', privacyAddress);
};

Separate connect() and login()

For more control:
const { connect, login, isConnected, isAuthenticated } = useAuth();

// Step 1: Connect wallet
const handleConnect = async () => {
  await connect(adapter);
};

// Step 2: Login (after connect)
const handleLogin = async () => {
  const { privacyAddress } = await login();
};

Logout Methods

logout()

Clear all authentication state:
const { logout } = useAuth();

<button onClick={logout}>Logout</button>

disconnect()

Disconnect wallet but keep privacy keys:
const { disconnect } = useAuth();

<button onClick={disconnect}>Disconnect Wallet</button>

Complete Example

import { useAuth } from '@testinprod-io/privacy-boost-react';
import { createWalletRegistry } from '@testinprod-io/privacy-boost';

function AuthComponent() {
  const {
    isConnected,
    isAuthenticated,
    isWalletAvailable,
    address,
    privacyAddress,
    authenticateInjected,
    authenticate,
    logout,
  } = useAuth();

  const [loading, setLoading] = useState(false);

  const handleMetaMask = async () => {
    setLoading(true);
    try {
      await authenticateInjected();
    } catch (error) {
      if (error.code !== 'WALLET_USER_REJECTED') {
        alert('Connection failed');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleWalletConnect = async () => {
    setLoading(true);
    try {
      const registry = createWalletRegistry({
        chains: [1],
        walletConnect: { projectId: 'your-project-id' },
      });
      const adapter = registry.getAdapter('walletconnect');
      await authenticate(adapter);
    } finally {
      setLoading(false);
    }
  };

  if (isAuthenticated) {
    return (
      <div>
        <p>Wallet: {address?.slice(0, 10)}...</p>
        <p>Privacy: {privacyAddress?.slice(0, 20)}...</p>
        <button onClick={logout}>Logout</button>
      </div>
    );
  }

  return (
    <div>
      <button
        onClick={handleMetaMask}
        disabled={loading || !isWalletAvailable}
      >
        MetaMask
      </button>
      <button onClick={handleWalletConnect} disabled={loading}>
        WalletConnect
      </button>
    </div>
  );
}

Error Handling

const handleConnect = async () => {
  try {
    await authenticateInjected();
  } catch (error) {
    switch (error.code) {
      case 'WALLET_USER_REJECTED':
        // User cancelled - don't show error
        break;
      case 'WALLET_CHAIN_MISMATCH':
        alert('Please switch to the correct network');
        break;
      case 'AUTH_SIGNATURE_REJECTED':
        alert('Please sign the message to continue');
        break;
      default:
        alert('Connection failed');
    }
  }
};

Listening for Changes

function WalletStatus() {
  const { isAuthenticated, address } = useAuth();

  useEffect(() => {
    if (isAuthenticated) {
      console.log('User authenticated:', address);
    } else {
      console.log('User not authenticated');
    }
  }, [isAuthenticated, address]);

  return <div>Status: {isAuthenticated ? 'Logged in' : 'Logged out'}</div>;
}

Next Steps