Skip to content

Commit

Permalink
Merge pull request #1 from SutuLabs/feat_o1js
Browse files Browse the repository at this point in the history
migrate to o1js
  • Loading branch information
wizicer authored Nov 20, 2023
2 parents 45a5128 + 29ba658 commit 22bc88c
Show file tree
Hide file tree
Showing 38 changed files with 211 additions and 175 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/build-ui.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ on:
- main
paths:
- "contracts/src/**"
- "contracts/utils/fetchAccount.ts"
- "contracts/server/challengeData.ts"
- "contracts/server/services/model.ts"
- "ui/**"
Expand All @@ -15,6 +16,7 @@ on:
- main
paths:
- "contracts/src/**"
- "contracts/utils/fetchAccount.ts"
- "contracts/server/challengeData.ts"
- "contracts/server/services/model.ts"
- "ui/**"
Expand Down
4 changes: 2 additions & 2 deletions contracts/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ module.exports = {
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:snarkyjs/recommended',
'plugin:o1js/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
},
plugins: ['@typescript-eslint', 'snarkyjs'],
plugins: ['@typescript-eslint', 'o1js'],
rules: {
'no-constant-condition': 'off',
'prefer-const': 'off',
Expand Down
8 changes: 8 additions & 0 deletions contracts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ npm run testw # watch mode
npm run coverage
```

## Dependencies

- PocketBase 0.16.7

## Important Notes

Don't forget to recompile the contract by `npm run compile` when 1) changed contract code and 2) upgraded framework version.

## License

[Apache-2.0](LICENSE)
4 changes: 2 additions & 2 deletions contracts/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
"version": 1,
"deployAliases": {
"bk": {
"url": "http://berkeley.mina.sutulabs.com/graphql",
"url": "https://proxy.berkeley.minaexplorer.com/",
"keyPath": "keys/bk.json",
"fee": "0.1",
"smartContract": "MazeContract"
}
}
}
}
2 changes: 1 addition & 1 deletion contracts/jest-resolver.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module.exports = (request, options) => {
...options,
packageFilter: (pkg) => {
// When importing snarkyjs, we specify the Node ESM import as Jest by default imports the web version
if (pkg.name === 'snarkyjs') {
if (pkg.name === 'o1js') {
return {
...pkg,
main: pkg.exports.node.import,
Expand Down
105 changes: 61 additions & 44 deletions contracts/package-lock.json

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

8 changes: 4 additions & 4 deletions contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
"watch:ts": "tsc --watch",
"build:docker": "docker build -f Dockerfile -t wizicer/ctf-server:latest .",
"publish:docker": "docker push wizicer/ctf-server:latest",
"serve": "nodemon server/server.ts",
"compile": "ts-node scripts/compile.ts server/vkey.json",
"dev": "nodemon server/server.ts",
"compile": "ts-node scripts/compile.ts server/vkey.json all",
"coverage": "node --experimental-vm-modules --experimental-wasm-threads node_modules/jest/bin/jest.js --coverage",
"format": "prettier --write --ignore-unknown **/*",
"test": "node --experimental-vm-modules --experimental-wasm-threads node_modules/jest/bin/jest.js --verbose",
Expand All @@ -46,15 +46,15 @@
"cross-fetch": "^4.0.0",
"dotenv": "^16.3.1",
"eslint": "^8.7.0",
"eslint-plugin-snarkyjs": "^0.1.0",
"eslint-plugin-o1js": "^0.4.0",
"express": "^4.18.2",
"jest": "^27.3.1",
"lint-staged": "^11.0.1",
"mina-signer": "^2.1.0",
"nodemon": "^2.0.22",
"o1js": "0.14.*",
"pocketbase": "^0.15.2",
"prettier": "^2.3.2",
"snarkyjs": "^0.11.0",
"ts-jest": "^27.0.7",
"ts-node": "^10.9.1",
"typescript": "^4.7.2"
Expand Down
2 changes: 1 addition & 1 deletion contracts/scripts/compile.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs';
import { Field } from 'snarkyjs';
import { Field } from 'o1js';
import '../server/config';

import { CheckinContract } from '../src/checkin.js';
Expand Down
7 changes: 6 additions & 1 deletion contracts/server/app.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import './config';
import express from 'express';
import { Mina } from 'snarkyjs';
import { Mina } from 'o1js';
import cors from 'cors';
import PocketBase from 'pocketbase';
// import 'cross-fetch/polyfill';
import { checkChallenge, createChallenge } from './services/challenge';
import { getPkChallenges, getScoreList } from './services/score';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
(BigInt.prototype as any).toJSON = function () {
return this.toString();
};

const pbUrl = process.env.PB_EP_URL;
const pbUsername = process.env.PB_USERNAME;
const pbPassword = process.env.PB_PASSWORD;
Expand Down
56 changes: 37 additions & 19 deletions contracts/server/services/challenge.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import express from 'express';
import { fetchAccount, PrivateKey, PublicKey, SmartContract } from 'snarkyjs';
import { PrivateKey, PublicKey, SmartContract } from 'o1js';
import { CheckinContract } from '../../src/checkin.js';
import { MazeContract } from '../../src/maze.js';
import { PrimeContract } from '../../src/prime.js';
import { VerifierContract } from '../../src/verifier.js';
import { authenticate, getContractTx, num2Arr, tryGetAccount } from './utils';
import { authenticate, getContractTx, tryGetAccount } from './utils';
import PocketBase from 'pocketbase';
import { StartRequest, StartResponse, CaptureRequest, CaptureResponse } from './model';
import { challengeData as cdata } from '../challengeData';
import vkeyraw from '../vkey.json' assert { type: 'json' };
import { MeowHeroContract } from '../../src/meowHero.js';
import { fetchAccount } from '../../utils/fetchAccount';

const vkey = vkeyraw as unknown as {
[key: string]: {
Expand Down Expand Up @@ -47,20 +48,23 @@ export async function createChallenge(pb: PocketBase, req: express.Request, res:
return;
}

// check deployer pk balance
let account = await tryGetAccount({
account: deployerPublicKey,
isZkAppAccount: false,
});
const isCheckAccountBalance = false; // this check can be disabled, UI part can do this instead.
if (isCheckAccountBalance) {
// check deployer pk balance
let account = await tryGetAccount({
account: deployerPublicKey,
isZkAppAccount: false,
});

if (!account) {
const msg =
'Deployer account does not exist. ' +
'Request funds at faucet https://berkeley.minaexplorer.com/faucet or ' +
'https://faucet.minaprotocol.com/?address=' +
deployerPublicKey.toBase58();
res.status(400).send(JSON.stringify({ success: false, error: msg }));
return;
if (!account) {
const msg =
'Deployer account does not exist. ' +
'Request funds at faucet https://berkeley.minaexplorer.com/faucet or ' +
'https://faucet.minaprotocol.com/?address=' +
deployerPublicKey.toBase58();
res.status(400).send(JSON.stringify({ success: false, error: msg }));
return;
}
}
// console.log(
// `Using fee payer account with nonce ${account.nonce}, balance ${account.balance}`
Expand Down Expand Up @@ -149,11 +153,17 @@ export async function checkChallenge(endpointUrl: string, pb: PocketBase, req: e

// check challenge status
let { account } = await fetchAccount({ publicKey: contractId }, endpointUrl);
const state = account?.zkapp?.appState;
if (account === undefined) {
res.send({ success: false, error: 'network issue, try again later' });
return;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const state = account?.zkappState;
const flagpos = challenge.flagPosition;
const flagarr = state?.[flagpos]?.value?.[1];
const targetArr = num2Arr(challenge.flagNumber);
if (JSON.stringify(flagarr) != JSON.stringify(targetArr)) {
const flag = state?.[flagpos];

if (BigInt(flag ?? 0) != challenge.flagNumber) {
res.send({ success: false, error: 'flag not caught yet' });
return;
}
Expand All @@ -169,7 +179,15 @@ export async function checkChallenge(endpointUrl: string, pb: PocketBase, req: e
console.log(`Challenge complete by ${citem.publicKey}, contract id: ${contractId}`);
res.send({ success: true } as CaptureResponse);
} catch (err) {
if (err instanceof Error && err.message == 'fetch failed') {
res.send({
success: false,
error: 'network issue, please try again later',
});
return;
}
console.warn(err);
if (err instanceof Error) console.log(err.message, err.name);
res.status(500).send({
success: false,
error: err instanceof Error ? err.message : err,
Expand Down
Loading

0 comments on commit 22bc88c

Please sign in to comment.