Skip to content
This repository has been archived by the owner on Jul 25, 2024. It is now read-only.

Backend features #2

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema

# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL="postgresql://validatorinfo:password@localhost:5432/mydb?schema=public"
18 changes: 18 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
create-deps:
docker run --rm --name postgres -p "5432:5432" -e POSTGRES_DB=validatorinfo -e POSTGRES_USER=validatorinfo -e POSTGRES_PASSWORD=password -d "postgres:14-bullseye"
@sleep 5

destroy-deps:
docker rm -f postgres

deploy-migrations:
npx prisma migrate deploy

init-chains:
yarn ts-node-esm src/tools/chains/init-chains.ts

generate-schema:
npx prisma migrate dev

start-indexer:
yarn ts-node-esm server/server.ts
11 changes: 10 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,34 @@
"lint": "next lint"
},
"dependencies": {
"@prisma/client": "^5.16.2",
"cron": "^3.1.7",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"next": "14.2.3",
"next-themes": "^0.3.0",
"react": "^18",
"react-dom": "^18",
"sharp": "^0.33.4",
"tailwind-scrollbar": "^3.1.0",
"usehooks-ts": "^3.1.0"
"usehooks-ts": "^3.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
"@types/express": "^4.17.21",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/ws": "^8.5.11",
"eslint": "^8",
"eslint-config-next": "14.2.3",
"postcss": "^8",
"prettier": "^3.2.5",
"prettier-plugin-tailwindcss": "^0.5.14",
"prisma": "^5.16.2",
"tailwindcss": "^3.4.1",
"ts-node": "^10.9.2",
"typescript": "^5"
}
}
62 changes: 62 additions & 0 deletions prisma/migrations/20240714162839_init_chains/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
-- CreateTable
CREATE TABLE "Chain" (
"chainId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"coinType" INTEGER NOT NULL,
"denom" TEXT NOT NULL,
"minimalDenom" TEXT NOT NULL,
"coinDecimals" INTEGER NOT NULL,
"logoUrl" TEXT NOT NULL,
"walletUrlForStaking" TEXT NOT NULL,
"coinGeckoId" TEXT NOT NULL,
"bech32Prefix" TEXT NOT NULL,
"twitterUrl" TEXT NOT NULL,
"docs" TEXT,

CONSTRAINT "Chain_pkey" PRIMARY KEY ("chainId")
);

-- CreateTable
CREATE TABLE "Github" (
"chainId" TEXT NOT NULL,
"url" TEXT NOT NULL,
"mainRepo" TEXT NOT NULL,

CONSTRAINT "Github_pkey" PRIMARY KEY ("chainId")
);

-- CreateTable
CREATE TABLE "RpcNode" (
"chainId" TEXT NOT NULL,
"url" TEXT NOT NULL,

CONSTRAINT "RpcNode_pkey" PRIMARY KEY ("chainId","url")
);

-- CreateTable
CREATE TABLE "LcdNode" (
"chainId" TEXT NOT NULL,
"url" TEXT NOT NULL,

CONSTRAINT "LcdNode_pkey" PRIMARY KEY ("chainId","url")
);

-- CreateTable
CREATE TABLE "GrpcNode" (
"chainId" TEXT NOT NULL,
"url" TEXT NOT NULL,

CONSTRAINT "GrpcNode_pkey" PRIMARY KEY ("chainId","url")
);

-- AddForeignKey
ALTER TABLE "Github" ADD CONSTRAINT "Github_chainId_fkey" FOREIGN KEY ("chainId") REFERENCES "Chain"("chainId") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "RpcNode" ADD CONSTRAINT "RpcNode_chainId_fkey" FOREIGN KEY ("chainId") REFERENCES "Chain"("chainId") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "LcdNode" ADD CONSTRAINT "LcdNode_chainId_fkey" FOREIGN KEY ("chainId") REFERENCES "Chain"("chainId") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "GrpcNode" ADD CONSTRAINT "GrpcNode_chainId_fkey" FOREIGN KEY ("chainId") REFERENCES "Chain"("chainId") ON DELETE RESTRICT ON UPDATE CASCADE;
8 changes: 8 additions & 0 deletions prisma/migrations/20240714172811_fix/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:

- You are about to drop the column `walletUrlForStaking` on the `Chain` table. All the data in the column will be lost.

*/
-- AlterTable
ALTER TABLE "Chain" DROP COLUMN "walletUrlForStaking";
10 changes: 10 additions & 0 deletions prisma/migrations/20240714173826_add_ws_node/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- CreateTable
CREATE TABLE "WsNode" (
"chainId" TEXT NOT NULL,
"url" TEXT NOT NULL,

CONSTRAINT "WsNode_pkey" PRIMARY KEY ("chainId","url")
);

