Skip to main content
Session keys only work with CHIPI wallets - not ARGENT wallets. Make sure your wallet was created with walletType: "CHIPI".

Usage

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

Parameters

ParameterTypeRequiredDescription
encryptKeystringYesUser’s PIN/password to encrypt the session private key
durationSecondsnumberNoSession duration in seconds (default: 21600 = 6 hours)

Return Value

Returns an object containing:
PropertyTypeDescription
createSessionKeyfunctionTrigger session key generation (fire-and-forget)
createSessionKeyAsyncfunctionTrigger session key generation (returns Promise)
dataSessionKeyDataGenerated session key data
isLoadingbooleanWhether generation is in progress
isErrorbooleanWhether an error occurred
errorError | nullError details if any
isSuccessbooleanWhether generation succeeded
resetfunctionReset mutation state

SessionKeyData Structure

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

Example Implementation

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

Never store session keys in your backend database. This defeats the purpose of self-custodial security. Store only in client-side secure storage.
PlatformRecommended Storage
WeblocalStorage or sessionStorage
iOSSecure Enclave / Keychain
AndroidAndroid Keystore
React Nativeexpo-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
This hook only generates the session keypair locally. You must call useAddSessionKeyToContract to register it on-chain before it can be used for transactions.