Skip to content

Commit

Permalink
chore: add logger for contract helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
0xmad committed Feb 28, 2025
1 parent d88b4c5 commit a688400
Show file tree
Hide file tree
Showing 34 changed files with 264 additions and 218 deletions.
9 changes: 4 additions & 5 deletions packages/cli/ts/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import {
deployFreeForAllSignUpGatekeeper,
deployVerifier,
deployMaci,
logGreen,
success,
} from "maci-sdk";

import {
banner,
logError,
logGreen,
success,
readContractAddresses,
storeContractAddresses,
DEFAULT_INITIAL_VOICE_CREDITS,
Expand Down Expand Up @@ -37,7 +36,7 @@ export const deploy = async ({
banner(quiet);

if (initialVoiceCreditsProxyAddress && initialVoiceCredits) {
logError("Please provide either an initialVoiceCreditProxyAddress or initialVoiceCredits, not both");
throw new Error("Please provide either an initialVoiceCreditProxyAddress or initialVoiceCredits, not both");
}

const network = await signer.provider?.getNetwork();
Expand Down Expand Up @@ -122,7 +121,7 @@ export const deploy = async ({
network?.name,
);

logGreen(quiet, success(`MACI deployed at: ${maciContractAddress}`));
logGreen({ quiet, text: success(`MACI deployed at: ${maciContractAddress}`) });

// return all addresses
return {
Expand Down
105 changes: 58 additions & 47 deletions packages/cli/ts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ import {
deployVkRegistryContract,
timeTravel,
fundWallet,
info,
success,
logGreen,
logRed,
logYellow,
type ITallyData,
} from "maci-sdk";

Expand All @@ -42,17 +47,11 @@ import {
DEFAULT_SG_DATA,
banner,
contractAddressesStore,
info,
logError,
logGreen,
logRed,
logYellow,
oldContractAddressesStore,
promptSensitiveValue,
readContractAddresses,
resetContractAddresses,
storeContractAddresses,
success,
} from "./utils";
import { DEFAULT_INITIAL_VOICE_CREDITS, DEFAULT_VOTE_OPTIONS } from "./utils/defaults";

Expand Down Expand Up @@ -140,7 +139,7 @@ program
const network = await signer.provider?.getNetwork();
const [vkContractAddress] = await readContractAddresses(["VkRegistry"], network?.name, [cmdOptions.vkContract]);

logYellow(cmdOptions.quiet, info("Retrieving verifying keys from the contract..."));
logYellow({ quiet: cmdOptions.quiet, text: info("Retrieving verifying keys from the contract...") });

await checkVerifyingKeys({
stateTreeDepth: cmdOptions.stateTreeDepth,
Expand All @@ -156,7 +155,7 @@ program
signer,
});

logGreen(cmdOptions.quiet, success("Verifying keys match"));
logGreen({ quiet: cmdOptions.quiet, text: success("Verifying keys match") });
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand All @@ -169,7 +168,7 @@ program
.option("-r, --rpc-provider <provider>", "the rpc provider URL")
.action((cmdObj) => {
const publicKey = generateMaciPublicKey(cmdObj.privkey);
logGreen(cmdObj.quiet, success(`Public key: ${publicKey}`));
logGreen({ quiet: cmdObj.quiet, text: success(`Public key: ${publicKey}`) });
});
program
.command("genMaciKeyPair")
Expand All @@ -178,8 +177,8 @@ program
.option("-q, --quiet <quiet>", "whether to print values to the console", (value) => value === "true", false)
.action((cmdObj) => {
const { publicKey, privateKey } = generateKeypair({ seed: cmdObj.seed });
logGreen(cmdObj.quiet, success(`Public key: ${publicKey}`));
logGreen(cmdObj.quiet, success(`Private key: ${privateKey}`));
logGreen({ quiet: cmdObj.quiet, text: success(`Public key: ${publicKey}`) });
logGreen({ quiet: cmdObj.quiet, text: success(`Private key: ${privateKey}`) });
});
program
.command("deployVkRegistry")
Expand All @@ -204,7 +203,7 @@ program
const vkRegistryAddress = await deployVkRegistryContract({ signer });
await storeContractAddresses({ VkRegistry: vkRegistryAddress }, network?.name);

logGreen(cmdObj.quiet, success(`VkRegistry deployed at: ${vkRegistryAddress}`));
logGreen({ quiet: cmdObj.quiet, text: success(`VkRegistry deployed at: ${vkRegistryAddress}`) });
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand All @@ -217,15 +216,15 @@ program
banner(false);

if (!fs.existsSync(contractAddressesStore)) {
logError("No contracts have been deployed yet");
throw new Error("No contracts have been deployed yet");
}

const data = JSON.parse(
await fs.promises.readFile(contractAddressesStore, "utf8").then((result) => result.toString()),
) as Record<string, string>;

Object.entries(data).forEach(([key, value]) => {
logGreen(false, info(`${key}: ${value}`));
logGreen({ quiet: false, text: info(`${key}: ${value}`) });
});
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
Expand Down Expand Up @@ -304,15 +303,21 @@ program
initialVoiceCreditProxyContractAddress: initialVoiceCreditProxyAddress,
});

logGreen(cmdObj.quiet, success(`Poll ID: ${pollId}`));
logGreen(cmdObj.quiet, success(`Poll contract address: ${pollContractAddress}`));
logGreen(cmdObj.quiet, success(`Tally contract address: ${tallyContractAddress}`));
logGreen(cmdObj.quiet, success(`Message processor contract address: ${messageProcessorContractAddress}`));
logGreen(
cmdObj.quiet,
success(`Initial voice credit proxy contract address: ${initialVoiceCreditProxyContractAddress}`),
);
logGreen(cmdObj.quiet, success(`Signup gatekeeper contract address: ${gatekeeperContractAddress}`));
logGreen({ quiet: cmdObj.quiet, text: success(`Poll ID: ${pollId}`) });
logGreen({ quiet: cmdObj.quiet, text: success(`Poll contract address: ${pollContractAddress}`) });
logGreen({ quiet: cmdObj.quiet, text: success(`Tally contract address: ${tallyContractAddress}`) });
logGreen({
quiet: cmdObj.quiet,
text: success(`Message processor contract address: ${messageProcessorContractAddress}`),
});
logGreen({
quiet: cmdObj.quiet,
text: success(`Initial voice credit proxy contract address: ${initialVoiceCreditProxyContractAddress}`),
});
logGreen({
quiet: cmdObj.quiet,
text: success(`Signup gatekeeper contract address: ${gatekeeperContractAddress}`),
});
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand Down Expand Up @@ -372,9 +377,9 @@ program
ivcpDataArg: cmdObj.ivcpData ?? DEFAULT_IVCP_DATA,
});

logGreen(cmdObj.quiet, info(`User joined poll with nullifier: ${data.nullifier}`));
logGreen(cmdObj.quiet, info(`User joined poll with state index: ${data.pollStateIndex}`));
logGreen(cmdObj.quiet, info(`User joined poll with ${data.voiceCredits} voice credits`));
logGreen({ quiet: cmdObj.quiet, text: info(`User joined poll with nullifier: ${data.nullifier}`) });
logGreen({ quiet: cmdObj.quiet, text: info(`User joined poll with state index: ${data.pollStateIndex}`) });
logGreen({ quiet: cmdObj.quiet, text: info(`User joined poll with ${data.voiceCredits} voice credits`) });
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand Down Expand Up @@ -514,8 +519,11 @@ program
signer,
});

