Интеграция с Lens Protocol
Lens Protocol — децентрализованный social graph на Polygon. Ваше приложение становится одним из клиентов единого протокола: пользователи приносят свой профиль, подписчиков и контент из других Lens-совместимых приложений. Это network effect без необходимости строить социальный граф с нуля.
Что такое Lens Protocol
Lens работает на принципе: пользователь владеет своим социальным графом как NFT. Profile — это ERC-721, Follow — ERC-721 от каждого подписчика. Публикации, зеркала, комментарии — on-chain транзакции (но газ может быть sponsored).
Ключевые компоненты:
- LensHub — главный контракт, управляет профилями и публикациями
- Open Action Modules — кастомные действия при collect/interact (монетизация)
- Follow Modules — логика подписки (платная, с NFT-gate, etc.)
- Lens API — GraphQL API для индексированных данных
Настройка SDK
import { LensClient, production, SessionType } from "@lens-protocol/client";
import { providers } from "ethers";
const lensClient = new LensClient({
environment: production,
});
// Аутентификация через кошелёк
async function authenticateWithLens(
walletClient: WalletClient,
address: string
): Promise<void> {
const profileManaged = await lensClient.profile.fetchAll({
where: { ownedBy: [address] },
});
if (profileManaged.items.length === 0) {
throw new Error("No Lens profile found");
}
const profile = profileManaged.items[0];
// Login создаёт сессию с EIP-712 подписью
const session = await lensClient.login({
onboardingUser: {
app: process.env.LENS_APP_ADDRESS!,
wallet: walletClient,
},
});
}
Основные операции
Лента публикаций
// Получение feed для пользователя (публикации тех на кого он подписан)
const feed = await lensClient.feed.fetch({
where: {
for: profileId,
},
limit: LimitType.TwentyFive,
});
// Получение публикаций конкретного профиля
const publications = await lensClient.publication.fetchAll({
where: {
from: [profileId],
publicationTypes: [PublicationType.Post],
},
orderBy: PublicationsOrderByType.Latest,
});
// Пагинация
if (publications.pageInfo.next) {
const nextPage = await lensClient.publication.fetchAll({
where: { from: [profileId] },
cursor: publications.pageInfo.next,
});
}
Публикация с изображением
import { image } from "@lens-protocol/metadata";
import { StorageClient } from "@lens-protocol/storage-node-client";
const storageClient = StorageClient.create();
async function postWithImage(
file: File,
caption: string
): Promise<string> {
// Загружаем изображение на IPFS через Lens storage
const imageResult = await storageClient.uploadFile(file);
// Создаём metadata
const metadata = image({
title: caption,
image: {
item: imageResult.uri,
type: MediaImageMimeType.Jpeg,
},
content: caption,
locale: "en",
tags: ["photography"],
});
// Загружаем metadata
const metadataResult = await storageClient.uploadAsJson(metadata);
// Публикуем
const result = await sessionClient.publication.postOnchain({
contentURI: metadataResult.uri,
});
return result.id;
}
Follow и проверка подписки
// Подписаться
const followResult = await sessionClient.follow.follow({
follow: [{ profileId: targetProfileId }],
});
// Проверить подписку
const isFollowing = await lensClient.profile.following({
for: followerProfileId,
});
const isFollowingTarget = isFollowing.items.some(
p => p.id === targetProfileId
);
// Список подписчиков профиля
const followers = await lensClient.profile.followers({
of: profileId,
limit: LimitType.Fifty,
});
Open Actions (collect, tip)
// Collect публикации
const collectResult = await sessionClient.publication.actions.actOn({
actOn: { simpleCollectOpenAction: true },
for: publicationId,
});
// Кастомный tip через Open Action
const tipResult = await sessionClient.publication.actions.actOn({
actOn: {
unknownOpenAction: {
address: TIP_ACTION_MODULE_ADDRESS,
data: encodeAbiParameters(
[{ type: "address" }, { type: "uint256" }],
[recipient, tipAmount]
),
},
},
for: publicationId,
});
Уведомления
// Уведомления для пользователя (mentions, follows, collects)
const notifications = await lensClient.notifications.fetch({
where: {
publishedOn: [process.env.LENS_APP_ADDRESS!],
},
});
for (const notification of notifications.items) {
switch (notification.__typename) {
case "FollowNotification":
console.log(`New follower: ${notification.followers[0].handle?.fullHandle}`);
break;
case "CommentNotification":
console.log(`New comment on ${notification.publication.id}`);
break;
case "MentionNotification":
console.log(`Mentioned in ${notification.publication.id}`);
break;
case "ActedNotification":
console.log(`Someone collected ${notification.publication.id}`);
break;
}
}
Создание профиля
// Создание нового Lens профиля
const createProfileResult = await lensClient.wallet.createProfileWithHandle({
handle: "myhandle",
to: walletAddress,
});
// Обновление метаданных профиля
const profileMetadata = profile({
name: "Alice",
bio: "Web3 developer and creator",
picture: "ipfs://QmAvatarCID",
coverPicture: "ipfs://QmCoverCID",
attributes: [
{ key: "twitter", value: "@alice", type: MetadataAttributeType.String },
{ key: "website", value: "https://alice.xyz", type: MetadataAttributeType.String },
],
});
const metadataURI = await storageClient.uploadAsJson(profileMetadata);
await sessionClient.profile.setProfileMetadata({
metadataURI,
});
Lens + TheGraph для кастомных queries
Lens предоставляет свой API, но для специфических queries можно обращаться к TheGraph напрямую:
import { createClient } from "@urql/core";
const LENS_SUBGRAPH = "https://api.thegraph.com/subgraphs/name/lens-protocol/lens-polygon-mainnet";
const client = createClient({ url: LENS_SUBGRAPH });
// Топ авторы по collect count за последние 7 дней
const TOP_CREATORS = `
query TopCreators($since: Int!) {
publications(
where: { timestamp_gt: $since, collectCount_gt: 10 }
orderBy: collectCount
orderDirection: desc
first: 20
) {
id
profile {
handle
followersCount
}
collectCount
metadata {
content
}
}
}
`;
const weekAgo = Math.floor(Date.now() / 1000) - 7 * 24 * 3600;
const result = await client.query(TOP_CREATORS, { since: weekAgo }).toPromise();
Интеграция Lens Protocol в существующее приложение — 2-4 недели. Включает: настройку SDK, основные CRUD операции (профиль, посты, follows), notifications и UI компоненты. Lens снимает с вас задачу построения социального графа — вы получаете готовую аудиторию экосистемы.







