Skip to content

Commit

Permalink
Testnetv2 version
Browse files Browse the repository at this point in the history
  • Loading branch information
aii23 committed Oct 21, 2024
1 parent d56ef1c commit 9585612
Show file tree
Hide file tree
Showing 8 changed files with 20 additions and 15 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "l1-lottery-contracts",
"version": "0.7.41",
"version": "0.7.43",
"description": "",
"author": "",
"license": "Apache-2.0",
Expand Down
2 changes: 1 addition & 1 deletion random_request_cid.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const cidBuffer = 'bafkreiawtijhfijbc6qflpakv5j6tm4xzpkfy72uahbvre33ybztejr5em'
export const cidBuffer = 'bafkreiemddwsrxjiy34ktrqolqbjggidkqhgevvfzss6ayp2clcczcuebi'
2 changes: 1 addition & 1 deletion random_request_file
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"method": "GET",
"baseURL": "https://random-data-api.com/api/number/random_number",
"path": "number",
"zkapp": "import{Field as c,MerkleMap as D,Poseidon as M,PublicKey as L,SmartContract as W,State as h,Struct as G,UInt32 as V,ZkProgram as H,method as R,state as g}from\"o1js\";import{PublicKey as v,UInt64 as T}from\"o1js\";var Q=T.from(10*10**9),I=480;var Y=v.fromBase58(\"B62qnBkcyABfjz2cqJPzNZKjVt9M9kx1vgoiWLbkJUnk16Cz8KX8qC4\"),q=v.fromBase58(\"B62qnmsn4Bm4MzPujKeN1faxedz4p1cCAwA9mKAWzDjfb4c1ysVvWeK\");import{ZkonZkProgram as J,ZkonRequestCoordinator as S,ExternalRequestEvent as F}from\"zkon-zkapp\";import{Field as y,Provable as E,provable as j,Struct as _,UInt32 as m,UInt64 as st}from\"o1js\";import{StringCircuitValue as P}from\"zkon-zkapp\";var x=\"bafkreif2uuhoeskvfumqoxy7ylmjylnipg4ftm3dgslsheud7rim42b5eq\";var N=254n,U=7,B=32n;function Z(o,t,n){if(n*BigInt(t)>N)throw new Error(\"The Packing Plant is only accepting orders that can fit into one Field, try using MultiPackingPlant\");class r extends _({packed:y}){constructor(e){super({packed:e})}static extractField(e){throw new Error(\"Must implement extractField\")}static sizeInBits(){throw new Error(\"Must implement sizeInBits\")}static unpack(e){throw new Error(\"Must implement unpack\")}static checkPack(e){if(e.length>t)throw new Error(`Input of size ${e.length} is larger than expected size of ${t}`)}static pack(e){this.checkPack(e);let i=this.extractField(e[0]),l=Math.min(e.length,t);for(let d=1;d<l;d++){let z=y((2n**this.sizeInBits())**BigInt(d));i=i.add(this.extractField(e[d]).mul(z))}return i}static unpackToBigints(e){let i=new Array(t);i.fill(0n);let l;if(e)l=e.toBigInt();else throw new Error(\"No Packed Value Provided\");for(let d=0;d<t;d++)i[d]=l&(1n<<this.sizeInBits())-1n,l>>=this.sizeInBits();return i}toFields(){return[this.packed]}assertEquals(e){this.packed.assertEquals(e.packed)}}return r.type=j({packed:y},{}),r.l=t,r.bitSize=n,r}function K(o=U){class t extends Z(m,o,B){static extractField(r){return r.value}static sizeInBits(){return B}static unpack(r){let s=E.witness(E.Array(m,o),()=>this.unpackToBigints(r).map(i=>m.from(i)));return r.assertEquals(t.pack(s)),s}static fromUInt32s(r){let s=t.pack(r);return new t(s)}static fromBigInts(r){let s=r.map(e=>m.from(e));return t.fromUInt32s(s)}toBigInts(){return t.unpack(this.packed).map(r=>r.toBigint())}}return t}var w=class extends K(){};var C=()=>{function o(t){let n=t.slice(0,30),r=t.slice(30),s=new P(n).toField(),e=new P(r).toField();return{hashPart1:s,hashPart2:e}}return o(x.toString())};var p=function(o,t,n,r){var s=arguments.length,e=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,i;if(typeof Reflect==\"object\"&&typeof Reflect.decorate==\"function\")e=Reflect.decorate(o,t,n,r);else for(var l=o.length-1;l>=0;l--)(i=o[l])&&(e=(s<3?i(e):s>3?i(t,n,e):i(t,n))||e);return s>3&&e&&Object.defineProperty(t,n,e),e},a=function(o,t){if(typeof Reflect==\"object\"&&typeof Reflect.metadata==\"function\")return Reflect.metadata(o,t)},dt=new D().getRoot(),X=H.Proof(J),k=class extends X{},f=class extends G({value:c,salt:c}){hash(){return M.hash([this.value,this.salt])}},{hashPart1:A,hashPart2:b}=C(),O=q,pt=L.fromBase58(\"B62qjGsPY47SMkTykivPBAU3riS9gvMMrGr7ve6ynoHJNBzAhQmtoBn\"),u=class extends W{constructor(){super(...arguments),this.startSlot=h(),this.commit=h(),this.result=h(),this.curRandomValue=h(),this.events={requested:F}}async commitValue(t){this.permissionCheck(),this.commit.getAndRequireEquals().assertEquals(c(0),\"Already committed\"),this.commit.set(t.hash())}async reveal(t){this.permissionCheck(),this.result.getAndRequireEquals().assertEquals(c(0),\"reveal: Result already computed\");let r=this.curRandomValue.getAndRequireEquals();this.commit.getAndRequireEquals().assertEquals(t.hash(),\"reveal: wrong commit value\"),this.checkRoundPass();let e=M.hash([t.value,r]);this.result.set(e)}async callZkon(){this.curRandomValue.getAndRequireEquals().assertEquals(c(0),\"random value have already been computed\");let r=await new S(O).sendRequest(this.address,A,b),s=new F({id:r,hash1:A,hash2:b});this.emitEvent(\"requested\",s)}async receiveZkonResponse(t,n){this.curRandomValue.getAndRequireEquals().assertEquals(c(0),\"receiveZkonResponse: prev random value was not consumed. Call reveal first\"),await new S(O).recordRequestFullfillment(t,n),this.curRandomValue.set(n.publicInput.dataField)}permissionCheck(){}checkRoundPass(){let t=this.startSlot.getAndRequireEquals();this.network.globalSlotSinceGenesis.requireBetween(t.add(I),V.MAXINT())}};p([g(V),a(\"design:type\",Object)],u.prototype,\"startSlot\",void 0);p([g(c),a(\"design:type\",Object)],u.prototype,\"commit\",void 0);p([g(c),a(\"design:type\",Object)],u.prototype,\"result\",void 0);p([g(c),a(\"design:type\",Object)],u.prototype,\"curRandomValue\",void 0);p([R,a(\"design:type\",Function),a(\"design:paramtypes\",[f]),a(\"design:returntype\",Promise)],u.prototype,\"commitValue\",null);p([R,a(\"design:type\",Function),a(\"design:paramtypes\",[f]),a(\"design:returntype\",Promise)],u.prototype,\"reveal\",null);p([R,a(\"design:type\",Function),a(\"design:paramtypes\",[c,k]),a(\"design:returntype\",Promise)],u.prototype,\"receiveZkonResponse\",null);var mt=u;export{f as CommitValue,u as RandomManager,k as ZkonProof,X as ZkonProof_,mt as default};\n"
"zkapp": "import{Field as c,MerkleMap as D,Poseidon as M,PublicKey as L,SmartContract as W,State as h,Struct as G,UInt32 as z,ZkProgram as H,method as R,state as g}from\"o1js\";import{PublicKey as v,UInt64 as j}from\"o1js\";var Q=j.from(10*10**9),I=480;var Y=v.fromBase58(\"B62qnBkcyABfjz2cqJPzNZKjVt9M9kx1vgoiWLbkJUnk16Cz8KX8qC4\"),q=v.fromBase58(\"B62qnmsn4Bm4MzPujKeN1faxedz4p1cCAwA9mKAWzDjfb4c1ysVvWeK\");import{ZkonZkProgram as J,ZkonRequestCoordinator as S,ExternalRequestEvent as F}from\"zkon-zkapp\";import{Field as k,Provable as E,provable as T,Struct as _,UInt32 as m,UInt64 as st}from\"o1js\";import{StringCircuitValue as P}from\"zkon-zkapp\";var x=\"bafkreibjk5hg5nd7j6uow62yv445wafadoqr7klvkmz7qakugx42fwt53y\";var N=254n,U=7,B=32n;function Z(o,t,n){if(n*BigInt(t)>N)throw new Error(\"The Packing Plant is only accepting orders that can fit into one Field, try using MultiPackingPlant\");class r extends _({packed:k}){constructor(e){super({packed:e})}static extractField(e){throw new Error(\"Must implement extractField\")}static sizeInBits(){throw new Error(\"Must implement sizeInBits\")}static unpack(e){throw new Error(\"Must implement unpack\")}static checkPack(e){if(e.length>t)throw new Error(`Input of size ${e.length} is larger than expected size of ${t}`)}static pack(e){this.checkPack(e);let a=this.extractField(e[0]),l=Math.min(e.length,t);for(let d=1;d<l;d++){let V=k((2n**this.sizeInBits())**BigInt(d));a=a.add(this.extractField(e[d]).mul(V))}return a}static unpackToBigints(e){let a=new Array(t);a.fill(0n);let l;if(e)l=e.toBigInt();else throw new Error(\"No Packed Value Provided\");for(let d=0;d<t;d++)a[d]=l&(1n<<this.sizeInBits())-1n,l>>=this.sizeInBits();return a}toFields(){return[this.packed]}assertEquals(e){this.packed.assertEquals(e.packed)}}return r.type=T({packed:k},{}),r.l=t,r.bitSize=n,r}function K(o=U){class t extends Z(m,o,B){static extractField(r){return r.value}static sizeInBits(){return B}static unpack(r){let s=E.witness(E.Array(m,o),()=>this.unpackToBigints(r).map(a=>m.from(a)));return r.assertEquals(t.pack(s)),s}static fromUInt32s(r){let s=t.pack(r);return new t(s)}static fromBigInts(r){let s=r.map(e=>m.from(e));return t.fromUInt32s(s)}toBigInts(){return t.unpack(this.packed).map(r=>r.toBigint())}}return t}var w=class extends K(){};var C=()=>{function o(t){let n=t.slice(0,30),r=t.slice(30),s=new P(n).toField(),e=new P(r).toField();return{hashPart1:s,hashPart2:e}}return o(x.toString())};var p=function(o,t,n,r){var s=arguments.length,e=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,a;if(typeof Reflect==\"object\"&&typeof Reflect.decorate==\"function\")e=Reflect.decorate(o,t,n,r);else for(var l=o.length-1;l>=0;l--)(a=o[l])&&(e=(s<3?a(e):s>3?a(t,n,e):a(t,n))||e);return s>3&&e&&Object.defineProperty(t,n,e),e},i=function(o,t){if(typeof Reflect==\"object\"&&typeof Reflect.metadata==\"function\")return Reflect.metadata(o,t)},dt=new D().getRoot(),X=H.Proof(J),y=class extends X{},f=class extends G({value:c,salt:c}){hash(){return M.hash([this.value,this.salt])}},{hashPart1:A,hashPart2:b}=C(),O=q,pt=L.fromBase58(\"B62qjGsPY47SMkTykivPBAU3riS9gvMMrGr7ve6ynoHJNBzAhQmtoBn\"),u=class extends W{constructor(){super(...arguments),this.startSlot=h(),this.commit=h(),this.result=h(),this.curRandomValue=h(),this.events={requested:F}}async commitValue(t){this.permissionCheck(),this.checkRoundPass(),this.commit.getAndRequireEquals().assertEquals(c(0),\"Already committed\"),this.commit.set(t.hash())}async reveal(t){this.permissionCheck(),this.result.getAndRequireEquals().assertEquals(c(0),\"reveal: Result already computed\");let r=this.curRandomValue.getAndRequireEquals();this.commit.getAndRequireEquals().assertEquals(t.hash(),\"reveal: wrong commit value\"),this.checkRoundPass();let e=M.hash([t.value,r]);this.result.set(e)}async callZkon(){this.curRandomValue.getAndRequireEquals().assertEquals(c(0),\"random value have already been computed\");let r=await new S(O).sendRequest(this.address,A,b),s=new F({id:r,hash1:A,hash2:b});this.emitEvent(\"requested\",s)}async receiveZkonResponse(t,n){this.curRandomValue.getAndRequireEquals().assertEquals(c(0),\"receiveZkonResponse: prev random value was not consumed. Call reveal first\"),await new S(O).recordRequestFullfillment(t,n),this.curRandomValue.set(n.publicInput.dataField)}permissionCheck(){}checkRoundPass(){let t=this.startSlot.getAndRequireEquals();this.network.globalSlotSinceGenesis.requireBetween(t.add(I),z.MAXINT())}};p([g(z),i(\"design:type\",Object)],u.prototype,\"startSlot\",void 0);p([g(c),i(\"design:type\",Object)],u.prototype,\"commit\",void 0);p([g(c),i(\"design:type\",Object)],u.prototype,\"result\",void 0);p([g(c),i(\"design:type\",Object)],u.prototype,\"curRandomValue\",void 0);p([R,i(\"design:type\",Function),i(\"design:paramtypes\",[f]),i(\"design:returntype\",Promise)],u.prototype,\"commitValue\",null);p([R,i(\"design:type\",Function),i(\"design:paramtypes\",[f]),i(\"design:returntype\",Promise)],u.prototype,\"reveal\",null);p([R,i(\"design:type\",Function),i(\"design:paramtypes\",[c,y]),i(\"design:returntype\",Promise)],u.prototype,\"receiveZkonResponse\",null);var mt=u;export{f as CommitValue,u as RandomManager,y as ZkonProof,X as ZkonProof_,mt as default};\n"
}
8 changes: 7 additions & 1 deletion src/PLottery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ export class BuyTicketEvent extends Struct({

export class ProduceResultEvent extends Struct({
result: Field,
totalScore: UInt64,
bank: Field,
}) {}

export class GetRewardEvent extends Struct({
Expand Down Expand Up @@ -226,9 +228,11 @@ export class PLottery extends SmartContract {
amount: convertToUInt64(bankValue.mul(COMMISSION).div(PRECISION)),
});

const newBankValue = bankValue.mul(PRECISION - COMMISSION).div(PRECISION);

// Update onchain values
this.ticketRoot.set(reduceProof.publicOutput.newTicketRoot);
this.bank.set(bankValue.mul(PRECISION - COMMISSION).div(PRECISION));
this.bank.set(newBankValue);
this.totalScore.set(reduceProof.publicOutput.totalScore);
this.result.set(winningNumbersPacked);

Expand All @@ -238,6 +242,8 @@ export class PLottery extends SmartContract {
'produce-result',
new ProduceResultEvent({
result: winningNumbersPacked,
bank: newBankValue,
totalScore: reduceProof.publicOutput.totalScore,
})
);
}
Expand Down
3 changes: 1 addition & 2 deletions src/Random/RandomManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,7 @@ export class RandomManager extends SmartContract {
@method async commitValue(commitValue: CommitValue) {
this.permissionCheck();

// Add time check
// this.checkRoundPass();
this.checkRoundPass();

const currentCommit = this.commit.getAndRequireEquals();
currentCommit.assertEquals(Field(0), 'Already committed');
Expand Down
12 changes: 6 additions & 6 deletions src/Tests/PLottery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,10 @@ describe('Add', () => {
checkConsistency();

console.log('Commiting value');
// Commit value for random
await commitValue(curRound);
// Wait next round
mineNBlocks(BLOCK_PER_ROUND);
// Commit value for random
await commitValue(curRound);

console.log('Revealing');
await produceResultInRM(curRound);
Expand Down Expand Up @@ -343,10 +343,10 @@ describe('Add', () => {
});
await tx1_1.prove();
await tx1_1.sign([senderKey]).send();
// Commit value for random
await commitValue(curRound);
// Wait 3 more rounds
mineNBlocks(3 * BLOCK_PER_ROUND + 1);
// Commit value for random
await commitValue(curRound);
// Reduce tickets
// let winningNumbers = getWinningCombinationPacked(curRound);
let reduceProof = await state.reduceTickets(Field(0));
Expand Down Expand Up @@ -436,10 +436,10 @@ describe('Add', () => {
expect(balanceBefore.sub(balanceAfter)).toEqual(TICKET_PRICE);
checkConsistency();
}
// Commit value for random
await commitValue(round);
// Wait for the end of round
mineNBlocks(BLOCK_PER_ROUND);
// Commit value for random
await commitValue(round);
// Produce random value
await produceResultInRM(round);

Expand Down
2 changes: 1 addition & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { PublicKey, UInt64 } from 'o1js';
export const NUMBERS_IN_TICKET = 6;

export const TICKET_PRICE = UInt64.from(10 * 10 ** 9);
export const BLOCK_PER_ROUND = 480; // Approximate blocks per 2 hour
export const BLOCK_PER_ROUND = 480; // Approximate blocks per 1 day

export const SCORE_COEFFICIENTS = [0, 90, 324, 2187, 26244, 590490, 31886460]; // Should be updated with appropriate probability

Expand Down
4 changes: 2 additions & 2 deletions vk.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9585612

Please sign in to comment.