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/openfort-react';
function SessionKeyExample() {
const { grantPermissions, isLoading } = useGrantPermissions({
onSuccess: (result) => {
console.log('Session created for:', result.address);
// Store session key securely
localStorage.setItem('sessionKey', result.privateKey);
},
});
const createSession = async () => {
const sessionKey = generatePrivateKey();
const accountSession = privateKeyToAccount(sessionKey);
const result = await grantPermissions({
sessionKey,
request: {
signer: {
type: 'account',
data: { id: accountSession.address },
},
expiry: 60 * 60 * 24, // 24 hours
permissions: [
{
type: 'contract-call',
data: {
address: '0x2522f4fc9af2e1954a3d13f7a5b2683a00a4543a',
calls: [],
},
policies: [],
},
],
},
});
if (result.address) {
console.log('Session key registered:', result.address);
console.log('Private key (store securely!):', result.privateKey);
}
};
return (
<button onClick={createSession} disabled={isLoading}>
{isLoading ? 'Creating...' : 'Create Session Key'}
</button>
);
}For more details and advanced usage, see the useGrantPermissions documentation.