Skip to content

Commit

Permalink
refactor: update and move constants to actions package
Browse files Browse the repository at this point in the history
BREAKING CHANGE: constants are now part of actions package
  • Loading branch information
0xjei committed Jan 30, 2023
1 parent c7d280e commit e1a98a8
Show file tree
Hide file tree
Showing 22 changed files with 527 additions and 460 deletions.
4 changes: 2 additions & 2 deletions packages/actions/src/core/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { firstZkeyIndex } from "../../helpers/constants"
import { genesisZkeyIndex } from "../../helpers/constants"

/**
* Get the powers from pot file name
Expand Down Expand Up @@ -27,7 +27,7 @@ export const extractPrefix = (str: string): string =>
export const formatZkeyIndex = (progress: number): string => {
let index = progress.toString()

while (index.length < firstZkeyIndex.length) {
while (index.length < genesisZkeyIndex.length) {
index = `0${index}`
}

Expand Down
164 changes: 112 additions & 52 deletions packages/actions/src/helpers/constants.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,115 @@
export const terms = {
output: `output`,
setup: `setup`,
contribute: `contribute`,
finalize: `finalize`,
pot: `pot`,
zkeys: `zkeys`,
vkeys: `vkeys`,
metadata: `metadata`,
transcripts: `transcripts`,
attestation: `attestation`,
verifiers: `verifiers`
}

export const potDownloadUrlTemplate = `https://hermez.s3-eu-west-1.amazonaws.com/`
/**
* Core constant values.
* @notice the theme currently supports a single color palette, which displays well on both dark and light terminal windows.
*/
// Main part for the Hermez Phase 1 Trusted Setup URLs to download PoT files.
export const potFileDownloadMainUrl = `https://hermez.s3-eu-west-1.amazonaws.com/`
// Main part for the Hermez Phase 1 Trusted Setup PoT files to be downloaded.
export const potFilenameTemplate = `powersOfTau28_hez_final_`
// The genesis zKey index.
export const genesisZkeyIndex = `00000`
// The number of exponential iterations to be executed by SnarkJS when finalizing the ceremony.
export const numExpIterations = 10
// The Solidity version of the Verifier Smart Contract generated with SnarkJS when finalizing the ceremony.
export const solidityVersion = "0.8.0"

/** Firebase */
export const collections = {
users: "users",
participants: "participants",
ceremonies: "ceremonies",
circuits: "circuits",
contributions: "contributions",
timeouts: "timeouts"
}

export const contributionsCollectionFields = {
contributionTime: "contributionTime",
files: "files",
lastUpdated: "lastUpdated",
participantId: "participantId",
valid: "valid",
verificationTime: "verificationTime",
zkeyIndex: "zKeyIndex"
}

export const firstZkeyIndex = `00000`

export const timeoutsCollectionFields = {
startDate: "startDate",
endDate: "endDate"
}

