> For the complete documentation index, see [llms.txt](https://docs.cometh.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cometh.io/advanced/session-keys/tutorial.md).

# Tutorial

### 1 - Create a Session Key

```typescript
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
import {
    type ComethSmartAccountClient,
    type SafeSigner,
    erc7579Actions,
    smartSessionActions,
} from "@cometh/connect-sdk-4337";

export const COUNTER_CONTRACT_ADDRESS =
    "0x4FbF9EE4B2AF774D4617eAb027ac2901a41a7b5F";


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

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

const createSessionsResponse = await safe7559AccountClient.grantPermission({
    sessionRequestedInfo: [
        {
            sessionPublicKey: sessionOwner.address,
            actionPoliciesInfo: [
                {
                    contractAddress: COUNTER_CONTRACT_ADDRESS,
                    functionSelector: toFunctionSelector(
                        "function count()"
                    ) as Hex,
                },
            ],
        },
    ],
});

await safe7559AccountClient.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.

<pre class="language-typescript"><code class="lang-typescript">import { SmartSessionMode } from "@cometh/connect-sdk-4337";
<strong>
</strong><strong>const sessionData = {
</strong>    granter: smartAccountClient?.account?.address as Address,
    privateKey: privateKey,
    sessionPublicKey: sessionOwner.address,
    description: `Session to increment a counter`,
    moduleData: {
        permissionIds: createSessionsResponse.permissionIds,
        action: createSessionsResponse.action,
        mode: SmartSessionMode.USE,
        sessions: createSessionsResponse.sessions,
    },
};

// This is for example purposes.
const sessionParams = stringify(sessionData);

localStorage.setItem(
    `session-key-${smartAccountClient?.account?.address}`,
    sessionParams
);
</code></pre>

### 3 - Use the Session Key

```typescript
import {
    createComethPaymasterClient,
    createSafeSmartAccount,
    createSmartAccountClient,
    smartSessionActions,
    toSmartSessionsSigner
} from "@cometh/connect-sdk-4337";
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";

const apiKey = process.env.COMETH_API_KEY;
const bundlerUrl = process.env.4337_BUNDLER_URL;
const paymasterUrl = process.env.4337_PAYMASTER_URL
const publicClient = createPublicClient({
    chain,
    transport: http(),
});


const stringifiedSessionData = localStorage.getItem(
    `session-key-${WALLETADDRESS}`
);
const sessionData = parse(stringifiedSessionData);

const sessionKeySigner = await toSmartSessionsSigner(safe7559Account, 
{
    moduleData: sessionData.moduleData,
    signer: privateKeyToAccount(sessionData.privateKey),
})

const sessionKeyAccount = await createSafeSmartAccount({
    apiKey,
    chain,
    smartAccountAddress: smartAccountClient?.account?.address,
    smartSessionSigner: sessionKeySigner,
});

const paymasterClient = await createComethPaymasterClient({
    transport: http(paymasterUrl),
    chain,
});

const sessionKeyClient = createSmartAccountClient({
    account: sessionKeyAccount,
    chain,
    bundlerTransport: http(bundlerUrl),
    paymaster: paymasterClient,
    userOperation: {
        estimateFeesPerGas: async () => {
            return await paymasterClient.getUserOperationGasPrice();
        },
    },
}).extend(smartSessionActions());

const callData = encodeFunctionData({
    abi: countContractAbi,
    functionName: "count",
});

const hash = await sessionKeyClient.usePermission({
    actions: [
        {
            target: COUNTER_CONTRACT_ADDRESS,
            callData: callData,
            value: BigInt(0),
        },
    ],
});
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.cometh.io/advanced/session-keys/tutorial.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
