Skip to content

Commit

Permalink
Merge pull request #275 from EYBlockchain/swati/ConstructorFix
Browse files Browse the repository at this point in the history
constructor fixes
  • Loading branch information
SwatiEY authored Jun 18, 2024
2 parents c35cd85 + 3c69195 commit 173eebc
Show file tree
Hide file tree
Showing 10 changed files with 52 additions and 20 deletions.
4 changes: 0 additions & 4 deletions src/boilerplate/common/bin/setup
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ cp docker-compose.zapp.override.default.yml docker-compose.zapp.override.yml

cp entrypoint_default.sh entrypoint.sh

cp bin/default_startup bin/startup

perl -i -pe "s,docker-compose.zapp.yml -f docker-compose.zapp.override.yml,docker-compose.zapp.yml,g" package.json

if [[ $network == 'mumbai' ]] || [[ $network == 'sepolia' ]] || [[ $network == 'goerli' ]]
Expand Down Expand Up @@ -97,7 +95,5 @@ printf "\n${GREEN}*** Setup complete! Writing verification key to db... ***${NC}

docker-compose -f docker-compose.zapp.yml run zapp-setup node /app/write-vk.mjs -i ''

CONSTRUCTOR_CALL

fi
printf "\n${GREEN}*** Finished! ***${NC}\n"
2 changes: 2 additions & 0 deletions src/boilerplate/common/bin/startup
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ docker-compose -f docker-compose.zapp.yml up -d zokrates

sleep 5

CONSTRUCTOR_CALL

docker-compose -f docker-compose.zapp.yml up -d deployer

sleep 25
Expand Down
24 changes: 24 additions & 0 deletions src/boilerplate/common/commitment-storage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { poseidonHash } from './number-theory.mjs';
import { generateProof } from './zokrates.mjs';
import { SumType, reduceTree, toBinArray, poseidonConcatHash } from './smt_utils.mjs';
import { hlt } from './hash-lookup.mjs';
import fs from "fs";

