Skip to main content

CavosProvider

The provider component that initializes the SDK and provides context to child components.
import { CavosProvider } from '@cavos/react';

<CavosProvider config={config}>
  <App />
</CavosProvider>

Config Props

interface CavosConfig {
  appId: string;                    // Required: Your Cavos App ID
  network?: 'sepolia' | 'mainnet';  // Default: 'sepolia'
  paymasterApiKey?: string;         // Custom paymaster key
  starknetRpcUrl?: string;          // Custom RPC URL
  enableLogging?: boolean;          // Enable debug logs
  passkeyModal?: {                  // Modal customization
    title?: string;
    description?: string;
    buttonText?: string;
  };
}

useCavos Hook

Access SDK functionality from any child component:
import { useCavos } from '@cavos/react';

function MyComponent() {
  const {
    // State
    isAuthenticated,
    user,
    address,
    isLoading,
    hasActiveSession,
    requiresWalletCreation,
    walletStatus,           // NEW: Detailed wallet state
    
    // Actions
    login,
    register,
    createWallet,
    execute,
    signMessage,
    registerCurrentSession, // Register current login session
    revokeSession,          // Revoke specific session
    emergencyRevokeAllSessions,  // Revoke all sessions
    exportSession,          // Export session for CLI
    logout,
    deleteAccount,
    retryWalletUnlock,
    getOnramp,
    
    // SDK instance
    cavos,
  } = useCavos();

  return <div>...</div>;
}

State Properties

PropertyTypeDescription
isAuthenticatedbooleanUser is authenticated (OAuth or passkey)
userUserInfo | nullUser info from OAuth (or placeholder for passkey)
addressstring | nullWallet address if loaded
isLoadingbooleanSDK is initializing or processing
hasActiveSessionbooleanSession is active and not expired
requiresWalletCreationbooleanUser needs to create wallet (shows modal)
walletStatusWalletStatusDetailed wallet deployment and session state

Action Methods

login(provider, credentials?, redirectUri?)

Start authentication flow: Social Login (Google/Apple):
await login('google');
await login('apple');
await login('google', undefined, 'https://myapp.com/callback');
Email/Password (Firebase):
await login('firebase', {
  email: 'user@example.com',
  password: 'password123'
});
Error Handling:
try {
  await login('firebase', { email, password });
} catch (error) {
  if (error.name === 'EmailNotVerifiedError') {
    // Email not verified yet
    console.log('Unverified email:', error.email);
  } else if (error.message?.includes('auth/wrong-password')) {
    // Invalid credentials
  }
}

register(provider, credentials)

Register a new user with email/password:
try {
  await register('firebase', {
    email: 'user@example.com',
    password: 'secure123'
  });
  // Verification email sent
  alert('Check your email to verify your account!');
} catch (error) {
  if (error.name === 'EmailVerificationRequiredError') {
    // Registration successful, email sent
  } else if (error.error === 'rate_limited') {
    // Too many requests
    console.log('Wait seconds:', error.wait_seconds);
  }
}

createWallet()

Create or recover a wallet:
await createWallet();
For passkey-only mode, call this without prior login().

execute(calls)

Execute transactions using session keys:
// Requires active session!
const txHash = await execute({
  contractAddress: '0x...',
  entrypoint: 'transfer',
  calldata: ['0x...', '1000', '0'],
});
[!NOTE] All transactions are signed with the session key and are gasless. No signature prompt appears.

signMessage(messageHash)

Sign a message with the session key:
const signature = await signMessage('0x123...'); // hex string message hash
// Returns { r: string, s: string }

logout()

Clear session and wallet:
await logout();

deleteAccount()

Permanently delete account:
await deleteAccount();

Additional Methods

The cavos instance provides additional utility methods:
const { cavos } = useCavos();

// Check email verification status
const isVerified = await cavos.isEmailVerified('user@example.com');

// Resend verification email
await cavos.resendVerificationEmail('user@example.com');

// Get wallet balance
const balance = await cavos.getBalance();

const deployed = await cavos.isAccountDeployed();

WalletStatus

The walletStatus object provides detailed information about your wallet’s on-chain state:
interface WalletStatus {
  isDeploying: boolean;     // Account is currently being deployed
  isDeployed: boolean;      // Account contract is deployed on-chain
  isRegistering: boolean;   // Session key is currently being registered
  isSessionActive: boolean; // Session key is registered and not expired
  isReady: boolean;         // Wallet is fully deployed + session active — ready for transactions
}
Example Usage:
const { walletStatus, address } = useCavos();

if (!address) {
  return <LoginButton />;
}

// After login, deploy + session registration happen automatically.
// The consumer only needs to observe walletStatus:
if (!walletStatus.isReady) {
  return (
    <div>
      {walletStatus.isDeploying && <p>Deploying wallet...</p>}
      {walletStatus.isRegistering && <p>Registering session...</p>}
      <span className="loading" />
    </div>
  );
}