logGreen(cmdObj.quiet, info(`Transaction hash: ${receipt.hash}`));
logGreen(cmdObj.quiet, success(`Executed mergeSignups(); gas used: ${receipt.gasUsed.toString()}`));
logGreen({ quiet: cmdObj.quiet, text: info(`Transaction hash: ${receipt.hash}`) });
logGreen({
quiet: cmdObj.quiet,
text: success(`Executed mergeSignups(); gas used: ${receipt.gasUsed.toString()}`),
});
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand All @@ -534,7 +542,7 @@ program

await timeTravel({ seconds: cmdObj.seconds, signer });

logGreen(cmdObj.quiet, success(`Fast-forwarded ${cmdObj.seconds} seconds`));
logGreen({ quiet: cmdObj.quiet, text: success(`Fast-forwarded ${cmdObj.seconds} seconds`) });
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand Down Expand Up @@ -604,10 +612,10 @@ program
signer,
});

logGreen(
cmdObj.quiet,
success(`State index: ${data.stateIndex.toString()}\n Transaction hash: ${data.transactionHash}`),
);
logGreen({
quiet: cmdObj.quiet,
text: success(`State index: ${data.stateIndex.toString()}\n Transaction hash: ${data.transactionHash}`),
});
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand All @@ -632,9 +640,9 @@ program
});

