Skip to content

Commit

Permalink
feat: script for vote in package json
Browse files Browse the repository at this point in the history
  • Loading branch information
Spacylion committed Mar 23, 2024
1 parent fcbe6f1 commit 8f02800
Show file tree
Hide file tree
Showing 10 changed files with 245 additions and 202 deletions.
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions .idea/week2.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions configs/viemConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {createPublicClient, createWalletClient, http} from "viem";
import {sepolia} from "viem/chains";
import {privateKeyToAccount} from "viem/accounts";

/** FOR READ CONTRACTS*/
export const publicClient = createPublicClient({
batch: {
multicall: true,
},
chain: sepolia,
transport: http(),
})

/** FOR WRITE CONTRACTS*/
export type HexStringType = `0x${string}`;

const privateKey: HexStringType = `0x${process.env.PRIVATE_KEY}`;
const account = privateKeyToAccount(privateKey)
export const privateClient = createWalletClient({
account,
chain: sepolia,
transport: http()
})
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"delegate": "",
"vote": "npx ts-node ./scripts/viem/CastVote.ts 0xe3c392ce25492b970775de78a157677e04a617e7 1",
"giveRightToVote": "",
"winningProposal": ""
},

"author": "",
"license": "ISC",
"devDependencies": {
Expand Down
56 changes: 28 additions & 28 deletions scripts/hardhat/Deploy.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
import { viem } from "hardhat";
import { formatEther, hexToString, toHex } from "viem";
import {viem} from "hardhat";
import {formatEther, hexToString, toHex} from "viem";

const PROPOSALS = ["Proposal 1", "Proposal 2", "Proposal 3"];

async function main() {
const publicClient = await viem.getPublicClient();
const blockNumber = await publicClient.getBlockNumber();
console.log("Last block number:", blockNumber);
const publicClient = await viem.getPublicClient();
const blockNumber = await publicClient.getBlockNumber();
console.log("Last block number:", blockNumber);

const [deployer] = await viem.getWalletClients();
console.log("Deployer address:", deployer.account.address);
const balance = await publicClient.getBalance({
address: deployer.account.address,
});
console.log(
"Deployer balance:",
formatEther(balance),
deployer.chain.nativeCurrency.symbol
);
const [deployer] = await viem.getWalletClients();
console.log("Deployer address:", deployer.account.address);
const balance = await publicClient.getBalance({
address: deployer.account.address,
});
console.log(
"Deployer balance:",
formatEther(balance),
deployer.chain.nativeCurrency.symbol
);

console.log("\nDeploying Ballot contract");
const ballotContract = await viem.deployContract("Ballot", [
PROPOSALS.map((prop) => toHex(prop, { size: 32 })),
]);
console.log("Ballot contract deployed to:", ballotContract.address);
console.log("Proposals: ");
for (let index = 0; index < PROPOSALS.length; index++) {
const proposal = await ballotContract.read.proposals([BigInt(index)]);
const name = hexToString(proposal[0], { size: 32 });
console.log({ index, name, proposal });
}
console.log("\nDeploying Ballot contract");
const ballotContract = await viem.deployContract("Ballot", [
PROPOSALS.map((prop) => toHex(prop, {size: 32})),
]);
console.log("Ballot contract deployed to:", ballotContract.address);
console.log("Proposals: ");
for (let index = 0; index < PROPOSALS.length; index++) {
const proposal = await ballotContract.read.proposals([BigInt(index)]) as unknown;
const name = hexToString((proposal as any)[0], {size: 32});
console.log({index, name, proposal});
}
}

main().catch((error) => {
console.error(error);
process.exitCode = 1;
console.error(error);
process.exitCode = 1;
});
118 changes: 54 additions & 64 deletions scripts/viem/CastVote.ts
Original file line number Diff line number Diff line change
@@ -1,77 +1,67 @@
import {
createPublicClient,
createWalletClient,
hexToString,
http,
} from "viem";
import { sepolia } from "viem/chains";
import {
abi,
bytecode,
} from "../../artifacts/contracts/Ballot.sol/Ballot.json";
import {createPublicClient, createWalletClient, hexToString, http,} from "viem";
import {sepolia} from "viem/chains";
import {abi} from "../../artifacts/contracts/Ballot.sol/Ballot.json";

import * as dotenv from "dotenv";
import { privateKeyToAccount } from "viem/accounts";
import {privateKeyToAccount} from "viem/accounts";

dotenv.config();

const deployerPrivateKey = process.env.PRIVATE_KEY || "";
const providerApiKey = process.env.ALCHEMY_API_KEY || "";

async function main() {
//RECEIVING PARAMETERS
const parameters = process.argv.slice(2);
if (!parameters || parameters.length < 2)
throw new Error("Parameters not provided");
const contractAddress = parameters[0] as `0x${string}`;
if (!contractAddress) throw new Error("Contract address not provided");
if (!/^0x[a-fA-F0-9]{40}$/.test(contractAddress))
throw new Error("Invalid contract address");
const proposalIndex = parameters[1];
if (isNaN(Number(proposalIndex))) throw new Error("Invalid proposal index");
//RECEIVING PARAMETERS
const parameters = process.argv.slice(2);
if (!parameters || parameters.length < 2)
throw new Error("Parameters not provided");
const contractAddress = parameters[0] as `0x${string}`;
if (!contractAddress) throw new Error("Contract address not provided");
if (!/^0x[a-fA-F0-9]{40}$/.test(contractAddress))
throw new Error("Invalid contract address");
const proposalIndex = parameters[1];
if (isNaN(Number(proposalIndex))) throw new Error("Invalid proposal index");

//ATTACH CONTRACT AND CHECK SELECTED OPTION
const publicClient = createPublicClient({
chain: sepolia,
transport: http(`https://eth-sepolia.g.alchemy.com/v2/${providerApiKey}`),
});
console.log("Proposal selected: ");
const proposal = (await publicClient.readContract({
address: contractAddress,
abi,
functionName: "proposals",
args: [BigInt(proposalIndex)],
})) as any[];
const name = hexToString(proposal[0], { size: 32 });
console.log("Voting to proposal", name);
console.log("Confirm? (Y/n)");

//SEND TX ON USER CONFIRMATION
const account = privateKeyToAccount(`0x${deployerPrivateKey}`);
const voter = createWalletClient({
account,
chain: sepolia,
transport: http(`https://eth-sepolia.g.alchemy.com/v2/${providerApiKey}`),
});
const stdin = process.openStdin();
stdin.addListener("data", async function (d) {
if (d.toString().trim().toLowerCase() != "n") {
const hash = await voter.writeContract({
address: contractAddress,
abi,
functionName: "vote",
//ATTACH CONTRACT AND CHECK SELECTED OPTION
const publicClient = createPublicClient({
chain: sepolia,
transport: http(`https://eth-sepolia.g.alchemy.com/v2/${providerApiKey}`),
});
console.log("Proposal selected: ");
const proposal = (await publicClient.readContract({
address: contractAddress, abi,
functionName: "proposals",
args: [BigInt(proposalIndex)],
});
console.log("Transaction hash:", hash);
console.log("Waiting for confirmations...");
const receipt = await publicClient.waitForTransactionReceipt({ hash });
console.log("Transaction confirmed");
} else {
console.log("Operation cancelled");
}
process.exit();
});
})) as any[];
const name = hexToString(proposal[0], {size: 32});
console.log("Voting to proposal", name);
console.log("Confirm? (Y/n)");

//SEND TX ON USER CONFIRMATION
const account = privateKeyToAccount(`0x${deployerPrivateKey}`);
const voter = createWalletClient({
account,
chain: sepolia,
transport: http(`https://eth-sepolia.g.alchemy.com/v2/${providerApiKey}`),
});
const stdin = process.openStdin();
stdin.addListener("data", async function (d) {
if (d.toString().trim().toLowerCase() != "n") {
const hash = await voter.writeContract({
address: contractAddress, abi, functionName: "vote", args: [BigInt(proposalIndex)],
});
console.log("Transaction hash:", hash);
console.log("Waiting for confirmations...");
const receipt = await publicClient.waitForTransactionReceipt({hash});
console.log("Transaction confirmed");
} else {
console.log("Operation cancelled");
}
process.exit();
});
}

main().catch((error) => {
console.error(error);
process.exitCode = 1;
console.error(error);
process.exitCode = 1;
});
82 changes: 41 additions & 41 deletions scripts/viem/Delegate.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,57 @@
import { createPublicClient, createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { sepolia } from "viem/chains";
import {createPublicClient, createWalletClient, http} from "viem";
import {privateKeyToAccount} from "viem/accounts";
import {sepolia} from "viem/chains";

import { abi } from "../../artifacts/contracts/Ballot.sol/Ballot.json";
import {abi} from "../../artifacts/contracts/Ballot.sol/Ballot.json";

import config from "../../config";

async function main() {
const parameters = process.argv.slice(2);
if (!parameters || parameters.length < 2)
throw new Error("Parameters not provided");
const contractAddress = parameters[0] as `0x${string}`;
const delegateTo = parameters[1] as `0x${string}`;
const parameters = process.argv.slice(2);
if (!parameters || parameters.length < 2)
throw new Error("Parameters not provided");
const contractAddress = parameters[0] as `0x${string}`;
const delegateTo = parameters[1] as `0x${string}`;

if (!/^0x[a-fA-F0-9]{40}$/.test(contractAddress))
throw new Error("Invalid contract address");
if (!/^0x[a-fA-F0-9]{40}$/.test(contractAddress))
throw new Error("Invalid contract address");

if (!/^0x[a-fA-F0-9]{40}$/.test(delegateTo))
throw new Error("Invalid delegateTo address");
if (!/^0x[a-fA-F0-9]{40}$/.test(delegateTo))
throw new Error("Invalid delegateTo address");

await delegate(contractAddress, delegateTo);
await delegate(contractAddress, delegateTo);
}

async function delegate(
contractAddress: `0x${string}`,
delegateTo: `0x${string}`
contractAddress: `0x${string}`,
delegateTo: `0x${string}`
) {
const account = privateKeyToAccount(`0x${config.PRIVATE_KEY}`);
const publicClient = createPublicClient({
chain: sepolia,
transport: http(config.ALCHEMY_URL),
});
const walletClient = createWalletClient({
account,
chain: sepolia,
transport: http(config.ALCHEMY_URL),
});

console.log("Delegating vote to", delegateTo);
// machinery
const hash = await walletClient.writeContract({
address: contractAddress as `0x${string}`,
abi,
functionName: "delegate",
args: [delegateTo],
});
console.log("Transaction hash:", hash);
console.log("Waiting for confirmations...");
const receipt = await publicClient.waitForTransactionReceipt({ hash });
console.log("Transaction confirmed", { receipt });
const account = privateKeyToAccount(`0x${config.PRIVATE_KEY}`);
const publicClient = createPublicClient({
chain: sepolia,
transport: http(config.ALCHEMY_URL),
});
const walletClient = createWalletClient({
account,
chain: sepolia,
transport: http(config.ALCHEMY_URL),
});

console.log("Delegating vote to", delegateTo);
// machinery
const hash = await walletClient.writeContract({
address: contractAddress as `0x${string}`,
abi,
functionName: "delegate",
args: [delegateTo],
});
console.log("Transaction hash:", hash);
console.log("Waiting for confirmations...");
const receipt = await publicClient.waitForTransactionReceipt({hash});
console.log("Transaction confirmed", {receipt});
}

main().catch((error) => {
console.error(error);
process.exitCode = 1;
console.error(error);
process.exitCode = 1;
});
Loading

0 comments on commit 8f02800

Please sign in to comment.