Skip to content
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
/src/ai-summary
/src/rf6-data-import
src/rf6-data-import
src/ai-summary-rf5

# Envs

Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,14 @@
"mathjs": "^11.9.1",
"ml-matrix": "^6.10.5",
"node-cron": "^3.0.3",
"openai": "^4.68.4",
"prisma": "^5.0.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
"siwe": "^2.3.2",
"viem": "^2.21.5"
"thirdweb": "^5.64.2",
"viem": "^2.21.5",
"zod": "^3.23.8"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
Expand Down
12 changes: 12 additions & 0 deletions prisma/migrations/20241027180330_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
Warnings:

- A unique constraint covering the columns `[attestation_id]` on the table `UserAttestation` will be added. If there are existing duplicate values, this will fail.
- Added the required column `attestation_id` to the `UserAttestation` table without a default value. This is not possible if the table is not empty.

*/
-- AlterTable
ALTER TABLE "UserAttestation" ADD COLUMN "attestation_id" TEXT NOT NULL;

-- CreateIndex
CREATE UNIQUE INDEX "UserAttestation_attestation_id_key" ON "UserAttestation"("attestation_id");
15 changes: 15 additions & 0 deletions prisma/migrations/20241029125304_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-- CreateTable
CREATE TABLE "UserBudgetAttestation" (
"user_id" INTEGER NOT NULL,
"attestation_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "UserBudgetAttestation_pkey" PRIMARY KEY ("user_id")
);

-- CreateIndex
CREATE UNIQUE INDEX "UserBudgetAttestation_attestation_id_key" ON "UserBudgetAttestation"("attestation_id");

-- AddForeignKey
ALTER TABLE "UserBudgetAttestation" ADD CONSTRAINT "UserBudgetAttestation_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
40 changes: 26 additions & 14 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ generator client {
}

