Skip to main content
Session keys only work with CHIPI wallets. This hook requires the owner’s encryptKey (PIN) to sign the registration transaction.

Usage

const { 
  addSessionKeyToContract,
  addSessionKeyToContractAsync, 
  data, 
  isLoading, 
  error,
  isSuccess,
  reset
} = useAddSessionKeyToContract();

Parameters

ParameterTypeRequiredDescription
params.encryptKeystringYesOwner’s PIN to decrypt wallet private key for signing
params.walletWalletDataYesWallet object with publicKey, encryptedPrivateKey, walletType
params.sessionConfigSessionConfigYesSession configuration (see below)
bearerTokenstringYesAuthentication token from your auth provider

SessionConfig Structure

{
  sessionPublicKey: string;    // From useCreateSessionKey().data.publicKey
  validUntil: number;          // Unix timestamp (seconds)
  maxCalls: number;            // Maximum transactions allowed
  allowedEntrypoints: string[]; // Whitelisted function selectors (empty = all allowed)
}

Return Value

PropertyTypeDescription
addSessionKeyToContractfunctionTrigger registration (fire-and-forget)
addSessionKeyToContractAsyncfunctionTrigger registration (returns Promise with tx hash)
datastringTransaction hash of registration
isLoadingbooleanWhether registration is in progress
isErrorbooleanWhether an error occurred
errorError | nullError details if any
isSuccessbooleanWhether registration succeeded
resetfunctionReset mutation state

Example Implementation

import { 
  useAddSessionKeyToContract,
  useCreateSessionKey,
  useGetWallet 
} from "@chipi-stack/chipi-react";

export function RegisterSession() {
  const { createSessionKeyAsync } = useCreateSessionKey();
  const { addSessionKeyToContractAsync, isLoading, error } = useAddSessionKeyToContract();
  const { data: wallet } = useGetWallet({ 
    params: { externalUserId: "user-123" },
    getBearerToken 
  });
  
  const [pin, setPin] = useState('');

  const handleRegisterSession = async () => {
    const bearerToken = await getBearerToken();
    
    // Step 1: Create session key
    const session = await createSessionKeyAsync({
      encryptKey: pin,
      durationSeconds: 3600,
    });
    
    // Step 2: Register on contract
    const txHash = await addSessionKeyToContractAsync({
      params: {
        encryptKey: pin,
        wallet: {
          publicKey: wallet.publicKey,
          encryptedPrivateKey: wallet.encryptedPrivateKey,
          walletType: "CHIPI",
        },
        sessionConfig: {
          sessionPublicKey: session.publicKey,
          validUntil: session.validUntil,
          maxCalls: 100,           // Allow 100 transactions
          allowedEntrypoints: [],  // Empty = all functions allowed
        },
      },
      bearerToken,
    });
    
    // Store session for later use
    localStorage.setItem('chipiSession', JSON.stringify(session));
    
    console.log('Session registered:', txHash);
  };

  return (
    <div className="p-6 bg-white rounded-lg shadow">
      <h2 className="text-xl font-semibold mb-4">Register Session Key</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={handleRegisterSession}
        disabled={isLoading || !pin || !wallet}
        className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700 disabled:bg-gray-400"
      >
        {isLoading ? 'Registering...' : 'Register Session'}
      </button>

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

Restricting Session Permissions

For enhanced security, whitelist specific function selectors:
const txHash = await addSessionKeyToContractAsync({
  params: {
    encryptKey: pin,
    wallet: walletData,
    sessionConfig: {
      sessionPublicKey: session.publicKey,
      validUntil: session.validUntil,
      maxCalls: 10,  // Only 10 calls allowed
      allowedEntrypoints: [
        "0x83afd3f4caedc6eebf44246fe54e38c95e3179a5ec9ea81740eca5b482d12e", // transfer
        "0x219209e083275171774dab1df80982e9df2096516f06319c5c6d71ae0a8480c", // approve
      ],
    },
  },
  bearerToken,
});
Limiting allowedEntrypoints restricts what functions the session can call. This is recommended for production to minimize attack surface.

Error Handling

Common errors:
ErrorCauseSolution
Session keys require CHIPI wallet typeWallet is ARGENT typeCreate a new wallet with walletType: "CHIPI"
Invalid encryptKeyWrong PIN enteredVerify the PIN matches the one used during wallet creation
Session already existsSession already registeredUse useGetSessionData to check status
Registration requires a blockchain transaction. The transaction is gas-sponsored but may take 10-30 seconds to confirm.