Skip to content

Commit

Permalink
ready for deployment
Browse files Browse the repository at this point in the history
  • Loading branch information
Agastya18 committed Jul 31, 2024
1 parent 3e68b69 commit 69890ea
Show file tree
Hide file tree
Showing 24 changed files with 359 additions and 281 deletions.
9 changes: 7 additions & 2 deletions .env-sample
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
PORT=8000
JWT_SECRET=***
JWT_SECRET=
DATABASE_URL=

DATABASE_URL=***
NODE_ENV=development
RAZORPAY_API_KEY=
RAZORPAY_APT_SECRET=

WEBHOOK_SECRET=
108 changes: 94 additions & 14 deletions backend/controllers/gameController.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,119 @@
import { prisma } from "../db/prisma.js";

function getRandomNumber() {
const loseProbability = 0.6; // 60% chance of losing
const winProbability = 0.4; // 40% chance of winning
const winNumbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; // Possible numbers (multiples of 10 up to 100)
const winningNumber = winNumbers[winNumbers.length - 1]; // Define the winning number as the highest number (100)

if (Math.random() < loseProbability) {
// Select a losing number
let randomNumber;
do {
randomNumber = winNumbers[Math.floor(Math.random() * (winNumbers.length - 1))];
} while (randomNumber === winningNumber); // Ensure the number is not the winning number
return randomNumber;
} else {
// Select a winning number
return winningNumber;
}
}


