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: backend API endpoints #63

Merged
merged 8 commits into from
Aug 27, 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
2 changes: 1 addition & 1 deletion apps/data-backend/src/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const resolvers = {
};

// Create the Apollo Server
const server = new ApolloServer({
export const server = new ApolloServer({
typeDefs,
resolvers,
context: () => ({ prisma }),
Expand Down
50 changes: 22 additions & 28 deletions apps/data-backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,33 @@
import express from "express";
import {server} from "./graphql"
import dotenv from "dotenv";
import router from "./router";
import helmet from "helmet"
import helmet from "helmet";
import { launchBot, sendWebAppButton } from "./services/telegram-app";
const cors = require("cors")
const cors = require("cors");

dotenv.config();
const app = express();
app.use(cors())
app.use(helmet())
// Alternatively, you can configure CORS for specific routes or origins

app.use(helmet());
app.use(cors({
origin: 'http://localhost:8081' // Adjust this to match the URL of your React Native web version if necessary
origin: 'http://localhost:8081'
MSghais marked this conversation as resolved.
Show resolved Hide resolved
}));
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
// app.use(cors)
// app.use(express.urlencoded({ extended: false }))
// app.use(express.json())
// Start the Backend
const port = process.env.PORT || 5050;
app.use('/', router)
app.use('/telegram-app', router)
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use('/', router);
const port = process.env.PORT || 5050;
app.listen(port, () => {
console.log(`🚀 Backend server running at http://localhost:${port}`);
try {
launchBot(process.env.TELEGRAM_BOT_TOKEN)
}catch(e) {

}
// sendWebAppButton(process.env.TG_ADMIN_CHAT_ID)
console.log(`🚀 Backend server running at http://localhost:${port}`);
try {
launchBot(process.env.TELEGRAM_BOT_TOKEN);
} catch (error) {
console.error("Error launching bot:", error);
}
});

// Start the server GraphQL
// server.listen().then(({ url }) => {
// console.log(`🚀 Backend server running at http://localhost:${port}/graphql`);
// });
// Optionally re-enable GraphQL if you plan to use it
/*
server.listen({ port: 4000 }).then(({ url }) => {
console.log(`🚀 GraphQL server ready at ${url}`);
});
*/
27 changes: 18 additions & 9 deletions apps/data-backend/src/router.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import express from 'express'
import express from 'express';

import deploy from './routes/indexer/deploy-token'
import deployLaunch from './routes/indexer/deploy-launch'
import buyCoin from './routes/indexer/buy-coin'
import deploy from './routes/indexer/deploy-token';
import deployLaunch from './routes/indexer/deploy-launch';
import buyCoin from './routes/indexer/buy-coin';
import tokenStats from './routes/indexer/token_stats';
import tokenGraph from './routes/indexer/graph';
import holdings from './routes/indexer/holdings';
import transactions from './routes/indexer/transactions';

const Router = express.Router()
Router.use('/deploy', deploy)
Router.use('/deploy-launch', deployLaunch)
Router.use("/buy-coin", buyCoin)
const Router = express.Router();

export default Router
Router.use('/deploy', deploy);
Router.use('/deploy-launch', deployLaunch);
Router.use('/buy-coin', buyCoin);
Router.use('/stats', tokenStats);
Router.use('/candles', tokenGraph);
Router.use('/token-distribution', holdings);
Router.use('/my-share', transactions);

export default Router;
6 changes: 0 additions & 6 deletions apps/data-backend/src/routes/indexer/deploy-launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,9 @@ const Router = express.Router()
Router.get('/', async (req, res) => {
try {
const launches = await prisma.token_launch.findMany({})
// console.log("launches", launches)
res.status(HTTPStatus.OK).json({
data:launches
})
// res.status(HTTPStatus.OK).json({
// data: launches
// })
} catch (error) {
res.status(HTTPStatus.InternalServerError).send(error)
}
Expand Down Expand Up @@ -64,6 +60,4 @@ Router.get('/stats/:launch', async (req, res) => {
}
})



export default Router
54 changes: 54 additions & 0 deletions apps/data-backend/src/routes/indexer/graph.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import express from 'express';
const { prisma } = require("indexer-prisma");
import { HTTPStatus } from '../../utils/http';
import { isValidStarknetAddress } from '../../utils/starknet';

const Router = express.Router();

Router.get('/candles/:tokenAddress', async (req, res) => {
const { tokenAddress } = req.params;

if (!isValidStarknetAddress(tokenAddress)) {
return res.status(HTTPStatus.BadRequest).json({
error: "Invalid token address format."
});
}

try {
const transactions = await prisma.token_transactions.findMany({
where: { memecoin_address: tokenAddress },
orderBy: { block_timestamp: 'asc' },
select: {
price: true,
block_timestamp: true,
transaction_type: true
}
});

if (transactions.length === 0) {
return res.status(HTTPStatus.NotFound).json({
error: "No transactions found for this token address."
});
}
// Hourly candles
const candles = transactions.reduce((acc, { block_timestamp, price }) => {
const hour = block_timestamp.getHours();
if (!acc[hour]) {
acc[hour] = { open: price, high: price, low: price, close: price };
} else {
acc[hour].high = Math.max(acc[hour].high, price);
acc[hour].low = Math.min(acc[hour].low, price);
acc[hour].close = price;
}
return acc;
}, {});

res.status(HTTPStatus.OK).json(candles);
} catch (error) {
res.status(HTTPStatus.InternalServerError).json({
error: "Internal Server Error while generating candles."
});
}
});

export default Router;
44 changes: 44 additions & 0 deletions apps/data-backend/src/routes/indexer/holdings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import express from 'express';
const { prisma } = require("indexer-prisma");
import { HTTPStatus } from '../../utils/http';
import { isValidStarknetAddress } from '../../utils/starknet';

const Router = express.Router();

Router.get('/token-distribution/:tokenAddress', async (req, res) => {
const { tokenAddress } = req.params;

if (!isValidStarknetAddress(tokenAddress)) {
return res.status(HTTPStatus.BadRequest).json({
error: "Invalid token address format."
});
}

try {
const distributions = await prisma.token_transactions.groupBy({
by: ['owner_address'],
where: { memecoin_address: tokenAddress },
_sum: {
amount: true
},
_count: {
owner_address: true
}
});

if (distributions.length === 0) {
return res.status(HTTPStatus.NotFound).json({
error: "No holders found for this token address."
});
}

res.status(HTTPStatus.OK).json(distributions);
} catch (error) {
console.error("Failed to fetch token distribution:", error);
res.status(HTTPStatus.InternalServerError).json({
error: "Internal Server Error while fetching token distribution."
});
}
});

export default Router;
43 changes: 43 additions & 0 deletions apps/data-backend/src/routes/indexer/token_stats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import express from 'express';
const { prisma } = require("indexer-prisma");
import { HTTPStatus } from '../../utils/http';
import { isValidStarknetAddress } from '../../utils/starknet';

const Router = express.Router();

// Endpoint to get the latest statistics for a specific token address
Router.get('/stats/:tokenAddress', async (req, res) => {
const { tokenAddress } = req.params;

if (!isValidStarknetAddress(tokenAddress)) {
return res.status(HTTPStatus.BadRequest).json({
error: "Invalid token address format."
});
}

try {
// Query the latest price and liquidity raised
const stats = await prisma.token_transactions.findFirst({
where: { memecoin_address: tokenAddress },
orderBy: { created_at: 'desc' },
select: {
price: true,
liquidity_raised: true
}
});

if (stats) {
res.status(HTTPStatus.OK).json(stats);
} else {
res.status(HTTPStatus.NotFound).json({
error: "No data found for the specified token address."
});
}
} catch (error) {
res.status(HTTPStatus.InternalServerError).json({
error: "Internal Server Error while fetching statistics."
});
}
});

export default Router;
54 changes: 54 additions & 0 deletions apps/data-backend/src/routes/indexer/transactions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import express from 'express';
const { prisma } = require("indexer-prisma");
import { HTTPStatus } from '../../utils/http';
import { isValidStarknetAddress } from '../../utils/starknet';

const Router = express.Router();

Router.get('/my-share/:tokenAddress/:userId', async (req, res) => {
const { tokenAddress, userId } = req.params;

if (!isValidStarknetAddress(tokenAddress)) {
return res.status(HTTPStatus.BadRequest).json({
error: "Invalid token address format."
});
}

try {
const transactions = await prisma.token_transactions.findMany({
where: {
memecoin_address: tokenAddress,
owner_address: userId
},
select: {
transaction_type: true,
amount: true
}
});

if (transactions.length === 0) {
return res.status(HTTPStatus.NotFound).json({
error: "No transactions found for this user and token address."
});
}

const result = transactions.reduce((acc, cur) => {
acc.total += parseFloat(cur.amount || 0);
if (cur.transaction_type === 'buy') {
acc.buy += parseFloat(cur.amount || 0);
} else if (cur.transaction_type === 'sell') {
acc.sell += parseFloat(cur.amount || 0);
}
return acc;
}, { total: 0, buy: 0, sell: 0 });

res.status(HTTPStatus.OK).json(result);
} catch (error) {
console.error("Failed to retrieve user transactions:", error);
res.status(HTTPStatus.InternalServerError).json({
error: "Internal Server Error while fetching user transactions."
});
}
});

export default Router;
2 changes: 1 addition & 1 deletion packages/afk_nostr_sdk/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ export * from "./src/store"
// export default {hooks, NostrContext, TanstackProvider ,
// NDKEvent, NDKKind, NDKUser,
// AFK_RELAYS
// };
// }
Loading