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

Add slack stats to web faucet #38

Merged
merged 7 commits into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
6 changes: 3 additions & 3 deletions .vscode/faucet.code-workspace
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@
],
"settings": {
"editor.codeActionsOnSave": {
"source.sortImports": true,
"source.fixAll.eslint": true,
"source.fixAll.tslint": true
"source.sortImports": "explicit",
"source.fixAll.eslint": "explicit",
"source.fixAll.tslint": "explicit"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"javascript.updateImportsOnFileMove.enabled": "always",
Expand Down
6 changes: 3 additions & 3 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"editor.codeActionsOnSave": {
"source.sortImports": true,
"source.fixAll.eslint": true,
"source.fixAll.tslint": true
"source.sortImports": "explicit",
"source.fixAll.eslint": "explicit",
"source.fixAll.tslint": "explicit"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"javascript.updateImportsOnFileMove.enabled": "always",
Expand Down
22 changes: 20 additions & 2 deletions web-app/src/pages/api/requestTokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Client, FaunaHttpErrorResponseContent, query as faunaQuery } from 'faun
import { NextApiRequest, NextApiResponse } from 'next'
import { contracts } from '../../constants/contracts'
import { networks } from '../../constants/networks'
import { createStats, findStats, updateStats } from '../../utils'
import { buildSlackStatsMessage, createStats, findStats, sendSlackMessage, updateStats } from '../../utils'

type AccountType = 'github' | 'discord'

Expand Down Expand Up @@ -69,9 +69,27 @@ const incrementFaucetRequestsCount = async (address: string, accountType: Accoun
const stats = await findStats(requestDate)
console.log('stats', stats)
if (!stats || stats === null || stats.length === 0) {
await createStats(address, accountType, requestDate)
const slackMessageId = await sendSlackMessage(
'Current week evm-faucet requests',
buildSlackStatsMessage('update', 1, 1)
)
await createStats(address, accountType, slackMessageId, requestDate)
} else {
const statsFound = stats[0].data
const isExistingAddresses = statsFound.addresses.find((a: string) => a === address)
await sendSlackMessage(
'Current week evm-faucet requests',
buildSlackStatsMessage(
'update',
statsFound.requests + 1,
isExistingAddresses ? statsFound.uniqueAddresses : statsFound.uniqueAddresses + 1,
{
...statsFound.requestsByType,
[accountType]: statsFound.requestsByType[accountType] ? statsFound.requestsByType[accountType] + 1 : 1
}
),
statsFound.slackMessageId
)
await updateStats(stats[0].ref, accountType, statsFound, address)
}
}
Expand Down
9 changes: 7 additions & 2 deletions web-app/src/utils/fauna.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@ export const findStats = async (
return stats
}

export const createStats = async (address: string, accountType: string, requestDate: string) => {
export const createStats = async (
address: string,
accountType: string,
slackMessageId: string | undefined,
requestDate: string
) => {
await faunaDbClient
.query(
faunaQuery.Create(faunaQuery.Ref('classes/stats'), {
Expand All @@ -97,7 +102,7 @@ export const createStats = async (address: string, accountType: string, requestD
[accountType]: 1
},
requestDate,
slackMessageId: '',
slackMessageId: slackMessageId || '',
createdAt: faunaQuery.Now()
}
})
Expand Down
1 change: 1 addition & 0 deletions web-app/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './fauna'
export * from './slack'
export * from './time'
151 changes: 151 additions & 0 deletions web-app/src/utils/slack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
interface SlackBlock {
type: string
text: {
type: string
text: string
}
}

interface RequestsByType {
[key: string]: number
}

interface SlackPayload {
channel: string
text: string
blocks: SlackBlock[]
ts?: string
}

export const sendSlackMessage = async (
message: string,
blocks: SlackBlock[],
messageIdToEdit?: string
): Promise<string | undefined> => {
if (process.env.SLACK_ENABLED) {
const token = process.env.SLACK_TOKEN || ''
const conversationId = process.env.SLACK_CONVERSATION_ID || ''
const url = messageIdToEdit ? 'https://slack.com/api/chat.update' : 'https://slack.com/api/chat.postMessage'

const payload: SlackPayload = {
channel: conversationId,
text: message,
blocks: blocks
}

if (messageIdToEdit) {
payload.ts = messageIdToEdit
}

try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(payload)
})

const data = await response.json()

if (!data.ok) {
throw new Error(data.error)
}

return data.ts || undefined
} catch (e) {
console.error('Error sending slack message', e)
}
}
}

export const buildSlackStatsMessage = (
type: 'weekRecap' | 'update',
requestCount: number,
uniqueAddresses: number,
requestsByType?: RequestsByType
): SlackBlock[] => {
const blocks: SlackBlock[] = [
{
type: 'header',
text: {
type: 'plain_text',
text: 'Faucet stats'
}
}
]

switch (type) {
case 'weekRecap':
blocks.push(
{
type: 'section',
text: {
type: 'mrkdwn',
text: `This week total requests: ${requestCount} :subspace-hype:`
}
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `Unique addresses: ${uniqueAddresses} :subheart-white:`
}
}
)
break

case 'update':
blocks.push(
{
type: 'section',
text: {
type: 'mrkdwn',
text: `Current total requests: ${requestCount} ${
requestCount > 100 ? ':subspace-hype:' : ':subheart-black:'
}`
}
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `Unique addresses: ${uniqueAddresses} :subheart-white:`
}
}
)
if (requestsByType) {
blocks.push({
type: 'section',
text: {
type: 'mrkdwn',
text: `Requests by type:\n\`\`\`${JSON.stringify(requestsByType, null, 2)}\`\`\``
}
})
}
break
}

return blocks
}

export const faucetBalanceLowSlackMessage = async (balance: string) => {
const blocks: SlackBlock[] = [
{
type: 'header',
text: {
type: 'plain_text',
text: 'Faucet balance is low'
}
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `The faucet balance is ${balance} ${process.env.TOKEN_SYMBOL}, please refill the faucet.`
}
}
]
await sendSlackMessage('Faucet balance low', blocks)
}
Loading