Інтеграція Lens Protocol
Lens Protocol—децентралізований соціальний граф на Polygon. Ваш додаток стає одним з клієнтів єдиного протоколу: користувачі приносять свій профіль, послідовників та контент з інших сумісних з Lens додатків. Цей мережевий ефект без необхідності будувати соціальний граф з нуля.
Що таке Lens Protocol
Lens працює за принципом: користувач володіє своїм соціальним графом як NFT. Профіль—це ERC-721, Follow—ERC-721 від кожного послідовника. Публікації, дзеркала, коментарі—on-chain транзакції (але газ може бути спонсорований).
Ключові компоненти:
- LensHub—основний контракт, управляє профілями та публікаціями
- Open Action Modules—користувацькі дії при collect/взаємодії (монетизація)
- Follow Modules—логіка підписки (платна, NFT-gate тощо)
- 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,
},
});
}
Основні операції
Стрічка публікацій
// Отримати стрічку для користувача (публікації від тих, за ким вони слідкують)
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);
// Створити метаданні
const metadata = image({
title: caption,
image: {
item: imageResult.uri,
type: MediaImageMimeType.Jpeg,
},
content: caption,
locale: "en",
tags: ["photography"],
});
// Завантажити метаданні
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)
// Зібрати публікацію
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,
});
Сповіщення
// Сповіщення для користувача (згадування, підписки, колекції)
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 для користувацьких запитів
Lens надає власний API, але для конкретних запитів можна звернутися до 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 });
// Топ авторів за кількістю колекцій за останні 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 (профіль, пости, підписки), сповіщення та UI компоненти. Lens знімає з вас завдання побудови соціального графа—ви отримуєте готову аудиторію екосистеми.