export const ceremoniesCollectionFields = {
coordinatorId: "coordinatorId",
description: "description",
endDate: "endDate",
lastUpdated: "lastUpdated",
prefix: "prefix",
startDate: "startDate",
state: "state",
title: "title",
type: "type"
/**
* Commonly used terms.
* @dev useful for creating paths, references to collections and queries, object properties, folder names, and so on.
*/
export const commonTerms = {
collections: {
users: {
name: "users",
fields: {
creationTime: "creationTime",
displayName: "displayName",
email: "email",
emailVerified: "emailVerified",
lastSignInTime: "lastSignInTime",
lastUpdated: "lastUpdated",
name: "name",
photoURL: "photoURL"
}
},
participants: {
name: "participants",
fields: {
contributionProgress: "contributionProgress",
contributionStartedAt: "contributionStartedAt",
contributionStep: "contributionStep",
contributions: "contributions",
lastUpdated: "lastUpdated",
status: "status",
verificationStartedAt: "verificationStartedAt"
}
},
ceremonies: {
name: "ceremonies",
fields: {
coordinatorId: "coordinatorId",
description: "description",
endDate: "endDate",
lastUpdated: "lastUpdated",
penalty: "penalty",
prefix: "prefix",
startDate: "startDate",
state: "state",
timeoutType: "timeoutType",
title: "title",
type: "type"
}
},
circuits: {
name: "circuits",
fields: {
avgTimings: "avgTimings",
compiler: "compiler",
description: "description",
files: "files",
lastUpdated: "lastUpdated",
metadata: "metadata",
name: "name",
prefix: "prefix",
sequencePosition: "sequencePosition",
template: "template",
timeoutMaxContributionWaitingTime: "timeoutMaxContributionWaitingTime",
waitingQueue: "waitingQueue",
zKeySizeInBytes: "zKeySizeInBytes"
}
},
contributions: {
name: "contributions",
fields: {
contributionComputationTime: "contributionComputationTime",
files: "files",
lastUpdated: "lastUpdated",
participantId: "participantId",
valid: "valid",
verificationComputationTime: "verificationComputationTime",
zkeyIndex: "zKeyIndex"
}
},
timeouts: {
name: "timeouts",
fields: {
type: "type",
startDate: "startDate",
endDate: "endDate"
}
}
},
foldersAndPathsTerms: {
output: `output`,
setup: `setup`,
contribute: `contribute`,
finalize: `finalize`,
pot: `pot`,
zkeys: `zkeys`,
vkeys: `vkeys`,
metadata: `metadata`,
transcripts: `transcripts`,
attestation: `attestation`,
verifiers: `verifiers`
}
}
27 changes: 13 additions & 14 deletions packages/actions/src/helpers/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,7 @@ import {
where
} from "firebase/firestore"
import { CeremonyState, FirebaseDocumentInfo } from "../../types/index"
import {
ceremoniesCollectionFields,
collections,
contributionsCollectionFields,
timeoutsCollectionFields
} from "./constants"
import { commonTerms } from "./constants"

/**
* Helper for query a collection based on certain constraints.
Expand Down Expand Up @@ -101,8 +96,8 @@ export const getCurrentContributorContribution = async (
): Promise<Array<FirebaseDocumentInfo>> => {
const participantContributionQuerySnap = await queryCollection(
firestoreDatabase,
`${collections.ceremonies}/${ceremonyId}/${collections.circuits}/${circuitId}/${collections.contributions}`,
[where(contributionsCollectionFields.participantId, "==", participantId)]
`${commonTerms.collections.ceremonies.name}/${ceremonyId}/${commonTerms.collections.circuits.name}/${circuitId}/${commonTerms.collections.contributions.name}`,
[where(commonTerms.collections.contributions.fields.participantId, "==", participantId)]
)

return fromQueryToFirebaseDocumentInfo(participantContributionQuerySnap.docs)
Expand All @@ -121,8 +116,8 @@ export const getCurrentActiveParticipantTimeout = async (
): Promise<Array<FirebaseDocumentInfo>> => {
const participantTimeoutQuerySnap = await queryCollection(
firestoreDatabase,
`${collections.ceremonies}/${ceremonyId}/${collections.participants}/${participantId}/${collections.timeouts}`,
[where(timeoutsCollectionFields.endDate, ">=", Timestamp.now().toMillis())]
`${commonTerms.collections.ceremonies.name}/${ceremonyId}/${commonTerms.collections.participants.name}/${participantId}/${commonTerms.collections.timeouts.name}`,
[where(commonTerms.collections.timeouts.fields.endDate, ">=", Timestamp.now().toMillis())]
)

return fromQueryToFirebaseDocumentInfo(participantTimeoutQuerySnap.docs)
Expand All @@ -137,10 +132,14 @@ export const getClosedCeremonies = async (firestoreDatabase: Firestore): Promise
let closedStateCeremoniesQuerySnap: any

try {
closedStateCeremoniesQuerySnap = await queryCollection(firestoreDatabase, collections.ceremonies, [
where(ceremoniesCollectionFields.state, "==", CeremonyState.CLOSED),
where(ceremoniesCollectionFields.endDate, "<=", Date.now())
])
closedStateCeremoniesQuerySnap = await queryCollection(
firestoreDatabase,
commonTerms.collections.ceremonies.name,
[
where(commonTerms.collections.ceremonies.fields.state, "==", CeremonyState.CLOSED),
where(commonTerms.collections.ceremonies.fields.endDate, "<=", Date.now())
]
)

if (closedStateCeremoniesQuerySnap.empty && closedStateCeremoniesQuerySnap.size === 0)
throw new Error("Queries-0001: There are no ceremonies ready to finalization")
Expand Down
9 changes: 8 additions & 1 deletion packages/actions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,11 @@ export {
getCurrentFirebaseAuthUser,
isCoordinator
} from "./helpers/firebase"
export { terms } from "./helpers/constants"
export {
commonTerms,
potFileDownloadMainUrl,
potFilenameTemplate,
genesisZkeyIndex,
numExpIterations,
solidityVersion
} from "./helpers/constants"
6 changes: 3 additions & 3 deletions packages/phase2cli/src/commands/auth.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#!/usr/bin/env node
import dotenv from "dotenv"
import { symbols, theme } from "../lib/constants"
import { exchangeGithubTokenForCredentials, getGithubUserHandle, terminate } from "../lib/utils"
import { bootstrapCommandExecutionAndServices } from "../lib/commands"
import { executeGithubDeviceFlow, signInToFirebase } from "../lib/authorization"
import { checkLocalAccessToken, getLocalAccessToken, setLocalAccessToken } from "../lib/localStorage"
import theme from "../lib/theme"

dotenv.config()

Expand Down Expand Up @@ -39,9 +39,9 @@ const auth = async () => {
// Get Github handle.
const githubUserHandle = await getGithubUserHandle(String(token))

console.log(`${symbols.success} You are authenticated as ${theme.bold(`@${githubUserHandle}`)}`)
console.log(`${theme.symbols.success} You are authenticated as ${theme.text.bold(`@${githubUserHandle}`)}`)
console.log(
`${symbols.info} You are now able to compute contributions for zk-SNARK Phase2 Trusted Setup opened ceremonies`
`${theme.symbols.info} You are now able to compute contributions for zk-SNARK Phase2 Trusted Setup opened ceremonies`
)

terminate(githubUserHandle)
Expand Down
8 changes: 4 additions & 4 deletions packages/phase2cli/src/commands/clean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import { deleteDir, directoryExists } from "@zkmpc/actions"
import { bootstrapCommandExecutionAndServices } from "../lib/commands"
import { emojis, symbols, theme } from "../lib/constants"
import { showError } from "../lib/errors"
import { askForConfirmation } from "../lib/prompts"
import { outputLocalFolderPath } from "../lib/paths"
import { customSpinner, sleep } from "../lib/utils"
import theme from "../lib/theme"

/**
* Clean command.
Expand All @@ -19,7 +19,7 @@ const clean = async () => {
const spinner = customSpinner(`Cleaning up...`, "clock")

if (directoryExists(outputLocalFolderPath)) {
console.log(theme.bold(`${symbols.warning} Be careful, this action is irreversible!`))
console.log(theme.text.bold(`${theme.symbols.warning} Be careful, this action is irreversible!`))

const { confirmation } = await askForConfirmation(
"Are you sure you want to continue with the clean up?",
Expand All @@ -36,10 +36,10 @@ const clean = async () => {
// nb. simulate waiting time for 1s.
await sleep(1000)

spinner.succeed(`Cleanup was successfully completed ${emojis.broom}`)
spinner.succeed(`Cleanup was successfully completed ${theme.emojis.broom}`)
}
} else {
console.log(`${symbols.info} There is nothing to clean ${emojis.eyes}`)
console.log(`${theme.symbols.info} There is nothing to clean ${theme.emojis.eyes}`)
}
} catch (err: any) {
showError(`Something went wrong: ${err.toString()}`, true)
Expand Down
Loading

0 comments on commit e1a98a8

Please sign in to comment.