if (data.isRegistered) {
logGreen(cmdObj.quiet, success(`State index: ${data.stateIndex?.toString()}`));
logGreen({ quiet: cmdObj.quiet, text: success(`State index: ${data.stateIndex?.toString()}`) });
} else {
logRed(cmdObj.quiet, "User is not registered");
logRed({ quiet: cmdObj.quiet, text: "User is not registered" });
}
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
Expand Down Expand Up @@ -666,17 +674,17 @@ program
});

if (data.isJoined) {
logGreen(
cmdObj.quiet,
success(
logGreen({
quiet: cmdObj.quiet,
text: success(
[
`Poll state index: ${data.pollStateIndex?.toString()}, registered: ${data.isJoined}`,
`Voice credits: ${data.voiceCredits?.toString()}`,
].join("\n"),
),
);
});
} else {
logRed(cmdObj.quiet, "User has not joined the poll");
logRed({ quiet: cmdObj.quiet, text: "User has not joined the poll" });
}
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
Expand All @@ -701,9 +709,9 @@ program
signer,
});

logGreen(
true,
success(
logGreen({
quiet: true,
text: success(
[
`ID: ${details.id}`,
`Start time: ${new Date(Number(details.startDate) * 1000).toString()}`,
Expand All @@ -713,7 +721,7 @@ program
`Mode: ${details.mode === 0n ? "Quadratic Voting" : "Non-Quadratic Voting"}`,
].join("\n"),
),
);
});
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand All @@ -733,8 +741,11 @@ program

const hash = await fundWallet({ amount: cmdObj.amount, address: cmdObj.address, signer });

logYellow(cmdObj.quiet, info(`Transaction hash: ${hash}`));
logGreen(cmdObj.quiet, success(`Successfully funded ${cmdObj.address} with ${cmdObj.amount} wei`));
logYellow({ quiet: cmdObj.quiet, text: info(`Transaction hash: ${hash}`) });
logGreen({
quiet: cmdObj.quiet,
text: success(`Successfully funded ${cmdObj.address} with ${cmdObj.amount} wei`),
});
} catch (error) {
program.error((error as Error).message, { exitCode: 1 });
}
Expand All @@ -760,7 +771,7 @@ program
const isTallyFileExists = fs.existsSync(cmdObj.tallyFile);

if (!cmdObj.tallyFile || !isTallyFileExists) {
logError(`Unable to open ${cmdObj.tallyFile}`);
throw new Error(`Unable to open ${cmdObj.tallyFile}`);
}

const tallyData = JSON.parse(await fs.promises.readFile(cmdObj.tallyFile, { encoding: "utf8" })) as ITallyData;
Expand Down
10 changes: 5 additions & 5 deletions packages/cli/ts/utils/banner.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { logRed, logYellow } from "./theme";
import { logRed, logYellow } from "maci-sdk";

