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

merge: prod #74

Merged
merged 4 commits into from
Aug 2, 2023
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
52 changes: 35 additions & 17 deletions src/services/apecoin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import axios from 'axios';
import pool from '../../config/database-config';
import { Client, Intents } from 'discord.js';
import getTokenBalance from '../../utils/get-token-balance';
import { BulkWriter } from '../bulk-writer';

const ROLE_NAME = 'Assembly';

Expand All @@ -24,23 +25,32 @@ async function fetchDaoData() {
}

async function fetchDelegates(daoName: string, publicAddress?: string) {
const delegateQuery = `
SELECT "t1"."discordHandle",
"u"."publicAddress",
"t2"."offChainVotesPct",
"t1"."snapshotDelegatedVotes" as "balance",
"t3"."handle"
const params: any[] = [daoName];

let delegateQuery = `
SELECT
"t1"."id",
"t1"."discordHandle",
"u"."publicAddress",
"t2"."offChainVotesPct",
"t1"."snapshotDelegatedVotes" as "balance",
"t3"."handle"
FROM "Delegate" AS t1
INNER JOIN "User" as u on "t1"."userId" = "u"."id"
INNER JOIN "DelegateStat" AS t2 ON "t1"."id" = "t2"."delegateId"
LEFT JOIN "DelegateDiscourseEth" AS t3 ON "t1"."id" = "t3"."delegateId"
WHERE "t1"."daoName" = $1
AND "t2"."period" = '1y'
AND "t1"."discordHandle" IS NOT NULL
${publicAddress ? `AND "u"."publicAddress" = $2` : ''}
`;

if (publicAddress) {
params.push(publicAddress);
delegateQuery += ` AND "u"."publicAddress" = $2`;
}

try {
const result = await pool.query(delegateQuery, [daoName, publicAddress]);
const result = await pool.query(delegateQuery, params);
return result?.rows;
} catch (err) {
console.error('Error fetching delegates:', err);
Expand Down Expand Up @@ -84,22 +94,30 @@ async function manageRoles(client: Client, guildId: string, handles: any[], acti
const role = guild.roles.cache.find((role) => role.name === ROLE_NAME);

if (!role) throw new Error('Role not found');
const sucessHandles = [];

for (const handle of handles) {
const member = await guild.members.fetch(handle.discordHandle).catch(console.error);

if (member) {
await member.roles[action](role).catch(console.error);
console.log(
`Role: ${role.name} | action: ${action} | user: ${member.user.tag} | address: ${handle.publicAddress} | offChain: ${handle.offChainVotesPct} | balance: ${handle.balance} | forumLevel: ${handle.trustLevel} | hasCriterea: ${handle.hasPermission}`
);
try {
const member = await guild.members.fetch(handle.discordHandle).catch(() => null);

if (member) {
await member.roles[action](role);
console.log(
`Role: ${role.name} | action: ${action} | user: ${member.user.tag} | address: ${handle.publicAddress} | offChain: ${handle.offChainVotesPct} | balance: ${handle.balance} | forumLevel: ${handle.trustLevel} | hasCriterea: ${handle.hasPermission}`
);
sucessHandles.push(handle);
}
} catch (err) {
console.log(err);
}
}

const BulkWriterClient = new BulkWriter();
await BulkWriterClient.updateRolesLogs(action, sucessHandles, ROLE_NAME);
}

export async function discordRoleManager(daoName?: string, publicAddress?: string) {
export async function discordRoleManager(_?: string, publicAddress?: string) {
const dao = await fetchDaoData();

const delegates = await fetchDelegates(dao.name, publicAddress);

if (!delegates?.length) return console.log('No delegates found');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import pool from '../config/database-config';

const BULK_SIZE = 1000;
Expand All @@ -11,7 +12,7 @@ export interface Message {
messageType: string;
}

export class MessageBulkWriter {
export class BulkWriter {
private messages: Message[] = [];
private messageCount = 0;
private messageInsertCount = 0;
Expand Down Expand Up @@ -51,4 +52,29 @@ export class MessageBulkWriter {

await pool.query(sql);
}

async updateRolesLogs(action: string, delegates: any[], role: string) {
const integration = 'discord';
const description = 'discord role';
const dateNow = Date.now();

const insertValues = delegates
.map(
(d) =>
`('${d.id}', '${integration}', '${description}', '${role.toLowerCase()}', '${dateNow}')`
)
.join(',');

const sql =
action === 'add'
? `INSERT INTO "DelegateIntegrations" ("delegateId", "integration", "description", "attribute", "issuedAt") VALUES ${insertValues}
ON CONFLICT ("delegateId", "integration", "attribute")
DO UPDATE SET "issuedAt" = CASE WHEN "DelegateIntegrations"."issuedAt" IS NULL THEN '${dateNow}'
ELSE "DelegateIntegrations"."issuedAt" END`
: `UPDATE "DelegateIntegrations" SET "issuedAt" = null
WHERE "delegateId" IN (${delegates.map((d) => d.id as number).join(', ')})
AND "attribute" = '${role.toLowerCase()}' `;

await pool.query(sql);
}
}
4 changes: 2 additions & 2 deletions src/services/get-messages.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Client } from 'discord.js';
import { delay } from '../utils/delay';
import dotenv from 'dotenv';
import { LastMessageIdGetterService } from './last-message-id-getter.service';
import { Message, MessageBulkWriter } from './message-bulk-writer';
import { Message, BulkWriter } from './bulk-writer';
import { DiscordSQSMessage } from '../@types/discord-message-update';
import _ from 'lodash';
import { DelegateStatUpdateProducerService } from './delegate-stat-update-producer/delegate-stat-update-producer.service';
Expand Down Expand Up @@ -47,7 +47,7 @@ interface MessageCustom extends Message {
export default class GetPastMessagesService {
constructor(
private readonly getMessageService = new LastMessageIdGetterService(),
private readonly messageBulkWriter = new MessageBulkWriter(),
private readonly messageBulkWriter = new BulkWriter(),
private readonly delegateStatUpdateProducerService = new DelegateStatUpdateProducerService()
) {}

Expand Down
Loading