-- AddForeignKey
ALTER TABLE "WsNode" ADD CONSTRAINT "WsNode_chainId_fkey" FOREIGN KEY ("chainId") REFERENCES "Chain"("chainId") ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:

- Added the required column `prettyName` to the `Chain` table without a default value. This is not possible if the table is not empty.

*/
-- AlterTable
ALTER TABLE "Chain" ADD COLUMN "prettyName" TEXT NOT NULL;
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
68 changes: 68 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model Chain {
chainId String @id
name String
prettyName String
coinType Int
denom String
minimalDenom String
coinDecimals Int
logoUrl String
coinGeckoId String
bech32Prefix String
twitterUrl String
docs String?

github Github?
lcdNodes LcdNode[]
rpcNodes RpcNode[]
wsNodes WsNode[]
grpc GrpcNode[]
}

model Github {
chainId String @id
chain Chain @relation(fields: [chainId], references: [chainId])
url String
mainRepo String
}

model WsNode {
chainId String
chain Chain @relation(fields: [chainId], references: [chainId])
url String

@@id([chainId, url])
}

model RpcNode {
chainId String
chain Chain @relation(fields: [chainId], references: [chainId])
url String

@@id([chainId, url])
}

model LcdNode {
chainId String
chain Chain @relation(fields: [chainId], references: [chainId])
url String

@@id([chainId, url])
}

model GrpcNode {
chainId String
chain Chain @relation(fields: [chainId], references: [chainId])
url String

@@id([chainId, url])
}
58 changes: 58 additions & 0 deletions server/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { PrismaClient } from '@prisma/client';
import { CronJob } from 'cron';
import express, { Express } from 'express';
import WebSocket from 'ws';

const app: Express = express();
const port = process.env.PORT || 3333;

const client = new PrismaClient();

async function initWss() {
const chains = await client.chain.findMany({
include: { wsNodes: true },
});
console.log('Connecting chains to ws');
for (const chain of chains) {
console.log(chain.prettyName + ' connecting...');
try {
const wss = new WebSocket(chain.wsNodes[0].url);
wss.on('open', () => {
console.log(chain.prettyName + ' connected ✅');
const subscriptionRequest = JSON.stringify({
jsonrpc: '2.0',
method: 'subscribe',
params: ["tm.event = 'NewBlock'"],
id: 1,
});

wss.send(subscriptionRequest);
});

wss.on('message', (message) => {
const parsedMessage = JSON.parse(message.toString());
console.log(parsedMessage.result.data ? parsedMessage.result.data.value.signatures : null);
});
} catch (e) {
console.log('Something went wrong: ' + e);
}
}
}

initWss();

app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
});

const job = new CronJob(
'* * * * * *', // cronTime
function () {
console.log('You will see this message every second');
}, // onTick
null, // onComplete
true, // start
'America/Los_Angeles', // timeZone
);

job.start();
26 changes: 26 additions & 0 deletions server/types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
declare type NewBlock = {
jsonrpc: '2.0';
id: 1;
result: {
query: "tm.event = 'NewBlock'";
data: { type: 'tendermint/event/NewBlock'; value: [] };
events: {
'transfer.recipient': any[];
'transfer.amount': any[];
'rewards.amount': any[];
'rewards.validator': any[];
'liveness.address': string[];
'liveness.missed_blocks': string[];
'coin_received.receiver': any[];
'coin_received.amount': any[];
'tm.event': ['NewBlock'];
'message.sender': string[];
'commission.validator': string[];
'liveness.height': string[];
'coin_spent.spender': string[];
'transfer.sender': string[];
'coin_spent.amount': string[];
'commission.amount': string[];
};
};
};
10 changes: 10 additions & 0 deletions src/app/api/[chain]/apr/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { PrismaClient } from '@prisma/client';
import type { NextApiRequest, NextApiResponse } from 'next';

export async function GET(request: Request, { params }: { params: { chain: string } }) {
const { chain } = params;
const client = new PrismaClient()


return Response.json(chain)
}
9 changes: 9 additions & 0 deletions src/app/api/[chain]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { PrismaClient } from '@prisma/client';
import type { NextApiRequest, NextApiResponse } from 'next';

export async function GET(request: Request, { params }: { params: { chain: string } }) {
const { chain } = params;
const client = new PrismaClient();
const dbResponse = await client.chain.findFirst({ where: { name: chain } });
return Response.json(dbResponse);
}
11 changes: 11 additions & 0 deletions src/app/api/chains/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { PrismaClient } from '@prisma/client';
import type { NextApiRequest, NextApiResponse } from 'next';

const client = new PrismaClient();

export async function GET(req: NextApiRequest) {
const networks = await client.chain.findMany({
include: { lcdNodes: true, rpcNodes: true, grpc: true, wsNodes: true, github: true },
});
return Response.json(networks);
}
Empty file added src/constants.ts
Empty file.
Loading