> ## 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.

# useCreateSessionKey

> Generate a session keypair locally for temporary, delegated transaction execution. Session keys enable gasless, frictionless UX without requiring the owner private key for each transaction.

<Info>
  Session keys only work with **CHIPI wallets** - not READY wallets. Make sure your wallet was created with `walletType: "CHIPI"`.
</Info>

## Usage

```typescript theme={null}
const { 
  createSessionKey,
  createSessionKeyAsync, 
  data, 
  isLoading, 
  error,
  isSuccess,
  reset
} = useCreateSessionKey();
```

### Parameters

| Parameter         | Type   | Required | Description                                            |
| ----------------- | ------ | -------- | ------------------------------------------------------ |
| `encryptKey`      | string | Yes      | User's PIN/password to encrypt the session private key |
| `durationSeconds` | number | No       | Session duration in seconds (default: 21600 = 6 hours) |

### Return Value

Returns an object containing:

| Property                | Type           | Description                                      |
| ----------------------- | -------------- | ------------------------------------------------ |
| `createSessionKey`      | function       | Trigger session key generation (fire-and-forget) |
| `createSessionKeyAsync` | function       | Trigger session key generation (returns Promise) |
| `data`                  | SessionKeyData | Generated session key data                       |
| `isLoading`             | boolean        | Whether generation is in progress                |
| `isError`               | boolean        | Whether an error occurred                        |
| `error`                 | Error \| null  | Error details if any                             |
| `isSuccess`             | boolean        | Whether generation succeeded                     |
| `reset`                 | function       | Reset mutation state                             |

### SessionKeyData Structure

```typescript theme={null}
{
  publicKey: string;           // Session public key (hex)
  encryptedPrivateKey: string; // AES encrypted with encryptKey
  validUntil: number;          // Unix timestamp (seconds)
}
```

## Example Implementation

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

export function CreateSession() {
  const { 
    createSessionKeyAsync, 
    data: session, 
    isLoading, 
    error 
  } = useCreateSessionKey();
  
  const [pin, setPin] = useState('');

  const handleCreateSession = async () => {
    try {
      const sessionData = await createSessionKeyAsync({
        encryptKey: pin,
        durationSeconds: 3600, // 1 hour session
      });
      
      // Store session in client-side storage (NOT your database!)
      localStorage.setItem('chipiSession', JSON.stringify(sessionData));
      
      console.log('Session created:', sessionData.publicKey);
    } catch (err) {
      console.error('Failed to create session:', err);
    }
  };

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

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

      {session && (
        <div className="mt-4 p-3 bg-green-50 rounded">
          <p className="text-sm text-green-800">
            Session created! Expires: {new Date(session.validUntil * 1000).toLocaleString()}
          </p>
        </div>
      )}
    </div>
  );
}
```

## Security Considerations

<Danger>
  **Never store session keys in your backend database.** This defeats the purpose of self-custodial security. Store only in client-side secure storage.
</Danger>

| Platform         | Recommended Storage                            |
| ---------------- | ---------------------------------------------- |
| **Web**          | `localStorage` or `sessionStorage`             |
| **iOS**          | Secure Enclave / Keychain                      |
| **Android**      | Android Keystore                               |
| **React Native** | `expo-secure-store` or `react-native-keychain` |

## Best Practices

1. **Set short durations** - Use 1-6 hours, not days
2. **Clear on logout** - Always remove session from storage when user logs out
3. **Register on-chain** - After creating, use `useAddSessionKeyToContract` to register it

<Note>
  This hook only generates the session keypair locally. You must call `useAddSessionKeyToContract` to register it on-chain before it can be used for transactions.
</Note>
