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

# useRevokeSessionKey

> Revoke a session key from the CHIPI wallet smart contract. After revocation, the session key can no longer execute transactions.

<Warning>
  Always revoke active sessions when a user logs out to prevent unauthorized access.
</Warning>

## Usage

```typescript theme={null}
const { 
  revokeSessionKey,
  revokeSessionKeyAsync, 
  data, 
  isLoading, 
  error,
  isSuccess,
  reset
} = useRevokeSessionKey();
```

### Parameters

| Parameter                 | Type       | Required | Description                                                         |
| ------------------------- | ---------- | -------- | ------------------------------------------------------------------- |
| `params.encryptKey`       | string     | Yes      | Owner's PIN to decrypt wallet private key for signing               |
| `params.wallet`           | WalletData | Yes      | Wallet object with `publicKey`, `encryptedPrivateKey`, `walletType` |
| `params.sessionPublicKey` | string     | Yes      | Public key of the session to revoke                                 |
| `bearerToken`             | string     | Yes      | Authentication token from your auth provider                        |

### Return Value

| Property                | Type          | Description                                       |
| ----------------------- | ------------- | ------------------------------------------------- |
| `revokeSessionKey`      | function      | Trigger revocation (fire-and-forget)              |
| `revokeSessionKeyAsync` | function      | Trigger revocation (returns Promise with tx hash) |
| `data`                  | string        | Transaction hash of revocation                    |
| `isLoading`             | boolean       | Whether revocation is in progress                 |
| `isError`               | boolean       | Whether an error occurred                         |
| `error`                 | Error \| null | Error details if any                              |
| `isSuccess`             | boolean       | Whether revocation succeeded                      |
| `reset`                 | function      | Reset mutation state                              |

## Example Implementation

```typescript theme={null}
import { useRevokeSessionKey } from "@chipi-stack/chipi-react";

export function RevokeSession() {
  const { revokeSessionKeyAsync, isLoading, error, isSuccess } = useRevokeSessionKey();
  const [pin, setPin] = useState('');

  const handleRevoke = async () => {
    const bearerToken = await getBearerToken();
    const session = JSON.parse(localStorage.getItem('chipiSession') || '{}');
    
    if (!session.publicKey) {
      alert('No active session found');
      return;
    }

    try {
      const txHash = await revokeSessionKeyAsync({
        params: {
          encryptKey: pin,
          wallet: {
            publicKey: wallet.publicKey,
            encryptedPrivateKey: wallet.encryptedPrivateKey,
            walletType: "CHIPI",
          },
          sessionPublicKey: session.publicKey,
        },
        bearerToken,
      });
      
      // Clear from local storage
      localStorage.removeItem('chipiSession');
      
      console.log('Session revoked:', txHash);
    } catch (err) {
      console.error('Failed to revoke session:', err);
    }
  };

  return (
    <div className="p-6 bg-white rounded-lg shadow">
      <h2 className="text-xl font-semibold mb-4">Revoke Session</h2>
      
      <input
        type="password"
        value={pin}
        onChange={(e) => setPin(e.target.value)}
        placeholder="Enter your PIN"
        className="w-full p-2 border rounded mb-4"
      />
      
      <button
        onClick={handleRevoke}
        disabled={isLoading || !pin}
        className="w-full bg-red-600 text-white py-2 rounded hover:bg-red-700 disabled:bg-gray-400"
      >
        {isLoading ? 'Revoking...' : 'Revoke Session'}
      </button>

      {error && (
        <div className="mt-4 p-3 bg-red-50 text-red-700 rounded">
          Error: {error.message}
        </div>
      )}

      {isSuccess && (
        <div className="mt-4 p-3 bg-green-50 text-green-700 rounded">
          Session revoked successfully!
        </div>
      )}
    </div>
  );
}
```

## Secure Logout Handler

Always revoke sessions during logout:

```typescript theme={null}
import { useRevokeSessionKey } from "@chipi-stack/chipi-react";

export function useSecureLogout() {
  const { revokeSessionKeyAsync } = useRevokeSessionKey();

  const logout = async (wallet: WalletData, pin: string) => {
    const sessionStr = localStorage.getItem('chipiSession');
    
    if (sessionStr) {
      const session = JSON.parse(sessionStr);
      const bearerToken = await getBearerToken();
      
      try {
        // Revoke session on-chain before logout
        await revokeSessionKeyAsync({
          params: {
            encryptKey: pin,
            wallet: { ...wallet, walletType: "CHIPI" },
            sessionPublicKey: session.publicKey,
          },
          bearerToken,
        });
      } catch (error) {
        console.warn("Failed to revoke session:", error);
        // Continue with logout even if revoke fails
      }
      
      // Clear from local storage
      localStorage.removeItem('chipiSession');
    }
    
    // Proceed with auth logout
    await authProvider.signOut();
  };

  return { logout };
}
```

<Tip>
  If revocation fails (e.g., network error), the session will still expire at its `validUntil` timestamp. However, it's best practice to always attempt revocation.
</Tip>

## When to Revoke

| Scenario                  | Should Revoke?                                |
| ------------------------- | --------------------------------------------- |
| User logs out             | ✅ Yes - always                                |
| Session expired naturally | ❌ No - already inactive                       |
| User requests new session | ⚠️ Optional - old session will expire         |
| Security concern          | ✅ Yes - immediately                           |
| App uninstall             | N/A - Can't revoke, session expires naturally |

<Warning>
  Revocation requires a blockchain transaction which may take 10-30 seconds. Don't block the logout flow - fire the revocation and continue.
</Warning>