const { MONGO_URL, COMMITMENTS_DB, COMMITMENTS_COLLECTION } = config;
const { generalise } = gen;
Expand Down Expand Up @@ -879,3 +880,26 @@ export function getupdatedNullifierPaths(nullifier) {
const witness = { path: membershipPath.path, root: root };
return witness;
}
// This updates the nullifier Tree with constructor inputs
export async function addConstructorNullifiers() {
const constructorInput = JSON.parse(
fs.readFileSync("/app/orchestration/common/db/constructorTx.json", "utf-8")
);
const { nullifiers } = constructorInput;
console.log(nullifiers);
const { isNullfiersAdded } = constructorInput;
if(isNullfiersAdded == false)
{
nullifiers.forEach(nullifier => {
smt_tree = insertLeaf(nullifier, smt_tree);
})
temp_smt_tree = smt_tree;
console.log(getHash(smt_tree));
constructorInput.isNullfiersAdded = true;
fs.writeFileSync(
"/app/orchestration/common/db/constructorTx.json",
JSON.stringify(constructorInput, null, 4)
);

}
}
1 change: 1 addition & 0 deletions src/boilerplate/common/services/generic-api_services.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export async function service_FUNCTION_NAME (req, res, next){
try {
await startEventFilter('CONTRACT_NAME');
const FUNCTION_SIG;
CONSTRUCTOR_INPUTS;
const { tx , encEvent, _RESPONSE_} = await FUNCTION_NAME(FUNCTION_SIG);
// prints the tx
console.log(tx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -304,13 +304,15 @@ export function buildBoilerplateNode(nodeType: string, fields: any = {}): any {
case 'IntegrationApiServicesBoilerplate': {
const {
contractName,
functionNames = [],
functions = [],
constructorParams = [],
contractImports = [],
} = fields;
return {
nodeType,
contractName,
functionNames,
functions,
constructorParams,
contractImports,
Expand Down Expand Up @@ -350,13 +352,15 @@ export function buildBoilerplateNode(nodeType: string, fields: any = {}): any {
parameters = buildNode('ParameterList', fields),
returnParameters = buildNode('ParameterList', fields),
decrementsSecretState = [],
isConstructor = false,
} = fields;
return {
nodeType,
name,
parameters,
returnParameters,
decrementsSecretState,
isConstructor
};
}
case 'IntegrationApiRoutesFunction': {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@ sendTransaction = {
mappingKey,
burnedOnly,
structProperties,
isConstructor
}): string[] {
let value;
switch (stateType) {
Expand Down Expand Up @@ -706,7 +707,7 @@ integrationApiServicesBoilerplate = {
`
},
preStatements(): string{
return ` import { startEventFilter, getSiblingPath } from './common/timber.mjs';\nimport fs from "fs";\nimport logger from './common/logger.mjs';\nimport { decrypt } from "./common/number-theory.mjs";\nimport { getAllCommitments, getCommitmentsByState, reinstateNullifiers, getBalance, getBalanceByState, } from "./common/commitment-storage.mjs";\nimport web3 from './common/web3.mjs';\n\n
return ` import { startEventFilter, getSiblingPath } from './common/timber.mjs';\nimport fs from "fs";\nimport logger from './common/logger.mjs';\nimport { decrypt } from "./common/number-theory.mjs";\nimport { getAllCommitments, getCommitmentsByState, reinstateNullifiers, getBalance, getBalanceByState, addConstructorNullifiers } from "./common/commitment-storage.mjs";\nimport web3 from './common/web3.mjs';\n\n
/**
NOTE: this is the api service file, if you need to call any function use the correct url and if Your input contract has two functions, add() and minus().
minus() cannot be called before an initial add(). */
Expand Down Expand Up @@ -824,11 +825,6 @@ integrationApiRoutesBoilerplate = {

zappFilesBoilerplate = () => {
return [
{
readPath: pathPrefix + '/bin/startup',
writePath: '/bin/startup',
generic: true,
},
{
readPath: pathPrefix + '/bin/startup',
writePath: '/bin/default_startup',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
: ``,
burnedOnly: false,
structProperties: stateNode.structProperties,
isConstructor: node.isConstructor,
}));

break;
Expand All @@ -613,6 +614,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
: ``,
burnedOnly: false,
structProperties: stateNode.structProperties,
isConstructor: node.isConstructor,
}));

break;
Expand All @@ -630,6 +632,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
: ``,
burnedOnly: stateNode.burnedOnly,
structProperties: stateNode.structProperties,
isConstructor: node.isConstructor,
}));
}
}
Expand Down Expand Up @@ -834,7 +837,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
if (node.functionName === 'cnstrctr') return {
statements: [
`\n\n// Save transaction for the constructor:
\nconst tx = { proofInput: [${params[0][0]}${params[0][1]} ${params[0][2]} ${params[0][3]} proof], ${node.publicInputs?.map(input => `${input}: ${input}.integer,`)}};`
\nconst tx = { proofInput: [${params[0][0]}${params[0][1]} ${params[0][2]} ${params[0][3]} proof], nullifiers: ${params[0][1]} isNullfiersAdded: false, ${node.publicInputs?.map(input => `${input}: ${input}.integer,`)}};`
]
}

Expand Down
22 changes: 13 additions & 9 deletions src/codeGenerators/orchestration/files/toOrchestration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ const prepareIntegrationTest = (node: any) => {
};

const prepareIntegrationApiServices = (node: any) => {
// import generic test skeleton
// import generic test skeletonfr
const genericApiServiceFile: any = Orchestrationbp.integrationApiServicesBoilerplate;
// replace references to contract and functions with ours
let outputApiServiceFile = genericApiServiceFile.preStatements().replace(
Expand All @@ -141,7 +141,8 @@ const prepareIntegrationApiServices = (node: any) => {
relevantFunctions.forEach((fn: any) => {
let fnboilerplate = genericApiServiceFile.postStatements()
.replace(/CONTRACT_NAME/g, node.contractName)
.replace(/FUNCTION_NAME/g, fn.name);
.replace(/FUNCTION_NAME/g, fn.name)
.replace(/CONSTRUCTOR_INPUTS/g, node.functionNames.includes('cnstrctr') ? `await addConstructorNullifiers();` : ``);
let fnParam: string[] = [];
let structparams;
const paramName = fn.parameters.parameters.map((obj: any) => obj.name);
Expand Down Expand Up @@ -354,6 +355,7 @@ const prepareMigrationsFile = (file: localFile, node: any) => {
customProofImport += `const constructorInput = JSON.parse(
fs.readFileSync('/app/orchestration/common/db/constructorTx.json', 'utf-8'),
);
\nconst { proofInput } = constructorInput;`;
iwsConstructorParams?.forEach((param: any) => {
customProofImport += `\nconst { ${param.name} } = constructorInput;`
Expand All @@ -375,7 +377,7 @@ const prepareMigrationsFile = (file: localFile, node: any) => {
* @param node - a SetupCommonFilesBoilerplate node
*/

const prepareSetupScript = (file: localFile, node: any) => {
const prepareStartupScript = (file: localFile, node: any) => {
let constructorCall = ``;
if (!node.functionNames.includes('cnstrctr')) {
file.file = file.file.replace(/CONSTRUCTOR_CALL/g, ``);
Expand All @@ -392,6 +394,7 @@ const prepareSetupScript = (file: localFile, node: any) => {
file.file = file.file.replace(/CONSTRUCTOR_CALL/g, constructorCall);
}


/**
* @param {string} file - a stringified file
* @param {string} contextDirPath - the import statements of the `file` will be
Expand All @@ -408,8 +411,6 @@ export default function fileGenerator(node: any) {
.filter((x: any) => x.nodeType !== 'NonSecretFunction')
.flatMap(fileGenerator));



case 'File':
return [
{
Expand Down Expand Up @@ -440,8 +441,11 @@ export default function fileGenerator(node: any) {
'orchestration',
);

const readPath = path.resolve(fileURLToPath(import.meta.url), '../../../../../src/boilerplate/common/bin/setup');
const startupScript = { filepath: 'bin/setup', file: fs.readFileSync(readPath, 'utf8') };
let readPath = path.resolve(fileURLToPath(import.meta.url), '../../../../../src/boilerplate/common/bin/setup');
const setupScript = { filepath: 'bin/setup', file: fs.readFileSync(readPath, 'utf8') };
files.push(setupScript);
readPath = path.resolve(fileURLToPath(import.meta.url), '../../../../../src/boilerplate/common/bin/startup');
const startupScript = { filepath: 'bin/startup', file: fs.readFileSync(readPath, 'utf8') };
files.push(startupScript);
const vkfile = files.filter(obj => obj.filepath.includes(`write-vk`))[0];
const setupfile = files.filter(obj =>
Expand All @@ -454,7 +458,7 @@ export default function fileGenerator(node: any) {
if (node.functionNames.includes('cnstrctr')) {
const redeployPath = path.resolve(fileURLToPath(import.meta.url), '../../../../../src/boilerplate/common/bin/redeploy');
const redeployFile = { filepath: 'bin/redeploy', file: fs.readFileSync(redeployPath, 'utf8') };
prepareSetupScript(redeployFile, node);
prepareStartupScript(redeployFile, node);
files.push(redeployFile);
}
// replace placeholder values with ours
Expand All @@ -468,7 +472,7 @@ export default function fileGenerator(node: any) {
);
// build the migrations file
prepareMigrationsFile(migrationsfile, node);
prepareSetupScript(startupScript, node);
prepareStartupScript(startupScript, node);
return files;
}

Expand Down
1 change: 1 addition & 0 deletions src/transformers/visitors/toOrchestrationVisitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ const visitor = {
}
}
if (file.nodes?.[0].nodeType === 'IntegrationApiServicesBoilerplate') {
file.nodes?.[0].functionNames.push(node.fileName);
for (const fn of file.nodes[0].functions) {
if (fn.name === node.fileName) thisIntegrationApiServiceFunction = fn;
}
Expand Down
1 change: 1 addition & 0 deletions test/contracts/Assign.zol
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ contract Assign {
function remove(secret uint256 value) public {
a -= value;
}

}

0 comments on commit 173eebc

Please sign in to comment.