Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Skip to content

Using Session Keys with React

Session keys are programmable access tokens with specific permissions, designed for controlled interactions. Examples include:

  • Granting access to specific areas or features.
  • Limiting usage to a set amount of resources (e.g., 1000 units of currency).
  • Time-bound validity (e.g., expiring after 3 days).

Permissions can be combined, enabling fine-tuned, context-specific capabilities.

Using the useGrantPermissions Hook

The useGrantPermissions hook provides a simple, client-side way to create and manage session keys using the EIP-7715 standard.

Quick Example

import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
import { useGrantPermissions } from '@openfort/react';
 
function SessionKeyExample() {
  const { grantPermissions, isLoading } = useGrantPermissions({
    onSuccess: (result) => {
      console.log('Permissions granted for wallet:', result.address);
    },
  });
 
  const createSession = async () => {
    // Generate a new session key
    const sessionKey = generatePrivateKey();
    const sessionAccount = privateKeyToAccount(sessionKey);
 
    // Store the session key BEFORE granting permissions
    // The hook does not return the private key
    localStorage.setItem('sessionKey', sessionKey);
 
    const result = await grantPermissions({
      request: {
        signer: {
          type: 'account',
          data: { id: sessionAccount.address },
        },
        expiry: 60 * 60 * 24, // 24 hours
        permissions: [
          {
            type: 'contract-call',
            data: {
              address: '0x2522f4fc9af2e1954a3d13f7a5b2683a00a4543a',
              calls: [],
            },
            policies: [],
          },
        ],
      },
    });
 
    if (result.address) {
      console.log('Session key registered for wallet:', result.address);
    }
  };
 
  return (
    <button onClick={createSession} disabled={isLoading}>
      {isLoading ? 'Creating...' : 'Create Session Key'}
    </button>
  );
}

For more details and advanced usage, see the useGrantPermissions documentation.

Copyright © 2023-present Alamas Labs, Inc