// console.log(getRandomNumber());
export const diceLogic = async (req, res) => {
const { betAmount, multiplier, rollOver, } = req.body;

const rollUnder = 100 - rollOver;
const winAmount = betAmount * multiplier;
const roll = Math.floor(Math.random() * 100) ;
let winAmount = betAmount * multiplier;
const roll = getRandomNumber();
const isWin = roll <= rollUnder;
const newBalance = isWin ? winAmount : -betAmount;
const user = await prisma.user.findUnique({

// const getBalance = await prisma.balance.findUnique({
// where: {
// userId: req.user.id,
// },
// })



const user = await prisma.balance.findUnique({
where: {
id: req.user.id,
userId: req.user.id,

},
});
if (user.balance < betAmount) {
// console.log(user);
let payout;

let newBalance = user.amount;
if (isWin) {
newBalance += winAmount;
payout=winAmount;
}else{
newBalance -= betAmount;
payout=-betAmount;
}

if (user.amount < betAmount) {
return res.status(400).json({ message: "Insufficient balance" });
}


if(newBalance <=0) {
newBalance = 0;
winAmount=0;
}


const updatedUser = await prisma.balance.update({
where: {
userId: req.user.id,
},
data: {
amount: {
increment: parseInt(newBalance),
},
amount: parseInt(newBalance),
},
});
const game = await prisma.gameTransaction.create({
data: {
userId: req.user.id,
betAmount: betAmount,
multiplier: multiplier,
status: isWin,
payout: payout,
},
});
// console.log(`Roll: ${roll}, Roll under: ${rollUnder}, Win: ${isWin}, Win amount: ${winAmount}, New balance: ${updatedUser.balance}`);
res.json({


res.status(200).json({
isWin,
roll,
winAmount,
// winAmount,
payout,
newBalance: updatedUser.amount,
})

;
});


}

export const getGamesTxn=async(req,res)=>{
try {
const games = await prisma.gameTransaction.findMany({
where: {
userId:req.user.id
},
orderBy: {
createdAt: "desc",
},
take:5,
});
res.status(200).json(games);

} catch (error) {
console.error(error);
res.status(500).json({ message: "Internal server error" });

}

}
55 changes: 37 additions & 18 deletions backend/controllers/walletController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import crypto from 'crypto';
export const OnRampTransactionsUpdated = async (req, res) => {

const { amount, provider } = req.body;
if(amount<100 ){
return res.status(400).json({
message: "Minimum amount is 100"
});
}
const token = crypto.randomBytes(5).toString('hex');

const transaction = await prisma.onRampTransaction.create({
Expand All @@ -14,7 +19,7 @@ export const OnRampTransactionsUpdated = async (req, res) => {
provider: provider,
token: token,
userId: req.user.id,
startTime: new Date() // Add the startTime property with the current date/time
// Add the startTime property with the current date/time
},
});

Expand All @@ -29,23 +34,37 @@ export const OnRampTransactionsUpdated = async (req, res) => {
}
export const checkout = async (req, res) => {

const {amount}= req.body
const options = {
amount: Math.floor(amount) , // amount in the smallest currency unit
currency: "INR",
// receipt:crypto.randomBytes(4).toString('hex'),
notes: {
userId: req.user.id,
}

};
try {
const {amount}= req.body

if(amount<100 ){
return res.status(400).json({
message: "Minimum amount is 100"
});
}

const order = await instance.orders.create(options);
// console.log(amount)
const options = {
amount: Math.floor(amount) , // amount in the smallest currency unit
currency: "INR",
// receipt:crypto.randomBytes(4).toString('hex'),
notes: {
userId: req.user.id,
}

};

res.status(200).json({
success: true,
order,
});
const order = await instance.orders.create(options);

res.status(200).json({
success: true,
order,
});

} catch (error) {
console.log(error);

}

}

Expand Down Expand Up @@ -98,7 +117,7 @@ export const webhook = async (req, res) => {

// Verify the signature
if (digest === req.headers['x-razorpay-signature'] ) {
console.log('Webhook signature verified');
// console.log('Webhook signature verified');

// Process the webhook payload
const event = req.body;
Expand All @@ -115,7 +134,7 @@ export const webhook = async (req, res) => {
userId: event.payload.payment.entity.notes.userId,
amount: event.payload.payment.entity.amount
};
console.log(paymentInformation);
// console.log(paymentInformation);
try {

await prisma.$transaction([
Expand Down
3 changes: 2 additions & 1 deletion backend/routes/gameRoute.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Router } from "express";
import { verifyUser } from "../middleware/protectRoute.js";
import { diceLogic } from "../controllers/gameController.js";
import { diceLogic,getGamesTxn } from "../controllers/gameController.js";

const router = Router();

router.route('/dice').post(verifyUser, diceLogic);
router.route('/get-games').get(verifyUser, getGamesTxn);



Expand Down
20 changes: 15 additions & 5 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import express from "express";
import dotenv from 'dotenv';
// import cors from 'cors';
import path from "path"
import Razorpay from 'razorpay';
import userRoute from './routes/userRoute.js'
import cookieParser from 'cookie-parser';
Expand All @@ -11,8 +12,8 @@ const app = express();
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const PORT= process.env.PORT || 5000;
const __dirname = path.resolve()
const PORT= process.env.PORT || 8000;
// app.use(cors(

// {
Expand All @@ -22,9 +23,7 @@ const PORT= process.env.PORT || 5000;
// }
// ));

// app.get('/', (req, res) => {
// res.send('Server is ready');
// });


export const instance = new Razorpay({
key_id: process.env.RAZORPAY_API_KEY || "",
Expand All @@ -36,6 +35,17 @@ app.use('/api', userRoute);
app.use('/api/wallet', walletRoute);
app.use('/api/game', gameRoute);

if (process.env.NODE_ENV !== "development") {

// Serve static assets from the frontend build directory
app.use(express.static(path.join(__dirname, "/frontend/dist")));

// Handle all other requests to serve the React app
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "frontend", "dist", "index.html"));
});
}

app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
})
Expand Down
10 changes: 7 additions & 3 deletions frontend/src/components/AddMoneyCard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,23 @@ export const AddMoney = () => {
const [name, setName] = useState(SUPPORTED_BANKS[0]?.name);

const addMoney = async (amount,name) => {
if(amount<100){
alert("Minimum amount is 100");
return;
}
const resp= await axios.post("/api/wallet/onramp", {
amount: amount,
provider: name
});
console.log("onramp data--",resp);
// console.log("onramp data--",resp);

//window.location.reload();
try {
const {data:orders} = await axios.post("/api/wallet/checkout", {
amount: resp.data.transaction.amount,

});
console.log("this is orders frontend",orders);
// console.log("this is orders frontend",orders);


const options = {
Expand All @@ -46,7 +50,7 @@ export const AddMoney = () => {
description: 'deposit money on wallet',
order_id: orders.order.id,
handler: function (response) {
console.log(response);
// console.log(response);
//alert(response);

},
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/BalanceCard.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Card } from "./cards";
export const BalanceCard = ({amount, locked}) => {
console.log(`Balance card: ${amount} ${locked}`)
// console.log(`Balance card: ${amount} ${locked}`)
return <Card title={"Balance"}>
<div className="flex justify-between border-b border-slate-300 pb-2">
<div>
Expand Down
22 changes: 7 additions & 15 deletions frontend/src/components/Footer.jsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
import React from 'react'

import { Link } from 'react-router-dom'
import stake from '../assets/stak.svg'
const Footer = () => {
return (
<footer className="footer bg-neutral text-neutral-content items-center p-4">
<aside className="grid-flow-col items-center">
<svg
width="36"
height="36"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
fillRule="evenodd"
clipRule="evenodd"
className="fill-current">
<path
d="M22.672 15.226l-2.432.811.841 2.515c.33 1.019-.209 2.127-1.23 2.456-1.15.325-2.148-.321-2.463-1.226l-.84-2.518-5.013 1.677.84 2.517c.391 1.203-.434 2.542-1.831 2.542-.88 0-1.601-.564-1.86-1.314l-.842-2.516-2.431.809c-1.135.328-2.145-.317-2.463-1.229-.329-1.018.211-2.127 1.231-2.456l2.432-.809-1.621-4.823-2.432.808c-1.355.384-2.558-.59-2.558-1.839 0-.817.509-1.582 1.327-1.846l2.433-.809-.842-2.515c-.33-1.02.211-2.129 1.232-2.458 1.02-.329 2.13.209 2.461 1.229l.842 2.515 5.011-1.677-.839-2.517c-.403-1.238.484-2.553 1.843-2.553.819 0 1.585.509 1.85 1.326l.841 2.517 2.431-.81c1.02-.33 2.131.211 2.461 1.229.332 1.018-.21 2.126-1.23 2.456l-2.433.809 1.622 4.823 2.433-.809c1.242-.401 2.557.484 2.557 1.838 0 .819-.51 1.583-1.328 1.847m-8.992-6.428l-5.01 1.675 1.619 4.828 5.011-1.674-1.62-4.829z"></path>
</svg>
<Link to={'/'}>
<img src={stake} alt="img" className='h-10 w-18 bg-white rounded-md' />
</Link>
<p>Copyright © {new Date().getFullYear()} - All right reserved</p>
</aside>
<nav className="grid-flow-col gap-4 md:place-self-center md:justify-self-end">
<a>
<Link >
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
Expand All @@ -28,7 +20,7 @@ const Footer = () => {
<path
d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z"></path>
</svg>
</a>
</Link>
<a>
<svg
xmlns="http://www.w3.org/2000/svg"
Expand Down
Loading

0 comments on commit 69890ea

Please sign in to comment.