// Ready for transactions!
return <TransactionButtons />;
[!NOTE] walletStatus.isReady is true only when the account is deployed and the session is registered. Both steps happen automatically after login() — no manual calls needed.

Session Management Methods

registerSession()

Register a session key on-chain. This activates your session and enables signature-free transactions.
const { registerSession, walletStatus } = useCavos();

if (!walletStatus.isSessionActive) {
  const txHash = await registerSession();
  console.log('Session registered:', txHash);
}
[!IMPORTANT] After calling registerSession(), walletStatus.isSessionActive will automatically update to true.

revokeSession(sessionKey?)

Revoke a session key on-chain. If no sessionKey is provided, revokes the current active session.
const { revokeSession } = useCavos();

// Revoke current session
await revokeSession();

// Or revoke a specific session
await revokeSession('0x123abc...');
[!NOTE] This operation requires JWT verification on-chain and uses the OAuth signature.

emergencyRevokeAllSessions()

Revoke all active sessions for the wallet. Use this if you suspect a session key has been compromised.
const { emergencyRevokeAllSessions } = useCavos();

if (confirm('This will revoke all sessions. Continue?')) {
  await emergencyRevokeAllSessions();
}
[!WARNING] This invalidates all sessions immediately. You’ll need to create and register a new session to transact again.

exportSession()

Export the current session as a base64-encoded token for use in the Cavos CLI or other tools.
const { exportSession, walletStatus } = useCavos();

// Only export when session is active
if (walletStatus.isSessionActive) {
  const token = exportSession();
  
  // Copy to clipboard
  navigator.clipboard.writeText(token);
  
  // Or display for user to copy
  console.log('Session token:', token);
  console.log('Use in CLI: export CAVOS_TOKEN=' + token);
}
CLI Usage: Once exported, the session token can be used in the Cavos CLI:
# Set environment variable
export CAVOS_TOKEN="<base64_token>"

# Or import directly
cavos session import <base64_token>

# Now execute CLI commands
cavos balance
cavos transfer --to 0x... --amount 1.5 --token STRK
[!NOTE] The exported token contains the session private key and wallet address. Store it securely and never share it publicly.
Manage session keys for signature-free transactions:
import { useSession } from '@cavos/react';

function SessionManager() {
  const {
    hasActiveSession,
    createSession,
    clearSession,
    executeWithSession,
  } = useSession();

  return <div>Session: {hasActiveSession ? 'Active' : 'Inactive'}</div>;
}

Session Properties

PropertyTypeDescription
hasActiveSessionbooleanSession is active and not expired

Session Methods

createSession(policy)

Create a session with a policy defining allowed actions:
await createSession({
  allowedMethods: [
    { contractAddress: '0x...token', selector: 'transfer' },
    { contractAddress: '0x...token', selector: 'approve' },
    { contractAddress: '0x...nft', selector: 'mint' },
  ],
  expiresAt: Date.now() + 60 * 60 * 1000, // 1 hour
});
[!IMPORTANT] After createSession(), the user’s private key is cleared from memory. Only the session key remains.

clearSession()

Invalidate the current session:
clearSession();

executeWithSession(calls)

Execute transactions with the session key:
const txHash = await executeWithSession({
  contractAddress: '0x...',
  entrypoint: 'transfer',
  calldata: ['0x...', '1000', '0'],
});

Complete Example

import { useCavos, useSession } from '@cavos/react';

function App() {
  const { login, logout, address, isAuthenticated } = useCavos();
  const { hasActiveSession, createSession } = useSession();

  const handleSetup = async () => {
    // 1. Authenticate
    await login('google');
    
    // 2. Create session (user signs once)
    await createSession({
      allowedMethods: [
        { contractAddress: TOKEN_ADDRESS, selector: 'transfer' },
      ],
      expiresAt: Date.now() + 60 * 60 * 1000,
    });
    
    // ✓ Ready for signature-free transactions
  };

  const handleTransfer = async () => {
    const { execute } = useCavos();
    
    // No signature popup!
    const txHash = await execute({
      contractAddress: TOKEN_ADDRESS,
      entrypoint: 'transfer',
      calldata: [recipient, amount, '0'],
    });
  };

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

  return (
    <div>
      <p>Address: {address}</p>
      <p>Session: {hasActiveSession ? '✅ Active' : '❌ Create session first'}</p>
      <button onClick={handleTransfer} disabled={!hasActiveSession}>
        Transfer
      </button>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

Session Policy Reference

interface SessionPolicy {
  allowedMethods: Array<{
    contractAddress: string;  // Contract address (hex)
    selector: string;         // Function name
  }>;
  expiresAt: number;          // Timestamp in milliseconds
  metadata?: string;          // Optional metadata
}

Best Practices

  1. Limit scope: Only include methods your app actually needs
  2. Short expiration: Use 1 hour or less for sensitive operations
  3. Re-create on demand: Create new sessions when needed rather than long-lived ones
  4. Check before execute: Always verify hasActiveSession before execute()