Manage session keys

Example of a session key with an action policy.

1 - Create a Session Key

When using a Permissionless account configured like in section Setup Smart Account Client, you have to skip the Safe 7579 module installation step.

This is unnecessary because the Permissionless flow automatically handles module installation during Smart Account creation via the ERC-7579 Launchpad. Including this step may lead to redundant or conflicting behavior.

import type { Address, PublicClient } from "viem";
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
import {
    erc7579Actions,
    smartSessionActions,
    type SafeSigner,
} from "@cometh/session-keys";
import { isSmartAccountDeployed } from "permissionless";

export const COUNTER_CONTRACT_ADDRESS =
    "0x4FbF9EE4B2AF774D4617eAb027ac2901a41a7b5F";


const safe7559Account = smartAccountClient.extend(smartSessionActions())
            .extend(erc7579Actions());

const privateKey = generatePrivateKey();
const sessionOwner = privateKeyToAccount(privateKey);

 if (!(await isSmartAccountDeployed(
     safe7559Account?.account?.client as PublicClient, 
     safe7559Account?.account?.address as Address,
 ))) {
     safe7559Account.addSafe7579Module()
 }
        
const createSessionsResponse = await safe7559Account.grantPermission({
    sessionRequestedInfo: [
        {
            sessionPublicKey: sessionOwner.address,
            actionPoliciesInfo: [
                {
                    contractAddress: COUNTER_CONTRACT_ADDRESS,
                    functionSelector: toFunctionSelector(
                        "function count()"
                    ) as Hex,
                },
            ],
        },
    ],
});

await safe7559Account.waitForUserOperationReceipt({
    hash: createSessionsResponse.userOpHash,
});

2 - Store the Session Key

In our example, we will store the session key details in local storage. You are free to store it wherever you want.

3 - Use the Session Key

Last updated