model User {
id Int @id @default(autoincrement())
budget Int @default(2000000) // 2M In OP
address String @unique()
smartaddress String? @unique()
ballotSuccess Int? @map("ballot_success")
opAddress String? @unique() @map("op_address")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
id Int @id @default(autoincrement())
budget Int @default(2000000) // 2M In OP
address String @unique()
smartaddress String? @unique()
ballotSuccess Int? @map("ballot_success")
opAddress String? @unique() @map("op_address")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
identity Json? // Ideally should be unique except {} and null values but Prisma doesn't support partial
// unique constraints
badges Json?
Expand All @@ -29,6 +29,7 @@ model User {
finishedCollection UserCollectionFinish[]
shares Share[]
attestations UserAttestation[]
budgetAttestations UserBudgetAttestation[]
projectStars ProjectStar[]
cois ProjectCoI[]
}
Expand Down Expand Up @@ -201,16 +202,27 @@ model UserCollectionFinish {
}

model UserAttestation {
userId Int @map("user_id")
collectionId Int @map("collection_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id])
collection Project @relation(fields: [collectionId], references: [id])
userId Int @map("user_id")
collectionId Int @map("collection_id")
attestationId String @unique() @map("attestation_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id])
collection Project @relation(fields: [collectionId], references: [id])

@@id([userId, collectionId])
}

model UserBudgetAttestation {
userId Int @map("user_id")
attestationId String @unique() @map("attestation_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id])

@@id([userId])
}

enum DelegationPlatform {
FARCASTER
TWITTER
Expand Down
42 changes: 41 additions & 1 deletion src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { PrismaService } from 'src/prisma.service';
import { Response } from 'express';
import { UsersService } from 'src/user/users.service';
import { AuthGuard } from './auth.guard';
import { LoginDTO } from './dto/login.dto';
import { LoginDTO, ThirdwebLoginDTO } from './dto/login.dto';
import { ApiResponse } from '@nestjs/swagger';
import { AuthedReq } from 'src/utils/types/AuthedReq.type';
import { STAGING_API, generateRandomString } from 'src/utils';
Expand Down Expand Up @@ -125,6 +125,46 @@ export class AuthController {
res.status(200).send({ token, isNewUser });
}

@UseGuards(AuthGuard)
@ApiResponse({ status: 200, description: 'Gets the sa address of a user' })
@Get('/thirdweb/sa-address')
async getSaAddress(@Req() { userId }: AuthedReq) {
const res = await this.prismaService.user.findUnique({
select: { smartaddress: true },
where: {
id: userId,
},
});

return res?.smartaddress || null;
}

@UseGuards(AuthGuard)
@ApiResponse({ status: 200, description: 'Sets an auth cookie' })
@Post('/thirdweb/login')
async loginWithThirdweb(
@Req() { userId }: AuthedReq,
@Body() { message, signature, address }: ThirdwebLoginDTO,
) {
const isAuthentic = await this.authService.verifyThirdwebUser(
message,
signature,
address,
);
if (!isAuthentic) throw new UnauthorizedException('Invalid signature');

await this.prismaService.user.update({
where: {
id: userId,
},
data: {
smartaddress: address,
},
});

return 'Success';
}

// @ApiResponse({
// status: 200,
// type: String,
Expand Down
18 changes: 18 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { generateRandomString } from 'src/utils';
import { PrismaService } from 'src/prisma.service';
import { SiweMessage } from 'siwe';
import { verifyMessage } from 'viem';
import { chain, thirdwebClient } from './thirdweb';
import { verifySignature } from 'thirdweb/auth';
// import { chain, thirdwebClient } from 'src/thirdweb';

@Injectable()
Expand Down Expand Up @@ -140,6 +142,22 @@ export class AuthService {
return user;
};

verifyThirdwebUser = async (
message: string,
signature: string,
address: string,
) => {
const isValid = await verifySignature({
message,
signature,
address,
client: thirdwebClient,
chain,
});

return isValid;
};

verifyUser = async (
message: string,
signature: `0x${string}`,
Expand Down
11 changes: 10 additions & 1 deletion src/auth/dto/login.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { ApiProperty } from '@nestjs/swagger';
import { SiweMessage } from 'siwe';

export class SiweMessageClass {
@ApiProperty({
Expand Down Expand Up @@ -86,3 +85,13 @@ export class LoginDTO {
@ApiProperty()
address: string;
}
export class ThirdwebLoginDTO {
@ApiProperty()
message: string;

@ApiProperty()
signature: string;

@ApiProperty()
address: string;
}
13 changes: 13 additions & 0 deletions src/auth/thirdweb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { createThirdwebClient } from 'thirdweb';
import { optimism, optimismSepolia } from 'thirdweb/chains';

const secretKey = process.env.SECRET_KEY;

if (!secretKey) throw new Error('No Third Web Secret Key');

export const chain =
process.env.ACTIVE_CHAIN === 'optimism' ? optimism : optimismSepolia;

export const thirdwebClient = createThirdwebClient({
secretKey,
});
6 changes: 3 additions & 3 deletions src/cronJobs.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { schedule } from 'node-cron';
import { sendCastsFor12Hours } from './neynar/utils';
import { sendDailyCasts } from './neynar/utils';

const sendCastsCronJobTime = '21 21 0,12 * * *'; // at 00:21 and 12:21 every day
const sendCastsCronJobTime = '21 1 17 * * *'; // at 17:01 every day

export const initializeCronJobs = () => {
sendCastsCronJob();
Expand All @@ -10,7 +10,7 @@ export const initializeCronJobs = () => {
const sendCastsCronJob = () => {
schedule(sendCastsCronJobTime, async () => {
try {
await sendCastsFor12Hours();
await sendDailyCasts();
} catch (e) {
console.error('sendCastsCronJob error', e);
}
Expand Down
12 changes: 12 additions & 0 deletions src/flow/dto/bodies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,15 @@ export const exampleRankingDto = {
],
},
};

export class AttestationDto {
@IsDefined()
@Validate(IsPositiveOrNegativeOneConstraint)
@ApiProperty()
collectionId: number;

@IsString()
@IsDefined()
@ApiProperty()
attestationId: string;
}
16 changes: 11 additions & 5 deletions src/flow/dto/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ export const delegateStatusExample = {
],
},
toYou: {
uniqueCollection: 3,
uniqueCollectionDelegators: 1,
uniqueBudgetDelegators: 3,
budget: [
{
metadata: {
Expand All @@ -158,13 +161,13 @@ export const delegateStatusExample = {
},
{
metadata: {
username: 'some2.eth',
username: 'some.eth',
profileUrl: 'https://example.com/some.png',
},
},
{
metadata: {
username: 'some3.eth',
username: 'some.eth',
profileUrl: 'https://example.com/some.png',
},
},
Expand All @@ -173,14 +176,14 @@ export const delegateStatusExample = {
{
collectionId: 1,
metadata: {
username: 'elon.eth',
username: 'some.eth',
profileUrl: 'https://example.com/elon.png',
},
},
{
collectionId: 1,
collectionId: 2,
metadata: {
username: 'adele.eth',
username: 'some.eth',
profileUrl: 'https://example.com/some.png',
},
},
Expand All @@ -202,6 +205,9 @@ export const delegateStatusExample2 = {
],
},
toYou: {
uniqueCollection: 0,
uniqueCollectionDelegators: 0,
uniqueBudgetDelegators: 0,
budget: [],
collections: [],
},
Expand Down
Loading
Loading