/**
* Print a nice MACI banner
* @param quiet - whether to print the text or not
*/
export const banner = (quiet: boolean): void => {
logRed(
logRed({
quiet,
`
text: `
███▄ ▄███▓ ▄▄▄ ▄████▄ ██▓
▓██▒▀█▀ ██▒▒████▄ ▒██▀ ▀█ ▓██▒
Expand All @@ -21,6 +21,6 @@ export const banner = (quiet: boolean): void => {
`,
);
logYellow(quiet, "Welcome to MACI - Minimal Anti Collusion Infrastructure\n\n");
});
logYellow({ quiet, text: "Welcome to MACI - Minimal Anti Collusion Infrastructure\n\n" });
};
1 change: 0 additions & 1 deletion packages/cli/ts/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,4 @@ export {
resetContractAddresses,
doesPathExist,
} from "./storage";
export { logRed, logGreen, logYellow, logMagenta, logError, info, success, warning, error } from "./theme";
export { promptSensitiveValue } from "./prompts";
3 changes: 1 addition & 2 deletions packages/cli/ts/utils/storage.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import fs from "fs";

import { contractAddressesStore } from "./constants";
import { logError } from "./theme";

/**
* Read a JSON file from disk
Expand All @@ -12,7 +11,7 @@ export const readJSONFile = async (path: string): Promise<Record<string, Record<
const isExists = fs.existsSync(path);

if (!isExists) {
logError(`File ${path} does not exist`);
throw new Error(`File ${path} does not exist`);
}

return fs.promises
Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/tasks/deploy/maci/01-gatekeepers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { hexToBigInt, uuidToBigInt } from "@pcd/util";

import { info, logGreen } from "../../../ts/logger";
import { HatsGatekeeperBase } from "../../../typechain-types";
import { EDeploySteps, ESupportedChains } from "../../helpers/constants";
import { ContractStorage } from "../../helpers/ContractStorage";
Expand Down Expand Up @@ -59,7 +60,7 @@ deployment.deployTask(EDeploySteps.Gatekeepers, "Deploy gatekeepers").then((task

if (canSkipDeploy) {
// eslint-disable-next-line no-console
console.log(`Skipping deployment of the Gatekeeper contract`);
logGreen({ text: info(`Skipping deployment of the Gatekeeper contract`) });
return;
}

Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/tasks/deploy/maci/02-verifier.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { info, logGreen } from "../../../ts/logger";
import { EDeploySteps } from "../../helpers/constants";
import { ContractStorage } from "../../helpers/ContractStorage";
import { Deployment } from "../../helpers/Deployment";
Expand All @@ -18,7 +19,7 @@ deployment.deployTask(EDeploySteps.Verifier, "Deploy verifier").then((task) =>

if (incremental && verifierContractAddress) {
// eslint-disable-next-line no-console
console.log(`Skipping deployment of the ${EContracts.Verifier} contract`);
logGreen({ text: info(`Skipping deployment of the ${EContracts.Verifier} contract`) });
return;
}

Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/tasks/deploy/maci/03-poseidon.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { info, logGreen } from "../../../ts/logger";
import { EDeploySteps } from "../../helpers/constants";
import { ContractStorage } from "../../helpers/ContractStorage";
import { Deployment } from "../../helpers/Deployment";
Expand Down Expand Up @@ -27,7 +28,7 @@ deployment.deployTask(EDeploySteps.Poseidon, "Deploy poseidon contracts").then((
poseidonT6ContractAddress
) {
// eslint-disable-next-line no-console
console.log(`Skipping deployment of the Poseidon contracts`);
logGreen({ text: info(`Skipping deployment of the Poseidon contracts`) });
return;
}

Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/tasks/deploy/maci/04-pollFactory.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { info, logGreen } from "../../../ts/logger";
import { EDeploySteps } from "../../helpers/constants";
import { ContractStorage } from "../../helpers/ContractStorage";
import { Deployment } from "../../helpers/Deployment";
Expand All @@ -18,7 +19,7 @@ deployment.deployTask(EDeploySteps.PollFactory, "Deploy poll factory").then((tas

if (incremental && pollFactoryContractAddress) {
// eslint-disable-next-line no-console
console.log(`Skipping deployment of the ${EContracts.PollFactory} contract`);
logGreen({ text: info(`Skipping deployment of the ${EContracts.PollFactory} contract`) });
return;
}

Expand Down
Loading

0 comments on commit a688400

Please sign in to comment.