Skip to content

Commit

Permalink
Update ZKLottoGame.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
startapple authored Jun 26, 2024
1 parent 83d66ce commit cf48615
Showing 1 changed file with 24 additions and 18 deletions.
42 changes: 24 additions & 18 deletions src/ZKLottoGame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,7 @@ class ZKLottoGame extends SmartContract {

//Lotto Winning numbers Hash
@state(Field) LottoWinHash = State<Field>();


// @state(Field) storageTreeRoot = State<Field>();
@state(Field) storageTreeRoot = State<Field>();


init() {
Expand All @@ -98,9 +96,8 @@ class ZKLottoGame extends SmartContract {
this.currentGameTimeStart.set(UInt64.from(0));
this.currentGameTimeEnd.set(this.network.timestamp.get());
this.gameduration.set(UInt64.from(518400)); //game duration is 6 days, winning lotto numbers generated on day 7
//initiate gameRoot
// const emptyTreeRoot = new MerkleTree(8).getRoot();
// this.storageTreeRoot.set(emptyTreeRoot);
const emptyTreeRoot = new MerkleTree(8).getRoot();
this.storageTreeRoot.set(emptyTreeRoot);
}

@method async startLottoWeek() {
Expand Down Expand Up @@ -178,29 +175,38 @@ class ZKLottoGame extends SmartContract {
// const lottoEntryHash = lottoEntry.hash();
signature.verify(pubkey, [week_, lottoEntryHash]).assertTrue();

/*TO-DO
add user's lotto numbers entry to merkleTree for the Game week
*/

// retrieve the current Merkle root
const currentRoot = this.storageTreeRoot.get();
this.storageTreeRoot.requireEquals(currentRoot);

// generate a new Merkle leaf for this entry
const leaf = lottoEntryHash;

// create a Merkle Tree and update it with the new leaf
let tree = new MerkleTree(8);
tree.setLeaf(week_.toBigInt() % BigInt(256), leaf);

// compute the new root and update the state
const newRoot = tree.getRoot();
this.storageTreeRoot.set(newRoot);
}

@method.returns(Bool) async ClaimWinning(
pubkey: PublicKey,
signature: Signature,
week_: Field,
winningNums: LottoNumbers,
witness: MerkleWitness8,
) {
//proof user is winner of the claim week's lotto
const winninglottoEntryHash = this.LottoWinHash.get();
this.LottoWinHash.requireEquals(this.LottoWinHash.get());
const winningLeaf = [week_].concat(winninglottoEntryHash.toFields());
signature.verify(pubkey, winningLeaf).assertTrue();
const currentRoot = this.storageTreeRoot.get();
this.storageTreeRoot.requireEquals(currentRoot);

const leaf = winningNums.hash();
const isValid = witness.calculateRoot(leaf).equals(currentRoot);
isValid.assertTrue("Invalid proof");

signature.verify(pubkey, [week_, leaf]).assertTrue();

//transfer winnings to user after successful proof verification
return Bool(true);

}
}
}

0 comments on commit cf48615

Please sign in to comment.