Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add direct calls stats for protocol users #158

Merged
merged 7 commits into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fast-turtles-brush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"stackspulse": minor
---

Send weekly tweet reply to direct calls made to protocols.
5 changes: 5 additions & 0 deletions .changeset/twenty-days-pull.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"stackspulse": minor
---

Allow users to select direct / nested for the protocols users chart.
5 changes: 5 additions & 0 deletions .changeset/wise-colts-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@stackspulse/server": minor
---

Accept `mode` param for the protocol users.
2 changes: 1 addition & 1 deletion apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"h3": "1.13.0",
"nitro-cors": "0.7.1",
"postgres": "3.4.5",
"twitter-api-v2": "1.17.1",
"twitter-api-v2": "1.18.2",
"unstorage": "1.13.1",
"zod": "3.23.8",
"zod-validation-error": "3.4.0"
Expand Down
88 changes: 73 additions & 15 deletions apps/server/src/api/protocols/users/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import type { Protocol } from "@stackspulse/protocols";
import type postgres from "postgres";
import { z } from "zod";
import { sql } from "~/db/db";
import { apiCacheConfig } from "~/lib/api";
import { getValidatedQueryZod } from "~/lib/nitro";

const protocolUsersRouteSchema = z.object({
mode: z.enum(["direct", "nested"]).optional(),
date: z.enum(["7d", "30d", "all"]),
limit: z.coerce.number().min(1).max(100).optional(),
});
Expand All @@ -17,16 +19,77 @@ export type ProtocolUsersRouteResponse = {
export default defineCachedEventHandler(async (event) => {
const query = await getValidatedQueryZod(event, protocolUsersRouteSchema);
const limit = query.limit || 10;
const mode = query.mode || "nested";
const daysToSubtractMap = {
all: undefined,
"7d": 7,
"30d": 30,
};
const daysToSubtract = daysToSubtractMap[query.date];

let result: postgres.Row[];
if (mode === "direct") {
result = await getProtocolUsersDirect({
limit,
daysToSubtract,
});
} else {
result = await getProtocolUsersNested({
limit,
daysToSubtract,
});
}

const stats: ProtocolUsersRouteResponse = result.map((stat) => ({
protocol_name: stat.protocol_name as Protocol,
unique_senders: Number.parseInt(stat.unique_senders),
}));

return stats;
}, apiCacheConfig);

interface QueryParams {
limit: number;
daysToSubtract?: number;
}

const getProtocolUsersDirect = async ({
limit,
daysToSubtract,
}: QueryParams) => {
let dateCondition = "";
if (daysToSubtract) {
dateCondition = `AND txs.block_time >= EXTRACT(EPOCH FROM (NOW() - INTERVAL '${daysToSubtract} days'))`;
}

const result = await sql`
SELECT
dapps.id as protocol_name,
COUNT(DISTINCT txs.sender_address) AS unique_senders
FROM
txs
JOIN
dapps ON txs.contract_call_contract_id = ANY (dapps.contracts)
WHERE
txs.type_id = 2
${sql.unsafe(dateCondition)}
GROUP BY
dapps.id
ORDER BY
unique_senders DESC
LIMIT ${limit};
`;

return result;
};

const getProtocolUsersNested = async ({
limit,
daysToSubtract,
}: QueryParams) => {
let dateCondition = "";
if (query.date !== "all") {
const daysToSubtract = {
"7d": 7,
"30d": 30,
};
dateCondition = `AND txs.block_time >= EXTRACT(EPOCH FROM (NOW() - INTERVAL '${
daysToSubtract[query.date]
} days'))`;
if (daysToSubtract) {
dateCondition = `AND txs.block_time >= EXTRACT(EPOCH FROM (NOW() - INTERVAL '${daysToSubtract} days'))`;
}

const result = await sql`
Expand Down Expand Up @@ -84,10 +147,5 @@ ORDER BY
LIMIT ${limit};
`;

const stats: ProtocolUsersRouteResponse = result.map((stat) => ({
protocol_name: stat.protocol_name as Protocol,
unique_senders: Number.parseInt(stat.unique_senders),
}));

return stats;
}, apiCacheConfig);
return result;
};
62 changes: 53 additions & 9 deletions apps/server/src/api/root/tweet-weekly-users/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,79 @@ import { sendTweet } from "~/lib/twitter";
export default defineEventHandler(async () => {
const apiParams = new URLSearchParams();
apiParams.append("noCache", "true");
apiParams.append("mode", "nested");
apiParams.append("date", "7d");
apiParams.append("limit", "5");

const stats: ProtocolUsersRouteResponse = await fetch(
// Get stats with nested mode
console.log("Getting stats with nested mode...", apiParams.toString());
const statsNested: ProtocolUsersRouteResponse = await fetch(
`${env.API_URL}/api/protocols/users?${apiParams.toString()}`,
).then((res) => res.json());

const data = stats.map((stat) => ({
const dataNested = statsNested.map((stat) => ({
name: protocolsInfo[stat.protocol_name].name,
value: stat.unique_senders,
}));

// Get stats with direct mode
apiParams.set("mode", "direct");
console.log("Getting stats with direct mode...", apiParams.toString());
const statsDirect: ProtocolUsersRouteResponse = await fetch(
`${env.API_URL}/api/protocols/users?${apiParams.toString()}`,
).then((res) => res.json());

const dataDirect = statsDirect.map((stat) => ({
name: protocolsInfo[stat.protocol_name].name,
value: stat.unique_senders,
}));

// Generate nested tweet
const params = new URLSearchParams();
params.append("title", "Last 7 Days Unique Users");
params.append("data", JSON.stringify(data));
params.append("data", JSON.stringify(dataNested));

const imageUrlNested = `${
env.WEB_URL
}/api/images/weekly-users?${params.toString()}`;

let messageNested = "📈 Last 7 days unique users:\n\n";
for (const stat of statsNested) {
messageNested += `\n- @${protocolsInfo[stat.protocol_name].x.replace(
"https://twitter.com/",
"",
)}: ${stat.unique_senders.toLocaleString("en-US")} users`;
}

const nestedTweetId = await sendTweet({
message: messageNested,
images: [imageUrlNested],
});
console.log("Nested tweet id:", nestedTweetId);

// Generate direct tweet
params.set("title", "Last 7 Days Direct Unique Users");
params.set("data", JSON.stringify(dataDirect));

const imageUrl = `${
const imageUrlDirect = `${
env.WEB_URL
}/api/images/weekly-users?${params.toString()}`;

let message = "📈 Last 7 days unique users:\n\n";
for (const stat of stats) {
message += `\n- @${protocolsInfo[stat.protocol_name].x.replace(
let messageDirect =
"📈 Last 7 days unique users that interacted directly with the protocols:\n\n";
for (const stat of statsDirect) {
messageDirect += `\n- @${protocolsInfo[stat.protocol_name].x.replace(
"https://twitter.com/",
"",
)}: ${stat.unique_senders.toLocaleString("en-US")} users`;
}

const tweetId = await sendTweet({ message, images: [imageUrl] });
const directTweetId = await sendTweet({
message: messageDirect,
images: [imageUrlDirect],
in_reply_to_tweet_id: nestedTweetId,
});
console.log("Direct tweet id:", directTweetId);

return { ok: true, tweetId };
return { ok: true, nestedTweetId, directTweetId };
});
7 changes: 5 additions & 2 deletions apps/server/src/lib/twitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ const twitterClient = new TwitterApi({
export const sendTweet = async ({
message,
images,
in_reply_to_tweet_id,
}: {
message: string;
images?: string[];
in_reply_to_tweet_id?: string;
}) => {
if (env.TWITTER_API_KEY === "dev") {
console.log("Debug Send Tweet:\n", message);
Expand All @@ -29,11 +31,12 @@ export const sendTweet = async ({
});
}),
)
: [];
: undefined;

const data = await twitterClient.v2.tweet({
text: message,
media: { media_ids: mediaIds },
media: { media_ids: mediaIds as [string, string] },
reply: in_reply_to_tweet_id ? { in_reply_to_tweet_id } : undefined,
});

return data.data.id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import { protocolsInfo } from "@stackspulse/protocols";

interface TopProtocolsBarListClientProps {
dateFilter: ProtocolUsersRouteQuery["date"];
modeFilter: ProtocolUsersRouteQuery["mode"];
}

export const TopProtocolsBarListQuery = ({
dateFilter,
modeFilter,
}: TopProtocolsBarListClientProps) => {
const { data: stats } = useGetProtocolsUsers({
date: dateFilter,
mode: modeFilter,
limit: 6,
});

Expand Down
69 changes: 48 additions & 21 deletions apps/web/src/components/Stats/TopProtocolsBarList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,54 @@ import { TopProtocolsBarListQuery } from "./TopProtocolsBarListQuery";
export const TopProtocolsBarList = () => {
const [dateFilter, setDateFilter] =
useState<ProtocolUsersRouteQuery["date"]>("all");
const [modeFilter, setModeFilter] =
useState<ProtocolUsersRouteQuery["mode"]>("nested");

return (
<Card size="2" className="mt-5">
<div className="-mt-2 flex items-center justify-between">
<Text as="div" size="2" weight="medium" color="gray" highContrast>
Top Stacks protocols
</Text>
<TabNav.Root size="2">
<TabNav.Link asChild active={dateFilter === "7d"}>
<button type="button" onClick={() => setDateFilter("7d")}>
7d
</button>
</TabNav.Link>
<TabNav.Link asChild active={dateFilter === "30d"}>
<button type="button" onClick={() => setDateFilter("30d")}>
30d
</button>
</TabNav.Link>
<TabNav.Link asChild active={dateFilter === "all"}>
<button type="button" onClick={() => setDateFilter("all")}>
all
</button>
</TabNav.Link>
</TabNav.Root>
<div>
<Text as="div" size="2" weight="medium" color="gray" highContrast>
Top Stacks protocols
</Text>
<Text as="div" size="1" color="gray" className="mt-1">
{modeFilter === "nested"
? "Unique addresses that have interacted with the protocol contracts"
: "Unique addresses that have interacted with the protocol directly"}
</Text>
</div>

<div className="flex flex-col justify-end items-end gap-1">
<TabNav.Root size="2">
<TabNav.Link asChild active={dateFilter === "7d"}>
<button type="button" onClick={() => setDateFilter("7d")}>
7d
</button>
</TabNav.Link>
<TabNav.Link asChild active={dateFilter === "30d"}>
<button type="button" onClick={() => setDateFilter("30d")}>
30d
</button>
</TabNav.Link>
<TabNav.Link asChild active={dateFilter === "all"}>
<button type="button" onClick={() => setDateFilter("all")}>
all
</button>
</TabNav.Link>
</TabNav.Root>
<TabNav.Root size="1">
<TabNav.Link asChild active={modeFilter === "direct"}>
<button type="button" onClick={() => setModeFilter("direct")}>
direct
</button>
</TabNav.Link>
<TabNav.Link asChild active={modeFilter === "nested"}>
<button type="button" onClick={() => setModeFilter("nested")}>
nested
</button>
</TabNav.Link>
</TabNav.Root>
</div>
</div>

<div className="mt-4 flex justify-between">
Expand Down Expand Up @@ -77,7 +101,10 @@ export const TopProtocolsBarList = () => {
/>
}
>
<TopProtocolsBarListQuery dateFilter={dateFilter} />
<TopProtocolsBarListQuery
dateFilter={dateFilter}
modeFilter={modeFilter}
/>
</Suspense>
</Card>
);
Expand Down
6 changes: 5 additions & 1 deletion apps/web/src/hooks/api/useGetProtocolsUsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@ import type {
import { useSuspenseQuery } from "@tanstack/react-query";

export const useGetProtocolsUsers = ({
mode,
date,
limit,
}: ProtocolUsersRouteQuery) => {
return useSuspenseQuery<ProtocolUsersRouteResponse>({
queryKey: ["get-protocols-users", date, limit],
queryKey: ["get-protocols-users", mode, date, limit],
queryFn: async () => {
const url = new URL(`${env.NEXT_PUBLIC_API_URL}/api/protocols/users`);
url.searchParams.set("date", date);
if (mode) {
url.searchParams.set("mode", mode);
}
if (limit) {
url.searchParams.set("limit", limit.toString());
}
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type ProtocolUsersRouteResponse = {
}[];

export type ProtocolUsersRouteQuery = {
mode?: "direct" | "nested";
/**
* Date range to query
*/
Expand Down
Loading