Skip to content

Commit

Permalink
partial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
yashgo0018 committed Apr 26, 2024
1 parent af70db4 commit c70fbaa
Show file tree
Hide file tree
Showing 27 changed files with 6,905 additions and 98 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"workspaces": {
"packages": [
"packages/hardhat",
"packages/nextjs"
"packages/nextjs",
"packages/prover"
]
},
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/hardhat/deploy/99_generateTsAbis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ const generateTsAbis: DeployFunction = async function () {
fs.writeFileSync(
`${TARGET_DIR}deployedContracts.ts`,
prettier.format(
`${generatedContractComment} import { GenericContractsDeclaration } from "~~/utils/scaffold-eth/contract"; \n\n
`${generatedContractComment} import { GenericContractsDeclaration } from "../utils/scaffold-eth/contract"; \n\n
const deployedContracts = {${fileContent}} as const; \n\n export default deployedContracts satisfies GenericContractsDeclaration`,
{
parser: "typescript",
Expand Down
37 changes: 33 additions & 4 deletions packages/nextjs/app/admin/_components/CreatePollModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import { RxCross2 } from "react-icons/rx";
import Modal from "~~/components/Modal";
import { useScaffoldContractWrite } from "~~/hooks/scaffold-eth";

enum PollType {
SINGLE_VOTE,
MULTIPLE_VOTE,
}

export default function Example({
show,
setOpen,
Expand All @@ -15,7 +20,12 @@ export default function Example({
setOpen: (value: boolean) => void;
refetchPolls: () => void;
}) {
const [pollData, setPollData] = useState({ title: "Dummy Title", options: [""] });
const [pollData, setPollData] = useState({
title: "Dummy Title",
expiry: new Date(),
pollType: PollType.SINGLE_VOTE,
options: [""],
});
const [isEditingTitle, setIsEditingTitle] = useState<boolean>(false);

const handleAddOption = () => {
Expand Down Expand Up @@ -46,14 +56,30 @@ export default function Example({
setPollData({ ...pollData, options: newOptions });
}

const { writeAsync, data, isLoading } = useScaffoldContractWrite({
const duration = Math.round((new Date().getTime() - pollData.expiry.getTime()) / 1000);

const { writeAsync } = useScaffoldContractWrite({
contractName: "PollManager",
functionName: "createPoll",
args: [pollData?.title, pollData?.options || [], "", 60n],
args: [pollData?.title, pollData?.options || [], "", duration > 0 ? BigInt(duration) : 0n],
});

async function onSubmit() {
console.log("A");
// validate the inputs
for (const option of pollData.options) {
if (!option) {
// TODO: throw error that the option cannot be blank
return;
}
}

if (duration < 60) {
// TODO: throw error that the expiry cannot be before atleast 1 min of creation
return;
}

// save the poll data to ipfs or find another way for saving the poll type on the smart contract.

try {
await writeAsync();
refetchPolls();
Expand Down Expand Up @@ -107,6 +133,9 @@ export default function Example({
</label>
</div>

{/* Datetime selector here */}
{/* Poll Type Selector Here */}

<div className="w-full h-[0.5px] bg-[#3647A4] shadow-2xl my-5" />

<div className="mb-3 text-neutral-content">Create the options</div>
Expand Down
61 changes: 55 additions & 6 deletions packages/nextjs/app/api/polls/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,56 @@
import { NextRequest, NextResponse } from "next/server";
import { coordinator } from "~~/utils/coordinator";
"use server";

export const POST = async (req: NextRequest, { params: { id } }: { params: { id: string } }) => {
coordinator.closePoll(parseInt(id));
return NextResponse.json({ message: "Hello, World!" });
};
import { NextResponse } from "next/server";

// import { execSync } from "child_process";
// import fs from "fs";
// import { pollManagerContract } from "~~/constants";
// import { mergeMessages } from "~~/utils/mergeMessages";
// import { mergeSignups } from "~~/utils/mergeSignups";

export async function POST(req: Request) {
let pollId: string;
try {
pollId = (await req.json()).pollId;
} catch (err) {
return NextResponse.json({ error: "invalid body" }, { status: 409 });
}

if (!pollId) {
return NextResponse.json({ error: "invalid body" }, { status: 409 });
}

// try {
// const poll = await pollManagerContract.read.fetchPoll([BigInt(pollId)]);

// await mergeSignups({ pollContractAddress: poll.pollContracts.poll });
// await mergeMessages({ pollContractAddress: poll.pollContracts.poll });

// const cliDirectory = "/Users/yash/Development/buidlguidl/maci/cli";
// const dataFile = `${cliDirectory}/tally-${poll.maciPollId.toString()}.json`;
// execSync(
// `node ${cliDirectory}/build/ts/index.js genProofs \
// --privkey ${process.env.COORDINATOR_PRIVATE_KEY} \
// --poll-id ${poll.maciPollId.toString()} \
// --process-zkey ${cliDirectory}/zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test.0.zkey \
// --tally-zkey ${cliDirectory}/zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test.0.zkey \
// --tally-file ${dataFile} \
// --output proofs1/ \
// -tw ${cliDirectory}/zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test_js/TallyVotes_10-1-2_test.wasm \
// -pw ${cliDirectory}/zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test_js/ProcessMessages_10-2-1-2_test.wasm \
// -w true`,
// { encoding: "utf-8" },
// ); // the default is 'buffer'

// const data = JSON.parse(fs.readFileSync(dataFile).toString("utf-8"));

// const votesSerialized = JSON.stringify(data.results.tally.slice(0, 10).map((v: any) => (v ? parseInt(v) || 0 : 0)));

// console.log(votesSerialized);
// } catch (err) {
// console.log(err);
// return NextResponse.json({ error: "something went wrong" }, { status: 500 });
// }

return NextResponse.json({ message: "finalized the poll successfully" });
}
60 changes: 40 additions & 20 deletions packages/nextjs/app/polls/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ export default function PollDetail() {

const { keypair, stateIndex } = useAuthContext();

const [votes] = useState<{ index: number; votes: number; voteMessage: { message: Message; encKeyPair: Keypair } }[]>(
[],
);

const [clickedIndex, setClickedIndex] = useState<number | null>(null);
const handleCardClick = (index: number) => {
setClickedIndex(clickedIndex === index ? null : index);
Expand All @@ -28,23 +32,30 @@ export default function PollDetail() {
const castVote = async () => {
console.log("Voting for candidate", clickedIndex);
console.log("A", message?.message.asContractParam(), message?.encKeyPair.pubKey.asContractParam());
// navigate to the home page
try {
// setLoaderMessage("Casting the vote, please wait...");

await writeAsync();
// router.push(`/voted-success?id=${clickedIndex}`);
} catch (err) {
console.log("err", err);
// toast.error("Casting vote failed, please try again ");
}
// // navigate to the home page
// try {
// // setLoaderMessage("Casting the vote, please wait...");

// // router.push(`/voted-success?id=${clickedIndex}`);
// } catch (err) {
// console.log("err", err);
// // toast.error("Casting vote failed, please try again ");
// }
};

const { data: maxValues } = useContractRead({
abi: PollAbi,
address: poll?.pollContracts.poll,
functionName: "maxValues",
});
useEffect(() => {
if (votes.length === 0) {
return;
}

(async () => {
try {
await writeAsync();
} catch (err) {
console.log({ err });
}
})();
}, [votes]);

const { data: coordinatorPubKeyResult } = useContractRead({
abi: PollAbi,
Expand Down Expand Up @@ -79,16 +90,26 @@ export default function PollDetail() {
}, [coordinatorPubKeyResult]);

useEffect(() => {
if (!clickedIndex || !coordinatorPubKey || !keypair || !stateIndex) {
if (clickedIndex === null || !coordinatorPubKey || !keypair || !stateIndex) {
return;
}

const command: PCommand = new PCommand(
console.log(
stateIndex, // stateindex
keypair.pubKey, // userMaciPubKey
BigInt(clickedIndex),
1n,
1n, // nonce
BigInt(id),
genRandomSalt(),
);

const command: PCommand = new PCommand(
stateIndex, // stateindex
keypair.pubKey, // userMaciPubKey
BigInt(clickedIndex),
1n,
1n, // nonce
BigInt(id),
genRandomSalt(),
);
Expand All @@ -102,9 +123,6 @@ export default function PollDetail() {
setMessage({ message, encKeyPair });
}, [id, clickedIndex, coordinatorPubKey, keypair, stateIndex]);

console.log(maxValues && (maxValues as any)[1]);
console.log(coordinatorPubKeyResult);

if (isLoading) return <div>Loading...</div>;

if (error) return <div>Poll not found</div>;
Expand All @@ -121,6 +139,8 @@ export default function PollDetail() {
<VoteCard clicked={clickedIndex === index} onClick={() => handleCardClick(index)}>
<div>{candidate}</div>
</VoteCard>

{/* add a votes number input here */}
</div>
))}
<div className={`mt-2 ${clickedIndex !== null ? " shadow-2xl" : ""}`}>
Expand Down
36 changes: 36 additions & 0 deletions packages/nextjs/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"use server";

import deployedContracts from "./contracts/deployedContracts";
import scaffoldConfig from "./scaffold.config";
import { createPublicClient, createWalletClient, getContract, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";

export const chain = scaffoldConfig.targetNetworks[0];

export const publicClient = createPublicClient({ chain, transport: http() });

console.log(process.env.SERVER_PRIVATE_KEY as `0x${string}`);

export const serverAccount = privateKeyToAccount(process.env.SERVER_PRIVATE_KEY as `0x${string}`);
export const serverWalletClient = createWalletClient({
chain: chain,
transport: http(),
key: process.env.SERVER_PRIVATE_KEY,
account: serverAccount,
});

export const pollManagerContract = getContract({
abi: deployedContracts[chain.id].PollManager.abi,
address: deployedContracts[chain.id].PollManager.address,
publicClient: publicClient,
walletClient: serverWalletClient,
});

export const maciContract = getContract({
abi: deployedContracts[chain.id].MACI.abi,
address: deployedContracts[chain.id].MACI.address,
publicClient: publicClient,
walletClient: serverWalletClient,
});

export const deploymentBlock = BigInt(deployedContracts[chain.id].MACI.deploymentBlockNumber);
21 changes: 8 additions & 13 deletions packages/nextjs/contracts/deployedContracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* This file is autogenerated by Scaffold-ETH.
* You should not edit it manually or your changes might be overwritten.
*/
import { GenericContractsDeclaration } from "~~/utils/scaffold-eth/contract";
import { GenericContractsDeclaration } from "../utils/scaffold-eth/contract";

const deployedContracts = {
31337: {
Expand Down Expand Up @@ -46,8 +46,7 @@ const deployedContracts = {
},
],
inheritedFunctions: {
getVoiceCredits:
"contracts/maci-contracts/initialVoiceCreditProxy/InitialVoiceCreditProxy.sol",
getVoiceCredits: "contracts/maci-contracts/initialVoiceCreditProxy/InitialVoiceCreditProxy.sol",
},
deploymentBlockNumber: 1,
},
Expand Down Expand Up @@ -1098,8 +1097,7 @@ const deployedContracts = {
hash4: "contracts/maci-contracts/utilities/Utilities.sol",
hash5: "contracts/maci-contracts/utilities/Utilities.sol",
hashLeftRight: "contracts/maci-contracts/utilities/Utilities.sol",
hashMessageAndEncPubKey:
"contracts/maci-contracts/utilities/Utilities.sol",
hashMessageAndEncPubKey: "contracts/maci-contracts/utilities/Utilities.sol",
hashStateLeaf: "contracts/maci-contracts/utilities/Utilities.sol",
padAndHashMessage: "contracts/maci-contracts/utilities/Utilities.sol",
sha256Hash: "contracts/maci-contracts/utilities/Utilities.sol",
Expand Down Expand Up @@ -1166,8 +1164,7 @@ const deployedContracts = {
},
],
inheritedFunctions: {
MESSAGE_DATA_LENGTH:
"contracts/maci-contracts/utilities/DomainObjs.sol",
MESSAGE_DATA_LENGTH: "contracts/maci-contracts/utilities/DomainObjs.sol",
},
deploymentBlockNumber: 19,
},
Expand Down Expand Up @@ -1294,14 +1291,13 @@ const deployedContracts = {
},
],
inheritedFunctions: {
MESSAGE_DATA_LENGTH:
"contracts/maci-contracts/utilities/DomainObjs.sol",
MESSAGE_DATA_LENGTH: "contracts/maci-contracts/utilities/DomainObjs.sol",
deploy: "contracts/maci-contracts/interfaces/IPollFactory.sol",
},
deploymentBlockNumber: 17,
},
PollManager: {
address: "0xc3e53F4d16Ae77Db1c982e75a937B9f60FE63690",
address: "0x0B306BF915C4d645ff596e518fAf3F9669b97016",
abi: [
{
inputs: [
Expand Down Expand Up @@ -1902,10 +1898,9 @@ const deployedContracts = {
},
],
inheritedFunctions: {
MESSAGE_DATA_LENGTH:
"contracts/maci-contracts/utilities/DomainObjs.sol",
MESSAGE_DATA_LENGTH: "contracts/maci-contracts/utilities/DomainObjs.sol",
},
deploymentBlockNumber: 48,
deploymentBlockNumber: 29,
},
PoseidonT3: {
address: "0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9",
Expand Down
5 changes: 5 additions & 0 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
"@se-2/hardhat": "*",
"@uniswap/sdk-core": "^4.0.1",
"@uniswap/v2-sdk": "^3.0.1",
"@zk-kit/circuits": "^0.4.0",
"blo": "^1.0.1",
"circomkit": "^0.0.24",
"circomlib": "^2.0.5",
"daisyui": "4.5.0",
"next": "^14.0.4",
"next-themes": "^0.2.1",
Expand All @@ -32,6 +35,7 @@
"react-dom": "^18.2.0",
"react-hot-toast": "^2.4.0",
"react-icons": "^5.0.1",
"snarkjs": "^0.7.3",
"use-debounce": "^8.0.4",
"usehooks-ts": "^2.13.0",
"viem": "1.19.9",
Expand All @@ -44,6 +48,7 @@
"@types/nprogress": "^0",
"@types/react": "^18.0.9",
"@types/react-copy-to-clipboard": "^5.0.4",
"@types/snarkjs": "^0",
"@typescript-eslint/eslint-plugin": "^5.39.0",
"autoprefixer": "^10.4.12",
"eslint": "^8.15.0",
Expand Down
Loading

0 comments on commit c70fbaa

Please sign in to comment.