├── .eslintrc.json ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── 1_exercise.ts ├── 2_exercise.ts ├── 3_exercise.ts ├── 4_exercise.ts ├── 5_exercise.ts ├── bonus.ts ├── hello_world.ts └── smart_contract.ts └── tsconfig.json /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es2021": true, 5 | "node": true 6 | }, 7 | "extends": "eslint:recommended", 8 | "parserOptions": { 9 | "ecmaVersion": 13, 10 | "sourceType": "module" 11 | }, 12 | "rules": { 13 | "no-unused-vars": "warn" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/* 2 | node_modules/* -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "singleQuote": true, 4 | "tabWidth": 2, 5 | "trailingComma": "es5" 6 | } 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # snarkyjs Workshop 2 | 3 | - slides: https://hackmd.io/@mimoo/rkPI5zluY#/ 4 | 5 | ```console 6 | $ git clone git@github.com:o1-labs/snarkyjs-workshop.git 7 | $ cd snarkyjs-workshop 8 | $ npm install 9 | $ npx tsc 10 | ``` 11 | 12 | Make sure you have node version >= 16.4! 13 | 14 | Then you can run individual examples with: 15 | 16 | ```console 17 | node dist/1_exercise.js 18 | node dist/2_exercise.js 19 | ... 20 | ``` 21 | 22 | If you change an example, you have to re-run typescript first: 23 | 24 | ```console 25 | npx tsc && node dist/1_exercise.js 26 | ``` 27 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "snarkyjs-workshop", 3 | "version": "1.0.0", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "snarkyjs-workshop", 9 | "version": "1.0.0", 10 | "license": "ISC", 11 | "dependencies": { 12 | "prettier": "^2.5.0", 13 | "snarkyjs": "^0.1.11", 14 | "typescript": "^4.5.2" 15 | }, 16 | "engines": { 17 | "node": ">=16.4.0" 18 | } 19 | }, 20 | "../snarkyjs": { 21 | "name": "@o1labs/snarkyjs", 22 | "version": "0.1.11", 23 | "extraneous": true, 24 | "license": "Apache-2.0", 25 | "dependencies": { 26 | "env": "^0.0.2", 27 | "reflect-metadata": "^0.1.13", 28 | "tslib": "^2.3.0" 29 | }, 30 | "bin": { 31 | "snarky-run": "src/build/run.mjs" 32 | }, 33 | "devDependencies": { 34 | "@types/jest": "^27.0.0", 35 | "@typescript-eslint/eslint-plugin": "^5.0.0", 36 | "esbuild": "^0.13.13", 37 | "eslint": "^8.0.0", 38 | "fs-extra": "^10.0.0", 39 | "jest": "^27.0.6", 40 | "minimist": "^1.2.5", 41 | "prettier": "^2.3.2", 42 | "ts-jest": "^27.0.4", 43 | "typedoc": "^0.22.9", 44 | "typescript": "^4.4.4" 45 | }, 46 | "engines": { 47 | "node": ">=16.4.0" 48 | } 49 | }, 50 | "node_modules/env": { 51 | "version": "0.0.2", 52 | "resolved": "https://registry.npmjs.org/env/-/env-0.0.2.tgz", 53 | "integrity": "sha1-UMGfMHsSmkWEW2tobfWzndQNHPA=", 54 | "engines": { 55 | "node": ">= 0.5.9" 56 | } 57 | }, 58 | "node_modules/prettier": { 59 | "version": "2.5.0", 60 | "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.0.tgz", 61 | "integrity": "sha512-FM/zAKgWTxj40rH03VxzIPdXmj39SwSjwG0heUcNFwI+EMZJnY93yAiKXM3dObIKAM5TA88werc8T/EwhB45eg==", 62 | "bin": { 63 | "prettier": "bin-prettier.js" 64 | }, 65 | "engines": { 66 | "node": ">=10.13.0" 67 | } 68 | }, 69 | "node_modules/reflect-metadata": { 70 | "version": "0.1.13", 71 | "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", 72 | "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==" 73 | }, 74 | "node_modules/snarkyjs": { 75 | "version": "0.1.11", 76 | "resolved": "https://registry.npmjs.org/snarkyjs/-/snarkyjs-0.1.11.tgz", 77 | "integrity": "sha512-fXt6nVO8uL9w/ZH2y/9jN0heUEj6qpIlazt2kBewm0jeS4lCN2K0uMOUcxxjf97vKTYsKjGuEv+ZUK6xnQJZtw==", 78 | "dependencies": { 79 | "env": "^0.0.2", 80 | "reflect-metadata": "^0.1.13", 81 | "tslib": "^2.3.0" 82 | }, 83 | "bin": { 84 | "snarky-run": "src/build/run.mjs" 85 | }, 86 | "engines": { 87 | "node": ">=16.4.0" 88 | } 89 | }, 90 | "node_modules/tslib": { 91 | "version": "2.3.1", 92 | "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", 93 | "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" 94 | }, 95 | "node_modules/typescript": { 96 | "version": "4.5.2", 97 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.2.tgz", 98 | "integrity": "sha512-5BlMof9H1yGt0P8/WF+wPNw6GfctgGjXp5hkblpyT+8rkASSmkUKMXrxR0Xg8ThVCi/JnHQiKXeBaEwCeQwMFw==", 99 | "bin": { 100 | "tsc": "bin/tsc", 101 | "tsserver": "bin/tsserver" 102 | }, 103 | "engines": { 104 | "node": ">=4.2.0" 105 | } 106 | } 107 | }, 108 | "dependencies": { 109 | "env": { 110 | "version": "0.0.2", 111 | "resolved": "https://registry.npmjs.org/env/-/env-0.0.2.tgz", 112 | "integrity": "sha1-UMGfMHsSmkWEW2tobfWzndQNHPA=" 113 | }, 114 | "prettier": { 115 | "version": "2.5.0", 116 | "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.0.tgz", 117 | "integrity": "sha512-FM/zAKgWTxj40rH03VxzIPdXmj39SwSjwG0heUcNFwI+EMZJnY93yAiKXM3dObIKAM5TA88werc8T/EwhB45eg==" 118 | }, 119 | "reflect-metadata": { 120 | "version": "0.1.13", 121 | "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", 122 | "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==" 123 | }, 124 | "snarkyjs": { 125 | "version": "0.1.11", 126 | "resolved": "https://registry.npmjs.org/snarkyjs/-/snarkyjs-0.1.11.tgz", 127 | "integrity": "sha512-fXt6nVO8uL9w/ZH2y/9jN0heUEj6qpIlazt2kBewm0jeS4lCN2K0uMOUcxxjf97vKTYsKjGuEv+ZUK6xnQJZtw==", 128 | "requires": { 129 | "env": "^0.0.2", 130 | "reflect-metadata": "^0.1.13", 131 | "tslib": "^2.3.0" 132 | } 133 | }, 134 | "tslib": { 135 | "version": "2.3.1", 136 | "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", 137 | "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" 138 | }, 139 | "typescript": { 140 | "version": "4.5.2", 141 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.2.tgz", 142 | "integrity": "sha512-5BlMof9H1yGt0P8/WF+wPNw6GfctgGjXp5hkblpyT+8rkASSmkUKMXrxR0Xg8ThVCi/JnHQiKXeBaEwCeQwMFw==" 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "snarkyjs-workshop", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "exec": "tsc && node dist/smart_contract.js", 8 | "helloworld": "npx tsc && node dist/hello_world.js", 9 | "run1": "npx tsc && node dist/1_exercise.js", 10 | "run2": "npx tsc && node dist/2_exercise.js", 11 | "run3": "npx tsc && node dist/3_exercise.js", 12 | "run4": "npx tsc && node dist/4_exercise.js", 13 | "run5": "npx tsc && node dist/5_exercise.js", 14 | "bonus": "npx tsc && node dist/bonus.js" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/o1-labs/snarkyjs-workshop.git" 19 | }, 20 | "keywords": [], 21 | "author": "", 22 | "license": "ISC", 23 | "type": "module", 24 | "bugs": { 25 | "url": "https://github.com/o1-labs/snarkyjs-workshop/issues" 26 | }, 27 | "engines": { 28 | "node": ">=16.4.0" 29 | }, 30 | "homepage": "https://github.com/o1-labs/snarkyjs-workshop#readme", 31 | "dependencies": { 32 | "prettier": "^2.5.0", 33 | "snarkyjs": "^0.1.11", 34 | "typescript": "^4.5.2" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/1_exercise.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Field, 3 | PrivateKey, 4 | PublicKey, 5 | SmartContract, 6 | state, 7 | State, 8 | method, 9 | UInt64, 10 | Mina, 11 | Party, 12 | isReady, 13 | shutdown, 14 | } from 'snarkyjs'; 15 | 16 | class Exercise1 extends SmartContract { 17 | @state(Field) x: State; 18 | 19 | constructor(initialBalance: UInt64, address: PublicKey, x: Field) { 20 | super(address); 21 | this.balance.addInPlace(initialBalance); 22 | this.x = State.init(x); 23 | } 24 | 25 | @method async update(cubed: Field) { 26 | const x = await this.x.get(); 27 | throw new Error('TODO: Set the state to x^3'); 28 | } 29 | } 30 | 31 | export async function run() { 32 | await isReady; 33 | 34 | const Local = Mina.LocalBlockchain(); 35 | Mina.setActiveInstance(Local); 36 | const account1 = Local.testAccounts[0].privateKey; 37 | const account2 = Local.testAccounts[1].privateKey; 38 | 39 | const snappPrivkey = PrivateKey.random(); 40 | const snappPubkey = snappPrivkey.toPublicKey(); 41 | 42 | let snappInstance: Exercise1; 43 | const initSnappState = new Field(3); 44 | 45 | // Deploys the snapp 46 | await Mina.transaction(account1, async () => { 47 | // account2 sends 1000000000 to the new snapp account 48 | const amount = UInt64.fromNumber(1000000000); 49 | const p = await Party.createSigned(account2); 50 | p.balance.subInPlace(amount); 51 | 52 | snappInstance = new Exercise1(amount, snappPubkey, initSnappState); 53 | }) 54 | .send() 55 | .wait(); 56 | 57 | // Update the snapp 58 | await Mina.transaction(account1, async () => { 59 | // 27 = 3^3 60 | await snappInstance.update(new Field(27)); 61 | }) 62 | .send() 63 | .wait(); 64 | 65 | const a = await Mina.getAccount(snappPubkey); 66 | 67 | console.log('Exercise 1'); 68 | console.log('final state value', a.snapp.appState[0].toString()); 69 | } 70 | 71 | run(); 72 | shutdown(); 73 | -------------------------------------------------------------------------------- /src/2_exercise.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Field, 3 | PrivateKey, 4 | PublicKey, 5 | SmartContract, 6 | state, 7 | State, 8 | method, 9 | UInt64, 10 | Mina, 11 | Party, 12 | Poseidon, 13 | isReady, 14 | shutdown, 15 | } from 'snarkyjs'; 16 | 17 | class Exercise2 extends SmartContract { 18 | @state(Field) x: State; 19 | 20 | static get UpdateReward(): UInt64 { 21 | return UInt64.fromNumber(1337); 22 | } 23 | 24 | constructor(initialBalance: UInt64, address: PublicKey, x: Field) { 25 | super(address); 26 | this.balance.addInPlace(initialBalance); 27 | this.x = State.init(x); 28 | } 29 | 30 | @method async update() { 31 | const x = await this.x.get(); 32 | throw new Error('TODO: Set the state to the hash of x'); 33 | } 34 | } 35 | 36 | export async function run() { 37 | await isReady; 38 | 39 | const Local = Mina.LocalBlockchain(); 40 | Mina.setActiveInstance(Local); 41 | const account1 = Local.testAccounts[0].privateKey; 42 | const account2 = Local.testAccounts[1].privateKey; 43 | const account2Pubkey = account2.toPublicKey(); 44 | 45 | const snappPrivkey = PrivateKey.random(); 46 | const snappPubkey = snappPrivkey.toPublicKey(); 47 | 48 | let snappInstance: Exercise2; 49 | const initSnappState = new Field(3); 50 | 51 | // Deploys the snapp 52 | await Mina.transaction(account1, async () => { 53 | // account2 sends 1000000000 to the new snapp account 54 | const amount = UInt64.fromNumber(1000000000); 55 | const p = await Party.createSigned(account2); 56 | p.balance.subInPlace(amount); 57 | 58 | snappInstance = new Exercise2(amount, snappPubkey, initSnappState); 59 | }) 60 | .send() 61 | .wait(); 62 | 63 | // Update the snapp, send the reward to account2 64 | await Mina.transaction(account1, async () => { 65 | await snappInstance.update(); 66 | const winner = Party.createUnsigned(account2Pubkey); 67 | winner.balance.addInPlace(Exercise2.UpdateReward); 68 | }) 69 | .send() 70 | .wait(); 71 | 72 | console.log('Exercise 2'); 73 | 74 | const a = await Mina.getAccount(snappPubkey); 75 | 76 | console.log('final state value', a.snapp.appState[0].toString()); 77 | } 78 | 79 | run(); 80 | shutdown(); 81 | -------------------------------------------------------------------------------- /src/3_exercise.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Field, 3 | PrivateKey, 4 | PublicKey, 5 | SmartContract, 6 | state, 7 | State, 8 | method, 9 | UInt64, 10 | Mina, 11 | Party, 12 | Poseidon, 13 | isReady, 14 | shutdown, 15 | } from 'snarkyjs'; 16 | 17 | class Exercise3 extends SmartContract { 18 | @state(Field) x: State; 19 | 20 | static get UpdateReward(): UInt64 { 21 | return UInt64.fromNumber(1337); 22 | } 23 | 24 | constructor(initialBalance: UInt64, address: PublicKey, x: Field) { 25 | super(address); 26 | this.balance.addInPlace(initialBalance); 27 | this.x = State.init(x); 28 | } 29 | 30 | @method async update() { 31 | const x = await this.x.get(); 32 | this.x.set(Poseidon.hash([x])); 33 | this.balance.subInPlace(Exercise3.UpdateReward); 34 | } 35 | } 36 | 37 | export async function run() { 38 | await isReady; 39 | 40 | const Local = Mina.LocalBlockchain(); 41 | Mina.setActiveInstance(Local); 42 | const account1 = Local.testAccounts[0].privateKey; 43 | const account2 = Local.testAccounts[1].privateKey; 44 | const account2Pubkey = account2.toPublicKey(); 45 | 46 | const snappPrivkey = PrivateKey.random(); 47 | const snappPubkey = snappPrivkey.toPublicKey(); 48 | 49 | let snappInstance: Exercise3; 50 | const initSnappState = new Field(3); 51 | 52 | // Deploys the snapp 53 | await Mina.transaction(account1, async () => { 54 | // account2 sends 1000000000 to the new snapp account 55 | const amount = UInt64.fromNumber(1000000000); 56 | const p = await Party.createSigned(account2); 57 | p.balance.subInPlace(amount); 58 | 59 | snappInstance = new Exercise3(amount, snappPubkey, initSnappState); 60 | }) 61 | .send() 62 | .wait(); 63 | 64 | // Update the snapp, send the reward to account2 65 | await Mina.transaction(account1, async () => { 66 | // 27 = 3^3 67 | await snappInstance.update(); 68 | const winner = Party.createUnsigned(account2Pubkey); 69 | winner.balance.addInPlace(Exercise3.UpdateReward); 70 | }) 71 | .send() 72 | .wait(); 73 | 74 | console.log('Exercise 3'); 75 | 76 | const a = await Mina.getAccount(account2Pubkey); 77 | 78 | console.log('Winner balance', a.balance.toString()); 79 | } 80 | 81 | run(); 82 | shutdown(); 83 | -------------------------------------------------------------------------------- /src/4_exercise.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Field, 3 | PrivateKey, 4 | PublicKey, 5 | SmartContract, 6 | state, 7 | State, 8 | method, 9 | UInt64, 10 | Mina, 11 | Party, 12 | Poseidon, 13 | shutdown, 14 | isReady, 15 | } from 'snarkyjs'; 16 | 17 | // We can define functions. Use a for-loop to define a function 18 | // that applies Poseidon.hash `n` times. 19 | function hashNTimes(n: number, x: Field): Field { 20 | throw new Error('TODO: hashNTimes'); 21 | } 22 | 23 | class Exercise4 extends SmartContract { 24 | @state(Field) x: State; 25 | 26 | constructor(initialBalance: UInt64, address: PublicKey, x: Field) { 27 | super(address); 28 | this.balance.addInPlace(initialBalance); 29 | this.x = State.init(x); 30 | } 31 | 32 | @method async update() { 33 | const x = await this.x.get(); 34 | // apply the hash function 10 times 35 | this.x.set(hashNTimes(10, x)); 36 | } 37 | } 38 | 39 | export async function run() { 40 | await isReady; 41 | 42 | const Local = Mina.LocalBlockchain(); 43 | Mina.setActiveInstance(Local); 44 | const account1 = Local.testAccounts[0].privateKey; 45 | const account2 = Local.testAccounts[1].privateKey; 46 | 47 | const snappPrivkey = PrivateKey.random(); 48 | const snappPubkey = snappPrivkey.toPublicKey(); 49 | 50 | let snappInstance: Exercise4; 51 | const initSnappState = new Field(3); 52 | 53 | // Deploys the snapp 54 | await Mina.transaction(account1, async () => { 55 | // account2 sends 1000000000 to the new snapp account 56 | const amount = UInt64.fromNumber(1000000000); 57 | const p = await Party.createSigned(account2); 58 | p.balance.subInPlace(amount); 59 | 60 | snappInstance = new Exercise4(amount, snappPubkey, initSnappState); 61 | }) 62 | .send() 63 | .wait(); 64 | 65 | // Update the snapp, send the reward to account2 66 | await Mina.transaction(account1, async () => { 67 | await snappInstance.update(); 68 | }) 69 | .send() 70 | .wait(); 71 | 72 | const a = await Mina.getAccount(snappPubkey); 73 | 74 | console.log('Exercise 4'); 75 | 76 | console.log('final state value', a.snapp.appState[0].toString()); 77 | } 78 | 79 | run(); 80 | shutdown(); 81 | -------------------------------------------------------------------------------- /src/5_exercise.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Field, 3 | PrivateKey, 4 | PublicKey, 5 | SmartContract, 6 | state, 7 | State, 8 | method, 9 | UInt32, 10 | UInt64, 11 | Mina, 12 | Party, 13 | Poseidon, 14 | CircuitValue, 15 | Circuit, 16 | prop, 17 | Signature, 18 | Bool, 19 | isReady, 20 | shutdown, 21 | } from 'snarkyjs'; 22 | 23 | // This exercise involves a user defined data type. 24 | class SignatureWithSigner extends CircuitValue { 25 | @prop signature: Signature; 26 | @prop signer: PublicKey; 27 | 28 | constructor(signature: Signature, signer: PublicKey) { 29 | super(); 30 | this.signature = signature; 31 | this.signer = signer; 32 | } 33 | 34 | static create(signer: PrivateKey, message: Field[]): SignatureWithSigner { 35 | return new SignatureWithSigner( 36 | Signature.create(signer, message), 37 | signer.toPublicKey() 38 | ); 39 | } 40 | } 41 | 42 | function containsPublicKey(xs: Array, x: PublicKey): Bool { 43 | throw new Error('TODO: Implement containsPublicKey'); 44 | } 45 | 46 | // This implements a snapp account that can be used if a user has 47 | // any of a list of public keys. The list of public keys is also 48 | // secret. 49 | class Exercise5 extends SmartContract { 50 | // This is not a state variable but a contract parameter 51 | owners: Array; 52 | 53 | // No state this time 54 | 55 | constructor( 56 | initialBalance: UInt64, 57 | address: PublicKey, 58 | owners: Array 59 | ) { 60 | super(address); 61 | this.owners = owners; 62 | this.balance.addInPlace(initialBalance); 63 | } 64 | 65 | // Spend requires a signature with one of the keys in the list 66 | @method async spend(amount: UInt64, s: SignatureWithSigner) { 67 | // Check that some owner is equal to the signer 68 | containsPublicKey(this.owners, s.signer).assertEquals(true); 69 | 70 | // Check that the signature verifies against the message which is 71 | // the current account nonce 72 | const nonce: UInt32 = await this.nonce; 73 | // Verify the signature 74 | s.signature.verify(s.signer, nonce.toFields()).assertEquals(true); 75 | 76 | // Allow the sender of this transaction to decrease the balance. 77 | this.balance.subInPlace(amount); 78 | } 79 | } 80 | 81 | export async function run() { 82 | await isReady; 83 | 84 | // Set up some keypairs for the account 85 | const privateKeys: Array = []; 86 | const publicKeys: Array = []; 87 | for (let i = 0; i < 10; ++i) { 88 | let k = PrivateKey.random(); 89 | privateKeys.push(k); 90 | publicKeys.push(k.toPublicKey()); 91 | } 92 | 93 | const Local = Mina.LocalBlockchain(); 94 | Mina.setActiveInstance(Local); 95 | const account1 = Local.testAccounts[0].privateKey; 96 | const account2 = Local.testAccounts[1].privateKey; 97 | 98 | const snappPrivkey = PrivateKey.random(); 99 | const snappPubkey = snappPrivkey.toPublicKey(); 100 | 101 | let snappInstance: Exercise5; 102 | 103 | // Deploys the snapp 104 | await Mina.transaction(account1, async () => { 105 | // account2 sends 1000000000 to the new snapp account 106 | const amount = UInt64.fromNumber(1000000000); 107 | const p = await Party.createSigned(account2); 108 | p.balance.subInPlace(amount); 109 | 110 | snappInstance = new Exercise5(amount, snappPubkey, publicKeys); 111 | }) 112 | .send() 113 | .wait(); 114 | 115 | const { nonce: snappNonce } = await Mina.getAccount(snappPubkey); 116 | 117 | // Update the snapp, send to account 2 118 | await Mina.transaction(account1, async () => { 119 | const amount = UInt64.fromNumber(123); 120 | // Pick one of the valid senders to sign with 121 | const sender = privateKeys[5]; 122 | 123 | await snappInstance.spend( 124 | amount, 125 | SignatureWithSigner.create(sender, snappNonce.toFields()) 126 | ); 127 | // Send it to account 2 128 | Party.createUnsigned(account2.toPublicKey()).balance.addInPlace(amount); 129 | }) 130 | .send() 131 | .wait(); 132 | 133 | const a = await Mina.getAccount(account2.toPublicKey()); 134 | 135 | console.log('Exercise 5'); 136 | console.log('account2 balance', a.balance.toString()); 137 | } 138 | 139 | run(); 140 | shutdown(); 141 | -------------------------------------------------------------------------------- /src/bonus.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Field, 3 | prop, 4 | PublicKey, 5 | CircuitValue, 6 | Signature, 7 | UInt64, 8 | UInt32, 9 | KeyedAccumulatorFactory, 10 | ProofWithInput, 11 | proofSystem, 12 | branch, 13 | MerkleStack, 14 | shutdown, 15 | } from 'snarkyjs'; 16 | 17 | const AccountDbDepth: number = 32; 18 | const AccountDb = KeyedAccumulatorFactory( 19 | AccountDbDepth 20 | ); 21 | type AccountDb = InstanceType; 22 | 23 | class RollupAccount extends CircuitValue { 24 | @prop balance: UInt64; 25 | @prop nonce: UInt32; 26 | @prop publicKey: PublicKey; 27 | 28 | constructor(balance: UInt64, nonce: UInt32, publicKey: PublicKey) { 29 | super(); 30 | this.balance = balance; 31 | this.nonce = nonce; 32 | this.publicKey = publicKey; 33 | } 34 | } 35 | 36 | class RollupTransaction extends CircuitValue { 37 | @prop amount: UInt64; 38 | @prop nonce: UInt32; 39 | @prop sender: PublicKey; 40 | @prop receiver: PublicKey; 41 | 42 | constructor( 43 | amount: UInt64, 44 | nonce: UInt32, 45 | sender: PublicKey, 46 | receiver: PublicKey 47 | ) { 48 | super(); 49 | this.amount = amount; 50 | this.nonce = nonce; 51 | this.sender = sender; 52 | this.receiver = receiver; 53 | } 54 | } 55 | 56 | class RollupDeposit extends CircuitValue { 57 | @prop publicKey: PublicKey; 58 | @prop amount: UInt64; 59 | constructor(publicKey: PublicKey, amount: UInt64) { 60 | super(); 61 | this.publicKey = publicKey; 62 | this.amount = amount; 63 | } 64 | } 65 | 66 | class RollupState extends CircuitValue { 67 | @prop pendingDepositsCommitment: Field; 68 | @prop accountDbCommitment: Field; 69 | constructor(p: Field, c: Field) { 70 | super(); 71 | this.pendingDepositsCommitment = p; 72 | this.accountDbCommitment = c; 73 | } 74 | } 75 | 76 | class RollupStateTransition extends CircuitValue { 77 | @prop source: RollupState; 78 | @prop target: RollupState; 79 | constructor(source: RollupState, target: RollupState) { 80 | super(); 81 | this.source = source; 82 | this.target = target; 83 | } 84 | } 85 | 86 | // a recursive proof system is kind of like an "enum" 87 | @proofSystem 88 | class RollupProof extends ProofWithInput { 89 | @branch static processDeposit( 90 | pending: MerkleStack, 91 | accountDb: AccountDb 92 | ): RollupProof { 93 | let before = new RollupState(pending.commitment, accountDb.commitment()); 94 | let deposit = pending.pop(); 95 | let [{ isSome }, mem] = accountDb.get(deposit.publicKey); 96 | isSome.assertEquals(false); 97 | 98 | let account = new RollupAccount( 99 | UInt64.zero, 100 | UInt32.zero, 101 | deposit.publicKey 102 | ); 103 | accountDb.set(mem, account); 104 | 105 | let after = new RollupState(pending.commitment, accountDb.commitment()); 106 | 107 | return new RollupProof(new RollupStateTransition(before, after)); 108 | } 109 | 110 | @branch static transaction( 111 | t: RollupTransaction, 112 | s: Signature, 113 | pending: MerkleStack, 114 | accountDb: AccountDb 115 | ): RollupProof { 116 | s.verify(t.sender, t.toFields()).assertEquals(true); 117 | let stateBefore = new RollupState( 118 | pending.commitment, 119 | accountDb.commitment() 120 | ); 121 | 122 | let [senderAccount, senderPos] = accountDb.get(t.sender); 123 | senderAccount.isSome.assertEquals(true); 124 | senderAccount.value.nonce.assertEquals(t.nonce); 125 | 126 | senderAccount.value.balance = senderAccount.value.balance.sub(t.amount); 127 | senderAccount.value.nonce = senderAccount.value.nonce.add(1); 128 | 129 | accountDb.set(senderPos, senderAccount.value); 130 | 131 | let [receiverAccount, receiverPos] = accountDb.get(t.receiver); 132 | receiverAccount.value.balance = receiverAccount.value.balance.add(t.amount); 133 | accountDb.set(receiverPos, receiverAccount.value); 134 | 135 | let stateAfter = new RollupState( 136 | pending.commitment, 137 | accountDb.commitment() 138 | ); 139 | return new RollupProof(new RollupStateTransition(stateBefore, stateAfter)); 140 | } 141 | 142 | @branch static merge(p1: RollupProof, p2: RollupProof): RollupProof { 143 | p1.publicInput.target.assertEquals(p2.publicInput.source); 144 | return new RollupProof( 145 | new RollupStateTransition(p1.publicInput.source, p2.publicInput.target) 146 | ); 147 | } 148 | } 149 | 150 | shutdown(); 151 | -------------------------------------------------------------------------------- /src/hello_world.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Field, 3 | PrivateKey, 4 | PublicKey, 5 | SmartContract, 6 | state, 7 | State, 8 | method, 9 | UInt64, 10 | Mina, 11 | Party, 12 | Group, 13 | shutdown, 14 | isReady, 15 | } from 'snarkyjs'; 16 | 17 | class HelloWorld extends SmartContract { 18 | @state(Field) value: State; 19 | 20 | constructor(initialBalance: UInt64, address: PublicKey, x: Field) { 21 | super(address); 22 | this.balance.addInPlace(initialBalance); 23 | this.value = State.init(x); 24 | } 25 | 26 | @method async update(squared: Field) { 27 | const x = await this.value.get(); 28 | x.square().assertEquals(squared); 29 | this.value.set(squared); 30 | } 31 | } 32 | 33 | function messingAround() { 34 | const x = new Field(10); 35 | console.log(x.add(x).toString()); 36 | console.log(x.square().toString()); 37 | 38 | const g = Group.generator; 39 | // (g + g) - g = g 40 | g.add(g).neg().add(g).assertEquals(g); 41 | } 42 | 43 | async function runSimpleApp() { 44 | await isReady; 45 | 46 | const Local = Mina.LocalBlockchain(); 47 | Mina.setActiveInstance(Local); 48 | const account1 = Local.testAccounts[0].privateKey; 49 | const account2 = Local.testAccounts[1].privateKey; 50 | 51 | const snappPrivkey = PrivateKey.random(); 52 | const snappPubkey = snappPrivkey.toPublicKey(); 53 | 54 | let snappInstance: HelloWorld; 55 | const initSnappState = new Field(3); 56 | 57 | // Deploys the snapp 58 | await Mina.transaction(account1, async () => { 59 | // account2 sends 1000000000 to the new snapp account 60 | const amount = UInt64.fromNumber(1000000000); 61 | const p = await Party.createSigned(account2); 62 | p.balance.subInPlace(amount); 63 | 64 | snappInstance = new HelloWorld(amount, snappPubkey, initSnappState); 65 | }) 66 | .send() 67 | .wait(); 68 | 69 | // Update the snapp 70 | await Mina.transaction(account1, async () => { 71 | // 9 = 3^2 72 | await snappInstance.update(new Field(9)); 73 | }) 74 | .send() 75 | .wait(); 76 | 77 | await Mina.transaction(account1, async () => { 78 | // Fails, because the provided value is wrong. 79 | await snappInstance.update(new Field(109)); 80 | }) 81 | .send() 82 | .wait() 83 | .catch((e) => console.log('second update attempt failed')); 84 | 85 | const a = await Mina.getAccount(snappPubkey); 86 | 87 | console.log('final state value', a.snapp.appState[0].toString()); 88 | } 89 | 90 | runSimpleApp(); 91 | 92 | shutdown(); 93 | -------------------------------------------------------------------------------- /src/smart_contract.ts: -------------------------------------------------------------------------------- 1 | import { Field, shutdown, isReady } from 'snarkyjs'; 2 | 3 | await isReady; 4 | 5 | const x0 = new Field('37'); 6 | 7 | shutdown(); 8 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["./src"], 3 | "compilerOptions": { 4 | "module": "esnext", 5 | "outDir": "dist", 6 | "target": "ES2020", 7 | "strict": true, 8 | "moduleResolution": "node", 9 | "skipLibCheck": true, 10 | "experimentalDecorators": true, 11 | "emitDecoratorMetadata": true 12 | } 13 | } 14 | --------------------------------------------------------------------------------