### Install Project Dependencies with pnpm
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Installs all necessary project dependencies using the pnpm package manager. This command should be run after cloning the repository.
```bash
pnpm install
```
--------------------------------
### Install Corepack for pnpm Version Management
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Enables and uses Corepack to manage and install the correct version of pnpm required by the project. This ensures consistent package management across different developer environments.
```bash
corepack install
```
--------------------------------
### LensProvider React Context Setup
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
React context provider that wraps your application to enable Lens SDK hooks and functionality. Integrates with TanStack Query for state management and provides authenticated user context throughout the component tree.
```typescript
import { LensProvider, PublicClient, mainnet } from '@lens-protocol/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
const client = PublicClient.create({
environment: mainnet,
origin: 'https://myapp.com',
storage: window.localStorage,
});
function App() {
return (
);
}
// Usage in components
function YourApp() {
const { data: authenticatedUser } = useAuthenticatedUser();
if (!authenticatedUser) {
return ;
}
return (
Welcome, {authenticatedUser.username?.value}!
);
}
```
--------------------------------
### Create a New Lens Account with Username (TypeScript)
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
Guides through the process of creating a new Lens Protocol account with a specified username. This function requires an active user session, metadata for the account (name, bio, picture), and the URI where this metadata is stored. It utilizes viem for transaction handling and returns the details of the newly created account.
```typescript
import { PublicClient, createAccountWithUsername, testnet } from '@lens-protocol/client';
import { account } from '@lens-protocol/metadata';
import { handleOperationWith } from '@lens-protocol/client/viem';
const client = PublicClient.create({ environment: testnet });
// Login as onboarding user
const sessionClient = await client.login({
onboardingUser: {
wallet: walletClient.account.address,
app: '0xe5439696f4057aF073c0FB2dc6e5e755392922e1',
},
signMessage: async (message) => walletClient.signMessage({ message }),
});
// Create account metadata
const metadata = account({
name: 'John Doe',
bio: 'Web3 developer and blockchain enthusiast',
picture: 'https://example.com/avatar.jpg',
});
// Upload metadata (using your storage solution)
const metadataUri = await uploadMetadata(metadata);
// Create account with username
const result = await createAccountWithUsername(sessionClient.value, {
metadataUri,
username: { localName: `john-doe-${Date.now()}` },
})
.andThen(handleOperationWith(walletClient))
.andThen((txHash) => sessionClient.value.waitForTransaction)
.andThen((txHash) => sessionClient.value.fetchAccount({ txHash }));
if (result.isOk()) {
console.log('Account created:', result.value.address);
console.log('Username:', result.value.username?.value);
} else {
console.error('Account creation failed:', result.error);
}
```
--------------------------------
### Clone Lens SDK Repository
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Clones the official Lens SDK repository from GitHub. This is the first step for setting up the development environment.
```bash
git clone https://github.com/lens-network/sdk.git
```
--------------------------------
### Run Lens SDK Client Tests
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Executes the test suite specifically for the `@lens-protocol/client` package within the Lens SDK monorepo. This helps verify the functionality of the client library.
```bash
pnpm test:client
```
--------------------------------
### Lint Lens SDK Code
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Runs the code linting process across the entire Lens SDK project to ensure code quality and adherence to style guidelines.
```bash
pnpm lint
```
--------------------------------
### Create Post with Text/Media on Lens Protocol
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
Demonstrates how to create a new post on Lens Protocol. It covers creating posts with text-only metadata and posts with media attachments. This function requires sessionClient and walletClient for authentication and transaction handling. It outputs the transaction hash and allows fetching the created post.
```typescript
import { post } from '@lens-protocol/client';
import { textOnly } from '@lens-protocol/metadata';
import { handleOperationWith } from '@lens-protocol/client/viem';
// Create post metadata
const metadata = textOnly({
content: 'Hello Lens! This is my first post.',
});
// Inline data URI (or upload to IPFS/Arweave)
const contentUri = `data:application/json,${encodeURIComponent(JSON.stringify(metadata))}`;
// Create post
const result = await post(sessionClient, {
contentUri,
})
.andThen(handleOperationWith(walletClient))
.andThen(sessionClient.waitForTransaction)
.andThen((txHash) => sessionClient.fetchPost({ txHash }));
if (result.isOk()) {
console.log('Post created with ID:', result.value.id);
console.log('Content:', result.value.metadata.content);
} else {
console.error('Post creation failed:', result.error);
}
// Create post with media
const imageMetadata = image({
content: 'Check out this amazing sunset!',
image: {
item: 'ipfs://QmExample123',
type: 'image/jpeg',
},
attachments: [
{
item: 'ipfs://QmExample456',
type: 'image/jpeg',
},
],
});
await post(sessionClient, {
contentUri: imageMetadataUri,
actions: [
{
type: 'SimpleCollectAction',
address: '0xCollectActionAddress',
},
],
})
.andThen(handleOperationWith(walletClient))
.andThen(sessionClient.waitForTransaction);
```
--------------------------------
### Switch to Correct Node.js Version with nvm
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Uses the Node Version Manager (nvm) to switch to the Node.js version specified in the project's configuration. Ensures compatibility with project requirements.
```bash
nvm use
```
--------------------------------
### Create New Package in Lens SDK Monorepo
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Initiates the process of creating a new package within the Lens SDK monorepo using a provided script. This streamlines the addition of new modules.
```bash
pnpm new:package
```
--------------------------------
### Create Authenticated Lens Client with Viem (TypeScript)
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
Demonstrates how to create an authenticated client (SessionClient) for performing write operations on the Lens Protocol. It involves setting up a viem wallet client and using it to sign messages during the login process. The authenticated client can then fetch details about the logged-in user.
```typescript
import { PublicClient, testnet } from '@lens-protocol/client';
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { zkSyncSepoliaTestnet } from 'viem/chains';
const client = PublicClient.create({
environment: testnet,
storage: window.localStorage,
});
const account = privateKeyToAccount('0x...');
const walletClient = createWalletClient({
account,
chain: zkSyncSepoliaTestnet,
transport: http(),
});
// Login to get SessionClient
const sessionClient = await client.login({
accountOwner: {
account: '0xAccountAddress',
owner: walletClient.account.address,
},
signMessage: async (message) => {
return walletClient.signMessage({ message });
},
});
if (sessionClient.isErr()) {
throw new Error('Login failed');
}
// Now use sessionClient for authenticated operations
const authenticated = sessionClient.value;
const meResult = await authenticated.fetchAuthenticatedUser();
console.log('Logged in as:', meResult.value?.username?.value);
```
--------------------------------
### useLogin React Hook - User Authentication
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
React hook for authenticating users and creating sessions with Lens Protocol. Supports both existing account owners and onboarding new users, integrating with wallet clients for message signing.
```typescript
import { useLogin } from '@lens-protocol/react';
import { useWalletClient } from 'wagmi';
import { handleOperationWith, signMessageWith } from '@lens-protocol/client/viem';
function LoginButton() {
const { data: wallet } = useWalletClient();
const { execute: login, loading, error } = useLogin();
const handleLogin = async () => {
if (!wallet) return;
const result = await login({
accountOwner: {
account: '0xYourAccountAddress',
owner: wallet.account.address,
},
signMessage: signMessageWith(wallet),
});
if (result.isOk()) {
console.log('Login successful!');
} else {
console.error('Login failed:', result.error);
}
};
return (
);
}
// Onboarding user login
function OnboardingLogin() {
const { data: wallet } = useWalletClient();
const { execute: login } = useLogin();
const handleOnboard = async () => {
await login({
onboardingUser: {
wallet: wallet.account.address,
app: '0xYourAppAddress',
},
signMessage: signMessageWith(wallet),
});
};
return ;
}
```
--------------------------------
### Publish Changeset Packages
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Publishes packages managed by Changesets to the npm registry. This command is used after version bumping and committing changes.
```bash
pnpm changeset publish
```
--------------------------------
### Create Group and Manage Members on Lens Protocol
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
Enables the creation of new groups on Lens Protocol for content and member organization. It includes functionality to create a group with specified metadata and rules, join an existing group, and fetch the list of members within a group. This requires sessionClient and walletClient.
```typescript
import { createGroup, joinGroup, fetchGroupMembers } from '@lens-protocol/client';
import { handleOperationWith } from '@lens-protocol/client/viem';
// Create group metadata
const groupMetadata = {
name: 'DeFi Enthusiasts',
description: 'A group for discussing DeFi protocols',
icon: 'ipfs://QmIcon123',
};
const metadataUri = await uploadMetadata(groupMetadata);
// Create group
const result = await createGroup(sessionClient, {
metadataUri,
rules: {
anyOf: [
{
followedBy: {
account: sessionClient.address,
},
},
],
},
})
.andThen(handleOperationWith(walletClient))
.andThen(sessionClient.waitForTransaction)
.andThen((txHash) => sessionClient.fetchGroup({ txHash }));
if (result.isOk()) {
const group = result.value;
console.log('Group created:', group.address);
// Join group
await joinGroup(sessionClient, {
group: group.address,
})
.andThen(handleOperationWith(walletClient))
.andThen(sessionClient.waitForTransaction);
// Fetch group members
const membersResult = await fetchGroupMembers(sessionClient, {
group: group.address,
});
console.log('Members:', membersResult.value?.items.length);
}
```
--------------------------------
### Push Git Tags Including Changeset Tags
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Pushes all local Git tags, including those generated by Changesets for versioning, to the remote repository. This ensures the tags are available for others and for CI/CD.
```bash
git push --follow-tags
```
--------------------------------
### Create Post with useCreatePost Hook (React)
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
A React hook for creating posts. It manages loading states and errors, and requires wallet client integration. It takes metadata (e.g., textOnly, image) and returns the creation result.
```typescript
import { useCreatePost } from '@lens-protocol/react';
import { textOnly, image } from '@lens-protocol/metadata';
import { useWalletClient } from 'wagmi';
import { handleOperationWith } from '@lens-protocol/client/viem';
function CreatePostForm() {
const { data: wallet } = useWalletClient();
const { execute: createPost, loading, data, error } = useCreatePost({
handler: handleOperationWith(wallet),
});
const [content, setContent] = React.useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const metadata = textOnly({ content });
const contentUri = `data:application/json,${encodeURIComponent(JSON.stringify(metadata))}`;
const result = await createPost({ contentUri });
if (result.isOk()) {
console.log('Post created:', result.value);
setContent('');
} else {
console.error('Failed to create post:', result.error);
}
};
return (
);
}
```
--------------------------------
### Batch Multiple Queries - Lens Protocol
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
Execute multiple queries in a single network request to improve performance. Demonstrates batching account, posts, and followers queries, as well as complex operations with authentication and timeline data.
```typescript
import { fetchAccount, fetchPosts, fetchFollowers } from '@lens-protocol/client';
// Batch multiple queries
const result = await sessionClient.batch((client) => [
fetchAccount(client, {
address: '0x1234567890123456789012345678901234567890',
}),
fetchPosts(client, {
filter: { searchQuery: 'blockchain' },
}),
fetchFollowers(client, {
account: '0x1234567890123456789012345678901234567890',
}),
]);
if (result.isOk()) {
const [accountResult, postsResult, followersResult] = result.value;
if (accountResult.isOk()) {
console.log('Account:', accountResult.value.username?.value);
}
if (postsResult.isOk()) {
console.log('Posts found:', postsResult.value.items.length);
}
if (followersResult.isOk()) {
console.log('Followers:', followersResult.value.items.length);
}
} else {
console.error('Batch operation failed:', result.error);
}
// Batch with complex operations
const batchResult = await sessionClient.batch((c) => [
c.fetchAuthenticatedUser(),
c.fetchTimeline({ pageSize: 10 }),
c.fetchNotifications({ pageSize: 5 }),
c.fetchAccountStats({ account: c.address }),
]);
```
--------------------------------
### Compile Lens SDK Code
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Compiles the TypeScript code for the Lens SDK project, generating JavaScript output for distribution and execution.
```bash
pnpm build
```
--------------------------------
### handleOperationWith - Viem Transaction Handler with Paymaster
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
Integrates Viem wallet client to handle blockchain transactions with automatic paymaster support for three transaction types: delegated (instant), sponsored (paymaster covers gas), and self-funded (user pays gas). Provides chainable error handling and transaction confirmation with support for zkSync testnet.
```typescript
import { handleOperationWith } from '@lens-protocol/client/viem';
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { zkSyncSepoliaTestnet } from 'viem/chains';
const account = privateKeyToAccount('0xPrivateKey');
const walletClient = createWalletClient({
account,
chain: zkSyncSepoliaTestnet,
transport: http(),
});
const result = await post(sessionClient, {
contentUri: 'data:application/json,...',
})
.andThen(handleOperationWith(walletClient))
.andThen(sessionClient.waitForTransaction)
.andThen((txHash) => {
console.log('Transaction confirmed:', txHash);
return sessionClient.fetchPost({ txHash });
});
const createPostWithHandler = async (contentUri: string) => {
return post(sessionClient, { contentUri })
.andThen(handleOperationWith(walletClient))
.match(
async (txHash) => {
const txResult = await sessionClient.waitForTransaction(txHash);
return txResult.match(
(confirmedTxHash) => ({ success: true, txHash: confirmedTxHash }),
(error) => ({ success: false, error: 'Transaction failed' })
);
},
(error) => ({ success: false, error: error.message })
);
};
```
--------------------------------
### Create Unauthenticated Lens Client (TypeScript)
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
Initializes a public client for read-only operations on the Lens Protocol. This client does not require authentication and is the primary entry point for SDK interactions. It takes configuration options like environment, origin, and storage. It can then be used to fetch public account details or posts.
```typescript
import { PublicClient, mainnet } from '@lens-protocol/client';
const client = PublicClient.create({
environment: mainnet, // or testnet
origin: 'https://myapp.com',
storage: window.localStorage,
});
// Fetch a public account
const result = await client.fetchAccount({
address: '0x1234567890123456789012345678901234567890',
});
if (result.isOk()) {
console.log(`Account: ${result.value.username?.value}`);
console.log(`Followers: ${result.value.stats.followers}`);
} else {
console.error('Failed to fetch account:', result.error.message);
}
// Fetch posts with pagination
const postsResult = await client.fetchPosts({
filter: {
searchQuery: 'defi',
},
pageSize: 10,
});
```
--------------------------------
### Follow/Unfollow Accounts and Fetch Follow Status on Lens Protocol
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
Manages follow relationships between accounts on Lens Protocol. It includes functions to check if an account is followed, to follow an account, and to unfollow an account. It also demonstrates fetching a list of followers and following lists for a given account. Requires sessionClient and walletClient.
```typescript
import { follow, unfollow, fetchFollowStatus } from '@lens-protocol/client';
import { handleOperationWith } from '@lens-protocol/client/viem';
const targetAccount = '0x1234567890123456789012345678901234567890';
// Check follow status first
const statusResult = await fetchFollowStatus(sessionClient, {
account: targetAccount,
});
if (statusResult.isOk() && !statusResult.value.isFollowedByMe) {
// Follow the account
const followResult = await follow(sessionClient, {
account: targetAccount,
})
.andThen(handleOperationWith(walletClient))
.andThen(sessionClient.waitForTransaction);
if (followResult.isOk()) {
console.log('Successfully followed account');
}
}
// Unfollow
const unfollowResult = await unfollow(sessionClient, {
account: targetAccount,
})
.andThen(handleOperationWith(walletClient))
.andThen(sessionClient.waitForTransaction);
// Fetch followers
const followersResult = await sessionClient.fetchFollowers({
account: targetAccount,
pageSize: 20,
});
// Fetch following
const followingResult = await sessionClient.fetchFollowing({
account: targetAccount,
});
```
--------------------------------
### Bump Package Version and Update Changelog
Source: https://github.com/lens-protocol/lens-sdk/blob/main/README.md
Uses `pnpm changeset version` to automatically increment package versions and update the changelog within the Lens SDK project. This is part of the release process.
```bash
pnpm changeset version
```
--------------------------------
### Fetch Account Data with useAccount and useAccounts Hooks (React)
Source: https://context7.com/lens-protocol/lens-sdk/llms.txt
React hooks for retrieving Lens Protocol account data. `useAccount` fetches a single account's details, supporting suspense. `useAccounts` fetches multiple accounts based on provided addresses. Both include loading and error states.
```typescript
import { useAccount, useAccounts } from '@lens-protocol/react';
function ProfileCard({ address }: { address: string }) {
const { data: account, loading, error } = useAccount({
address,
suspense: false,
});
if (loading) return