Skip to content

Commit

Permalink
Merge pull request #236 from EYBlockchain/balance
Browse files Browse the repository at this point in the history
GetBalance for non-nullified commitments.
  • Loading branch information
SwatiEY authored Apr 4, 2024
2 parents 2f1944f + 8fb3f83 commit eec9052
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 22 deletions.
42 changes: 37 additions & 5 deletions src/boilerplate/common/commitment-storage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -117,18 +117,50 @@ export async function getNullifiedCommitments() {
}

/**
* @returns all the commitments existent in this database.
* @returns {Promise<number>} The sum of the values ​​of all non-nullified commitments
*/
export async function getAllCommitments() {
export async function getBalance() {
const connection = await mongo.connection(MONGO_URL);
const db = connection.db(COMMITMENTS_DB);
const commitments = await db
.collection(COMMITMENTS_COLLECTION)
.find({ isNullified: false }) // no nullified
.toArray();

let sumOfValues = 0;
commitments.forEach(commitment => {
sumOfValues += parseInt(commitment.preimage.value, 10);
});
return sumOfValues;
}

export async function getBalanceByState(name, mappingKey = null) {
const connection = await mongo.connection(MONGO_URL);
const db = connection.db(COMMITMENTS_DB);
const allCommitments = await db
const query = { name: name };
if (mappingKey) query['mappingKey'] = generalise(mappingKey).integer;
const commitments = await db
.collection(COMMITMENTS_COLLECTION)
.find()
.find(query)
.toArray();
return allCommitments;
let sumOfValues = 0;
commitments.forEach(commitment => {
sumOfValues += commitment.isNullified ? 0 : parseInt(commitment.preimage.value, 10);
});
return sumOfValues;
}

/**
* @returns all the commitments existent in this database.
*/
export async function getAllCommitments() {
const connection = await mongo.connection(MONGO_URL);
const db = connection.db(COMMITMENTS_DB);
const allCommitments = await db.collection(COMMITMENTS_COLLECTION).find().toArray();
return allCommitments;
}


// function to update an existing commitment
export async function updateCommitment(commitment, updates) {
const connection = await mongo.connection(MONGO_URL);
Expand Down
2 changes: 1 addition & 1 deletion src/boilerplate/common/web3.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ export default {
}
return false;
},
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ class BoilerplateGenerator {
`\nimport fs from 'fs';
\n`,
`\nimport { getContractInstance, getContractAddress, registerKey } from './common/contract.mjs';`,
`\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, splitCommitments, markNullified,getnullifierMembershipWitness,getupdatedNullifierPaths,temporaryUpdateNullifier,updateNullifierTree } from './common/commitment-storage.mjs';`,
`\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, splitCommitments, markNullified,getnullifierMembershipWitness,getupdatedNullifierPaths,temporaryUpdateNullifier,updateNullifierTree} from './common/commitment-storage.mjs';`,
`\nimport { generateProof } from './common/zokrates.mjs';`,
`\nimport { getMembershipWitness, getRoot } from './common/timber.mjs';`,
`\nimport Web3 from './common/web3.mjs';`,
Expand Down Expand Up @@ -705,7 +705,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 } 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, } 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 @@ -741,6 +741,28 @@ integrationApiServicesBoilerplate = {
res.send({ errors: [err.message] });
}
}
export async function service_getBalance(req, res, next) {
try {
const sum = await getBalance();
res.send( {" Total Balance": sum} );
} catch (error) {
console.error("Error in calculation :", error);
res.status(500).send({ error: err.message });
}
}
export async function service_getBalanceByState(req, res, next) {
try {
const { name, mappingKey } = req.body;
const balance = await getBalanceByState(name, mappingKey);
res.send( {" Total Balance": balance} );
} catch (error) {
console.error("Error in calculation :", error);
res.status(500).send({ error: err.message });
}
}
export async function service_getCommitmentsByState(req, res, next) {
try {
Expand Down Expand Up @@ -785,12 +807,14 @@ integrationApiRoutesBoilerplate = {
(fs.readFileSync(apiRoutesReadPath, 'utf8').match(/router.post?[\s\S]*/g)|| [])[0]}`
},
commitmentImports(): string {
return `import { service_allCommitments, service_getCommitmentsByState, service_reinstateNullifiers } from "./api_services.mjs";\n`;
return `import { service_allCommitments, service_getCommitmentsByState, service_reinstateNullifiers, service_getBalance, service_getBalanceByState } from "./api_services.mjs";\n`;
},
commitmentRoutes(): string {
return `// commitment getter routes
router.get("/getAllCommitments", service_allCommitments);
router.get("/getCommitmentsByVariableName", service_getCommitmentsByState);
router.get("/getBalance", service_getBalance);
router.get("/getBalanceByState", service_getBalanceByState);
// nullifier route
router.post("/reinstateNullifiers", service_reinstateNullifiers);
`;
Expand Down
25 changes: 13 additions & 12 deletions src/codeGenerators/orchestration/files/toOrchestration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,17 +163,18 @@ const prepareIntegrationApiServices = (node: any) => {
fnParam = [...new Set(fnParam)];
// Adding Return parameters
let returnParams: string[] = [];
let returnParamsName = fn.returnParameters.parameters.filter((paramnode: any) => (paramnode.isSecret || paramnode.typeName.name === 'bool')).map(paramnode => (paramnode.name)) || [];
if(returnParamsName.length > 0){
returnParamsName.forEach(param => {
if(fn.decrementsSecretState.includes(param))
returnParams.push(param+'_2_newCommitment');
else if(param !== 'true')
returnParams.push(param+'_newCommitment');
else
returnParams.push('bool');
});
}
let returnParamsName = fn.returnParameters.parameters.filter((paramnode: any) => (paramnode.isSecret || paramnode.typeName.name === 'bool')).map(paramnode => (paramnode.name)) || []; // Adapt
if(returnParamsName.length > 0){
returnParamsName.forEach(param => {
if(fn.decrementsSecretState.includes(param))
returnParams.push(param+'_2_newCommitment');
else if(param !== 'true')
returnParams.push(param+'_newCommitment');
else
returnParams.push('bool');
});
}

// replace the signature with test inputs
fnboilerplate = fnboilerplate.replace(/const FUNCTION_SIG/g, fnParam);
fnboilerplate = fnboilerplate.replace(/,const/g, `const`);
Expand All @@ -195,7 +196,7 @@ const prepareIntegrationApiServices = (node: any) => {
});
// add linting and config
const preprefix = `/* eslint-disable prettier/prettier, camelcase, prefer-const, no-unused-vars */ \nimport config from 'config';\nimport assert from 'assert';\n`;
outputApiServiceFile = `${preprefix}\n${outputApiServiceFile}\n ${genericApiServiceFile.commitments()}\n`;
outputApiServiceFile = `${preprefix}\n${outputApiServiceFile}\n ${genericApiServiceFile.commitments()}\n`;
return outputApiServiceFile;
};
const prepareIntegrationApiRoutes = (node: any) => {
Expand Down
1 change: 0 additions & 1 deletion src/traverse/Binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ export class Binding {
export class VariableBinding extends Binding {
isSecret: boolean;
stateVariable: boolean;

isModified: boolean;
modificationCount: number = 0;
modifyingPaths: NodePath[] = []; // array of paths of `Identifier` nodes which modify this variable
Expand Down
26 changes: 26 additions & 0 deletions test/contracts/Assign-api.zol
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// SPDX-License-Identifier: CC0

pragma solidity ^0.8.0;

contract Assign {

secret uint256 private a;
uint256 public b;
bool public isTerminated;
function add(secret uint256 value) public {
require(isTerminated == false );
unknown a += value;
}

function remove(secret uint256 value) public {
a -= value;
}
function addPublic( uint256 value) public {
b = 2 * value;
}

function terminateContract() public {
isTerminated = true;
}

}

0 comments on commit eec9052

Please sign in to comment.