- {typeof problem.testcases[activeTestCaseId].input == "object"
+ {typeof problem.testcases[activeTestCaseId].input === "object"
? // login here to manage multiple object with
typeof Object.values(
problem.testcases[activeTestCaseId]?.input,
@@ -151,7 +169,11 @@ const TestCasesandResult = ({ problem }) => {
@@ -166,7 +188,7 @@ const TestCasesandResult = ({ problem }) => {
{showDetails ? (
- {output?.type == "submit" && (
+ {output?.type == "run" && (
<>
ExpectedOutput:{" "}
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index 723dc55..42e2e8c 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -36,17 +36,21 @@ const WorkSpace = ({ data, pid, contract }) => {
const [success, setSuccess] = useState(false);
const { address } = useWallet();
- const [, setOutputState] = useRecoilState(outputAtom);
+ const [outputState, setOutputState] = useRecoilState(outputAtom);
const [submissionProcessing, setSubmissionProcessing] = useState(false);
const [executionProcessing, setExecutionProcessing] = useState(false);
console.log("data : ", data);
- const checkStatus = async (token, type) => {
+ const checkStatus = async (tokens, type) => {
+ const token = tokens.map((item) => item.token).join(",");
+
+ console.log('token : ', token);
+
const options = {
method: "GET",
- url: import.meta.env.VITE_RAPID_API_URL + "/" + token,
+ url: "https://ce.judge0.com/submissions/" + "/batch?tokens=" + token,
params: { base64_encoded: "true", fields: "*" },
headers: {
"X-RapidAPI-Host": import.meta.env.VITE_RAPID_API_HOST,
@@ -57,6 +61,8 @@ const WorkSpace = ({ data, pid, contract }) => {
let response = await axios.request(options);
let statusId = response.data.status?.id;
+ console.log("res : ", response);
+
// Processed - we have a result
if (statusId === 1 || statusId === 2) {
setTimeout(() => {
@@ -66,7 +72,7 @@ const WorkSpace = ({ data, pid, contract }) => {
} else {
setOutputState({
type: type,
- data: response.data,
+ data: response.data.submissions,
expectedOutput: String(data?.examples[0]?.output).trim(),
});
toast.success(`Compiled Successfully!`, { position: "top-center" });
@@ -80,6 +86,9 @@ const WorkSpace = ({ data, pid, contract }) => {
}
};
+ console.log('outputstate : ', outputState);
+
+
const testcaseInput = JSON.stringify(data?.examples[0]?.input);
const [temp, setTemp] = useState(true); // make sures that the alert pop ups only once.
@@ -240,15 +249,31 @@ const WorkSpace = ({ data, pid, contract }) => {
// setProcessing(true);
setExecutionProcessing(true);
- const sourceCode = `
- function defaultFunc(inputs) {
- ${userCode}
+ const getInputString = (args, funcName) => {
+ return `\n
+ console.log(${funcName}(${args.join(",")}))
+ `;
+ };
- return ${data?.compileFunctionName}(inputs)
- }
+ const sourceCode = (input) => {
+ return `
+ function defaultFunc(inputs) {
+ ${userCode}
+
+ return ${data?.compileFunctionName}(inputs)
+ }
+
+ console.log(defaultFunc(${testcaseInput}));
+ `;
+ };
- console.log(defaultFunc(${testcaseInput}));
- `;
+ const submissions = data.testcases.map((testCase) => {
+ return {
+ source_code: btoa(sourceCode(testCase.input)),
+ language_id: 63,
+ expected_output: testCase.output,
+ };
+ });
const formData = {
language_id: 63,
@@ -256,9 +281,16 @@ const WorkSpace = ({ data, pid, contract }) => {
source_code: btoa(sourceCode),
stdin: btoa(testInput),
};
+
+ console.log(
+ JSON.stringify({
+ submissions,
+ }),
+ );
+
const options = {
method: "POST",
- url: import.meta.env.VITE_RAPID_API_URL,
+ url: import.meta.env.VITE_RAPID_API_URL + "/batch",
params: { base64_encoded: "true", fields: "*" },
headers: {
"content-type": "application/json",
@@ -266,15 +298,18 @@ const WorkSpace = ({ data, pid, contract }) => {
"X-RapidAPI-Host": import.meta.env.VITE_RAPID_API_HOST,
"X-RapidAPI-Key": import.meta.env.VITE_RAPID_API_KEY,
},
- data: formData,
+ data: JSON.stringify({
+ submissions,
+ }),
};
axios
.request(options)
.then(function (response) {
- const token = response.data.token;
+ const tokens = response.data;
setExecutionProcessing(false);
- checkStatus(token, "run");
+ console.log("token : ", tokens);
+ checkStatus(tokens, "run");
})
.catch((err) => {
let error = err.response ? err.response.data : err;
diff --git a/frontend/src/components/problems/Problem.jsx b/frontend/src/components/problems/Problem.jsx
index 28bee0e..e51f11e 100644
--- a/frontend/src/components/problems/Problem.jsx
+++ b/frontend/src/components/problems/Problem.jsx
@@ -11,7 +11,6 @@ import {
TooltipTrigger,
} from "../ui/tooltip";
-
const Problem = ({
index,
id,
@@ -88,7 +87,7 @@ const Problem = ({
/>
- Problem address :
{address}
-
+ */}
>
);
};
diff --git a/frontend/src/components/ui/tabs.jsx b/frontend/src/components/ui/tabs.jsx
new file mode 100644
index 0000000..1f011c6
--- /dev/null
+++ b/frontend/src/components/ui/tabs.jsx
@@ -0,0 +1,41 @@
+import * as React from "react"
+import * as TabsPrimitive from "@radix-ui/react-tabs"
+import { cn } from "@/lib/utils"
+
+
+const Tabs = TabsPrimitive.Root
+
+const TabsList = React.forwardRef(({ className, ...props }, ref) => (
+
+))
+TabsList.displayName = TabsPrimitive.List.displayName
+
+const TabsTrigger = React.forwardRef(({ className, ...props }, ref) => (
+
+))
+TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
+
+const TabsContent = React.forwardRef(({ className, ...props }, ref) => (
+
+))
+TabsContent.displayName = TabsPrimitive.Content.displayName
+
+export { Tabs, TabsList, TabsTrigger, TabsContent }
From e9f63b8a6b4fd1083e01e76f5e6eb5dfac9a575a Mon Sep 17 00:00:00 2001
From: spider076
Date: Tue, 1 Oct 2024 23:41:29 +0530
Subject: [PATCH 27/37] workspace page improvements
---
frontend/src/components/Navbar.jsx | 9 +-
.../components/problem/TestCasesandResult.jsx | 88 ++++++++++++++-----
frontend/src/components/problem/Workspace.jsx | 17 ++--
3 files changed, 80 insertions(+), 34 deletions(-)
diff --git a/frontend/src/components/Navbar.jsx b/frontend/src/components/Navbar.jsx
index 530a7fc..2952c4a 100644
--- a/frontend/src/components/Navbar.jsx
+++ b/frontend/src/components/Navbar.jsx
@@ -12,18 +12,21 @@ import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import LoginButton from "./LoginButton";
import { useWallet } from "@tronweb3/tronwallet-adapter-react-hooks";
+import { useRecoilValue, useRecoilValueLoadable } from "recoil";
+import { authTokenState } from "@/atoms/userAtom";
const Navbar = ({ className, dropdown = false }) => {
const navigate = useNavigate();
const [position, setPosition] = useState("bottom");
- const { address } = useWallet();
-
+ const authToken = useRecoilValue(authTokenState);
// REMOVE
// useEffect(() => {
// setUser(userState);
// }, []);
+ console.log("ssf", authToken);
+
return (
@@ -40,7 +43,7 @@ const Navbar = ({ className, dropdown = false }) => {
- {dropdown && (
+ {dropdown && window.tronLink.tronWeb.defaultAddress?.base58 && (
diff --git a/frontend/src/components/problem/TestCasesandResult.jsx b/frontend/src/components/problem/TestCasesandResult.jsx
index 2c3fd85..17f7a60 100644
--- a/frontend/src/components/problem/TestCasesandResult.jsx
+++ b/frontend/src/components/problem/TestCasesandResult.jsx
@@ -11,6 +11,8 @@ const TestCasesandResult = ({ problem }) => {
const [activeBar, setActiveBar] = useState(0);
const [showDetails, setShowDetails] = useState(false);
+ var testcasePassed = 0;
+
const output = useRecoilValue(outputAtom);
const outputState = output?.data;
@@ -35,11 +37,15 @@ const TestCasesandResult = ({ problem }) => {
}
}, [output]);
- console.log("output : ", output);
-
const getOutputs = () => {
return outputState.map((output, index) => {
let statusId = output?.status?.id;
+
+ if (output.status.description === "Accepted") {
+ testcasePassed++;
+ }
+
+ console.log("status : ", statusId);
if (statusId === 6) {
// compilation error
return (
@@ -50,33 +56,60 @@ const TestCasesandResult = ({ problem }) => {
{atob(output?.compile_output)}
);
- } else if (statusId === 3) {
- return (
-
- {atob(output?.stdout) !== null
- ? `${Number(atob(output?.stdout))}`
- : null}
-
- );
- } else if (statusId === 5) {
+ } else if (statusId === 3 || statusId === 4) {
return (
-
- {`Time Limit Exceeded`}
-
+
+
+
+
+
Input
+ {/* {problem.testcases.map((data, index) => {
+ return ( */}
+
+ {/* {argumentNames[index]} = */}
+
+ {problem.testcases[index].input}
+
+
+ {/* })} */}
+
+
+
Output
+
+
+ {atob(output.stdout)}
+
+
+
+
+
Expected
+
+
+ {problem.testcases[index]?.output}
+
+
+
+
+
+
);
} else {
return (
- {atob(output?.stderr)}
+ {output?.stderr.length > 0 ? (
+
+
ERROR :
+
{atob(output?.stderr)}
+
+ ) : (
+ {atob(output?.message)}
+ )}
);
}
@@ -166,12 +199,19 @@ const TestCasesandResult = ({ problem }) => {
) : (
-
+
Output :
-
+ {outputState[0]?.status?.id === 3 ||
+ outputState[0]?.status?.id === 4 ? (
+
+ {problem.testcases.length}/{testcasePassed} TestCases Passed
+
+ ) : null}
+
{outputState ? (
+ {/* temp */}
) : null}
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index 42e2e8c..701873c 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -46,7 +46,7 @@ const WorkSpace = ({ data, pid, contract }) => {
const checkStatus = async (tokens, type) => {
const token = tokens.map((item) => item.token).join(",");
- console.log('token : ', token);
+ console.log("token : ", token);
const options = {
method: "GET",
@@ -86,8 +86,7 @@ const WorkSpace = ({ data, pid, contract }) => {
}
};
- console.log('outputstate : ', outputState);
-
+ console.log("outputstate : ", outputState);
const testcaseInput = JSON.stringify(data?.examples[0]?.input);
@@ -249,9 +248,12 @@ const WorkSpace = ({ data, pid, contract }) => {
// setProcessing(true);
setExecutionProcessing(true);
- const getInputString = (args, funcName) => {
+ const getInputString = (args) => {
return `\n
- console.log(${funcName}(${args.join(",")}))
+
+
+
+ console.log(${data?.compileFunctionName}(${args.join(",")}))
`;
};
@@ -268,10 +270,11 @@ const WorkSpace = ({ data, pid, contract }) => {
};
const submissions = data.testcases.map((testCase) => {
+ console.log("testCase.output : ", testCase.output);
return {
- source_code: btoa(sourceCode(testCase.input)),
+ source_code: btoa(userCode + getInputString([testCase.input])),
language_id: 63,
- expected_output: testCase.output,
+ expected_output: btoa(testCase.output),
};
});
From 6db5225155c399b73a4e1248ee60bcb1dc7240e6 Mon Sep 17 00:00:00 2001
From: spider076
Date: Wed, 2 Oct 2024 11:20:53 +0530
Subject: [PATCH 28/37] minor changes
---
.../components/problem/TestCasesandResult.jsx | 13 +-
frontend/src/components/problem/Workspace.jsx | 12 +-
package-lock.json | 131 +++++++++++++++++-
3 files changed, 144 insertions(+), 12 deletions(-)
diff --git a/frontend/src/components/problem/TestCasesandResult.jsx b/frontend/src/components/problem/TestCasesandResult.jsx
index 17f7a60..79abe40 100644
--- a/frontend/src/components/problem/TestCasesandResult.jsx
+++ b/frontend/src/components/problem/TestCasesandResult.jsx
@@ -1,9 +1,9 @@
import { ChevronDown, ChevronUp } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { useRecoilValue } from "recoil";
import { outputAtom } from "../../atoms/problemAtom";
-const TestCasesandResult = ({ problem }) => {
+const TestCasesandResult = ({ problem, testcasePassed }) => {
const [, setLoading] = useState(true);
const [activeTestCaseId, setActiveTestCaseId] = useState(0); // indexing for testcases from the problem;
@@ -11,8 +11,6 @@ const TestCasesandResult = ({ problem }) => {
const [activeBar, setActiveBar] = useState(0);
const [showDetails, setShowDetails] = useState(false);
- var testcasePassed = 0;
-
const output = useRecoilValue(outputAtom);
const outputState = output?.data;
@@ -37,15 +35,12 @@ const TestCasesandResult = ({ problem }) => {
}
}, [output]);
+ console.log("tettt : ", testcasePassed);
+
const getOutputs = () => {
return outputState.map((output, index) => {
let statusId = output?.status?.id;
- if (output.status.description === "Accepted") {
- testcasePassed++;
- }
-
- console.log("status : ", statusId);
if (statusId === 6) {
// compilation error
return (
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index 701873c..cfc6f77 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -40,11 +40,13 @@ const WorkSpace = ({ data, pid, contract }) => {
const [submissionProcessing, setSubmissionProcessing] = useState(false);
const [executionProcessing, setExecutionProcessing] = useState(false);
+ const [testcasePassed, setTestcasePassed] = useState(0);
console.log("data : ", data);
const checkStatus = async (tokens, type) => {
const token = tokens.map((item) => item.token).join(",");
+ setTestcasePassed(0);
console.log("token : ", token);
@@ -75,6 +77,12 @@ const WorkSpace = ({ data, pid, contract }) => {
data: response.data.submissions,
expectedOutput: String(data?.examples[0]?.output).trim(),
});
+ response.data.submissions.map((output) => {
+ if (output.status.description == "Accepted") {
+ setTestcasePassed((t) => t + 1);
+ }
+ });
+
toast.success(`Compiled Successfully!`, { position: "top-center" });
return response.data;
}
@@ -82,7 +90,7 @@ const WorkSpace = ({ data, pid, contract }) => {
console.log("err", err);
setSubmissionProcessing(false);
setExecutionProcessing(false);
- toast.error("Error in the code !");
+ toast.error(err.message);
}
};
@@ -353,7 +361,7 @@ const WorkSpace = ({ data, pid, contract }) => {
{/* Test Cases */}
-
+
diff --git a/package-lock.json b/package-lock.json
index 03e5410..714af8e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -2,5 +2,134 @@
"name": "CodeHive",
"lockfileVersion": 3,
"requires": true,
- "packages": {}
+ "packages": {
+ "": {
+ "dependencies": {
+ "jsonwebtoken": "^9.0.2"
+ }
+ },
+ "node_modules/buffer-equal-constant-time": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="
+ },
+ "node_modules/ecdsa-sig-formatter": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/jsonwebtoken": {
+ "version": "9.0.2",
+ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
+ "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==",
+ "dependencies": {
+ "jws": "^3.2.2",
+ "lodash.includes": "^4.3.0",
+ "lodash.isboolean": "^3.0.3",
+ "lodash.isinteger": "^4.0.4",
+ "lodash.isnumber": "^3.0.3",
+ "lodash.isplainobject": "^4.0.6",
+ "lodash.isstring": "^4.0.1",
+ "lodash.once": "^4.0.0",
+ "ms": "^2.1.1",
+ "semver": "^7.5.4"
+ },
+ "engines": {
+ "node": ">=12",
+ "npm": ">=6"
+ }
+ },
+ "node_modules/jwa": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
+ "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
+ "dependencies": {
+ "buffer-equal-constant-time": "1.0.1",
+ "ecdsa-sig-formatter": "1.0.11",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/jws": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
+ "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
+ "dependencies": {
+ "jwa": "^1.4.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/lodash.includes": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
+ "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="
+ },
+ "node_modules/lodash.isboolean": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="
+ },
+ "node_modules/lodash.isinteger": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
+ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="
+ },
+ "node_modules/lodash.isnumber": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
+ "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="
+ },
+ "node_modules/lodash.isplainobject": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
+ "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="
+ },
+ "node_modules/lodash.isstring": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
+ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="
+ },
+ "node_modules/lodash.once": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
+ "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+ },
+ "node_modules/semver": {
+ "version": "7.6.3",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
+ "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ }
+ }
}
From a1cdb4ab74171669b1fab2c8c43417d307a3bbe0 Mon Sep 17 00:00:00 2001
From: spider076
Date: Wed, 2 Oct 2024 11:33:27 +0530
Subject: [PATCH 29/37] test commit
---
frontend/src/components/problem/Workspace.jsx | 1 +
1 file changed, 1 insertion(+)
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index cfc6f77..dfe9c85 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -93,6 +93,7 @@ const WorkSpace = ({ data, pid, contract }) => {
toast.error(err.message);
}
};
+// test
console.log("outputstate : ", outputState);
From 9e67592ba029c76f204e87dba740a1f649670ea3 Mon Sep 17 00:00:00 2001
From: spider076
Date: Wed, 2 Oct 2024 11:37:35 +0530
Subject: [PATCH 30/37] test-2
---
frontend/src/components/problem/Workspace.jsx | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index dfe9c85..efb1434 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -93,8 +93,7 @@ const WorkSpace = ({ data, pid, contract }) => {
toast.error(err.message);
}
};
-// test
-
+// test-1
console.log("outputstate : ", outputState);
const testcaseInput = JSON.stringify(data?.examples[0]?.input);
From 80c70f3db5d6446db0f85bdeba4de7a8c47e9a11 Mon Sep 17 00:00:00 2001
From: spider076
Date: Wed, 2 Oct 2024 14:39:08 +0530
Subject: [PATCH 31/37] submissions logic implemented
---
frontend/src/components/problem/Workspace.jsx | 110 ++++++++----------
1 file changed, 48 insertions(+), 62 deletions(-)
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index efb1434..cdf40fe 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -9,14 +9,15 @@ import { useWallet } from "@tronweb3/tronwallet-adapter-react-hooks";
import axios from "axios";
import { useState } from "react";
import ReactConfetti from "react-confetti";
-import { useRecoilState } from "recoil";
+import { useRecoilState, useRecoilValue } from "recoil";
import { Toaster, toast } from "sonner";
import CodeEditor from "./CodeEditor";
import ProblemDescription from "./ProblemDescription";
import SubmitBox from "./SubmitBox";
import TestCasesandResult from "./TestCasesandResult";
-import { alertAtom, submissionErrorAtom } from "@/atoms/userAtom";
+import { alertAtom, submissionErrorAtom, userState } from "@/atoms/userAtom";
import { ErrorAlert } from "../ErrorAlert";
+import { signMessageWithTimeConstraint } from "@/hooks/SigMessage";
// import TestCasesandResult from "./TestCasesandResult";
@@ -25,8 +26,6 @@ const WorkSpace = ({ data, pid, contract }) => {
const [, setSubmissionError] = useRecoilState(submissionErrorAtom);
let [userCode, setUserCode] = useState();
- const [lastUserValidCode, setLastUserValidCode] = useState("");
-
let testInput =
typeof data?.testcases[0].input == "object"
? Object.values(data.testcases[0].input).toString()
@@ -37,6 +36,7 @@ const WorkSpace = ({ data, pid, contract }) => {
const { address } = useWallet();
const [outputState, setOutputState] = useRecoilState(outputAtom);
+ const user = useRecoilValue(userState);
const [submissionProcessing, setSubmissionProcessing] = useState(false);
const [executionProcessing, setExecutionProcessing] = useState(false);
@@ -93,7 +93,7 @@ const WorkSpace = ({ data, pid, contract }) => {
toast.error(err.message);
}
};
-// test-1
+ // test-1
console.log("outputstate : ", outputState);
const testcaseInput = JSON.stringify(data?.examples[0]?.input);
@@ -101,15 +101,6 @@ const WorkSpace = ({ data, pid, contract }) => {
const [temp, setTemp] = useState(true); // make sures that the alert pop ups only once.
const handleSubmit = async () => {
- if (!address) {
- toast.error("Please login to submit your code", {
- position: "top-center",
- autoClose: 3000,
- theme: "dark",
- });
- return;
- }
-
if (temp) {
setAlert({
isOpen: true,
@@ -122,33 +113,26 @@ const WorkSpace = ({ data, pid, contract }) => {
return;
}
- setSubmissionProcessing(true);
- // default template + starter code
- const sourceCode = `
- function defaultFunc(inputs) {
- ${userCode}
+ const txnData = await signMessageWithTimeConstraint();
- return ${data?.compileFunctionName}(inputs)
- }
+ if (!txnData?.message) {
+ throw new Error("Transaction failed !");
+ }
- console.log(defaultFunc(${testcaseInput}));
- `;
+ setSubmissionProcessing(true);
const formData = {
- language_id: 63,
- // encode source code in base64
- source_code: btoa(sourceCode),
- stdin: btoa(testInput),
+ userId: user.id,
+ userCode: userCode,
+ problemId: pid,
};
const options = {
method: "POST",
- url: import.meta.env.VITE_RAPID_API_URL,
- params: { base64_encoded: "true", fields: "*" },
+ url: import.meta.env.VITE_BACKEND_URL + "/code/submit",
headers: {
- "content-type": "application/json",
"Content-Type": "application/json",
- "X-RapidAPI-Host": import.meta.env.VITE_RAPID_API_HOST,
- "X-RapidAPI-Key": import.meta.env.VITE_RAPID_API_KEY,
+ tron_message: txnData.message,
+ tron_signature: txnData.signature,
},
data: formData,
};
@@ -156,39 +140,39 @@ const WorkSpace = ({ data, pid, contract }) => {
axios
.request(options)
.then(async function (response) {
- const token = response.data.token;
- let output = await checkStatus(token, "submit");
- let statusId = output?.status?.id;
-
- console.log("output ; ", atob(output?.stdout));
-
- if (statusId !== 3) {
- // ! Dont run the contract if their is run time
- setSubmissionProcessing(false);
- toast.error(
- "RunTime Error | Please Check your Code before submission !",
- );
- return;
- }
-
- if (atob(output.stdout) && atob(output.stdout) != null) {
- const outputString = String(atob(output?.stdout)).trim();
- const expectedOutput = String(data?.examples[0]?.output).trim();
-
- if (outputString == expectedOutput) {
- setLastUserValidCode(userCode);
- // create a pop up for a upload code option...
- handleUpload(userCode);
- } else {
- setSubmissionProcessing(false);
- toast.error("Submission Failed ! 🚫");
- }
- }
+ const submission = response.data;
+ console.log("submission : ", submission);
+
+ // if (statusId !== 3) {
+ // // ! Dont run the contract if their is run time
+ // setSubmissionProcessing(false);
+ // toast.error(
+ // "RunTime Error | Please Check your Code before submission !",
+ // );
+ // return;
+ // }
+
+ // if (atob(output.stdout) && atob(output.stdout) != null) {
+ // const outputString = String(atob(output?.stdout)).trim();
+ // const expectedOutput = String(data?.examples[0]?.output).trim();
+
+ // if (outputString == expectedOutput) {
+ // // create a pop up for a upload code option...
+ // handleUpload(userCode);
+ // } else {
+ // setSubmissionProcessing(false);
+ // toast.error("Submission Failed !");
+ // }
+ // }
})
.catch((err) => {
let error = err.response ? err.response.data : err;
setSubmissionProcessing(false);
+ toast.error(err.message);
console.log(error);
+ })
+ .finally(() => {
+ setSubmissionProcessing(false);
});
};
const handleUpload = async (uploadCode) => {
@@ -304,7 +288,6 @@ const WorkSpace = ({ data, pid, contract }) => {
url: import.meta.env.VITE_RAPID_API_URL + "/batch",
params: { base64_encoded: "true", fields: "*" },
headers: {
- "content-type": "application/json",
"Content-Type": "application/json",
"X-RapidAPI-Host": import.meta.env.VITE_RAPID_API_HOST,
"X-RapidAPI-Key": import.meta.env.VITE_RAPID_API_KEY,
@@ -361,7 +344,10 @@ const WorkSpace = ({ data, pid, contract }) => {
{/* Test Cases */}
-
+
From b9313b94986c6b88cc2d3934d02f6e4afdfd6a57 Mon Sep 17 00:00:00 2001
From: spider076
Date: Thu, 3 Oct 2024 15:02:52 +0530
Subject: [PATCH 32/37] my submissions frontend and backend fully integrated
---
frontend/package-lock.json | 12 ++
frontend/package.json | 1 +
frontend/src/atoms/problemAtom.js | 30 +++-
frontend/src/atoms/userAtom.js | 5 +
.../src/components/problem/MySubmissions.jsx | 134 ++++++++++++++++++
.../src/components/problem/MySubmittion.jsx | 86 -----------
.../components/problem/ProblemDescription.jsx | 78 +++++++---
frontend/src/components/problem/Workspace.jsx | 69 ++++-----
.../components/problems/ProblemsContainer.jsx | 15 +-
.../submission/AcceptedSubmissionResult.jsx | 54 +++++++
.../submission/ErrorSubmissionResult.jsx | 42 ++++++
.../submission/SubmissionCreatedAt.jsx | 16 +++
.../submission/SubmissionDetail.jsx | 85 +++++++++++
.../submission/WrongSubmissionResult.jsx | 54 +++++++
frontend/src/hooks/getQuestions.js | 65 ---------
frontend/src/hooks/getSubmissions.js | 56 ++++++++
frontend/src/main.jsx | 6 +-
frontend/tailwind.config.cjs | 36 ++---
18 files changed, 608 insertions(+), 236 deletions(-)
create mode 100644 frontend/src/components/problem/MySubmissions.jsx
delete mode 100644 frontend/src/components/problem/MySubmittion.jsx
create mode 100644 frontend/src/components/submission/AcceptedSubmissionResult.jsx
create mode 100644 frontend/src/components/submission/ErrorSubmissionResult.jsx
create mode 100644 frontend/src/components/submission/SubmissionCreatedAt.jsx
create mode 100644 frontend/src/components/submission/SubmissionDetail.jsx
create mode 100644 frontend/src/components/submission/WrongSubmissionResult.jsx
delete mode 100644 frontend/src/hooks/getQuestions.js
create mode 100644 frontend/src/hooks/getSubmissions.js
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 7913c6f..4f29182 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -51,6 +51,7 @@
"recoil": "^0.7.7",
"sonner": "^1.4.0",
"tailwind-merge": "^2.2.1",
+ "tailwind-scrollbar": "^3.1.0",
"tailwindcss-animate": "^1.0.7",
"tronweb": "^6.0.0-beta.2"
},
@@ -8249,6 +8250,17 @@
"url": "https://github.com/sponsors/dcastil"
}
},
+ "node_modules/tailwind-scrollbar": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/tailwind-scrollbar/-/tailwind-scrollbar-3.1.0.tgz",
+ "integrity": "sha512-pmrtDIZeHyu2idTejfV59SbaJyvp1VRjYxAjZBH0jnyrPRo6HL1kD5Glz8VPagasqr6oAx6M05+Tuw429Z8jxg==",
+ "engines": {
+ "node": ">=12.13.0"
+ },
+ "peerDependencies": {
+ "tailwindcss": "3.x"
+ }
+ },
"node_modules/tailwindcss": {
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.1.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 2a47a6e..116b69f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -53,6 +53,7 @@
"recoil": "^0.7.7",
"sonner": "^1.4.0",
"tailwind-merge": "^2.2.1",
+ "tailwind-scrollbar": "^3.1.0",
"tailwindcss-animate": "^1.0.7",
"tronweb": "^6.0.0-beta.2"
},
diff --git a/frontend/src/atoms/problemAtom.js b/frontend/src/atoms/problemAtom.js
index 9242b32..a8e97db 100644
--- a/frontend/src/atoms/problemAtom.js
+++ b/frontend/src/atoms/problemAtom.js
@@ -1,4 +1,4 @@
-import { atom } from "recoil";
+import { atom, selector } from "recoil";
export const outputAtom = atom({
key: "outputAtom",
@@ -23,3 +23,31 @@ export const codeRunLoadingState = atom({
key: "codeRunLoadingState",
default: false,
});
+
+// submissions atoms
+
+export const submissionResultState = atom({
+ key: "submissionResultState",
+ default: null,
+});
+
+export const activeSubmissionIdState = atom({
+ key: "activeSubmissionIdState",
+ default: null,
+});
+
+export const activeSubmissionResultSelector = selector({
+ key: "activeSubmissionResultSelector",
+ get: ({ get }) => {
+ const activeSubmissionId = get(activeSubmissionIdState);
+ const submissionResult = get(submissionResultState);
+ return activeSubmissionId && submissionResult
+ ? submissionResult[activeSubmissionId]
+ : null;
+ },
+});
+
+export const fetchSubmissionsLoadingState = atom({
+ key: "fetchSubmissionsLoadingState",
+ default: false,
+});
diff --git a/frontend/src/atoms/userAtom.js b/frontend/src/atoms/userAtom.js
index 5c74796..6b58a55 100644
--- a/frontend/src/atoms/userAtom.js
+++ b/frontend/src/atoms/userAtom.js
@@ -24,6 +24,11 @@ export const alertAtom = atom({
},
});
+export const tabsSelectorAtom = atom({
+ key: "tabsSelectorAtom",
+ default: 0,
+})
+
export const submissionErrorAtom = atom({
key: "submissionErrorAtom",
default: {
diff --git a/frontend/src/components/problem/MySubmissions.jsx b/frontend/src/components/problem/MySubmissions.jsx
new file mode 100644
index 0000000..0dac00e
--- /dev/null
+++ b/frontend/src/components/problem/MySubmissions.jsx
@@ -0,0 +1,134 @@
+import { Clock4, Cpu } from "lucide-react";
+import { useSetRecoilState } from "recoil";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "../ui/table";
+import {
+ activeSubmissionIdState,
+ fetchSubmissionsLoadingState,
+} from "@/atoms/problemAtom";
+import { useGetMySubmissions } from "@/hooks/getSubmissions";
+
+function getTimeFromDateTime(dateTime) {
+ const now = new Date();
+ const createdTime = new Date(dateTime);
+ const diffInMs = now.getTime() - createdTime.getTime();
+
+ // Handle edge cases for "just now" and "a minute ago"
+ if (diffInMs < 60000) {
+ // Less than a minute
+ return "just now";
+ } else if (diffInMs < 120000) {
+ // Between 1 and 2 minutes
+ return "a minute ago";
+ }
+
+ const seconds = Math.floor(diffInMs / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days === 1) {
+ return "yesterday";
+ } else if (days > 1) {
+ return new Intl.DateTimeFormat("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ }).format(dateTime);
+ } else if (hours > 0) {
+ return `${hours} hours ago`;
+ } else if (minutes > 0) {
+ return `${minutes} minutes ago`;
+ }
+}
+
+const SubmissionList = () => {
+ const setActiveSubmissionId = useSetRecoilState(activeSubmissionIdState);
+ const setFetchSubmissionsLoading = useSetRecoilState(
+ fetchSubmissionsLoadingState,
+ );
+
+ const submissions = useGetMySubmissions();
+
+ if (submissions) {
+ return (
+
+ {submissions.length > 0 ? (
+
+
+
+ Status
+ Language
+ Runtime
+ Memory
+
+
+
+ {submissions.map(
+ ({
+ id,
+ statusDesc,
+ statusId,
+ memoryUsage,
+ runtime,
+ language,
+ createdAt,
+ }) => {
+ return (
+ {
+ setActiveSubmissionId(id);
+ setFetchSubmissionsLoading(true);
+ }}
+ >
+
+ 3 ? "text-red-800" : "text-[#0E902A]"}`}
+ >
+ {statusDesc}
+
+
+ {getTimeFromDateTime(createdAt)}
+
+
+
+
+ Javascript
+
+
+
+
+
+ {runtime} ms
+
+
+
+ {" "}
+
+
+ {Math.floor(memoryUsage / 1024)} MB
+
+
+
+ );
+ },
+ )}
+
+
+ ) : (
+ <>No Submission Yet!>
+ )}
+
+ );
+ }
+};
+
+export default SubmissionList;
diff --git a/frontend/src/components/problem/MySubmittion.jsx b/frontend/src/components/problem/MySubmittion.jsx
deleted file mode 100644
index 633bac1..0000000
--- a/frontend/src/components/problem/MySubmittion.jsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { useWallet } from "@tronweb3/tronwallet-adapter-react-hooks";
-import { useEffect, useState } from "react";
-
-export default function MySubmittion({ contract, claimer, loader }){
- const { address } = useWallet();
- const [ myCode, setMyCode ] = useState();
- const [ allData, setAllData ] = useState();
-
- const fetchTHeData = async (url) => {
- if( url == ""){
- //default case baby man...
- url = "bafkreib4sbyv6qwkrdpukntyv34c2qb6qqqwjr53rp4dezm4i56q4m4vsi";
- console.error("Im showing a default code cause my code was blure....");
- }
- const URL = import.meta.env.VITE_PINATA_URL + url;
-
- var myHeaders = new Headers();
- var requestOptions = {
- method: 'GET',
- headers: myHeaders,
- redirect: 'follow'
- };
- const data = await (await fetch(URL, requestOptions)).text();
- setMyCode(JSON.parse(data).code.split("\n"));
- }
-
- useEffect(()=>{
- //fetching the codes...via the contract...
- loader(true);
- contract
- .codes(address)
- .call()
- .then((res) => {
- if(res[0] == "410000000000000000000000000000000000000000"){
- return;
- }
- fetchTHeData(res.code);
- setAllData(res);
- loader(false);
- })
- .catch((error) => console.error(error));
- },[]);
-
- return (
-
-
-
-
-
- My Submissions:
-
-
-
-
-
-
-
- {myCode?
-
- {myCode.map((el,i)=>({el} ))}
-
- :
-
-
No Code submitted Yet....
-
-
- }
-
- {allData &&
-
t#_ {parseInt(allData.submitTime._hex, 16)}
- }
-
-
-
-
-
- )
-}
-
-function Code({code}){
- return (
-
- code code code code{code}
-
- )
-}
\ No newline at end of file
diff --git a/frontend/src/components/problem/ProblemDescription.jsx b/frontend/src/components/problem/ProblemDescription.jsx
index e0d0517..b36729c 100644
--- a/frontend/src/components/problem/ProblemDescription.jsx
+++ b/frontend/src/components/problem/ProblemDescription.jsx
@@ -1,14 +1,20 @@
-"use client";
-
-import { useTheContext } from "../../context/index";
+import {
+ activeSubmissionIdState,
+ activeSubmissionResultSelector,
+ fetchSubmissionsLoadingState,
+ submissionResultState,
+} from "@/atoms/problemAtom";
+import { CircleDollarSign } from "lucide-react";
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
-import AllSubmittion from "./AllSubmittion";
-import MySubmittion from "./MySubmittion";
-import { Button } from "../ui/button";
+import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
import ReportModal from "../ReportModal";
+import SubmissionDetail from "../submission/SubmissionDetail";
import { SubSkeletonPage } from "../SubSkeletonPage";
-import { CircleDollarSign } from "lucide-react";
+import AllSubmittion from "./AllSubmittion";
+import MySubmissions from "./MySubmissions";
+import { tabsSelectorAtom, userState } from "@/atoms/userAtom";
+import axios from "axios";
const ProblemDescription = ({ problem, pid, contract }) => {
const [loading, setLoading] = useState(false);
@@ -18,13 +24,53 @@ const ProblemDescription = ({ problem, pid, contract }) => {
const [bounty, setBounty] = useState();
const [isClaimed, setIsClaimed] = useState(false);
- const [selector, setSelector] = useState(0);
+ const [selector, setSelector] = useRecoilState(tabsSelectorAtom);
+ const activeSubmissionId = useRecoilValue(activeSubmissionIdState);
+ const setActiveSubmissionId = useSetRecoilState(activeSubmissionIdState);
+ const [submisionResult, setSubmissionResult] = useRecoilState(
+ submissionResultState,
+ );
+ const activeSubmissionResult = useRecoilValue(activeSubmissionResultSelector);
+ const [fetchSubmissionsLoading, setFetchSubmissionsLoading] = useRecoilState(
+ fetchSubmissionsLoadingState,
+ );
+ useEffect(() => {
+ (async () => {
+ if (fetchSubmissionsLoading && activeSubmissionId) {
+ if (!activeSubmissionResult) {
+ try {
+ const res = await axios.get(
+ import.meta.env.VITE_BACKEND_URL +
+ `/code/submission/${activeSubmissionId}`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ },
+ );
+ const data = res.data;
- console.log("claimer : ", isClaimed);
+ setSubmissionResult((prev) => ({
+ ...prev,
+ [activeSubmissionId]: data,
+ }));
+
+ console.log("updatin g? ?????");
+ } catch (err) {
+ console.log("Error", err.message);
+ } finally {
+ setFetchSubmissionsLoading(false);
+ }
+ } else {
+ setFetchSubmissionsLoading(false);
+ }
+ }
+ })();
+ }, [fetchSubmissionsLoading, activeSubmissionId, activeSubmissionResult]);
return (
-
-
+
+
{/* TAB */}
{
loader={setLoading}
/>
)}
- {selector == 2 && !loading && (
-
- )}
+ {selector == 2 &&
+ !loading &&
+ (activeSubmissionId ? : )}
);
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index cdf40fe..7cb5272 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -1,4 +1,4 @@
-import { outputAtom } from "@/atoms/problemAtom";
+import { activeSubmissionIdState, fetchSubmissionsLoadingState, outputAtom, submissionResultState } from "@/atoms/problemAtom";
import {
ResizableHandle,
ResizablePanel,
@@ -9,13 +9,13 @@ import { useWallet } from "@tronweb3/tronwallet-adapter-react-hooks";
import axios from "axios";
import { useState } from "react";
import ReactConfetti from "react-confetti";
-import { useRecoilState, useRecoilValue } from "recoil";
+import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
import { Toaster, toast } from "sonner";
import CodeEditor from "./CodeEditor";
import ProblemDescription from "./ProblemDescription";
import SubmitBox from "./SubmitBox";
import TestCasesandResult from "./TestCasesandResult";
-import { alertAtom, submissionErrorAtom, userState } from "@/atoms/userAtom";
+import { alertAtom, submissionErrorAtom, tabsSelectorAtom, userState } from "@/atoms/userAtom";
import { ErrorAlert } from "../ErrorAlert";
import { signMessageWithTimeConstraint } from "@/hooks/SigMessage";
@@ -41,6 +41,11 @@ const WorkSpace = ({ data, pid, contract }) => {
const [submissionProcessing, setSubmissionProcessing] = useState(false);
const [executionProcessing, setExecutionProcessing] = useState(false);
const [testcasePassed, setTestcasePassed] = useState(0);
+ const setActiveSubmissionId = useSetRecoilState(activeSubmissionIdState);
+ const [fetchSubmissionsLoading, setFetchSubmissionsLoading] = useRecoilState(fetchSubmissionsLoadingState);
+ const setSubmissionResult = useSetRecoilState(submissionResultState);
+
+ const setSelector = useSetRecoilState(tabsSelectorAtom);
console.log("data : ", data);
@@ -140,30 +145,31 @@ const WorkSpace = ({ data, pid, contract }) => {
axios
.request(options)
.then(async function (response) {
- const submission = response.data;
- console.log("submission : ", submission);
-
- // if (statusId !== 3) {
- // // ! Dont run the contract if their is run time
- // setSubmissionProcessing(false);
- // toast.error(
- // "RunTime Error | Please Check your Code before submission !",
- // );
- // return;
- // }
-
- // if (atob(output.stdout) && atob(output.stdout) != null) {
- // const outputString = String(atob(output?.stdout)).trim();
- // const expectedOutput = String(data?.examples[0]?.output).trim();
-
- // if (outputString == expectedOutput) {
- // // create a pop up for a upload code option...
- // handleUpload(userCode);
- // } else {
- // setSubmissionProcessing(false);
- // toast.error("Submission Failed !");
- // }
- // }
+ if (response.status === 200) {
+ setActiveSubmissionId(response.data.submissionId);
+
+ try {
+ const res = await axios.get(
+ import.meta.env.VITE_BACKEND_URL +
+ `/code/submission/${response.data.submissionId}`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ },
+ );
+ const data = res.data;
+
+ setSubmissionResult((prev) => ({
+ ...prev,
+ [response.data.submissionId]: data,
+ }));
+
+ console.log("updatin g? ?????");
+ } catch (err) {
+ console.log("Error", err.message);
+ }
+ }
})
.catch((err) => {
let error = err.response ? err.response.data : err;
@@ -173,6 +179,8 @@ const WorkSpace = ({ data, pid, contract }) => {
})
.finally(() => {
setSubmissionProcessing(false);
+ setFetchSubmissionsLoading(false);
+ setSelector(2);
});
};
const handleUpload = async (uploadCode) => {
@@ -270,13 +278,6 @@ const WorkSpace = ({ data, pid, contract }) => {
};
});
- const formData = {
- language_id: 63,
- // encode source code in base64
- source_code: btoa(sourceCode),
- stdin: btoa(testInput),
- };
-
console.log(
JSON.stringify({
submissions,
diff --git a/frontend/src/components/problems/ProblemsContainer.jsx b/frontend/src/components/problems/ProblemsContainer.jsx
index 914d04c..19a9da2 100644
--- a/frontend/src/components/problems/ProblemsContainer.jsx
+++ b/frontend/src/components/problems/ProblemsContainer.jsx
@@ -1,21 +1,14 @@
-import React, { useEffect, useState } from "react";
-import Problem from "./Problem";
-import { cn } from "@/lib/utils";
import {
Table,
TableBody,
- TableFooter,
TableHead,
TableHeader,
- TableRow,
- TableCell,
+ TableRow
} from "@/components/ui/table";
-import MaxWidthWrapper from "../MaxWidthWrapper";
-import axios from "axios";
-import { useGetQuestions } from "@/hooks/getQuestions";
import { ABI_Bank } from "@/utils/problems";
-import { Skeleton } from "../ui/skeleton";
-import { toast } from "sonner";
+import axios from "axios";
+import { useEffect, useState } from "react";
+import Problem from "./Problem";
const ProblemsContainer = () => {
const [activeIndex, setActiveIndex] = useState(null);
diff --git a/frontend/src/components/submission/AcceptedSubmissionResult.jsx b/frontend/src/components/submission/AcceptedSubmissionResult.jsx
new file mode 100644
index 0000000..6375e92
--- /dev/null
+++ b/frontend/src/components/submission/AcceptedSubmissionResult.jsx
@@ -0,0 +1,54 @@
+import { Clock4, Cpu } from "lucide-react";
+import SubmissionCreatedAt from "./SubmissionCreatedAt.jsx";
+import { useRecoilValue } from "recoil";
+import { activeSubmissionResultSelector } from "@/atoms/problemAtom";
+
+const SubmissionStats = ({ icon, label, measurement, value }) => {
+ return (
+
+
+ {icon}
+ {label}
+
+
+ {value}
+
+ {measurement}
+
+
+ );
+};
+
+const AcceptedSubmissionResult = () => {
+ const submissionDetails = useRecoilValue(activeSubmissionResultSelector);
+ const { statusDesc, createdAt, runtime, memoryUsage } = submissionDetails;
+
+ const stats = [
+ {
+ icon:
,
+ label: "Runtime",
+ measurement: "ms",
+ value: runtime,
+ },
+ {
+ icon:
,
+ label: "Memory",
+ measurement: "mb",
+ value: Math.floor(memoryUsage / 1024),
+ },
+ ];
+
+ return (
+
+
{statusDesc}
+
+
+ {stats.map((stat) => (
+
+ ))}
+
+
+ );
+};
+
+export default AcceptedSubmissionResult;
diff --git a/frontend/src/components/submission/ErrorSubmissionResult.jsx b/frontend/src/components/submission/ErrorSubmissionResult.jsx
new file mode 100644
index 0000000..a0195c3
--- /dev/null
+++ b/frontend/src/components/submission/ErrorSubmissionResult.jsx
@@ -0,0 +1,42 @@
+import { activeSubmissionResultSelector } from "@/atoms/problemAtom";
+import { useRecoilValue } from "recoil";
+import SubmissionCreatedAt from "./SubmissionCreatedAt";
+
+const ErrorSubmissionResult = () => {
+ const submissionDetails = useRecoilValue(activeSubmissionResultSelector);
+ const {
+ statusDesc,
+ createdAt,
+ testCasesPassed,
+ problem,
+ lastTestCase,
+ errorMessage,
+ } = submissionDetails;
+
+ return (
+
+
{statusDesc}
+
+
+ |
+ {testCasesPassed}/{problem?.testcases.length} testcases passed
+
+
+ {errorMessage && (
+
+ )}
+
+
+
Last Executed Input
+
+ {lastTestCase.input}
+
+
+
+
+ );
+};
+
+export default ErrorSubmissionResult;
diff --git a/frontend/src/components/submission/SubmissionCreatedAt.jsx b/frontend/src/components/submission/SubmissionCreatedAt.jsx
new file mode 100644
index 0000000..5d2825d
--- /dev/null
+++ b/frontend/src/components/submission/SubmissionCreatedAt.jsx
@@ -0,0 +1,16 @@
+const SubmissionCreatedAt = ({ createdAt }) => {
+ return (
+
+ submitted at{" "}
+ {new Intl.DateTimeFormat("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ }).format(new Date(createdAt))}
+
+ );
+};
+
+export default SubmissionCreatedAt;
diff --git a/frontend/src/components/submission/SubmissionDetail.jsx b/frontend/src/components/submission/SubmissionDetail.jsx
new file mode 100644
index 0000000..a25bed2
--- /dev/null
+++ b/frontend/src/components/submission/SubmissionDetail.jsx
@@ -0,0 +1,85 @@
+import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
+import { ArrowLeft } from "lucide-react";
+import AcceptedSubmissionResult from "./AcceptedSubmissionResult";
+import WrongSubmissionResult from "./WrongSubmissionResult";
+import ErrorSubmissionResult from "./ErrorSubmissionResult";
+import { Editor } from "@monaco-editor/react";
+import { Button } from "../ui/button";
+import {
+ activeSubmissionIdState,
+ activeSubmissionResultSelector,
+ fetchSubmissionsLoadingState,
+ submissionResultState,
+} from "@/atoms/problemAtom";
+import { useEffect } from "react";
+
+const renderSubmissionDetails = (submissionResult) => {
+ switch (submissionResult.statusId) {
+ case 3:
+ return
;
+ case 4:
+ return
;
+ default:
+ return
;
+ }
+};
+
+const SubmissionDetail = () => {
+ const [activeSubmissionId, setActiveSubmissionId] = useRecoilState(
+ activeSubmissionIdState,
+ );
+
+ const submissionDetails = useRecoilValue(activeSubmissionResultSelector);
+ const submissionResult = useRecoilValue(fetchSubmissionsLoadingState);
+
+ useEffect(() => {
+ console.log("submission datia l: ", submissionDetails);
+ }, [submissionDetails, submissionResult, activeSubmissionId]);
+
+ if (submissionDetails && submissionDetails?.statusId) {
+ const { code } = submissionDetails;
+ return (
+ <>
+
setActiveSubmissionId(null)}>
+ All submissions{" "}
+
+
+ {renderSubmissionDetails(submissionDetails)}
+
+
+
Code | {"javascript"}
+
+
+
+
+ >
+ );
+ } else
+ return (
+
+
setActiveSubmissionId(null)}
+ >
+ All submissions{" "}
+
+
+ Something went wrong !
+
+
+ );
+};
+
+export default SubmissionDetail;
diff --git a/frontend/src/components/submission/WrongSubmissionResult.jsx b/frontend/src/components/submission/WrongSubmissionResult.jsx
new file mode 100644
index 0000000..69ff93a
--- /dev/null
+++ b/frontend/src/components/submission/WrongSubmissionResult.jsx
@@ -0,0 +1,54 @@
+import { useRecoilValue } from "recoil";
+import SubmissionCreatedAt from "./SubmissionCreatedAt";
+import { activeSubmissionResultSelector } from "@/atoms/problemAtom";
+
+const WrongSubmissionResult = () => {
+ const submissionDetails = useRecoilValue(activeSubmissionResultSelector);
+ const {
+ statusDesc,
+ createdAt,
+ testCasesPassed,
+ problem,
+ lastTestCase,
+ stdout,
+ } = submissionDetails;
+ return (
+
+
{statusDesc}
+
+
+ |
+ {testCasesPassed}/{problem.testcases.length} testcases passed
+
+
+
+
+
Input
+
+ {lastTestCase.input}
+
+
+
+
+
Output
+
+ {stdout}
+
+
+
+
+
Expected
+
+
+ {lastTestCase.output}
+
+
+
+
+
+ );
+};
+
+export default WrongSubmissionResult;
diff --git a/frontend/src/hooks/getQuestions.js b/frontend/src/hooks/getQuestions.js
deleted file mode 100644
index 548d6d4..0000000
--- a/frontend/src/hooks/getQuestions.js
+++ /dev/null
@@ -1,65 +0,0 @@
-import axios from "axios";
-import { useEffect, useState } from "react";
-import { toast } from "sonner";
-
-export const useGetQuestions = async () => {
- const [questions, setQuestions] = useState([
- {
- title: "Two Sum",
- fees: 0,
- description:
- "Given an array of integers `nums` and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order."
- },
- {
- title: "Longest Substring Without Repeating Characters",
- fees: 10,
- description:
- "Given a string `s`, find the length of the longest substring without repeating characters."
- },
- {
- title: "Reverse Integer",
- fees: 0,
- description:
- "Given a signed 32-bit integer `x`, return `x` with its digits reversed. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-2^31, 2^31 - 1]`, then return 0."
- },
- {
- title: "Merge Two Sorted Lists",
- fees: 0,
- description:
- "Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists."
- }
- ]);
-
- const questionsHandler = async () => {
- // try {
- // const response = await axios.get(
- // `http://localhost:8000/api/get_question/0/${encodeURIComponent(
- // " "
- // )}/0/${encodeURIComponent(" ")}`,
- // {
- // headers: {
- // "Content-Type": "application/x-www-form-urlencoded"
- // }
- // }
- // );
- // console.log("Response:", response.data);
-
- // setQuestions(response.data);
-
- // if ("Err" in response.data) {
- // toast.error(`Error while fetching questions !`);
- // } else {
- // toast.success("questions fetched succesfully !");
- // }
- // } catch (error) {
- // console.log("errro : ", error);
- // toast.error("fetching of questions failed !");
- // }
- };
-
- useEffect(() => {
- questionsHandler();
- }, []);
-
- return questions;
-};
diff --git a/frontend/src/hooks/getSubmissions.js b/frontend/src/hooks/getSubmissions.js
new file mode 100644
index 0000000..0c18466
--- /dev/null
+++ b/frontend/src/hooks/getSubmissions.js
@@ -0,0 +1,56 @@
+import { userState } from "@/atoms/userAtom";
+import axios from "axios";
+import { useEffect, useState } from "react";
+import { useRecoilValue } from "recoil";
+import { toast } from "sonner";
+
+export const useGetMySubmissions = () => {
+ const [submissions, setSubmission] = useState([]);
+ const { id: userId } = useRecoilValue(userState);
+
+
+useEffect(() => {
+ (async () => {
+ await axios
+ .get(import.meta.env.VITE_BACKEND_URL + "/code/submissions?userid=" + userId)
+ .then((res) => {
+ setSubmission(res.data);
+ })
+ .catch((err) => {
+ console.error(err);
+ toast.error(err.message);
+ });
+ })();
+ }, []);
+
+ return submissions;
+};
+
+export const useGetAllSubmissions = () => {
+ const [submission, setSubmission] = useState([]);
+ const { id: userId } = useRecoilValue(userState);
+
+
+useEffect(() => {
+ (async () => {
+ await axios
+ .get(import.meta.env.VITE_BACKEND_URL + "/code/submission/", {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ data: {
+ userid: userId
+ }
+ })
+ .then((res) => {
+ setSubmission(res.data);
+ })
+ .catch((err) => {
+ console.error(err);
+ toast.error(err.message);
+ });
+ })();
+ }, []);
+
+ return submission;
+}
diff --git a/frontend/src/main.jsx b/frontend/src/main.jsx
index 5a68381..b0b07c9 100644
--- a/frontend/src/main.jsx
+++ b/frontend/src/main.jsx
@@ -1,5 +1,4 @@
-import { Buffer } from 'buffer';
-import { Toaster } from "@/components/ui/toaster"
+import { Buffer } from "buffer";
window.Buffer = Buffer;
import React from "react";
import ReactDOM from "react-dom/client";
@@ -7,13 +6,14 @@ import App from "./App.jsx";
import "./index.css";
import { RecoilRoot } from "recoil";
import ContextProvierAllOver from "./context/index.jsx";
+import { Toaster } from "sonner";
ReactDOM.createRoot(document.getElementById("root")).render(
-
+
,
diff --git a/frontend/tailwind.config.cjs b/frontend/tailwind.config.cjs
index 2edb28e..72c23f4 100644
--- a/frontend/tailwind.config.cjs
+++ b/frontend/tailwind.config.cjs
@@ -7,8 +7,8 @@ module.exports = {
center: true,
padding: "2rem",
screens: {
- "2xl": "1400px"
- }
+ "2xl": "1400px",
+ },
},
extend: {
colors: {
@@ -23,53 +23,53 @@ module.exports = {
third: "#262626",
primary: {
DEFAULT: "#F72045",
- foreground: "hsl(var(--primary-foreground))"
+ foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
- foreground: "hsl(var(--secondary-foreground))"
+ foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
- foreground: "hsl(var(--destructive-foreground))"
+ foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
- foreground: "hsl(var(--muted-foreground))"
+ foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
- foreground: "hsl(var(--accent-foreground))"
+ foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
- foreground: "hsl(var(--popover-foreground))"
+ foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
- foreground: "hsl(var(--card-foreground))"
- }
+ foreground: "hsl(var(--card-foreground))",
+ },
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
- sm: "calc(var(--radius) - 4px)"
+ sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: "0" },
- to: { height: "var(--radix-accordion-content-height)" }
+ to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
- to: { height: "0" }
- }
+ to: { height: "0" },
+ },
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
- "accordion-up": "accordion-up 0.2s ease-out"
- }
- }
+ "accordion-up": "accordion-up 0.2s ease-out",
+ },
+ },
},
- plugins: [require("tailwindcss-animate")],
+ plugins: [require("tailwindcss-animate"), require("tailwind-scrollbar")],
};
From af0c31a26fd2e4b229813a328091e2bf8db38636 Mon Sep 17 00:00:00 2001
From: spider076
Date: Thu, 3 Oct 2024 15:10:42 +0530
Subject: [PATCH 33/37] all submissions removed for now
---
.../{AllSubmittion.jsx => AllSubmissions.jsx} | 2 +-
.../src/components/problem/ProblemDescription.jsx | 12 ++++++------
2 files changed, 7 insertions(+), 7 deletions(-)
rename frontend/src/components/problem/{AllSubmittion.jsx => AllSubmissions.jsx} (97%)
diff --git a/frontend/src/components/problem/AllSubmittion.jsx b/frontend/src/components/problem/AllSubmissions.jsx
similarity index 97%
rename from frontend/src/components/problem/AllSubmittion.jsx
rename to frontend/src/components/problem/AllSubmissions.jsx
index a834114..eb9b518 100644
--- a/frontend/src/components/problem/AllSubmittion.jsx
+++ b/frontend/src/components/problem/AllSubmissions.jsx
@@ -6,7 +6,7 @@ import {
AccordionTrigger,
} from "@/components/ui/accordion";
-export default function AllSubmittion({ contract, claimer, loader }) {
+export default function AllSubmissions({ contract, claimer, loader }) {
const [codes, setCodes] = useState([]);
useEffect(() => {
loader(true);
diff --git a/frontend/src/components/problem/ProblemDescription.jsx b/frontend/src/components/problem/ProblemDescription.jsx
index b36729c..bfa3c2e 100644
--- a/frontend/src/components/problem/ProblemDescription.jsx
+++ b/frontend/src/components/problem/ProblemDescription.jsx
@@ -11,7 +11,7 @@ import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
import ReportModal from "../ReportModal";
import SubmissionDetail from "../submission/SubmissionDetail";
import { SubSkeletonPage } from "../SubSkeletonPage";
-import AllSubmittion from "./AllSubmittion";
+import AllSubmissions from "./AllSubmissions";
import MySubmissions from "./MySubmissions";
import { tabsSelectorAtom, userState } from "@/atoms/userAtom";
import axios from "axios";
@@ -79,12 +79,12 @@ const ProblemDescription = ({ problem, pid, contract }) => {
>
Description
-
setSelector(1)}
>
All Codes
-
+
*/}
setSelector(2)}
@@ -205,13 +205,13 @@ const ProblemDescription = ({ problem, pid, contract }) => {
)}
- {selector == 1 && !loading && (
-
- )}
+ )} */}
{selector == 2 &&
!loading &&
(activeSubmissionId ? : )}
From 2b8041ad021cfbe26ec5c2506be7444ce26888c1 Mon Sep 17 00:00:00 2001
From: spider076
Date: Thu, 3 Oct 2024 18:22:32 +0530
Subject: [PATCH 34/37] added trx send functionality
---
.../components/problem/TestCasesandResult.jsx | 12 +-
frontend/src/components/problem/Workspace.jsx | 124 ++++++------------
2 files changed, 43 insertions(+), 93 deletions(-)
diff --git a/frontend/src/components/problem/TestCasesandResult.jsx b/frontend/src/components/problem/TestCasesandResult.jsx
index 79abe40..8163df1 100644
--- a/frontend/src/components/problem/TestCasesandResult.jsx
+++ b/frontend/src/components/problem/TestCasesandResult.jsx
@@ -46,14 +46,14 @@ const TestCasesandResult = ({ problem, testcasePassed }) => {
return (
{atob(output?.compile_output)}
);
} else if (statusId === 3 || statusId === 4) {
return (
-
+
@@ -95,7 +95,7 @@ const TestCasesandResult = ({ problem, testcasePassed }) => {
return (
{output?.stderr.length > 0 ? (
@@ -119,7 +119,7 @@ const TestCasesandResult = ({ problem, testcasePassed }) => {
);
return (
-
+
{/* testcase heading */}
@@ -202,9 +202,9 @@ const TestCasesandResult = ({ problem, testcasePassed }) => {
{problem.testcases.length}/{testcasePassed} TestCases Passed
) : null}
-
+
{outputState ? (
-
+
{/* temp */}
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index 7cb5272..d66104b 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -1,4 +1,9 @@
-import { activeSubmissionIdState, fetchSubmissionsLoadingState, outputAtom, submissionResultState } from "@/atoms/problemAtom";
+import {
+ activeSubmissionIdState,
+ fetchSubmissionsLoadingState,
+ outputAtom,
+ submissionResultState,
+} from "@/atoms/problemAtom";
import {
ResizableHandle,
ResizablePanel,
@@ -15,7 +20,12 @@ import CodeEditor from "./CodeEditor";
import ProblemDescription from "./ProblemDescription";
import SubmitBox from "./SubmitBox";
import TestCasesandResult from "./TestCasesandResult";
-import { alertAtom, submissionErrorAtom, tabsSelectorAtom, userState } from "@/atoms/userAtom";
+import {
+ alertAtom,
+ submissionErrorAtom,
+ tabsSelectorAtom,
+ userState,
+} from "@/atoms/userAtom";
import { ErrorAlert } from "../ErrorAlert";
import { signMessageWithTimeConstraint } from "@/hooks/SigMessage";
@@ -42,7 +52,9 @@ const WorkSpace = ({ data, pid, contract }) => {
const [executionProcessing, setExecutionProcessing] = useState(false);
const [testcasePassed, setTestcasePassed] = useState(0);
const setActiveSubmissionId = useSetRecoilState(activeSubmissionIdState);
- const [fetchSubmissionsLoading, setFetchSubmissionsLoading] = useRecoilState(fetchSubmissionsLoadingState);
+ const [fetchSubmissionsLoading, setFetchSubmissionsLoading] = useRecoilState(
+ fetchSubmissionsLoadingState,
+ );
const setSubmissionResult = useSetRecoilState(submissionResultState);
const setSelector = useSetRecoilState(tabsSelectorAtom);
@@ -53,8 +65,6 @@ const WorkSpace = ({ data, pid, contract }) => {
const token = tokens.map((item) => item.token).join(",");
setTestcasePassed(0);
- console.log("token : ", token);
-
const options = {
method: "GET",
url: "https://ce.judge0.com/submissions/" + "/batch?tokens=" + token,
@@ -93,9 +103,10 @@ const WorkSpace = ({ data, pid, contract }) => {
}
} catch (err) {
console.log("err", err);
+ toast.error(err.message);
+ } finally {
setSubmissionProcessing(false);
setExecutionProcessing(false);
- toast.error(err.message);
}
};
// test-1
@@ -125,6 +136,23 @@ const WorkSpace = ({ data, pid, contract }) => {
}
setSubmissionProcessing(true);
+ const amountInSun = data.bounty * 1_000_000;
+
+ // send trx to codehive wallet
+ try {
+ const transaction =
+ await window.tronLink.tronWeb.transactionBuilder.sendTrx(
+ "TTJbVzrWBGfk82ChT61hR8cPdhAhS2FBvK",
+ amountInSun,
+ window.tronWeb.defaultAddress.base58,
+ );
+
+ console.log("transactoin : ", transaction);
+ } catch (err) {
+ console.log("err : ", err);
+ toast.error("unknown error occured !");
+ return;
+ }
const formData = {
userId: user.id,
@@ -165,7 +193,9 @@ const WorkSpace = ({ data, pid, contract }) => {
[response.data.submissionId]: data,
}));
- console.log("updatin g? ?????");
+ if (data.statusDesc == "Accepted") {
+ setSuccess(true);
+ }
} catch (err) {
console.log("Error", err.message);
}
@@ -183,66 +213,6 @@ const WorkSpace = ({ data, pid, contract }) => {
setSelector(2);
});
};
- const handleUpload = async (uploadCode) => {
- //check that if the useer has allready submitted code?
- //code fetch using the contract...
- try {
- const data = await contract.haveSubmitted().call();
-
- if (data) {
- setSubmissionError({
- isError: true,
- message: `You have already Submitted this Problem's Solution`,
- });
- setSubmissionProcessing(false);
- return;
- // alert("allready submitted the code..");
- }
- } catch (err) {
- setSubmissionError({
- isError: true,
- message: "Error Occured when fetching the submission contract info !",
- });
- setSubmissionProcessing(false);
- console.log("error : ", err);
- return;
- }
-
- if (uploadCode == null || uploadCode == "") {
- setSubmissionError({
- isError: true,
- message: "submit the code before uploding to chain..",
- });
- return;
- }
- const options = {
- method: "POST",
- headers: {
- Authorization: `Bearer ${import.meta.env.VITE_PINATA_JWT}`,
- "Content-Type": "application/json",
- },
- body: `{"pinataOptions":{"cidVersion":1},"pinataMetadata":{"name":"${address}.json"},"pinataContent":${JSON.stringify({ code: uploadCode })}}`,
- };
- const { IpfsHash } = await fetch(
- "https://api.pinata.cloud/pinning/pinJSONToIPFS",
- options,
- )
- .then((res) => res.text())
- .then((res) => JSON.parse(res));
- try {
- let result = await contract.submitCode(IpfsHash, address, 200).send({
- feeLimit: 100_000_000_0,
- shouldPollResponse: true,
- });
- setSuccess(true);
- toast.success("Congratulations your submission was accepted ! 🥳");
- setSubmissionProcessing(false);
- console.log("Result for that:", result);
- } catch (error) {
- setSubmissionProcessing(false);
- console.log("Error contacting the contract:", error);
- }
- };
const handleRun = async () => {
// setProcessing(true);
@@ -257,18 +227,6 @@ const WorkSpace = ({ data, pid, contract }) => {
`;
};
- const sourceCode = (input) => {
- return `
- function defaultFunc(inputs) {
- ${userCode}
-
- return ${data?.compileFunctionName}(inputs)
- }
-
- console.log(defaultFunc(${testcaseInput}));
- `;
- };
-
const submissions = data.testcases.map((testCase) => {
console.log("testCase.output : ", testCase.output);
return {
@@ -278,12 +236,6 @@ const WorkSpace = ({ data, pid, contract }) => {
};
});
- console.log(
- JSON.stringify({
- submissions,
- }),
- );
-
const options = {
method: "POST",
url: import.meta.env.VITE_RAPID_API_URL + "/batch",
@@ -302,13 +254,11 @@ const WorkSpace = ({ data, pid, contract }) => {
.request(options)
.then(function (response) {
const tokens = response.data;
- setExecutionProcessing(false);
console.log("token : ", tokens);
checkStatus(tokens, "run");
})
.catch((err) => {
let error = err.response ? err.response.data : err;
- setExecutionProcessing(false);
console.log(error);
});
};
From a810c2924846bea29b5d04a77ced72a06ca7340d Mon Sep 17 00:00:00 2001
From: spider076
Date: Sat, 5 Oct 2024 16:18:32 +0530
Subject: [PATCH 35/37] my questions page ready
---
frontend/src/components/AddProblemForm.jsx | 20 +++
frontend/src/components/Navbar.jsx | 7 -
.../components/problem/TestCasesandResult.jsx | 24 ++-
frontend/src/components/problem/Workspace.jsx | 39 ++---
frontend/src/pages/MyQuestionDesc.jsx | 145 ++++++------------
frontend/src/pages/MyQuestions.jsx | 109 +++++++------
6 files changed, 160 insertions(+), 184 deletions(-)
diff --git a/frontend/src/components/AddProblemForm.jsx b/frontend/src/components/AddProblemForm.jsx
index d8635d8..3fb7859 100644
--- a/frontend/src/components/AddProblemForm.jsx
+++ b/frontend/src/components/AddProblemForm.jsx
@@ -149,6 +149,25 @@ export default function ProblemForum({ data }) {
await DEPLOY(formData, bountyValue);
};
+ const testing = async (e) => {
+ // bounty
+ const amountInSun = 10 * 1_000_000;
+
+ try {
+ const transaction = await window.tronLink.tronWeb.trx.sendTrx(
+ import.meta.env.VITE_CODEHIVE_WALLET |
+ "TRAMAQH5hy2qSteh2WRWpwjme2ieiwg5wu",
+ amountInSun,
+ );
+
+ console.log("transactoin : ", transaction);
+ } catch (err) {
+ console.log("err : ", err);
+ toast.error("unknown error occured !");
+ return;
+ }
+ };
+
return (
@@ -517,6 +536,7 @@ export default function ProblemForum({ data }) {
>
Prev
+
Test
{formSelector == 5 ? (
{
const navigate = useNavigate();
const [position, setPosition] = useState("bottom");
- const authToken = useRecoilValue(authTokenState);
- // REMOVE
- // useEffect(() => {
- // setUser(userState);
- // }, []);
-
- console.log("ssf", authToken);
return (
diff --git a/frontend/src/components/problem/TestCasesandResult.jsx b/frontend/src/components/problem/TestCasesandResult.jsx
index 8163df1..99381b7 100644
--- a/frontend/src/components/problem/TestCasesandResult.jsx
+++ b/frontend/src/components/problem/TestCasesandResult.jsx
@@ -10,6 +10,7 @@ const TestCasesandResult = ({ problem, testcasePassed }) => {
const [innerNavs, setInnerNavs] = useState(["TestCases"]);
const [activeBar, setActiveBar] = useState(0);
const [showDetails, setShowDetails] = useState(false);
+ const [statusId, setStatusId] = useState(null);
const output = useRecoilValue(outputAtom);
const outputState = output?.data;
@@ -33,27 +34,31 @@ const TestCasesandResult = ({ problem, testcasePassed }) => {
) {
setInnerNavs((prev) => [...prev, "Console"]);
}
- }, [output]);
-
- console.log("tettt : ", testcasePassed);
+ }, [output, statusId]);
const getOutputs = () => {
+ // setStatusId(outputState[0]?.status?.id);
+
return outputState.map((output, index) => {
let statusId = output?.status?.id;
+ if (statusId == 2) {
+ return
Loading.... ;
+ }
+
if (statusId === 6) {
// compilation error
return (
{atob(output?.compile_output)}
);
} else if (statusId === 3 || statusId === 4) {
return (
-
+
@@ -95,7 +100,7 @@ const TestCasesandResult = ({ problem, testcasePassed }) => {
return (
{output?.stderr.length > 0 ? (
@@ -111,13 +116,6 @@ const TestCasesandResult = ({ problem, testcasePassed }) => {
});
};
- console.log(
- typeof Object.values(problem.testcases[activeTestCaseId]?.input)[0],
- );
- console.log(
- typeof Object.values(problem.testcases[activeTestCaseId]?.input)[0],
- );
-
return (
{/* testcase heading */}
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index d66104b..1af8f37 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -48,6 +48,8 @@ const WorkSpace = ({ data, pid, contract }) => {
const [outputState, setOutputState] = useRecoilState(outputAtom);
const user = useRecoilValue(userState);
+ console.log("user : ", user);
+
const [submissionProcessing, setSubmissionProcessing] = useState(false);
const [executionProcessing, setExecutionProcessing] = useState(false);
const [testcasePassed, setTestcasePassed] = useState(0);
@@ -59,8 +61,6 @@ const WorkSpace = ({ data, pid, contract }) => {
const setSelector = useSetRecoilState(tabsSelectorAtom);
- console.log("data : ", data);
-
const checkStatus = async (tokens, type) => {
const token = tokens.map((item) => item.token).join(",");
setTestcasePassed(0);
@@ -109,11 +109,6 @@ const WorkSpace = ({ data, pid, contract }) => {
setExecutionProcessing(false);
}
};
- // test-1
- console.log("outputstate : ", outputState);
-
- const testcaseInput = JSON.stringify(data?.examples[0]?.input);
-
const [temp, setTemp] = useState(true); // make sures that the alert pop ups only once.
const handleSubmit = async () => {
@@ -139,20 +134,20 @@ const WorkSpace = ({ data, pid, contract }) => {
const amountInSun = data.bounty * 1_000_000;
// send trx to codehive wallet
- try {
- const transaction =
- await window.tronLink.tronWeb.transactionBuilder.sendTrx(
- "TTJbVzrWBGfk82ChT61hR8cPdhAhS2FBvK",
- amountInSun,
- window.tronWeb.defaultAddress.base58,
- );
-
- console.log("transactoin : ", transaction);
- } catch (err) {
- console.log("err : ", err);
- toast.error("unknown error occured !");
- return;
- }
+ // try {
+ // const transaction =
+ // await window.tronLink.tronWeb.transactionBuilder.sendTrx(
+ // "TTJbVzrWBGfk82ChT61hR8cPdhAhS2FBvK",
+ // amountInSun,
+ // window.tronWeb.defaultAddress.base58,
+ // );
+
+ // console.log("transactoin : ", transaction);
+ // } catch (err) {
+ // console.log("err : ", err);
+ // toast.error("unknown error occured !");
+ // return;
+ // }
const formData = {
userId: user.id,
@@ -228,7 +223,6 @@ const WorkSpace = ({ data, pid, contract }) => {
};
const submissions = data.testcases.map((testCase) => {
- console.log("testCase.output : ", testCase.output);
return {
source_code: btoa(userCode + getInputString([testCase.input])),
language_id: 63,
@@ -254,7 +248,6 @@ const WorkSpace = ({ data, pid, contract }) => {
.request(options)
.then(function (response) {
const tokens = response.data;
- console.log("token : ", tokens);
checkStatus(tokens, "run");
})
.catch((err) => {
diff --git a/frontend/src/pages/MyQuestionDesc.jsx b/frontend/src/pages/MyQuestionDesc.jsx
index 5dc356f..1c0d7ec 100644
--- a/frontend/src/pages/MyQuestionDesc.jsx
+++ b/frontend/src/pages/MyQuestionDesc.jsx
@@ -12,66 +12,18 @@ import {
} from "@/components/ui/accordion";
import Navbar from "@/components/Navbar";
import axios from "axios";
-
-const fetchTHeData = async (url, fxn) => {
- console.log("fetching at the", import.meta.env.VITE_PINATA_URL + url);
- fetch(import.meta.env.VITE_PINATA_URL + url, {
- method: "GET",
- headers: {
- "ngrok-skip-browser-warning": true,
- },
- })
- .then(async (response) => {
- const decoder = new TextDecoder();
- const reader = response.body.getReader();
-
- return reader.read().then(({ value, done }) => {
- if (done) {
- console.log("Stream reading complete");
- return;
- }
- const decodedValue = decoder.decode(value, { stream: true });
- return JSON.parse(decodedValue);
- });
- })
- .then((data) => {
- console.log(data);
- fxn(data);
- })
- .catch((error) => {
- console.error("Error:", error);
- });
-};
-
-const fetchTHeCode = async (url, fxn) => {
- if (url == "") {
- //default case baby man...
- url = "bafkreib4sbyv6qwkrdpukntyv34c2qb6qqqwjr53rp4dezm4i56q4m4vsi";
- console.error("Im showing a default code cause my code was blure....");
- }
- const URL = import.meta.env.VITE_PINATA_URL + url;
-
- var myHeaders = new Headers();
- var requestOptions = {
- method: "GET",
- headers: myHeaders,
- redirect: "follow",
- };
- const data = await (await fetch(URL, requestOptions)).text();
- fxn(JSON.parse(data).code);
-};
+import { useTheContext } from "@/context";
export default function MyQuestionDesc() {
let { pid } = useParams();
const [loading, setLoading] = useState(true);
const [problem, setProblem] = useState();
const [claimer, setClaimer] = useState();
- const [claimed, setClaimed] = useState(false);
const [bounty, setBounty] = useState();
- const [codes, setCodes] = useState();
- const [name, setName] = useState();
const [difficulty, setDiff] = useState();
const [winnerCode, setWinnerCode] = useState();
+ const { tronWeb } = useTheContext();
+ const [submissions, setSubmissions] = useState([]);
const [contract, setContract] = useState();
@@ -82,13 +34,15 @@ export default function MyQuestionDesc() {
import.meta.env.VITE_BACKEND_URL + `/problems/${pid}`,
);
console.log("respnse : ", response.data);
+ setSubmissions(
+ response.data.submissions.filter((s) => s.statusDesc == "Accepted"),
+ );
setProblem(response.data);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
-
};
getProblem();
}, []);
@@ -135,9 +89,9 @@ export default function MyQuestionDesc() {
- {name}
+ {problem?.name}
- {claimed ? (
+ {problem?.bountyStatus === "CLAIMED" ? (
{problem?.description}
- {claimed && (
- // adding the winning code herer...
+ {/* {problem?.bountyStatus === "CLAIMED" && (
@@ -168,22 +121,24 @@ export default function MyQuestionDesc() {
- )}
+ )} */}
Code Submissions:
- {codes.map((code, index) => (
-
- ))}
+ {submissions.length > 0 &&
+ submissions.map((submission, index) => (
+
+ ))}
@@ -191,45 +146,41 @@ export default function MyQuestionDesc() {
);
}
-function CodeSegment({ contract, codeData, index, claimed }) {
- const [code, setCode] = useState();
+function CodeSegment({ submission, index, claimed, bounty }) {
const [loading, setLoading] = useState(true);
- useEffect(() => {
- fetchTHeCode(codeData.code, setCode);
- }, []);
- console.log(index, codeData);
- useEffect(() => {
- if (code) {
- setLoading(false);
- }
- }, [code]);
- if (loading) {
- return "skeleton small maannn";
- }
+ const { tronWeb } = useTheContext();
const fundAcc = async () => {
- //check if allready claime
- let isClaimed = await contract.claimed().call();
- if (!isClaimed) {
- //running the code to fund it.....
- //todo: set loading true
- const result = await contract.giveAway(codeData.by).send();
- console.log(result);
- //todo: set loading false
- } else {
- //todo: alert allready claimed
- }
+ const winner = submission.user.walletAddress;
+ const amount = bounty * 1000000;
+ const res = await tronWeb.trx.sendTrx(winner, amount);
+
+ // api call to update the question data on db
+ console.log("res : ", res);
};
return (
<>
- {codeData.by.slice(0, 6) + "..." + codeData.by.slice(-14)}
+
+
+ {submission.user?.username}
+
+
+ (
+ {submission.user.walletAddress.slice(0, 2) +
+ "..." +
+ submission.user.walletAddress.slice(-6)}
+ )
+
+
+
+ {/* {submission.by.} */}
- {code}
- {!claimed && (
+ {submission.code}
+ {claimed == "UNCLAIMED" && (
fundAcc()}
@@ -242,14 +193,14 @@ function CodeSegment({ contract, codeData, index, claimed }) {
Memory:{" "}
- {Math.floor(parseInt(codeData.runTime._hex, 16) / 10000)}
+ {submission.memoryUsage}b
{" "}
{/* number placed from index 4 to onwards are memory. */}
Run Time:{" "}
- {parseInt(codeData.runTime._hex, 16) % 10000}
+ {submission.runtime}ms
{" "}
{/* number placed as 0 to 3 index is the runtime of the code. */}
@@ -257,7 +208,7 @@ function CodeSegment({ contract, codeData, index, claimed }) {
Post Time:{" "}
{" "}
- {parseInt(codeData.submitTime._hex, 16)}
+ {new Date(submission.createdAt).toDateString()}
diff --git a/frontend/src/pages/MyQuestions.jsx b/frontend/src/pages/MyQuestions.jsx
index 0b3dfc0..16cfb4d 100644
--- a/frontend/src/pages/MyQuestions.jsx
+++ b/frontend/src/pages/MyQuestions.jsx
@@ -1,30 +1,35 @@
-import { useState, useEffect } from "react";
-import ComingSoon from "@/components/ComingSoon";
+import { userState } from "@/atoms/userAtom";
import MaxWidthWrapper from "@/components/MaxWidthWrapper";
-import { ABI_Bank } from "@/utils/problems";
-import { useNavigate } from "react-router-dom";
import Navbar from "@/components/Navbar";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { useTheContext } from "@/context";
+import { useNavigate } from "react-router-dom";
+import { useRecoilValue } from "recoil";
export default function MyQuestions() {
- const [Questions, setQuestions] = useState();
- useEffect(() => {
- const getQuestions = async () => {
- const contract = await window.tronLink.tronWeb.contract(
- ABI_Bank,
- import.meta.env.VITE_NILE_BANK_ADD,
- );
- const questions = await contract.questionList().call();
- setQuestions(
- questions.filter(
- (data) =>
- data.name.split("|")[1] ==
- window.tronLink.tronWeb.defaultAddress.base58,
- ),
- );
- };
- getQuestions();
- }, [ABI_Bank]);
- console.log(Questions);
+ const user = useRecoilValue(userState);
+ const questions = user.myProblems;
+
+ console.log(questions);
+
+ const { tronWeb } = useTheContext();
+ const Navigate = useNavigate();
+
+ const fundAcc = async () => {
+ const winner = "TQymTayyt9pPbSUFZjisyuanAsePL76VyG";
+ const amount = 1000000;
+ const res = await tronWeb.trx.sendTrx(winner, amount);
+
+ console.log("res : ", res);
+ };
+
return (
{/* right side */}
@@ -36,32 +41,48 @@ export default function MyQuestions() {
Your Questions
-
- {Questions &&
- Questions.map((el, index) => (
-
- ))}
-
+
+ {/*
fundAcc()}>Testtt */}
+
+
+
+ ID
+ Name
+ Status
+ Submissions
+
+
+
+
+ {questions &&
+ questions.length > 0 &&
+ questions.map((question, index) => (
+ {
+ Navigate("/myquestion/" + question.id);
+ }}
+ >
+
+
+ ))}
+
+
);
}
-function ContratElem({ el, i }) {
- const Navigate = useNavigate();
- console.log(el);
+function Question({ question, i }) {
+ console.log("question : ", question.name);
+
return (
-
{
- Navigate("/myquestion/" + el[0]);
- }}
- >
-
-
{i + 1}
-
{el[1].split("|")[0]}
-
{el[0].slice(0, 4) + "....." + el[0].slice(-8)}
-
-
+ <>
+
{i}
+
{question?.name}
+
{question.status}
+
{question?.submissions?.length || 0}
+ >
);
}
From 4d383f511939149cccbbfbc65e9802b82d6160ef Mon Sep 17 00:00:00 2001
From: spider076
Date: Sun, 6 Oct 2024 12:11:05 +0530
Subject: [PATCH 36/37] all set for deployment
---
frontend/src/App.jsx | 30 +-
frontend/src/components/AddProblemForm.jsx | 24 +-
.../src/components/problem/MySubmissions.jsx | 4 +-
frontend/src/components/problem/Nav.jsx | 4 +-
.../components/problem/ProblemDescription.jsx | 17 +-
frontend/src/components/problem/SubmitBox.jsx | 2 +-
frontend/src/components/problems/Problem.jsx | 14 +-
.../components/problems/ProblemsContainer.jsx | 2 +
frontend/src/hooks/getSubmissions.js | 22 +-
frontend/src/hooks/useDeployQuestion.js | 19 ++
frontend/src/pages/MyQuestionDesc.jsx | 266 ++++++++++++++++--
frontend/src/pages/MyQuestions.jsx | 32 +--
12 files changed, 331 insertions(+), 105 deletions(-)
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 062fc6b..429a9ce 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -15,17 +15,16 @@ import {
WalletDisconnectedError,
WalletNotFoundError,
} from "@tronweb3/tronwallet-abstract-adapter";
-import {
- WalletProvider
-} from "@tronweb3/tronwallet-adapter-react-hooks";
+import { WalletProvider } from "@tronweb3/tronwallet-adapter-react-hooks";
import { WalletModalProvider } from "@tronweb3/tronwallet-adapter-react-ui";
import "@tronweb3/tronwallet-adapter-react-ui/style.css";
import { TronLinkAdapter } from "@tronweb3/tronwallet-adapter-tronlink";
import { useEffect } from "react";
-import { useSetRecoilState } from "recoil";
+import { useRecoilState, useSetRecoilState } from "recoil";
import { authTokenState, userState } from "./atoms/userAtom";
import AlertModal from "./components/ui/AlertModal";
import { jwtDecode } from "jwt-decode";
+import axios from "axios";
globalThis.Buffer = Buffer;
@@ -54,17 +53,34 @@ function App() {
});
});
- const setAuthToken = useSetRecoilState(authTokenState);
+ const [authToken, setAuthToken] = useRecoilState(authTokenState);
const setUser = useSetRecoilState(userState);
useEffect(() => {
const token = localStorage.getItem("auth-token");
+
+ const getUser = async (userId) => {
+ try {
+ const { data } = await axios.get(
+ import.meta.env.VITE_BACKEND_URL + `/auth/user/${userId}`,
+ );
+
+ setUser(data);
+ } catch (err) {
+ console.error(err);
+ }
+ };
+
if (token) {
setAuthToken(token);
const decoded = jwtDecode(token);
- setUser(decoded?.user);
+ const userId = decoded?.user?.id;
+
+ if (userId) {
+ getUser(userId);
+ }
}
- }, [setAuthToken]);
+ }, [authToken, setAuthToken]);
return (
<>
diff --git a/frontend/src/components/AddProblemForm.jsx b/frontend/src/components/AddProblemForm.jsx
index 3fb7859..ab64599 100644
--- a/frontend/src/components/AddProblemForm.jsx
+++ b/frontend/src/components/AddProblemForm.jsx
@@ -149,24 +149,7 @@ export default function ProblemForum({ data }) {
await DEPLOY(formData, bountyValue);
};
- const testing = async (e) => {
- // bounty
- const amountInSun = 10 * 1_000_000;
-
- try {
- const transaction = await window.tronLink.tronWeb.trx.sendTrx(
- import.meta.env.VITE_CODEHIVE_WALLET |
- "TRAMAQH5hy2qSteh2WRWpwjme2ieiwg5wu",
- amountInSun,
- );
-
- console.log("transactoin : ", transaction);
- } catch (err) {
- console.log("err : ", err);
- toast.error("unknown error occured !");
- return;
- }
- };
+
return (
@@ -313,7 +296,7 @@ export default function ProblemForum({ data }) {
-
+ {/*
Hide this testcase
-
+
*/}
{
@@ -536,7 +519,6 @@ export default function ProblemForum({ data }) {
>
Prev
-
Test
{formSelector == 5 ? (
{
+const SubmissionList = ({ pid }) => {
const setActiveSubmissionId = useSetRecoilState(activeSubmissionIdState);
const setFetchSubmissionsLoading = useSetRecoilState(
fetchSubmissionsLoadingState,
);
- const submissions = useGetMySubmissions();
+ const submissions = useGetMySubmissions(pid);
if (submissions) {
return (
diff --git a/frontend/src/components/problem/Nav.jsx b/frontend/src/components/problem/Nav.jsx
index 0cb652a..67abe70 100644
--- a/frontend/src/components/problem/Nav.jsx
+++ b/frontend/src/components/problem/Nav.jsx
@@ -23,8 +23,8 @@ const Nav = () => {
size={28}
onClick={() => navigate(-1)}
/>
- {"Problem 1"}
-
+ {"Problem"}
+ {/* */}
{/* right side */}
diff --git a/frontend/src/components/problem/ProblemDescription.jsx b/frontend/src/components/problem/ProblemDescription.jsx
index bfa3c2e..f4cbb26 100644
--- a/frontend/src/components/problem/ProblemDescription.jsx
+++ b/frontend/src/components/problem/ProblemDescription.jsx
@@ -21,7 +21,6 @@ const ProblemDescription = ({ problem, pid, contract }) => {
//const { tronWeb } = useTheContext();
const location = useLocation();
const [claimer, setClaimer] = useState();
- const [bounty, setBounty] = useState();
const [isClaimed, setIsClaimed] = useState(false);
const [selector, setSelector] = useRecoilState(tabsSelectorAtom);
@@ -70,7 +69,7 @@ const ProblemDescription = ({ problem, pid, contract }) => {
return (
-
+
{/* TAB */}
{
Bounty Status :
{" "}
- {!bounty
+ {problem?.status != "Funded"
? "Not yet Set"
- : isClaimed
+ : problem?.bountyStatus == "CLAIMED"
? "Already Claimed"
: "Is yet to be Claimed."}
- {bounty && (
+ {problem?.bounty && (
- Reward if you solve this : {bounty / 1000000} TRX
+ Reward if you solve this : {problem?.bounty} TRX
)}
@@ -214,7 +213,11 @@ const ProblemDescription = ({ problem, pid, contract }) => {
)} */}
{selector == 2 &&
!loading &&
- (activeSubmissionId ?
:
)}
+ (activeSubmissionId ? (
+
+ ) : (
+
+ ))}
);
diff --git a/frontend/src/components/problem/SubmitBox.jsx b/frontend/src/components/problem/SubmitBox.jsx
index 56c4b51..6b2a9c3 100644
--- a/frontend/src/components/problem/SubmitBox.jsx
+++ b/frontend/src/components/problem/SubmitBox.jsx
@@ -19,7 +19,7 @@ const SubmitBox = ({
>
{executionLoading && (
)}{" "}
diff --git a/frontend/src/components/problems/Problem.jsx b/frontend/src/components/problems/Problem.jsx
index e51f11e..49a8234 100644
--- a/frontend/src/components/problems/Problem.jsx
+++ b/frontend/src/components/problems/Problem.jsx
@@ -19,7 +19,9 @@ const Problem = ({
difficulty,
isOpen,
handleOpen,
+ bounty,
status,
+ submissions,
}) => {
const navigate = useNavigate();
@@ -87,17 +89,19 @@ const Problem = ({
/>
- {/*
-
- Problem address :
- {address}
+
+ Bounty Set :{bounty}TRX
+
+ Total Submissions : {submissions}{" "}
+
- */}
+
>
);
};
diff --git a/frontend/src/components/problems/ProblemsContainer.jsx b/frontend/src/components/problems/ProblemsContainer.jsx
index 19a9da2..b50968b 100644
--- a/frontend/src/components/problems/ProblemsContainer.jsx
+++ b/frontend/src/components/problems/ProblemsContainer.jsx
@@ -104,6 +104,8 @@ const ProblemsContainer = () => {
title={p.name.split("|")[0]}
address={p.question}
difficulty={p.difficulty}
+ bounty={p.bounty}
+ submissions={p.submissions.length}
isOpen={isOpen}
isAnyOpen={isAnyOpen}
handleOpen={handleOpen}
diff --git a/frontend/src/hooks/getSubmissions.js b/frontend/src/hooks/getSubmissions.js
index 0c18466..e03e31c 100644
--- a/frontend/src/hooks/getSubmissions.js
+++ b/frontend/src/hooks/getSubmissions.js
@@ -4,15 +4,16 @@ import { useEffect, useState } from "react";
import { useRecoilValue } from "recoil";
import { toast } from "sonner";
-export const useGetMySubmissions = () => {
+export const useGetMySubmissions = (problemid) => {
const [submissions, setSubmission] = useState([]);
const { id: userId } = useRecoilValue(userState);
-
-useEffect(() => {
- (async () => {
+ useEffect(() => {
+ (async () => {
await axios
- .get(import.meta.env.VITE_BACKEND_URL + "/code/submissions?userid=" + userId)
+ .get(
+ `${import.meta.env.VITE_BACKEND_URL}/code/submissions?userid=${userId}&problemid=${problemid}`,
+ )
.then((res) => {
setSubmission(res.data);
})
@@ -30,17 +31,16 @@ export const useGetAllSubmissions = () => {
const [submission, setSubmission] = useState([]);
const { id: userId } = useRecoilValue(userState);
-
-useEffect(() => {
- (async () => {
+ useEffect(() => {
+ (async () => {
await axios
.get(import.meta.env.VITE_BACKEND_URL + "/code/submission/", {
headers: {
"Content-Type": "application/json",
},
data: {
- userid: userId
- }
+ userid: userId,
+ },
})
.then((res) => {
setSubmission(res.data);
@@ -53,4 +53,4 @@ useEffect(() => {
}, []);
return submission;
-}
+};
diff --git a/frontend/src/hooks/useDeployQuestion.js b/frontend/src/hooks/useDeployQuestion.js
index 8297d9a..a592b4b 100644
--- a/frontend/src/hooks/useDeployQuestion.js
+++ b/frontend/src/hooks/useDeployQuestion.js
@@ -18,6 +18,25 @@ export default function useDeployQuestion() {
const [, setStatus] = useRecoilState(questionAddStatus);
+ const testing = async (e) => {
+ // bounty
+ const amountInSun = 10 * 1_000_000;
+
+ try {
+ const transaction = await window.tronLink.tronWeb.trx.sendTrx(
+ import.meta.env.VITE_CODEHIVE_WALLET |
+ "TRAMAQH5hy2qSteh2WRWpwjme2ieiwg5wu",
+ amountInSun,
+ );
+
+ console.log("transactoin : ", transaction);
+ } catch (err) {
+ console.log("err : ", err);
+ toast.error("unknown error occured !");
+ return;
+ }
+ };
+
const DEPLOY = useCallback(async (formData, bounty) => {
setStateOfTransaction(0); // Deploying the question
setStatus(0);
diff --git a/frontend/src/pages/MyQuestionDesc.jsx b/frontend/src/pages/MyQuestionDesc.jsx
index 1c0d7ec..c4f9e24 100644
--- a/frontend/src/pages/MyQuestionDesc.jsx
+++ b/frontend/src/pages/MyQuestionDesc.jsx
@@ -2,7 +2,7 @@ import React, { useState, useEffect } from "react";
import MaxWidthWrapper from "@/components/MaxWidthWrapper";
// import Nav from "@/components/problems/Nav";
import { ABI } from "@/utils/problems";
-import { useParams } from "react-router-dom";
+import { Link, Router, useParams } from "react-router-dom";
import { SkeletonPage } from "@/components/SkeletonPage";
import {
Accordion,
@@ -13,27 +13,29 @@ import {
import Navbar from "@/components/Navbar";
import axios from "axios";
import { useTheContext } from "@/context";
+import { ArrowLeft, Loader2 } from "lucide-react";
+import { signMessageWithTimeConstraint } from "@/hooks/SigMessage";
+import { toast } from "sonner";
export default function MyQuestionDesc() {
let { pid } = useParams();
const [loading, setLoading] = useState(true);
+ const [fundLoading, setFundLoading] = useState(false);
const [problem, setProblem] = useState();
const [claimer, setClaimer] = useState();
- const [bounty, setBounty] = useState();
const [difficulty, setDiff] = useState();
- const [winnerCode, setWinnerCode] = useState();
+ const [winnerDetails, setWinnerDetails] = useState();
const { tronWeb } = useTheContext();
const [submissions, setSubmissions] = useState([]);
const [contract, setContract] = useState();
useEffect(() => {
- const getProblem = async () => {
+ const getProblemandwinner = async () => {
try {
const response = await axios.get(
import.meta.env.VITE_BACKEND_URL + `/problems/${pid}`,
);
- console.log("respnse : ", response.data);
setSubmissions(
response.data.submissions.filter((s) => s.statusDesc == "Accepted"),
);
@@ -44,9 +46,77 @@ export default function MyQuestionDesc() {
setLoading(false);
}
};
- getProblem();
+ getProblemandwinner();
}, []);
+ const fundProblem = async (e) => {
+ const txnData = await signMessageWithTimeConstraint();
+
+ try {
+ if (!txnData?.message) {
+ throw new Error("Transaction failed !");
+ }
+
+ setFundLoading(true);
+
+ const amountInSun = problem?.bounty * 1_000_000;
+ const txn = await window.tronLink.tronWeb.trx.sendTrx(
+ import.meta.env.VITE_CODEHIVE_WALLET ??
+ "TQymTayyt9pPbSUFZjisyuanAsePL76VyG",
+ amountInSun,
+ );
+ console.log("sdfsfs");
+
+ console.log("txn : ", txn);
+
+ if (!txn?.result) {
+ throw new Error("Transaction Failed !");
+ } else {
+ const options = {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ tron_message: txnData.message,
+ tron_signature: txnData.signature,
+ },
+ body: JSON.stringify({
+ problemId: pid,
+ }),
+ };
+
+ if (!window.tron.tronWeb.ready) {
+ toast.error("TronWeb not ready");
+ throw new Error("TronWeb not ready");
+ }
+
+ const response = await fetch(
+ import.meta.env.VITE_BACKEND_URL + "/code/fundproblem",
+ options,
+ );
+ const data = await response.json();
+ console.log("data; ", data);
+
+ if (response.ok) {
+ toast.success("Problem successfully funded !");
+ setTimeout(() => {
+ window.location.reload();
+ }, 4000);
+ } else {
+ throw new Error(
+ `Failed to fund problem. Status: ${data.status}, ${data.message}`,
+ );
+ }
+ }
+ } catch (err) {
+ console.error("Error during funding:", err);
+ const errMsg =
+ err?.message ?? "Error occurred, failed to fund the problem!";
+ toast.error(errMsg);
+ } finally {
+ setFundLoading(false);
+ }
+ };
+
if (loading) {
return (
@@ -86,6 +156,13 @@ export default function MyQuestionDesc() {
+
+
+ Back to Questions
+
@@ -103,42 +180,101 @@ export default function MyQuestionDesc() {
)}
-
{pid}
+
+ {problem?.status == "Unfunded" &&
+ (fundLoading ? (
+
+
+ Funding
+
+ ) : (
+
+ Fund Problem
+
+ ))}
+
+
+ {problem?.bounty} TRX Bounty
+
+
{problem?.description}
+ {problem?.txnHash && problem?.txnHash.length > 0 && (
+
+ )}
+
- {/* {problem?.bountyStatus === "CLAIMED" && (
+ {problem?.bountyStatus === "CLAIMED" && problem?.winnerCode && (
- Winner Code
+ Winner Details
-
- {winnerCode}
+
+
+
+ Winner : {problem?.winnerCode?.user?.username}
+
+ (
+ {problem?.winnerCode?.user?.walletAddress.slice(
+ 0,
+ 2,
+ ) +
+ "..." +
+ problem?.winnerCode?.user?.walletAddress.slice(-6)}
+ )
+
+
+
+
+
+ Code :{" "}
+
+ {problem?.winnerCode?.code}
- )} */}
+ )}
Code Submissions:
- {submissions.length > 0 &&
+ {submissions.length > 0 ? (
submissions.map((submission, index) => (
- ))}
+ ))
+ ) : (
+ No Submissions made !
+ )}
@@ -146,16 +282,75 @@ export default function MyQuestionDesc() {
);
}
-function CodeSegment({ submission, index, claimed, bounty }) {
- const [loading, setLoading] = useState(true);
+function CodeSegment({ submission, index, claimed, bounty, pid }) {
+ const [loading, setLoading] = useState(false);
const { tronWeb } = useTheContext();
- const fundAcc = async () => {
- const winner = submission.user.walletAddress;
- const amount = bounty * 1000000;
- const res = await tronWeb.trx.sendTrx(winner, amount);
+ const fundWinner = async (e) => {
+ e.preventDefault();
+ const txnData = await signMessageWithTimeConstraint();
+
+ try {
+ if (!txnData?.message) {
+ throw new Error("Transaction failed !");
+ }
+
+ setLoading(true);
- // api call to update the question data on db
- console.log("res : ", res);
+ const winner = submission.user.walletAddress;
+ const amount = bounty * 1000000;
+ const txn = await tronWeb.trx.sendTrx(winner, amount);
+
+ console.log("txn : ", txn);
+
+ if (!txn?.result) {
+ throw new Error("Transaction Failed !");
+ } else {
+ const options = {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ tron_message: txnData.message,
+ tron_signature: txnData.signature,
+ },
+ body: JSON.stringify({
+ winnerId: submission.user.id,
+ problemId: pid,
+ txnHash: txn.txid,
+ winnerSubId: submission.id,
+ }),
+ };
+
+ if (!window.tron.tronWeb.ready) {
+ toast.error("TronWeb not ready");
+ throw new Error("TronWeb not ready");
+ }
+
+ const response = await fetch(
+ import.meta.env.VITE_BACKEND_URL + "/code/fundwinner",
+ options,
+ );
+ const data = await response.json();
+ console.log("data; ", data);
+
+ if (response.ok) {
+ toast.success("Winner successfully funded !");
+ setTimeout(() => {
+ window.location.reload();
+ }, 4000);
+ } else {
+ throw new Error(
+ `Failed to fund winner. Status: ${data.status}, ${data.message}`,
+ );
+ }
+ }
+ } catch (err) {
+ console.error("Error during funding:", err.message);
+ const errMsg =
+ err?.message ?? "Error occurred, failed to fund the winner!";
+ toast.error(errMsg);
+ } finally {
+ setLoading(false);
+ }
};
return (
@@ -180,14 +375,23 @@ function CodeSegment({ submission, index, claimed, bounty }) {
{submission.code}
- {claimed == "UNCLAIMED" && (
- fundAcc()}
- >
- Fund This
-
- )}
+ {claimed == "UNCLAIMED" &&
+ (loading ? (
+
+
+ Funding
+
+ ) : (
+
+ Fund This
+
+ ))}
diff --git a/frontend/src/pages/MyQuestions.jsx b/frontend/src/pages/MyQuestions.jsx
index 16cfb4d..afa1b04 100644
--- a/frontend/src/pages/MyQuestions.jsx
+++ b/frontend/src/pages/MyQuestions.jsx
@@ -9,37 +9,35 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
-import { useTheContext } from "@/context";
-import { useNavigate } from "react-router-dom";
+import { ArrowLeft } from "lucide-react";
+import { Link, useNavigate } from "react-router-dom";
import { useRecoilValue } from "recoil";
export default function MyQuestions() {
const user = useRecoilValue(userState);
const questions = user.myProblems;
- console.log(questions);
+ console.log(user);
- const { tronWeb } = useTheContext();
const Navigate = useNavigate();
- const fundAcc = async () => {
- const winner = "TQymTayyt9pPbSUFZjisyuanAsePL76VyG";
- const amount = 1000000;
- const res = await tronWeb.trx.sendTrx(winner, amount);
-
- console.log("res : ", res);
- };
-
return (
{/* right side */}
-
-
+
+
Your Questions
+
+
+
Problems
+
{/*
fundAcc()}>Testtt */}
@@ -59,12 +57,12 @@ export default function MyQuestions() {
questions.map((question, index) => (
{
Navigate("/myquestion/" + question.id);
}}
>
-
+
))}
@@ -75,8 +73,6 @@ export default function MyQuestions() {
}
function Question({ question, i }) {
- console.log("question : ", question.name);
-
return (
<>
{i}
From d2c019a4b8f5c03a9418d8c6f67ed9715f84105d Mon Sep 17 00:00:00 2001
From: spider076
Date: Thu, 24 Oct 2024 00:42:45 +0530
Subject: [PATCH 37/37] minor changes
---
frontend/src/components/problem/SubmitBox.jsx | 22 +++++++++++++------
frontend/src/components/problem/Workspace.jsx | 16 +++++++++-----
2 files changed, 26 insertions(+), 12 deletions(-)
diff --git a/frontend/src/components/problem/SubmitBox.jsx b/frontend/src/components/problem/SubmitBox.jsx
index 6b2a9c3..b340866 100644
--- a/frontend/src/components/problem/SubmitBox.jsx
+++ b/frontend/src/components/problem/SubmitBox.jsx
@@ -7,6 +7,7 @@ const SubmitBox = ({
handleSubmit,
handleRun,
submissionloading,
+ problem,
}) => {
return (
@@ -19,7 +20,7 @@ const SubmitBox = ({
>
{executionLoading && (
)}{" "}
@@ -31,12 +32,19 @@ const SubmitBox = ({
Please wait
) : (
-
- Submit
-
+ <>
+ {problem?.bountyStatus == "CLAIMED" ||
+ problem?.status == "UNFUNDED" ? (
+
+ ) : (
+
+ Submit
+
+ )}
+ >
)}
diff --git a/frontend/src/components/problem/Workspace.jsx b/frontend/src/components/problem/Workspace.jsx
index 1af8f37..af1b766 100644
--- a/frontend/src/components/problem/Workspace.jsx
+++ b/frontend/src/components/problem/Workspace.jsx
@@ -48,7 +48,7 @@ const WorkSpace = ({ data, pid, contract }) => {
const [outputState, setOutputState] = useRecoilState(outputAtom);
const user = useRecoilValue(userState);
- console.log("user : ", user);
+ console.log("user : ", data);
const [submissionProcessing, setSubmissionProcessing] = useState(false);
const [executionProcessing, setExecutionProcessing] = useState(false);
@@ -183,6 +183,8 @@ const WorkSpace = ({ data, pid, contract }) => {
);
const data = res.data;
+ console.log("data : ", data);
+
setSubmissionResult((prev) => ({
...prev,
[response.data.submissionId]: data,
@@ -214,17 +216,20 @@ const WorkSpace = ({ data, pid, contract }) => {
setExecutionProcessing(true);
const getInputString = (args) => {
+ let validateArgs = Array.isArray(args) ? args.join(",") : `"${args}"`;
return `\n
-
-
- console.log(${data?.compileFunctionName}(${args.join(",")}))
+ console.log(${data?.compileFunctionName}(${validateArgs}))
`;
};
const submissions = data.testcases.map((testCase) => {
+ let testCaseInput = testCase?.input.startsWith("[")
+ ? [testCase.input]
+ : String(testCase.input);
+
return {
- source_code: btoa(userCode + getInputString([testCase.input])),
+ source_code: btoa(userCode + getInputString(testCaseInput)),
language_id: 63,
expected_output: btoa(testCase.output),
};
@@ -300,6 +305,7 @@ const WorkSpace = ({ data, pid, contract }) => {
executionLoading={executionProcessing}
submissionloading={submissionProcessing}
handleRun={handleRun}
+ problem={data}
/>
{success && (