├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── hardhat ├── .npmignore ├── .prettierignore ├── .prettierrc ├── .solcover.js ├── .solhint.json ├── .solhintignore ├── README.md ├── assets │ └── mnist_image.pgm ├── circuits │ ├── circuit.circom │ ├── circuit2.circom │ ├── sha256 │ │ ├── ch.circom │ │ ├── constants.circom │ │ ├── main.circom │ │ ├── maj.circom │ │ ├── rotate.circom │ │ ├── sha256.circom │ │ ├── sha256_2.circom │ │ ├── sha256compression.circom │ │ ├── sha256compression_function.circom │ │ ├── shift.circom │ │ ├── sigma.circom │ │ ├── sigmaplus.circom │ │ ├── t1.circom │ │ ├── t2.circom │ │ └── xor3.circom │ └── stat.circom ├── contracts │ ├── Bounty.sol │ ├── BountyFactory.sol │ ├── IVerifier.sol │ ├── basic-solidity-examples │ │ └── SimpleCoin.sol │ ├── cid.sol │ ├── filecoin-api-examples │ │ ├── DealRewarder.sol │ │ └── FilecoinMarketConsumer.sol │ ├── lib │ │ ├── buffer │ │ │ ├── .gitattributes │ │ │ ├── .gitignore │ │ │ ├── .npmignore │ │ │ ├── .soliumignore │ │ │ ├── .soliumrc.json │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── contracts │ │ │ │ └── Buffer.sol │ │ │ ├── hardhat.config.js │ │ │ ├── migrations │ │ │ │ ├── 1_initial_migration.js │ │ │ │ └── 2_deploy_contracts.js │ │ │ ├── package-lock.json │ │ │ ├── package.json │ │ │ ├── test │ │ │ │ ├── TestBuffer.js │ │ │ │ └── TestBuffer.sol │ │ │ └── truffle.js │ │ ├── filecoin-solidity │ │ │ └── contracts │ │ │ │ └── v0.8 │ │ │ │ ├── AccountAPI.sol │ │ │ │ ├── DataCapAPI.sol │ │ │ │ ├── InitAPI.sol │ │ │ │ ├── MarketAPI.sol │ │ │ │ ├── MinerAPI.sol │ │ │ │ ├── MultisigAPI.sol │ │ │ │ ├── PowerAPI.sol │ │ │ │ ├── PrecompilesAPI.sol │ │ │ │ ├── Utils.sol │ │ │ │ ├── VerifRegAPI.sol │ │ │ │ ├── cbor │ │ │ │ ├── AccountCbor.sol │ │ │ │ ├── BigIntCbor.sol │ │ │ │ ├── DataCapCbor.sol │ │ │ │ ├── FilecoinCbor.sol │ │ │ │ ├── InitCbor.sol │ │ │ │ ├── MarketCbor.sol │ │ │ │ ├── MinerCbor.sol │ │ │ │ ├── MultisigCbor.sol │ │ │ │ ├── PowerCbor.sol │ │ │ │ └── VerifRegCbor.sol │ │ │ │ ├── types │ │ │ │ ├── AccountTypes.sol │ │ │ │ ├── CommonTypes.sol │ │ │ │ ├── DataCapTypes.sol │ │ │ │ ├── InitTypes.sol │ │ │ │ ├── MarketTypes.sol │ │ │ │ ├── MinerTypes.sol │ │ │ │ ├── MultisigTypes.sol │ │ │ │ ├── PowerTypes.sol │ │ │ │ └── VerifRegTypes.sol │ │ │ │ └── utils │ │ │ │ ├── Actor.sol │ │ │ │ ├── CborDecode.sol │ │ │ │ └── Misc.sol │ │ ├── openzeppelin-contracts │ │ │ └── contracts │ │ │ │ └── utils │ │ │ │ ├── Strings.sol │ │ │ │ └── math │ │ │ │ ├── Math.sol │ │ │ │ ├── SafeCast.sol │ │ │ │ ├── SafeMath.sol │ │ │ │ ├── SignedMath.sol │ │ │ │ └── SignedSafeMath.sol │ │ └── solidity-cborutils │ │ │ ├── .gitattributes │ │ │ ├── .github │ │ │ └── workflows │ │ │ │ └── ci.yaml │ │ │ ├── .gitignore │ │ │ ├── .solhint.json │ │ │ ├── .soliumignore │ │ │ ├── .soliumrc.json │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── contracts │ │ │ └── CBOR.sol │ │ │ ├── hardhat.config.js │ │ │ ├── package.json │ │ │ ├── test │ │ │ ├── TestCBOR.sol │ │ │ └── testcbor.js │ │ │ └── yarn.lock │ └── verifier.sol ├── deploy │ └── 00_deploy.js ├── hardhat.config.js ├── helper-hardhat-config.js ├── package.json ├── sample_calldata │ ├── claimBounty.json │ ├── createBounty.json │ └── submitBounty.json ├── scripts │ ├── bump-solidity.js │ ├── compile-circuits.sh │ └── setup-circom.sh ├── tasks │ ├── deal-rewarder │ │ └── add-cid.js │ ├── filecoin-market-consumer │ │ └── store-all.js │ ├── get-address.js │ ├── index.js │ └── simple-coin │ │ ├── get-balance.js │ │ └── send-coin.js ├── test │ ├── bounty.test.js │ ├── circuit.test.js │ ├── circuit2.test.js │ ├── factory.test.js │ ├── lighthouse.test.js │ └── mnist_latest_input.json └── yarn.lock └── ui ├── .babelrc ├── .eslintrc.js ├── Bounty.json ├── BountyFactory.json ├── README.md ├── base32.d.ts ├── components ├── CreateBounty │ ├── CheckOutStep.tsx │ ├── InitializeStep.tsx │ ├── ProcessingStep.tsx │ └── VerifyStep.tsx ├── FlowCard.tsx ├── MainFlow.tsx ├── NavBar.tsx ├── NavList.tsx ├── TopBar.tsx └── TopSearchBar.tsx ├── local-env.d.ts ├── next.config.js ├── package-lock.json ├── package.json ├── pages ├── _app.tsx ├── api │ ├── chain.config.ts │ └── hello.ts ├── create.tsx ├── index.tsx ├── myspace.tsx ├── submissions.tsx └── tasks │ └── [slug].tsx ├── public └── staricon.svg ├── styles └── globals.css ├── tsconfig.json ├── typings.d.ts └── utils.tsx /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # vscode 2 | .vscode 3 | 4 | # hardhat 5 | hardhat/artifacts 6 | hardhat/cache 7 | hardhat/deployments 8 | hardhat/node_modules 9 | hardhat/coverage 10 | hardhat/coverage.json 11 | hardhat/typechain 12 | 13 | # don't push the environment vars! 14 | .env 15 | 16 | # Built application files 17 | .DS* 18 | *.apk 19 | *.ap_ 20 | *.aab 21 | 22 | # Files for the ART/Dalvik VM 23 | *.dex 24 | 25 | # Java class files 26 | *.class 27 | 28 | # Generated files 29 | bin/ 30 | gen/ 31 | out/ 32 | # Uncomment the following line in case you need and you don't have the release build type files in your app 33 | # release/ 34 | 35 | # Gradle files 36 | .gradle/ 37 | build/ 38 | 39 | # Local configuration file (sdk path, etc) 40 | local.properties 41 | 42 | # Proguard folder generated by Eclipse 43 | proguard/ 44 | 45 | # Log Files 46 | *.log 47 | 48 | # Android Studio Navigation editor temp files 49 | .navigation/ 50 | 51 | # Android Studio captures folder 52 | captures/ 53 | 54 | # IntelliJ 55 | *.iml 56 | .idea/workspace.xml 57 | .idea/tasks.xml 58 | .idea/gradle.xml 59 | .idea/assetWizardSettings.xml 60 | .idea/dictionaries 61 | .idea/libraries 62 | # Android Studio 3 in .gitignore file. 63 | .idea/caches 64 | .idea/modules.xml 65 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 66 | .idea/navEditor.xml 67 | 68 | # Keystore files 69 | # Uncomment the following lines if you do not want to check your keystore files in. 70 | #*.jks 71 | #*.keystore 72 | 73 | # External native build folder generated in Android Studio 2.2 and later 74 | .externalNativeBuild 75 | 76 | # Google Services (e.g. APIs or Firebase) 77 | # google-services.json 78 | 79 | # Freeline 80 | freeline.py 81 | freeline/ 82 | freeline_project_description.json 83 | 84 | # fastlane 85 | fastlane/report.xml 86 | fastlane/Preview.html 87 | fastlane/screenshots 88 | fastlane/test_output 89 | fastlane/readme.md 90 | 91 | # Version control 92 | vcs.xml 93 | 94 | # lint 95 | lint/intermediates/ 96 | lint/generated/ 97 | lint/outputs/ 98 | lint/tmp/ 99 | # lint/reports/ 100 | 101 | hardhat/gas-report.txt 102 | 103 | hardhat/contracts/test/fuzzing/crytic-export 104 | 105 | # circom 106 | hardhat/circuits/build 107 | *.ptau 108 | 109 | # ui 110 | # dependencies 111 | ui/node_modules 112 | ui/.pnp 113 | ui/.pnp.js 114 | 115 | # testing 116 | ui/coverage 117 | 118 | # next.js 119 | ui/.next/ 120 | ui/out/ 121 | 122 | # production 123 | ui/build 124 | 125 | # misc 126 | ui/.DS_Store 127 | ui/*.pem 128 | 129 | # debug 130 | ui/npm-debug.log* 131 | ui/yarn-debug.log* 132 | ui/yarn-error.log* 133 | ui/.pnpm-debug.log* 134 | 135 | # local env files 136 | ui/.env*.local 137 | 138 | # vercel 139 | ui/.vercel 140 | 141 | # typescript 142 | ui/*.tsbuildinfo 143 | ui/next-env.d.ts -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ZKaggle 2 | Bounty platform for incentivized decentralized computing on FVM 3 | 4 | Deployed on Hyperspace testnet: https://zkaggle.vercel.app/ 5 | 6 | ## Project Description 7 | This project makes decentralized computing not only available for storage providers, but for everyone who wants to share their processing power and/or monetize their proprietary models. Our browser-based frontend allows bounty providers to upload their data to Filecoin and set up a computing task with bounty rewards. Bounty hunters can browse all open bounties, download the data onto their local machine, and compute. When they are ready to submit, they construct a ZK proof to submit the hashed computed results on-chain. Bounty providers will then review the submission and release the bounty. Last but not least, bounty hunters can claim their rewards by providing the pre-image of the hashed computed results. ZKP serves two purposes here: (1) to keep the proof of computation succinct, and (2) to allow bounty hunters to monetize private models with credibility. 8 | 9 | ## How it's Made 10 | We use RainbowKit + wagmi + Next.js to build the frontend. Lighthouse SDK is used to handle file uploading and encryption. It has helped such that we do not need to handle storage deals by ourselves. Also, files that bounty hunters upload can only be viewed by bounty providers, but not by anyone else that hasn’t paid. We used the FEVM hardhat kit to develop our smart contracts. The ZKP tech stack consists of circom, which is the domain-specific language for writing ZKP circuits, and snarkjs, which is the library to produce ZK proofs from circuits, used both locally and on the browser. 11 | 12 | Presentation deck linked [here](https://www.canva.com/design/DAFZaRE7dgA/OSL5YjvS_jyt1WvqzEB8GQ/view?utm_content=DAFZaRE7dgA&utm_campaign=designshare&utm_medium=link&utm_source=publishsharelink) for more information. -------------------------------------------------------------------------------- /hardhat/.npmignore: -------------------------------------------------------------------------------- 1 | hardhat.config.js 2 | scripts 3 | test 4 | -------------------------------------------------------------------------------- /hardhat/.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | artifacts 3 | cache 4 | coverage* 5 | gasReporterOutput.json 6 | package.json 7 | img 8 | .env 9 | .* 10 | README.md 11 | coverage.json 12 | deployments -------------------------------------------------------------------------------- /hardhat/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "useTabs": false, 4 | "semi": false, 5 | "singleQuote": false, 6 | "printWidth": 100 7 | } 8 | -------------------------------------------------------------------------------- /hardhat/.solcover.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | skipFiles: ['test/fuzzing/KeepersCounterEchidnaTest.sol', 'test/LinkToken.sol', 'test/MockOracle.sol', 'test/MockV3Aggregator.sol', 'test/VRFCoordinatorV2Mock.sol'], 3 | }; -------------------------------------------------------------------------------- /hardhat/.solhint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solhint:recommended", 3 | "rules": { 4 | "compiler-version": ["error", "^0.8.0"], 5 | "func-visibility": ["warn", { "ignoreConstructors": true }] 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /hardhat/.solhintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | contracts/test -------------------------------------------------------------------------------- /hardhat/README.md: -------------------------------------------------------------------------------- 1 | # Setup 2 | 3 | ``` 4 | yarn 5 | yarn setup 6 | yarn test:full 7 | ``` 8 | If you have already compiled the circuits before, you can run `yarn test` instead. 9 | 10 | # FEVM Hardhat Kit 11 | 12 | ## Cloning the Repo 13 | 14 | Open up your terminal (or command prompt) and navigate to a directory you would like to store this code on. Once there type in the following command: 15 | 16 | 17 | ``` 18 | git clone https://github.com/filecoin-project/fevm-hardhat-kit.git 19 | cd fevm-hardhat-kit 20 | yarn install 21 | ``` 22 | 23 | 24 | This will clone the hardhat kit onto your computer, switch directories into the newly installed kit, and install the dependencies the kit needs to work. 25 | 26 | 27 | ## Get a Private Key 28 | 29 | You can get a private key from a wallet provider [such as Metamask](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-export-an-account-s-private-key). 30 | 31 | 32 | ## Add your Private Key as an Environment Variable 33 | 34 | Add your private key as an environment variable by running this command: 35 | 36 | ``` 37 | export PRIVATE_KEY='abcdef' 38 | ``` 39 | 40 | \ 41 | If you use a .env file, don't commit and push any changes to .env files that may contain sensitive information, such as a private key! If this information reaches a public GitHub repository, someone can use it to check if you have any Mainnet funds in that wallet address, and steal them! 42 | 43 | 44 | ## Get the Deployer Address 45 | 46 | Run this command: 47 | ``` 48 | yarn hardhat get-address 49 | ``` 50 | 51 | The will show you the ethereum-style address associated with that private key and the filecoin-style f4 address. The Ethereum address can now be exclusively used for almost all FEVM tools, including the faucet. 52 | 53 | 54 | ## Fund the Deployer Address 55 | 56 | Go to the [Hyperspace testnet faucet](https://hyperspace.yoga/#faucet), and paste in the Ethereum address from the previous step. This will send some hyperspace testnet FIL to the account. 57 | 58 | 59 | ## Deploy the Contracts 60 | 61 | Currently there are 2 main types of contracts: 62 | 63 | * Basic Solidity Examples: Simple contracts to show off basic solidity 64 | 65 | * Filecoin API Examples: Contracts that demo how to use the Filecoin APIs in Solidity to access storage deals and other Filecoin specific functions. 66 | 67 | 68 | Type in the following command in the terminal to deploy all contracts: 69 | 70 | ``` 71 | yarn hardhat deploy 72 | ``` 73 | 74 | This will compile all the contracts in the contracts folder and deploy them to the Hyperspace test network automatically! 75 | 76 | Keep note of the deployed contract addresses for the next step. 77 | 78 | ## Interact with the Contracts 79 | 80 | You can interact with contracts via hardhat tasks, found in the 'tasks' folder. For example, to interact with the SimpleCoin contract: 81 | 82 | Type in the following command in the terminal: 83 | 84 | ``` 85 | yarn hardhat get-balance --contract 'THE DEPLOYED CONTRACT ADDRESS HERE' --account 'YOUR ETHEREUM ADDRESS HERE' 86 | ``` 87 | 88 | The console should read that your account has 12000 SimpleCoin! 89 | 90 | ## Filecoin APIs 91 | 92 | The primary advantage of the FEVM over other EVM based chains is the ability to access and program around Filecoin storage deals. This can be done in the FEVM via the [Filecoin.sol library maintained by Zondax](https://github.com/Zondax/filecoin-solidity). **Note this library is currently in BETA**. It is unaudited, and the APIs will likely be changing with time. This repo will be updated as soon as possible when a breaking change occurs. 93 | 94 | The library is included in this kit as an NPM package and will automatically be downloaded when you perform the `yarn` command (don't confuse these with the included mocks)! 95 | 96 | Currently you will find a getter contract that calls the getter methods on the MarketAPI to get storage deal data and store that data. To do this you will need *dealIDs* which you can [find here on FilFox](https://hyperspace.filfox.info/en/deal). 97 | 98 | As an example to store most of the data available for a deal run the store-all command with a specified dealID. Below is an example of using this command below with the a deal on Hyperspace testnet with a dealID of 707. 99 | 100 | ``` 101 | yarn hardhat store-all --contract "DEPLOYED FILECOIN_MARKET_CONSUMER CONTRACT ADDRESS HERE" --dealid "707" 102 | ``` 103 | -------------------------------------------------------------------------------- /hardhat/assets/mnist_image.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/z-kaggle/ZKaggle/97babe49b2f99594f77c99745b1c73e92283cd30/hardhat/assets/mnist_image.pgm -------------------------------------------------------------------------------- /hardhat/circuits/circuit2.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.0.0; 2 | 3 | include "stat.circom"; 4 | 5 | // TODO: full circuit to read csv file and output mean and variance 6 | 7 | component main = MeanAndVariance(4); -------------------------------------------------------------------------------- /hardhat/circuits/sha256/ch.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | 20 | /* Ch 21 | 22 | 000 0 23 | 001 1 24 | 010 0 25 | 011 1 26 | 100 0 27 | 101 0 28 | 110 1 29 | 111 1 30 | 31 | out = a&b ^ (!a)&c => 32 | 33 | out = a*(b-c) + c 34 | 35 | */ 36 | pragma circom 2.0.0; 37 | 38 | template Ch_t(n) { 39 | signal input a[n]; 40 | signal input b[n]; 41 | signal input c[n]; 42 | signal output out[n]; 43 | 44 | for (var k=0; k. 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | template H(x) { 22 | signal output out[32]; 23 | var c[8] = [0x6a09e667, 24 | 0xbb67ae85, 25 | 0x3c6ef372, 26 | 0xa54ff53a, 27 | 0x510e527f, 28 | 0x9b05688c, 29 | 0x1f83d9ab, 30 | 0x5be0cd19]; 31 | 32 | for (var i=0; i<32; i++) { 33 | out[i] <== (c[x] >> i) & 1; 34 | } 35 | } 36 | 37 | template K(x) { 38 | signal output out[32]; 39 | var c[64] = [ 40 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 41 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 42 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 43 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 44 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 45 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 46 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 47 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 48 | ]; 49 | 50 | for (var i=0; i<32; i++) { 51 | out[i] <== (c[x] >> i) & 1; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/main.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | include "sha256_2.circom"; 22 | 23 | template Main() { 24 | signal input a; 25 | signal input b; 26 | signal output out; 27 | 28 | component sha256_2 = Sha256_2(); 29 | 30 | sha256_2.a <== a; 31 | sha256_2.b <== a; 32 | out <== sha256_2.out; 33 | } 34 | 35 | component main = Main(); 36 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/maj.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | 20 | /* Maj function for sha256 21 | 22 | out = a&b ^ a&c ^ b&c => 23 | 24 | out = a*b + a*c + b*c - 2*a*b*c => 25 | 26 | out = a*( b + c - 2*b*c ) + b*c => 27 | 28 | mid = b*c 29 | out = a*( b + c - 2*mid ) + mid 30 | 31 | */ 32 | pragma circom 2.0.0; 33 | 34 | template Maj_t(n) { 35 | signal input a[n]; 36 | signal input b[n]; 37 | signal input c[n]; 38 | signal output out[n]; 39 | signal mid[n]; 40 | 41 | for (var k=0; k. 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | template RotR(n, r) { 22 | signal input in[n]; 23 | signal output out[n]; 24 | 25 | for (var i=0; i> k)&1; 31 | } 32 | 33 | component ha0 = H(0); 34 | component hb0 = H(1); 35 | component hc0 = H(2); 36 | component hd0 = H(3); 37 | component he0 = H(4); 38 | component hf0 = H(5); 39 | component hg0 = H(6); 40 | component hh0 = H(7); 41 | 42 | component sha256compression[nBlocks]; 43 | 44 | for (i=0; i. 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | include "constants.circom"; 22 | include "sha256compression.circom"; 23 | include "../../node_modules/circomlib-ml/circuits/circomlib/bitify.circom"; 24 | 25 | template Sha256_2() { 26 | signal input a; 27 | signal input b; 28 | signal output out; 29 | 30 | var i; 31 | var k; 32 | 33 | component bits2num = Bits2Num(216); 34 | component num2bits[2]; 35 | 36 | num2bits[0] = Num2Bits(216); 37 | num2bits[1] = Num2Bits(216); 38 | 39 | num2bits[0].in <== a; 40 | num2bits[1].in <== b; 41 | 42 | 43 | component sha256compression = Sha256compression() ; 44 | 45 | component ha0 = H(0); 46 | component hb0 = H(1); 47 | component hc0 = H(2); 48 | component hd0 = H(3); 49 | component he0 = H(4); 50 | component hf0 = H(5); 51 | component hg0 = H(6); 52 | component hh0 = H(7); 53 | 54 | for (k=0; k<32; k++ ) { 55 | sha256compression.hin[0*32+k] <== ha0.out[k]; 56 | sha256compression.hin[1*32+k] <== hb0.out[k]; 57 | sha256compression.hin[2*32+k] <== hc0.out[k]; 58 | sha256compression.hin[3*32+k] <== hd0.out[k]; 59 | sha256compression.hin[4*32+k] <== he0.out[k]; 60 | sha256compression.hin[5*32+k] <== hf0.out[k]; 61 | sha256compression.hin[6*32+k] <== hg0.out[k]; 62 | sha256compression.hin[7*32+k] <== hh0.out[k]; 63 | } 64 | 65 | for (i=0; i<216; i++) { 66 | sha256compression.inp[i] <== num2bits[0].out[215-i]; 67 | sha256compression.inp[i+216] <== num2bits[1].out[215-i]; 68 | } 69 | 70 | sha256compression.inp[432] <== 1; 71 | 72 | for (i=433; i<503; i++) { 73 | sha256compression.inp[i] <== 0; 74 | } 75 | 76 | sha256compression.inp[503] <== 1; 77 | sha256compression.inp[504] <== 1; 78 | sha256compression.inp[505] <== 0; 79 | sha256compression.inp[506] <== 1; 80 | sha256compression.inp[507] <== 1; 81 | sha256compression.inp[508] <== 0; 82 | sha256compression.inp[509] <== 0; 83 | sha256compression.inp[510] <== 0; 84 | sha256compression.inp[511] <== 0; 85 | 86 | for (i=0; i<216; i++) { 87 | bits2num.in[i] <== sha256compression.out[255-i]; 88 | } 89 | 90 | out <== bits2num.out; 91 | } 92 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/sha256compression.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | include "constants.circom"; 22 | include "t1.circom"; 23 | include "t2.circom"; 24 | include "../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom"; 25 | include "sigmaplus.circom"; 26 | include "sha256compression_function.circom"; 27 | 28 | 29 | template Sha256compression() { 30 | signal input hin[256]; 31 | signal input inp[512]; 32 | signal output out[256]; 33 | signal a[65][32]; 34 | signal b[65][32]; 35 | signal c[65][32]; 36 | signal d[65][32]; 37 | signal e[65][32]; 38 | signal f[65][32]; 39 | signal g[65][32]; 40 | signal h[65][32]; 41 | signal w[64][32]; 42 | 43 | 44 | var outCalc[256] = sha256compression(hin, inp); 45 | 46 | var i; 47 | for (i=0; i<256; i++) out[i] <-- outCalc[i]; 48 | 49 | component sigmaPlus[48]; 50 | for (i=0; i<48; i++) sigmaPlus[i] = SigmaPlus(); 51 | 52 | component ct_k[64]; 53 | for (i=0; i<64; i++) ct_k[i] = K(i); 54 | 55 | component t1[64]; 56 | for (i=0; i<64; i++) t1[i] = T1(); 57 | 58 | component t2[64]; 59 | for (i=0; i<64; i++) t2[i] = T2(); 60 | 61 | component suma[64]; 62 | for (i=0; i<64; i++) suma[i] = BinSum(32, 2); 63 | 64 | component sume[64]; 65 | for (i=0; i<64; i++) sume[i] = BinSum(32, 2); 66 | 67 | component fsum[8]; 68 | for (i=0; i<8; i++) fsum[i] = BinSum(32, 2); 69 | 70 | var k; 71 | var t; 72 | 73 | for (t=0; t<64; t++) { 74 | if (t<16) { 75 | for (k=0; k<32; k++) { 76 | w[t][k] <== inp[t*32+31-k]; 77 | } 78 | } else { 79 | for (k=0; k<32; k++) { 80 | sigmaPlus[t-16].in2[k] <== w[t-2][k]; 81 | sigmaPlus[t-16].in7[k] <== w[t-7][k]; 82 | sigmaPlus[t-16].in15[k] <== w[t-15][k]; 83 | sigmaPlus[t-16].in16[k] <== w[t-16][k]; 84 | } 85 | 86 | for (k=0; k<32; k++) { 87 | w[t][k] <== sigmaPlus[t-16].out[k]; 88 | } 89 | } 90 | } 91 | 92 | for (k=0; k<32; k++ ) { 93 | a[0][k] <== hin[k]; 94 | b[0][k] <== hin[32*1 + k]; 95 | c[0][k] <== hin[32*2 + k]; 96 | d[0][k] <== hin[32*3 + k]; 97 | e[0][k] <== hin[32*4 + k]; 98 | f[0][k] <== hin[32*5 + k]; 99 | g[0][k] <== hin[32*6 + k]; 100 | h[0][k] <== hin[32*7 + k]; 101 | } 102 | 103 | for (t = 0; t<64; t++) { 104 | for (k=0; k<32; k++) { 105 | t1[t].h[k] <== h[t][k]; 106 | t1[t].e[k] <== e[t][k]; 107 | t1[t].f[k] <== f[t][k]; 108 | t1[t].g[k] <== g[t][k]; 109 | t1[t].k[k] <== ct_k[t].out[k]; 110 | t1[t].w[k] <== w[t][k]; 111 | 112 | t2[t].a[k] <== a[t][k]; 113 | t2[t].b[k] <== b[t][k]; 114 | t2[t].c[k] <== c[t][k]; 115 | } 116 | 117 | for (k=0; k<32; k++) { 118 | sume[t].in[0][k] <== d[t][k]; 119 | sume[t].in[1][k] <== t1[t].out[k]; 120 | 121 | suma[t].in[0][k] <== t1[t].out[k]; 122 | suma[t].in[1][k] <== t2[t].out[k]; 123 | } 124 | 125 | for (k=0; k<32; k++) { 126 | h[t+1][k] <== g[t][k]; 127 | g[t+1][k] <== f[t][k]; 128 | f[t+1][k] <== e[t][k]; 129 | e[t+1][k] <== sume[t].out[k]; 130 | d[t+1][k] <== c[t][k]; 131 | c[t+1][k] <== b[t][k]; 132 | b[t+1][k] <== a[t][k]; 133 | a[t+1][k] <== suma[t].out[k]; 134 | } 135 | } 136 | 137 | for (k=0; k<32; k++) { 138 | fsum[0].in[0][k] <== hin[32*0+k]; 139 | fsum[0].in[1][k] <== a[64][k]; 140 | fsum[1].in[0][k] <== hin[32*1+k]; 141 | fsum[1].in[1][k] <== b[64][k]; 142 | fsum[2].in[0][k] <== hin[32*2+k]; 143 | fsum[2].in[1][k] <== c[64][k]; 144 | fsum[3].in[0][k] <== hin[32*3+k]; 145 | fsum[3].in[1][k] <== d[64][k]; 146 | fsum[4].in[0][k] <== hin[32*4+k]; 147 | fsum[4].in[1][k] <== e[64][k]; 148 | fsum[5].in[0][k] <== hin[32*5+k]; 149 | fsum[5].in[1][k] <== f[64][k]; 150 | fsum[6].in[0][k] <== hin[32*6+k]; 151 | fsum[6].in[1][k] <== g[64][k]; 152 | fsum[7].in[0][k] <== hin[32*7+k]; 153 | fsum[7].in[1][k] <== h[64][k]; 154 | } 155 | 156 | for (k=0; k<32; k++) { 157 | out[31-k] === fsum[0].out[k]; 158 | out[32+31-k] === fsum[1].out[k]; 159 | out[64+31-k] === fsum[2].out[k]; 160 | out[96+31-k] === fsum[3].out[k]; 161 | out[128+31-k] === fsum[4].out[k]; 162 | out[160+31-k] === fsum[5].out[k]; 163 | out[192+31-k] === fsum[6].out[k]; 164 | out[224+31-k] === fsum[7].out[k]; 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/sha256compression_function.circom: -------------------------------------------------------------------------------- 1 | // signal input hin[256]; 2 | // signal input inp[512]; 3 | // signal output out[256]; 4 | pragma circom 2.0.0; 5 | 6 | function rrot(x, n) { 7 | return ((x >> n) | (x << (32-n))) & 0xFFFFFFFF; 8 | } 9 | 10 | function bsigma0(x) { 11 | return rrot(x,2) ^ rrot(x,13) ^ rrot(x,22); 12 | } 13 | 14 | function bsigma1(x) { 15 | return rrot(x,6) ^ rrot(x,11) ^ rrot(x,25); 16 | } 17 | 18 | function ssigma0(x) { 19 | return rrot(x,7) ^ rrot(x,18) ^ (x >> 3); 20 | } 21 | 22 | function ssigma1(x) { 23 | return rrot(x,17) ^ rrot(x,19) ^ (x >> 10); 24 | } 25 | 26 | function Maj(x, y, z) { 27 | return (x&y) ^ (x&z) ^ (y&z); 28 | } 29 | 30 | function Ch(x, y, z) { 31 | return (x & y) ^ ((0xFFFFFFFF ^x) & z); 32 | } 33 | 34 | function sha256K(i) { 35 | var k[64] = [ 36 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 37 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 38 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 39 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 40 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 41 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 42 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 43 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 44 | ]; 45 | return k[i]; 46 | } 47 | 48 | function sha256compression(hin, inp) { 49 | var H[8]; 50 | var a; 51 | var b; 52 | var c; 53 | var d; 54 | var e; 55 | var f; 56 | var g; 57 | var h; 58 | var out[256]; 59 | for (var i=0; i<8; i++) { 60 | H[i] = 0; 61 | for (var j=0; j<32; j++) { 62 | H[i] += hin[i*32+j] << j; 63 | } 64 | } 65 | a=H[0]; 66 | b=H[1]; 67 | c=H[2]; 68 | d=H[3]; 69 | e=H[4]; 70 | f=H[5]; 71 | g=H[6]; 72 | h=H[7]; 73 | var w[64]; 74 | var T1; 75 | var T2; 76 | for (var i=0; i<64; i++) { 77 | if (i<16) { 78 | w[i]=0; 79 | for (var j=0; j<32; j++) { 80 | w[i] += inp[i*32+31-j]<> j) & 1; 109 | } 110 | } 111 | return out; 112 | } 113 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/shift.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | template ShR(n, r) { 22 | signal input in[n]; 23 | signal output out[n]; 24 | 25 | for (var i=0; i= n) { 27 | out[i] <== 0; 28 | } else { 29 | out[i] <== in[ i+r ]; 30 | } 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/sigma.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | include "xor3.circom"; 22 | include "rotate.circom"; 23 | include "shift.circom"; 24 | 25 | template SmallSigma(ra, rb, rc) { 26 | signal input in[32]; 27 | signal output out[32]; 28 | var k; 29 | 30 | component rota = RotR(32, ra); 31 | component rotb = RotR(32, rb); 32 | component shrc = ShR(32, rc); 33 | 34 | for (k=0; k<32; k++) { 35 | rota.in[k] <== in[k]; 36 | rotb.in[k] <== in[k]; 37 | shrc.in[k] <== in[k]; 38 | } 39 | 40 | component xor3 = Xor3(32); 41 | for (k=0; k<32; k++) { 42 | xor3.a[k] <== rota.out[k]; 43 | xor3.b[k] <== rotb.out[k]; 44 | xor3.c[k] <== shrc.out[k]; 45 | } 46 | 47 | for (k=0; k<32; k++) { 48 | out[k] <== xor3.out[k]; 49 | } 50 | } 51 | 52 | template BigSigma(ra, rb, rc) { 53 | signal input in[32]; 54 | signal output out[32]; 55 | var k; 56 | 57 | component rota = RotR(32, ra); 58 | component rotb = RotR(32, rb); 59 | component rotc = RotR(32, rc); 60 | for (k=0; k<32; k++) { 61 | rota.in[k] <== in[k]; 62 | rotb.in[k] <== in[k]; 63 | rotc.in[k] <== in[k]; 64 | } 65 | 66 | component xor3 = Xor3(32); 67 | 68 | for (k=0; k<32; k++) { 69 | xor3.a[k] <== rota.out[k]; 70 | xor3.b[k] <== rotb.out[k]; 71 | xor3.c[k] <== rotc.out[k]; 72 | } 73 | 74 | for (k=0; k<32; k++) { 75 | out[k] <== xor3.out[k]; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/sigmaplus.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | include "../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom"; 22 | include "sigma.circom"; 23 | 24 | template SigmaPlus() { 25 | signal input in2[32]; 26 | signal input in7[32]; 27 | signal input in15[32]; 28 | signal input in16[32]; 29 | signal output out[32]; 30 | var k; 31 | 32 | component sigma1 = SmallSigma(17,19,10); 33 | component sigma0 = SmallSigma(7, 18, 3); 34 | for (k=0; k<32; k++) { 35 | sigma1.in[k] <== in2[k]; 36 | sigma0.in[k] <== in15[k]; 37 | } 38 | 39 | component sum = BinSum(32, 4); 40 | for (k=0; k<32; k++) { 41 | sum.in[0][k] <== sigma1.out[k]; 42 | sum.in[1][k] <== in7[k]; 43 | sum.in[2][k] <== sigma0.out[k]; 44 | sum.in[3][k] <== in16[k]; 45 | } 46 | 47 | for (k=0; k<32; k++) { 48 | out[k] <== sum.out[k]; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/t1.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | include "../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom"; 22 | include "sigma.circom"; 23 | include "ch.circom"; 24 | 25 | template T1() { 26 | signal input h[32]; 27 | signal input e[32]; 28 | signal input f[32]; 29 | signal input g[32]; 30 | signal input k[32]; 31 | signal input w[32]; 32 | signal output out[32]; 33 | 34 | var ki; 35 | 36 | component ch = Ch_t(32); 37 | component bigsigma1 = BigSigma(6, 11, 25); 38 | 39 | for (ki=0; ki<32; ki++) { 40 | bigsigma1.in[ki] <== e[ki]; 41 | ch.a[ki] <== e[ki]; 42 | ch.b[ki] <== f[ki]; 43 | ch.c[ki] <== g[ki]; 44 | } 45 | 46 | component sum = BinSum(32, 5); 47 | for (ki=0; ki<32; ki++) { 48 | sum.in[0][ki] <== h[ki]; 49 | sum.in[1][ki] <== bigsigma1.out[ki]; 50 | sum.in[2][ki] <== ch.out[ki]; 51 | sum.in[3][ki] <== k[ki]; 52 | sum.in[4][ki] <== w[ki]; 53 | } 54 | 55 | for (ki=0; ki<32; ki++) { 56 | out[ki] <== sum.out[ki]; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/t2.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | pragma circom 2.0.0; 20 | 21 | include "../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom"; 22 | include "sigma.circom"; 23 | include "maj.circom"; 24 | 25 | template T2() { 26 | signal input a[32]; 27 | signal input b[32]; 28 | signal input c[32]; 29 | signal output out[32]; 30 | var k; 31 | 32 | component bigsigma0 = BigSigma(2, 13, 22); 33 | component maj = Maj_t(32); 34 | for (k=0; k<32; k++) { 35 | bigsigma0.in[k] <== a[k]; 36 | maj.a[k] <== a[k]; 37 | maj.b[k] <== b[k]; 38 | maj.c[k] <== c[k]; 39 | } 40 | 41 | component sum = BinSum(32, 2); 42 | 43 | for (k=0; k<32; k++) { 44 | sum.in[0][k] <== bigsigma0.out[k]; 45 | sum.in[1][k] <== maj.out[k]; 46 | } 47 | 48 | for (k=0; k<32; k++) { 49 | out[k] <== sum.out[k]; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /hardhat/circuits/sha256/xor3.circom: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 0KIMS association. 3 | 4 | This file is part of circom (Zero Knowledge Circuit Compiler). 5 | 6 | circom is a free software: you can redistribute it and/or modify it 7 | under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | circom is distributed in the hope that it will be useful, but WITHOUT 12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 14 | License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with circom. If not, see . 18 | */ 19 | 20 | /* Xor3 function for sha256 21 | 22 | out = a ^ b ^ c => 23 | 24 | out = a+b+c - 2*a*b - 2*a*c - 2*b*c + 4*a*b*c => 25 | 26 | out = a*( 1 - 2*b - 2*c + 4*b*c ) + b + c - 2*b*c => 27 | 28 | mid = b*c 29 | out = a*( 1 - 2*b -2*c + 4*mid ) + b + c - 2 * mid 30 | 31 | */ 32 | pragma circom 2.0.0; 33 | 34 | template Xor3(n) { 35 | signal input a[n]; 36 | signal input b[n]; 37 | signal input c[n]; 38 | signal output out[n]; 39 | signal mid[n]; 40 | 41 | for (var k=0; k 0, "BountyFactory: must send more than 0 wei to create bounty"); 25 | address clone = Clones.clone(bountyTemplate); 26 | Bounty(clone).initialize{value: msg.value}(msg.sender, _name, _description, _dataCID); 27 | bounties.push(clone); 28 | emit BountyCreated(clone); 29 | bountyCount++; 30 | return clone; 31 | } 32 | } -------------------------------------------------------------------------------- /hardhat/contracts/IVerifier.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0 2 | 3 | pragma solidity ^0.8.17; 4 | 5 | interface IVerifier { 6 | function verifyProof( 7 | uint[2] memory a, 8 | uint[2][2] memory b, 9 | uint[2] memory c, 10 | uint[] memory input 11 | ) external view returns (bool); 12 | } -------------------------------------------------------------------------------- /hardhat/contracts/basic-solidity-examples/SimpleCoin.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity 0.8.17; 3 | 4 | 5 | error SimpleCoin__NotEnoughBalance(); 6 | 7 | contract SimpleCoin { 8 | mapping (address => uint) balances; 9 | uint256 private i_tokensToBeMinted; 10 | 11 | 12 | constructor(uint256 tokensToBeMinted) { 13 | balances[tx.origin] = tokensToBeMinted; 14 | i_tokensToBeMinted= tokensToBeMinted; 15 | } 16 | 17 | function sendCoin(address receiver, uint amount) public returns(bool sufficient) { 18 | if (balances[msg.sender] < amount) { 19 | // return false; 20 | revert SimpleCoin__NotEnoughBalance(); 21 | } 22 | 23 | balances[msg.sender] -= amount; 24 | balances[receiver] += amount; 25 | return true; 26 | } 27 | 28 | function getBalanceInEth(address addr) public view returns(uint){ 29 | return getBalance(addr) * 2; 30 | } 31 | 32 | function getBalance(address addr) public view returns(uint) { 33 | return balances[addr]; 34 | } 35 | 36 | function getMintedTokenBalance() public view returns(uint256){ 37 | return i_tokensToBeMinted; 38 | } 39 | 40 | 41 | } -------------------------------------------------------------------------------- /hardhat/contracts/cid.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0 2 | 3 | pragma solidity ^0.8.17; 4 | 5 | import "./IVerifier.sol"; 6 | 7 | contract CID { 8 | 9 | IVerifier public verifier; 10 | 11 | uint8 public constant CID_VERSION = 1; 12 | uint8 public constant CID_CODEC = 0x55; // for raw buffer 13 | uint8 public constant CID_HASH = 0x12; // for sha256 14 | uint8 public constant CID_LENGTH = 32; // for sha256 15 | 16 | constructor(address _verifier) { 17 | verifier = IVerifier(_verifier); 18 | } 19 | 20 | function computeCID( 21 | uint[2] memory a, 22 | uint[2][2] memory b, 23 | uint[2] memory c, 24 | uint[] memory input 25 | ) public view returns (bytes memory) { 26 | require(verifier.verifyProof(a, b, c, input), "Invalid proof"); 27 | 28 | uint digest = (input[2] << 128) + input[3]; 29 | return abi.encodePacked(CID_VERSION, CID_CODEC, CID_HASH, CID_LENGTH, digest); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /hardhat/contracts/filecoin-api-examples/DealRewarder.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity ^0.8.13; 3 | 4 | import { MarketAPI } from "../lib/filecoin-solidity/contracts/v0.8/MarketAPI.sol"; 5 | import { CommonTypes } from "../lib/filecoin-solidity/contracts/v0.8/types/CommonTypes.sol"; 6 | import { MarketTypes } from "../lib/filecoin-solidity/contracts/v0.8/types/MarketTypes.sol"; 7 | import { Actor, HyperActor } from "../lib/filecoin-solidity/contracts/v0.8/utils/Actor.sol"; 8 | import { Misc } from "../lib/filecoin-solidity/contracts/v0.8/utils/Misc.sol"; 9 | 10 | /* 11 | Contract Usage 12 | Step | Who | What is happening | Why 13 | ------------------------------------------------ 14 | Deploy | contract owner | contract owner deploys address is owner who can call addCID | create contract setting up rules to follow 15 | AddCID | data pinners | set up cids that the contract will incentivize in deals | add request for a deal in the filecoin network, "store data" function 16 | Fund | contract funders | add FIL to the contract to later by paid out by deal | ensure the deal actually gets stored by providing funds for bounty hunter and (indirect) storage provider 17 | Claim | bounty hunter | claim the incentive to complete the cycle | pay back the bounty hunter for doing work for the contract 18 | 19 | */ 20 | contract DealRewarder { 21 | mapping(bytes => bool) public cidSet; 22 | mapping(bytes => uint) public cidSizes; 23 | mapping(bytes => mapping(uint64 => bool)) public cidProviders; 24 | 25 | address public owner; 26 | address constant CALL_ACTOR_ID = 0xfe00000000000000000000000000000000000005; 27 | uint64 constant DEFAULT_FLAG = 0x00000000; 28 | uint64 constant METHOD_SEND = 0; 29 | 30 | 31 | constructor() { 32 | owner = msg.sender; 33 | } 34 | 35 | function fund(uint64 unused) public payable {} 36 | 37 | function addCID(bytes calldata cidraw, uint size) public { 38 | require(msg.sender == owner); 39 | cidSet[cidraw] = true; 40 | cidSizes[cidraw] = size; 41 | } 42 | 43 | function policyOK(bytes memory cidraw, uint64 provider) internal view returns (bool) { 44 | bool alreadyStoring = cidProviders[cidraw][provider]; 45 | return !alreadyStoring; 46 | } 47 | 48 | function authorizeData(bytes memory cidraw, uint64 provider, uint size) public { 49 | require(cidSet[cidraw], "cid must be added before authorizing"); 50 | require(cidSizes[cidraw] == size, "data size must match expected"); 51 | require(policyOK(cidraw, provider), "deal failed policy check: has provider already claimed this cid?"); 52 | 53 | cidProviders[cidraw][provider] = true; 54 | } 55 | 56 | function claim_bounty(uint64 deal_id) public { 57 | MarketTypes.GetDealDataCommitmentReturn memory commitmentRet = MarketAPI.getDealDataCommitment(MarketTypes.GetDealDataCommitmentParams({id: deal_id})); 58 | MarketTypes.GetDealProviderReturn memory providerRet = MarketAPI.getDealProvider(MarketTypes.GetDealProviderParams({id: deal_id})); 59 | 60 | authorizeData(commitmentRet.data, providerRet.provider, commitmentRet.size); 61 | 62 | // get dealer (bounty hunter client) 63 | MarketTypes.GetDealClientReturn memory clientRet = MarketAPI.getDealClient(MarketTypes.GetDealClientParams({id: deal_id})); 64 | 65 | // send reward to client 66 | send(clientRet.client); 67 | } 68 | 69 | function call_actor_id(uint64 method, uint256 value, uint64 flags, uint64 codec, bytes memory params, uint64 id) public returns (bool, int256, uint64, bytes memory) { 70 | (bool success, bytes memory data) = address(CALL_ACTOR_ID).delegatecall(abi.encode(method, value, flags, codec, params, id)); 71 | (int256 exit, uint64 return_codec, bytes memory return_value) = abi.decode(data, (int256, uint64, bytes)); 72 | return (success, exit, return_codec, return_value); 73 | } 74 | 75 | // send 1 FIL to the filecoin actor at actor_id 76 | function send(uint64 actorID) internal { 77 | bytes memory emptyParams = ""; 78 | delete emptyParams; 79 | 80 | uint oneFIL = 1000000000000000000; 81 | HyperActor.call_actor_id(METHOD_SEND, oneFIL, DEFAULT_FLAG, Misc.NONE_CODEC, emptyParams, actorID); 82 | 83 | } 84 | 85 | } 86 | 87 | -------------------------------------------------------------------------------- /hardhat/contracts/filecoin-api-examples/FilecoinMarketConsumer.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.8.0; 2 | 3 | import {MarketAPI} from "@zondax/filecoin-solidity/contracts/v0.8/MarketAPI.sol"; 4 | import {MarketTypes} from "@zondax/filecoin-solidity/contracts/v0.8/types/MarketTypes.sol"; 5 | 6 | contract FilecoinMarketConsumer { 7 | string public dealLabel; 8 | uint64 public dealClientActorId; 9 | uint64 public dealProviderActorId; 10 | bool public isDealActivated; 11 | MarketTypes.GetDealDataCommitmentReturn public dealCommitment; 12 | MarketTypes.GetDealTermReturn public dealTerm; 13 | MarketTypes.GetDealEpochPriceReturn public dealPricePerEpoch; 14 | MarketTypes.GetDealClientCollateralReturn public clientCollateral; 15 | MarketTypes.GetDealProviderCollateralReturn public providerCollateral; 16 | MarketTypes.GetDealActivationReturn public activationStatus; 17 | 18 | function storeAll(uint64 dealId) public { 19 | storeDealLabel(dealId); 20 | storeDealClient(dealId); 21 | storeDealClientProvider(dealId); 22 | storeDealCommitment(dealId); 23 | storeDealTerm(dealId); 24 | storeDealTotalPrice(dealId); 25 | storeClientCollateral(dealId); 26 | storeProviderCollateral(dealId); 27 | storeDealVerificaton(dealId); 28 | storeDealActivationStatus(dealId); 29 | } 30 | 31 | function storeDealLabel(uint64 dealId) public { 32 | dealLabel = MarketAPI.getDealLabel(dealId).label; 33 | } 34 | 35 | function storeDealClient(uint64 dealId) public { 36 | dealClientActorId = MarketAPI.getDealClient(dealId).client; 37 | } 38 | 39 | function storeDealClientProvider(uint64 dealId) public { 40 | dealProviderActorId = MarketAPI.getDealProvider(dealId).provider; 41 | } 42 | 43 | function storeDealCommitment(uint64 dealId) public { 44 | dealCommitment = MarketAPI.getDealDataCommitment(dealId); 45 | } 46 | 47 | function storeDealTerm(uint64 dealId) public { 48 | dealTerm = MarketAPI.getDealTerm(dealId); 49 | } 50 | 51 | function storeDealTotalPrice(uint64 dealId) public { 52 | dealPricePerEpoch = MarketAPI.getDealTotalPrice(dealId); 53 | } 54 | 55 | function storeClientCollateral(uint64 dealId) public { 56 | clientCollateral = MarketAPI.getDealClientCollateral(dealId); 57 | } 58 | 59 | function storeProviderCollateral(uint64 dealId) public { 60 | providerCollateral = MarketAPI.getDealProviderCollateral(dealId); 61 | } 62 | 63 | function storeDealVerificaton(uint64 dealId) public { 64 | isDealActivated = MarketAPI.getDealVerified(dealId).verified; 65 | } 66 | 67 | function storeDealActivationStatus(uint64 dealId) public { 68 | activationStatus = MarketAPI.getDealActivation(dealId); 69 | } 70 | } -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | node_modules/ 3 | 4 | node_modules 5 | 6 | #Hardhat files 7 | cache 8 | artifacts 9 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/.soliumignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/.soliumrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solium:all", 3 | "rules": { 4 | "indentation": ["error", 4], 5 | "quotes": ["error", "double"], 6 | "arg-overflow": "off", 7 | "blank-lines": "off" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | 3 | dist: trusty 4 | 5 | language: node_js 6 | 7 | node_js: 10 8 | env: 9 | - TASK=test 10 | - TASK=lint 11 | matrix: 12 | fast_finish: true 13 | allow_failures: 14 | - env: TASK=lint 15 | script: 16 | - npm run $TASK 17 | 18 | notifications: 19 | email: false 20 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/LICENSE: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2018, Ethereum Name Service 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/README.md: -------------------------------------------------------------------------------- 1 | # Buffer 2 | 3 | [![Build Status](https://travis-ci.com/ensdomains/buffer.svg?branch=master)](https://travis-ci.com/ensdomains/buffer) [![License](https://img.shields.io/badge/License-BSD--2--Clause-blue.svg)](LICENSE) 4 | 5 | A library for working with mutable byte buffers in Solidity. 6 | 7 | Byte buffers are mutable and expandable, and provide a variety of primitives for writing to them. At any time you can fetch a bytes object containing the current contents of the buffer. The bytes object should not be stored between operations, as it may change due to resizing of the buffer. 8 | 9 | ## Getting Started 10 | 11 | These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. 12 | 13 | ### Installing 14 | 15 | Buffer uses npm to manage dependencies, therefore the installation process is kept simple: 16 | 17 | ``` 18 | npm install 19 | ``` 20 | 21 | ### Running tests 22 | 23 | Buffer uses truffle for its ethereum development environment. All tests can be run using truffle: 24 | 25 | ``` 26 | truffle test 27 | ``` 28 | 29 | To run linting, use solium: 30 | 31 | ``` 32 | solium --dir ./contracts 33 | ``` 34 | 35 | ## Including Buffer in your project 36 | 37 | ### Installation 38 | 39 | ``` 40 | npm install buffer --save 41 | ``` 42 | 43 | ## Built With 44 | * [Truffle](https://github.com/trufflesuite/truffle) - Ethereum development environment 45 | 46 | 47 | ## Authors 48 | 49 | * **Nick Johnson** - [Arachnid](https://github.com/Arachnid) 50 | 51 | See also the list of [contributors](https://github.com/ensdomains/buffer/contributors) who participated in this project. 52 | 53 | ## License 54 | 55 | This project is licensed under the BSD 2-clause "Simplified" License - see the [LICENSE](LICENSE) file for details 56 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/hardhat.config.js: -------------------------------------------------------------------------------- 1 | require("@nomiclabs/hardhat-truffle5"); 2 | require("@nomiclabs/hardhat-waffle"); 3 | 4 | 5 | module.exports = { 6 | networks: { 7 | hardhat: {} 8 | }, 9 | mocha: { 10 | }, 11 | solidity: { 12 | version: "0.8.4" 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | var Migrations = artifacts.require("./Migrations.sol"); 2 | 3 | module.exports = function(deployer) { 4 | deployer.deploy(Migrations); 5 | }; 6 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/migrations/2_deploy_contracts.js: -------------------------------------------------------------------------------- 1 | module.exports = async (deployer) => { }; 2 | 3 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ensdomains/buffer", 3 | "version": "0.1.0", 4 | "requires": true, 5 | "lockfileVersion": 1, 6 | "devDependencies": { 7 | "@nomiclabs/hardhat-ethers": "^2.0.2", 8 | "@nomiclabs/hardhat-waffle": "^2.0.1", 9 | "@nomiclabs/hardhat-web3": "^2.0.0", 10 | "chai": "^4.3.6", 11 | "eth-gas-reporter": "^0.2.24", 12 | "ethereum-waffle": "^3.3.0", 13 | "ethers": "^5.1.4", 14 | "hardhat": "^2.3.0", 15 | "solium": "^1.0.4", 16 | "truffle": "^5.0.0", 17 | "truffle-assertions": "^0.9.2", 18 | "web3": "^1.3.6" 19 | }, 20 | "scripts": { 21 | "test": "npx hardhat test", 22 | "lint": "npx hardhat check", 23 | "build": "npx hardhat compile", 24 | "prepublishOnly": "yarn build", 25 | "pub": "yarn publish --access public" 26 | }, 27 | "dependencies": { 28 | "@nomiclabs/hardhat-truffle5": "^2.0.0" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/test/TestBuffer.js: -------------------------------------------------------------------------------- 1 | const TestBuffer = artifacts.require("TestBuffer"); 2 | const truffleAssert = require('truffle-assertions'); 3 | 4 | contract('Buffer', function(accounts) { 5 | let instance; 6 | 7 | before(async () => { 8 | instance = await TestBuffer.new(); 9 | }); 10 | 11 | for(const a of TestBuffer.abi) { 12 | if(a.name.startsWith('test')) { 13 | it(a.name, async () => { 14 | await instance[a.name](); 15 | }); 16 | } 17 | } 18 | 19 | it("should revert when calling checkBufferInitOverflow", async () => { 20 | await truffleAssert.reverts( 21 | instance["checkBufferInitOverflow"](), 22 | "Transaction reverted and Hardhat couldn't infer the reason. Please report this to help us improve Hardhat." 23 | ); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/test/TestBuffer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: BSD-2-Clause 2 | pragma solidity >=0.8.4; 3 | 4 | import "./../contracts/Buffer.sol"; 5 | 6 | contract TestBuffer { 7 | using Buffer for Buffer.buffer; 8 | 9 | function checkBufferInitOverflow() public pure { 10 | Buffer.buffer memory buf; 11 | buf.init(256); 12 | buf.init(2**256-1); 13 | } 14 | 15 | function testBufferAppend() public pure { 16 | Buffer.buffer memory buf; 17 | buf.init(256); 18 | buf.append("Hello"); 19 | buf.append(", "); 20 | buf.append("world!"); 21 | require( 22 | keccak256(abi.encodePacked(string(buf.buf))) == keccak256(abi.encodePacked("Hello, world!")), 23 | "Unexpected buffer contents." 24 | ); 25 | } 26 | 27 | function testBufferAppendUint8() public pure { 28 | Buffer.buffer memory buf; 29 | Buffer.init(buf, 256); 30 | buf.append("Hello,"); 31 | buf.appendUint8(0x20); 32 | buf.append("world!"); 33 | require( 34 | keccak256(abi.encodePacked(string(buf.buf))) == keccak256(abi.encodePacked("Hello, world!")), 35 | "Unexpected buffer contents." 36 | ); 37 | } 38 | 39 | function testBufferResizeAppendUint8() public pure { 40 | Buffer.buffer memory buf; 41 | Buffer.init(buf, 32); 42 | buf.append("01234567890123456789012345678901"); 43 | buf.appendUint8(0x20); 44 | require(buf.capacity == 96, "Expected buffer capacity to be 96"); 45 | require(buf.buf.length == 33, "Expected buffer length to be 33"); 46 | require( 47 | keccak256(abi.encodePacked(string(buf.buf))) == keccak256(abi.encodePacked("01234567890123456789012345678901 ")), 48 | "Unexpected buffer contents." 49 | ); 50 | } 51 | 52 | function testBufferResizeAppendBytes() public pure { 53 | Buffer.buffer memory buf; 54 | Buffer.init(buf, 32); 55 | buf.append("01234567890123456789012345678901"); 56 | buf.append("23"); 57 | require(buf.capacity == 96, "Expected buffer capacity to be 96"); 58 | require(buf.buf.length == 34, "Expected buffer length to be 33"); 59 | require( 60 | keccak256(abi.encodePacked(string(buf.buf))) == keccak256(abi.encodePacked("0123456789012345678901234567890123")), 61 | "Unexpected buffer contents." 62 | ); 63 | } 64 | 65 | function testBufferResizeAppendManyBytes() public pure { 66 | Buffer.buffer memory buf; 67 | Buffer.init(buf, 32); 68 | buf.append("01234567890123456789012345678901"); 69 | buf.append("0123456789012345678901234567890101234567890123456789012345678901"); 70 | require(buf.capacity == 192, "Expected buffer capacity to be 192"); 71 | require(buf.buf.length == 96, "Expected buffer length to be 96"); 72 | require( 73 | keccak256(abi.encodePacked(string(buf.buf))) == keccak256(abi.encodePacked("012345678901234567890123456789010123456789012345678901234567890101234567890123456789012345678901")), 74 | "Unexpected buffer contents." 75 | ); 76 | } 77 | 78 | function testBufferZeroSized() public pure { 79 | Buffer.buffer memory buf; 80 | Buffer.init(buf, 0); 81 | buf.append("first"); 82 | require(buf.capacity == 32, "Expected buffer capacity to be 32"); 83 | require(buf.buf.length == 5, "Expected buffer length to be 5"); 84 | require( 85 | keccak256(abi.encodePacked(string(buf.buf))) == keccak256(abi.encodePacked("first")), 86 | "Unexpected buffer contents." 87 | ); 88 | } 89 | 90 | function testBufferAppendInt() public pure { 91 | Buffer.buffer memory buf; 92 | Buffer.init(buf, 256); 93 | buf.append("Hello"); 94 | buf.appendInt(0x2c20, 2); 95 | buf.append("world!"); 96 | require( 97 | keccak256(abi.encodePacked(string(buf.buf))) == keccak256(abi.encodePacked("Hello, world!")), 98 | "Unexpected buffer contents." 99 | ); 100 | } 101 | 102 | function testBufferResizeAppendInt() public pure { 103 | Buffer.buffer memory buf; 104 | Buffer.init(buf, 32); 105 | buf.append("01234567890123456789012345678901"); 106 | buf.appendInt(0x2020, 2); 107 | require(buf.capacity == 96, "Expected buffer capacity to be 96"); 108 | require(buf.buf.length == 34, "Expected buffer length to be 34"); 109 | require( 110 | keccak256(abi.encodePacked(string(buf.buf))) == keccak256(abi.encodePacked("01234567890123456789012345678901 ")), 111 | "Unexpected buffer contents." 112 | ); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/buffer/truffle.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | networks: { 3 | local: { 4 | host: "localhost", 5 | port: 9545, 6 | network_id: "*", 7 | gas: 4000000, 8 | }, 9 | ropsten: { 10 | host: "localhost", 11 | port: 8545, 12 | network_id: "3", 13 | from: "0xa303ddc620aa7d1390baccc8a495508b183fab59", 14 | gas: 5000000, 15 | } 16 | }, 17 | mocha: { 18 | reporter: 'eth-gas-reporter', 19 | reporterOptions: { 20 | currency: 'USD', 21 | gasPrice: 1 22 | } 23 | }, 24 | solc: { 25 | optimizer: { 26 | enabled: true, 27 | runs: 200 28 | } 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/AccountAPI.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "./types/AccountTypes.sol"; 23 | import "./cbor/AccountCbor.sol"; 24 | import "./types/CommonTypes.sol"; 25 | import "./utils/Misc.sol"; 26 | import "./utils/Actor.sol"; 27 | 28 | /// @title This contract is a proxy to the Account actor. Calling one of its methods will result in a cross-actor call being performed. 29 | /// @author Zondax AG 30 | library AccountAPI { 31 | using AuthenticateMessageCBOR for AccountTypes.AuthenticateMessageParams; 32 | using UniversalReceiverHookCBOR for AccountTypes.UniversalReceiverParams; 33 | using BytesCBOR for bytes; 34 | 35 | /// @notice FIXME 36 | function authenticateMessage(bytes memory target, AccountTypes.AuthenticateMessageParams memory params) internal { 37 | bytes memory raw_request = params.serialize(); 38 | 39 | bytes memory raw_response = Actor.call(AccountTypes.AuthenticateMessageMethodNum, target, raw_request, Misc.CBOR_CODEC); 40 | 41 | Actor.readRespData(raw_response); 42 | } 43 | 44 | /// @notice FIXME 45 | function universalReceiverHook(bytes memory target, AccountTypes.UniversalReceiverParams memory params) internal { 46 | bytes memory raw_request = params.serialize(); 47 | 48 | bytes memory raw_response = Actor.call(AccountTypes.UniversalReceiverHookMethodNum, target, raw_request, Misc.CBOR_CODEC); 49 | 50 | Actor.readRespData(raw_response); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/InitAPI.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "./types/InitTypes.sol"; 23 | import "./cbor/InitCbor.sol"; 24 | import "./types/CommonTypes.sol"; 25 | import "./utils/Misc.sol"; 26 | import "./utils/Actor.sol"; 27 | 28 | /// @title This contract is a proxy to the singleton Init actor (address: f01). Calling one of its methods will result in a cross-actor call being performed. 29 | /// @author Zondax AG 30 | library InitAPI { 31 | using ExecCBOR for InitTypes.ExecParams; 32 | using ExecCBOR for InitTypes.ExecReturn; 33 | using Exec4CBOR for InitTypes.Exec4Params; 34 | using Exec4CBOR for InitTypes.Exec4Return; 35 | 36 | /// @notice FIXME 37 | function exec(InitTypes.ExecParams memory params) internal returns (InitTypes.ExecReturn memory) { 38 | bytes memory raw_request = params.serialize(); 39 | 40 | bytes memory raw_response = Actor.call(InitTypes.ExecMethodNum, InitTypes.ActorCode, raw_request, Misc.CBOR_CODEC); 41 | 42 | bytes memory result = Actor.readRespData(raw_response); 43 | 44 | InitTypes.ExecReturn memory response; 45 | response.deserialize(result); 46 | 47 | return response; 48 | } 49 | 50 | /// @notice FIXME 51 | function exec4(InitTypes.Exec4Params memory params) internal returns (InitTypes.Exec4Return memory) { 52 | bytes memory raw_request = params.serialize(); 53 | 54 | bytes memory raw_response = Actor.call(InitTypes.Exec4MethodNum, InitTypes.ActorCode, raw_request, Misc.CBOR_CODEC); 55 | 56 | bytes memory result = Actor.readRespData(raw_response); 57 | 58 | InitTypes.Exec4Return memory response; 59 | response.deserialize(result); 60 | 61 | return response; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/PowerAPI.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "./types/PowerTypes.sol"; 23 | import "./cbor/PowerCbor.sol"; 24 | 25 | import "./utils/Actor.sol"; 26 | 27 | /// @title FIXME 28 | /// @author Zondax AG 29 | library PowerAPI { 30 | using CreateMinerCBOR for PowerTypes.CreateMinerParams; 31 | using CreateMinerCBOR for PowerTypes.CreateMinerReturn; 32 | using MinerCountCBOR for PowerTypes.MinerCountReturn; 33 | using MinerConsensusCountCBOR for PowerTypes.MinerConsensusCountReturn; 34 | using NetworkRawPowerCBOR for PowerTypes.NetworkRawPowerReturn; 35 | using MinerRawPowerCBOR for PowerTypes.MinerRawPowerParams; 36 | using MinerRawPowerCBOR for PowerTypes.MinerRawPowerReturn; 37 | 38 | function createMiner(PowerTypes.CreateMinerParams memory params) internal returns (PowerTypes.CreateMinerReturn memory) { 39 | bytes memory raw_request = params.serialize(); 40 | 41 | bytes memory raw_response = Actor.call(PowerTypes.CreateMinerMethodNum, PowerTypes.ActorCode, raw_request, Misc.CBOR_CODEC); 42 | 43 | bytes memory result = Actor.readRespData(raw_response); 44 | 45 | PowerTypes.CreateMinerReturn memory response; 46 | response.deserialize(result); 47 | 48 | return response; 49 | } 50 | 51 | function minerCount() internal returns (PowerTypes.MinerCountReturn memory) { 52 | bytes memory raw_request = new bytes(0); 53 | 54 | bytes memory raw_response = Actor.call(PowerTypes.MinerCountMethodNum, PowerTypes.ActorCode, raw_request, Misc.NONE_CODEC); 55 | 56 | bytes memory result = Actor.readRespData(raw_response); 57 | 58 | PowerTypes.MinerCountReturn memory response; 59 | response.deserialize(result); 60 | 61 | return response; 62 | } 63 | 64 | function minerConsensusCount() internal returns (PowerTypes.MinerConsensusCountReturn memory) { 65 | bytes memory raw_request = new bytes(0); 66 | 67 | bytes memory raw_response = Actor.call(PowerTypes.MinerConsensusCountMethodNum, PowerTypes.ActorCode, raw_request, Misc.NONE_CODEC); 68 | 69 | bytes memory result = Actor.readRespData(raw_response); 70 | 71 | PowerTypes.MinerConsensusCountReturn memory response; 72 | response.deserialize(result); 73 | 74 | return response; 75 | } 76 | 77 | function networkRawPower() internal returns (PowerTypes.NetworkRawPowerReturn memory) { 78 | bytes memory raw_request = new bytes(0); 79 | 80 | bytes memory raw_response = Actor.call(PowerTypes.NetworkRawPowerMethodNum, PowerTypes.ActorCode, raw_request, Misc.NONE_CODEC); 81 | 82 | bytes memory result = Actor.readRespData(raw_response); 83 | 84 | PowerTypes.NetworkRawPowerReturn memory response; 85 | response.deserialize(result); 86 | 87 | return response; 88 | } 89 | 90 | function minerRawPower(PowerTypes.MinerRawPowerParams memory params) internal returns (PowerTypes.MinerRawPowerReturn memory) { 91 | bytes memory raw_request = params.serialize(); 92 | 93 | bytes memory raw_response = Actor.call(PowerTypes.MinerRawPowerMethodNum, PowerTypes.ActorCode, raw_request, Misc.CBOR_CODEC); 94 | 95 | bytes memory result = Actor.readRespData(raw_response); 96 | 97 | PowerTypes.MinerRawPowerReturn memory response; 98 | response.deserialize(result); 99 | 100 | return response; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/PrecompilesAPI.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity ^0.8.0; 21 | 22 | /// @title This library simplify the call of FEVM precompiles contracts. 23 | /// @author Zondax AG 24 | library PrecompilesAPI { 25 | uint64 constant GAS_LIMIT = 100000000; 26 | uint64 constant MAX_RAW_RESPONSE_SIZE = 0x300; 27 | 28 | function resolveAddress(bytes memory addr) internal view returns (bytes memory) { 29 | bytes memory raw_response = new bytes(MAX_RAW_RESPONSE_SIZE); 30 | uint len; 31 | 32 | assembly { 33 | len := mload(addr) 34 | let input := mload(0x40) 35 | mstore(input, len) 36 | let offset := 0 37 | for { 38 | offset := 0x00 39 | } lt(offset, len) { 40 | offset := add(offset, 0x20) 41 | } { 42 | mstore(add(input, add(0x20, offset)), mload(add(addr, add(0x20, offset)))) 43 | } 44 | 45 | if iszero(staticcall(GAS_LIMIT, 0x0a, input, add(0x20, len), raw_response, MAX_RAW_RESPONSE_SIZE)) { 46 | revert(0, 0) 47 | } 48 | } 49 | return raw_response; 50 | } 51 | 52 | function lookupAddress(uint64 actor_id) internal view returns (bytes memory) { 53 | bytes memory raw_response = new bytes(MAX_RAW_RESPONSE_SIZE); 54 | uint len; 55 | 56 | assembly { 57 | len := mload(actor_id) 58 | let input := mload(0x40) 59 | mstore(input, actor_id) 60 | 61 | if iszero(staticcall(GAS_LIMIT, 0x0b, input, len, raw_response, MAX_RAW_RESPONSE_SIZE)) { 62 | revert(0, 0) 63 | } 64 | } 65 | return raw_response; 66 | } 67 | 68 | function getActorType(uint64 actor_id) internal view returns (bytes memory) { 69 | bytes memory raw_response = new bytes(MAX_RAW_RESPONSE_SIZE); 70 | uint len; 71 | 72 | assembly { 73 | len := mload(actor_id) 74 | let input := mload(0x40) 75 | mstore(input, actor_id) 76 | 77 | if iszero(staticcall(GAS_LIMIT, 0x0c, input, len, raw_response, MAX_RAW_RESPONSE_SIZE)) { 78 | revert(0, 0) 79 | } 80 | } 81 | return raw_response; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/Utils.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity ^0.8.0; 21 | 22 | import "./types/AccountTypes.sol"; 23 | import "./types/DataCapTypes.sol"; 24 | import "./cbor/AccountCbor.sol"; 25 | 26 | /// @title This library compiles a bunch of help function. 27 | /// @author Zondax AG 28 | library Utils { 29 | using AuthenticateMessageCBOR for AccountTypes.AuthenticateMessageParams; 30 | using BytesCBOR for bytes; 31 | 32 | event ReceivedDataCap(string received); 33 | 34 | function handleFilecoinMethod( 35 | uint64 method, 36 | uint64, 37 | bytes calldata params 38 | ) internal returns (AccountTypes.AuthenticateMessageParams memory) { 39 | AccountTypes.AuthenticateMessageParams memory response; 40 | // dispatch methods 41 | if (method == AccountTypes.AuthenticateMessageMethodNum) { 42 | // deserialize params here 43 | response.deserialize(params); 44 | 45 | return response; 46 | } else if (method == DataCapTypes.ReceiverHookMethodNum) { 47 | emit ReceivedDataCap("DataCap Received!"); 48 | 49 | return response; 50 | } else { 51 | revert("the filecoin method that was called is not handled"); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/cbor/AccountCbor.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "solidity-cborutils/contracts/CBOR.sol"; 23 | 24 | import {AccountTypes} from "../types/AccountTypes.sol"; 25 | import "../utils/CborDecode.sol"; 26 | import "../utils/Misc.sol"; 27 | 28 | /// @title FIXME 29 | /// @author Zondax AG 30 | library AuthenticateMessageCBOR { 31 | using CBOR for CBOR.CBORBuffer; 32 | using CBORDecoder for bytes; 33 | 34 | function serialize(AccountTypes.AuthenticateMessageParams memory params) internal pure returns (bytes memory) { 35 | // FIXME what should the max length be on the buffer? 36 | CBOR.CBORBuffer memory buf = CBOR.create(64); 37 | 38 | buf.startFixedArray(2); 39 | buf.writeBytes(params.signature); 40 | buf.writeBytes(params.message); 41 | 42 | return buf.data(); 43 | } 44 | 45 | function deserialize(AccountTypes.AuthenticateMessageParams memory ret, bytes memory rawResp) internal pure { 46 | uint byteIdx = 0; 47 | uint len; 48 | 49 | (len, byteIdx) = rawResp.readFixedArray(byteIdx); 50 | assert(len == 2); 51 | 52 | (ret.signature, byteIdx) = rawResp.readBytes(byteIdx); 53 | (ret.message, byteIdx) = rawResp.readBytes(byteIdx); 54 | } 55 | } 56 | 57 | /// @title FIXME 58 | /// @author Zondax AG 59 | library UniversalReceiverHookCBOR { 60 | using CBOR for CBOR.CBORBuffer; 61 | using CBORDecoder for bytes; 62 | 63 | function serialize(AccountTypes.UniversalReceiverParams memory params) internal pure returns (bytes memory) { 64 | // FIXME what should the max length be on the buffer? 65 | CBOR.CBORBuffer memory buf = CBOR.create(64); 66 | 67 | buf.startFixedArray(2); 68 | buf.writeUInt64(params.type_); 69 | buf.writeBytes(params.payload); 70 | 71 | return buf.data(); 72 | } 73 | } 74 | 75 | library BytesCBOR { 76 | using CBOR for CBOR.CBORBuffer; 77 | using CBORDecoder for bytes; 78 | 79 | function serializeBytes(bytes memory data) internal pure returns (bytes memory) { 80 | // FIXME what should the max length be on the buffer? 81 | CBOR.CBORBuffer memory buf = CBOR.create(64); 82 | 83 | buf.writeBytes(data); 84 | 85 | return buf.data(); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/cbor/BigIntCbor.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | struct BigInt { 23 | bytes val; 24 | bool neg; 25 | } 26 | 27 | library BigIntCBOR { 28 | function serializeBigNum(BigInt memory num) internal pure returns (bytes memory) { 29 | // TODO improve gas efficiency by using assembly code 30 | bytes memory raw = new bytes(num.val.length + 1); 31 | 32 | if (num.neg) { 33 | raw[0] = 0x01; 34 | } 35 | 36 | uint index = 1; 37 | for (uint i = 0; i < num.val.length; i++) { 38 | raw[index] = num.val[i]; 39 | index++; 40 | } 41 | 42 | return raw; 43 | } 44 | 45 | function deserializeBigNum(bytes memory raw) internal pure returns (BigInt memory) { 46 | // TODO improve gas efficiency by using assembly code 47 | 48 | // Is an empty byte a valid BigInt ? We should have the sign byte at least 49 | if (raw.length == 0) { 50 | return BigInt(hex"00", false); 51 | } 52 | 53 | bytes memory val = new bytes(raw.length - 1); 54 | bool neg = false; 55 | 56 | if (raw[0] == 0x01) { 57 | neg = true; 58 | } 59 | 60 | for (uint i = 1; i < raw.length; i++) { 61 | val[i - 1] = raw[i]; 62 | } 63 | 64 | return BigInt(val, neg); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/cbor/FilecoinCbor.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "solidity-cborutils/contracts/CBOR.sol"; 23 | import "@ensdomains/buffer/contracts/Buffer.sol"; 24 | 25 | /// @title FIXME 26 | /// @author Zondax AG 27 | library FilecoinCbor { 28 | using Buffer for Buffer.buffer; 29 | using CBOR for CBOR.CBORBuffer; 30 | 31 | uint8 private constant MAJOR_TYPE_TAG = 6; 32 | uint8 private constant TAG_TYPE_CID_CODE = 42; 33 | uint8 private constant PAYLOAD_LEN_8_BITS = 24; 34 | 35 | function writeCid(CBOR.CBORBuffer memory buf, bytes memory value) internal pure { 36 | buf.buf.appendUint8(uint8(((MAJOR_TYPE_TAG << 5) | PAYLOAD_LEN_8_BITS))); 37 | buf.buf.appendUint8(TAG_TYPE_CID_CODE); 38 | buf.writeBytes(value); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/cbor/InitCbor.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "solidity-cborutils/contracts/CBOR.sol"; 23 | 24 | import {InitTypes} from "../types/InitTypes.sol"; 25 | import "./FilecoinCbor.sol"; 26 | import "../utils/CborDecode.sol"; 27 | import "../utils/Misc.sol"; 28 | 29 | /// @title FIXME 30 | /// @author Zondax AG 31 | library ExecCBOR { 32 | using CBOR for CBOR.CBORBuffer; 33 | using FilecoinCbor for CBOR.CBORBuffer; 34 | using CBORDecoder for bytes; 35 | 36 | function serialize(InitTypes.ExecParams memory params) internal pure returns (bytes memory) { 37 | // FIXME what should the max length be on the buffer? 38 | CBOR.CBORBuffer memory buf = CBOR.create(64); 39 | 40 | buf.startFixedArray(2); 41 | buf.writeCid(params.code_cid); 42 | buf.writeBytes(params.constructor_params); 43 | 44 | return buf.data(); 45 | } 46 | 47 | function deserialize(InitTypes.ExecReturn memory ret, bytes memory rawResp) internal pure { 48 | uint byteIdx = 0; 49 | uint len; 50 | 51 | (len, byteIdx) = rawResp.readFixedArray(byteIdx); 52 | assert(len == 2); 53 | 54 | (ret.id_address, byteIdx) = rawResp.readBytes(byteIdx); 55 | (ret.robust_address, byteIdx) = rawResp.readBytes(byteIdx); 56 | } 57 | } 58 | 59 | /// @title FIXME 60 | /// @author Zondax AG 61 | library Exec4CBOR { 62 | using CBOR for CBOR.CBORBuffer; 63 | using FilecoinCbor for CBOR.CBORBuffer; 64 | using CBORDecoder for bytes; 65 | 66 | function serialize(InitTypes.Exec4Params memory params) internal pure returns (bytes memory) { 67 | // FIXME what should the max length be on the buffer? 68 | CBOR.CBORBuffer memory buf = CBOR.create(64); 69 | 70 | buf.startFixedArray(3); 71 | buf.writeCid(params.code_cid); 72 | buf.writeBytes(params.constructor_params); 73 | buf.writeBytes(params.subaddress); 74 | 75 | return buf.data(); 76 | } 77 | 78 | function deserialize(InitTypes.Exec4Return memory ret, bytes memory rawResp) internal pure { 79 | uint byteIdx = 0; 80 | uint len; 81 | 82 | (len, byteIdx) = rawResp.readFixedArray(byteIdx); 83 | assert(len == 2); 84 | 85 | (ret.id_address, byteIdx) = rawResp.readBytes(byteIdx); 86 | (ret.robust_address, byteIdx) = rawResp.readBytes(byteIdx); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/cbor/PowerCbor.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "solidity-cborutils/contracts/CBOR.sol"; 23 | 24 | import {CommonTypes} from "../types/CommonTypes.sol"; 25 | import {PowerTypes} from "../types/PowerTypes.sol"; 26 | import "../utils/CborDecode.sol"; 27 | import "../utils/Misc.sol"; 28 | import "./BigIntCbor.sol"; 29 | 30 | /// @title FIXME 31 | /// @author Zondax AG 32 | library CreateMinerCBOR { 33 | using CBOR for CBOR.CBORBuffer; 34 | using CBORDecoder for bytes; 35 | 36 | function serialize(PowerTypes.CreateMinerParams memory params) internal pure returns (bytes memory) { 37 | // FIXME what should the max length be on the buffer? 38 | CBOR.CBORBuffer memory buf = CBOR.create(64); 39 | 40 | uint multiaddrsLen = params.multiaddrs.length; 41 | 42 | buf.startFixedArray(5); 43 | buf.writeBytes(params.owner); 44 | buf.writeBytes(params.worker); 45 | buf.writeInt64(int64(uint64(params.window_post_proof_type))); 46 | buf.writeBytes(params.peer); 47 | buf.startFixedArray(uint64(multiaddrsLen)); 48 | for (uint i = 0; i < multiaddrsLen; i++) { 49 | buf.writeBytes(params.multiaddrs[i]); 50 | } 51 | 52 | return buf.data(); 53 | } 54 | 55 | function deserialize(PowerTypes.CreateMinerReturn memory ret, bytes memory rawResp) internal pure { 56 | uint byteIdx = 0; 57 | uint len; 58 | 59 | (len, byteIdx) = rawResp.readFixedArray(byteIdx); 60 | assert(len == 2); 61 | 62 | (ret.id_address, byteIdx) = rawResp.readBytes(byteIdx); 63 | (ret.robust_address, byteIdx) = rawResp.readBytes(byteIdx); 64 | } 65 | } 66 | 67 | /// @title FIXME 68 | /// @author Zondax AG 69 | library MinerCountCBOR { 70 | using CBOR for CBOR.CBORBuffer; 71 | using CBORDecoder for bytes; 72 | 73 | function deserialize(PowerTypes.MinerCountReturn memory ret, bytes memory rawResp) internal pure { 74 | uint byteIdx = 0; 75 | 76 | // REVIEW: The ouput returned is '00' so it unsigned but the type described in buitin is i64. 77 | (ret.miner_count, byteIdx) = rawResp.readUInt64(byteIdx); 78 | } 79 | } 80 | 81 | /// @title FIXME 82 | /// @author Zondax AG 83 | library MinerConsensusCountCBOR { 84 | using CBOR for CBOR.CBORBuffer; 85 | using CBORDecoder for bytes; 86 | 87 | function deserialize(PowerTypes.MinerConsensusCountReturn memory ret, bytes memory rawResp) internal pure { 88 | uint byteIdx = 0; 89 | 90 | (ret.miner_consensus_count, byteIdx) = rawResp.readInt64(byteIdx); 91 | } 92 | } 93 | 94 | /// @title FIXME 95 | /// @author Zondax AG 96 | library NetworkRawPowerCBOR { 97 | using CBOR for CBOR.CBORBuffer; 98 | using CBORDecoder for bytes; 99 | using BigIntCBOR for bytes; 100 | 101 | function deserialize(PowerTypes.NetworkRawPowerReturn memory ret, bytes memory rawResp) internal pure { 102 | uint byteIdx = 0; 103 | 104 | bytes memory tmp; 105 | (tmp, byteIdx) = rawResp.readBytes(byteIdx); 106 | if (tmp.length > 0) { 107 | ret.raw_byte_power = tmp.deserializeBigNum(); 108 | } else { 109 | ret.raw_byte_power = BigInt(new bytes(0), false); 110 | } 111 | } 112 | } 113 | 114 | /// @title FIXME 115 | /// @author Zondax AG 116 | library MinerRawPowerCBOR { 117 | using CBOR for CBOR.CBORBuffer; 118 | using CBORDecoder for bytes; 119 | using BigIntCBOR for bytes; 120 | 121 | function serialize(PowerTypes.MinerRawPowerParams memory params) internal pure returns (bytes memory) { 122 | // FIXME what should the max length be on the buffer? 123 | CBOR.CBORBuffer memory buf = CBOR.create(64); 124 | 125 | buf.writeUInt64(params.miner); 126 | 127 | return buf.data(); 128 | } 129 | 130 | function deserialize(PowerTypes.MinerRawPowerReturn memory ret, bytes memory rawResp) internal pure { 131 | uint byteIdx = 0; 132 | uint len; 133 | 134 | (len, byteIdx) = rawResp.readFixedArray(byteIdx); 135 | assert(len == 2); 136 | 137 | bytes memory tmp; 138 | (tmp, byteIdx) = rawResp.readBytes(byteIdx); 139 | if (tmp.length > 0) { 140 | ret.raw_byte_power = tmp.deserializeBigNum(); 141 | } else { 142 | ret.raw_byte_power = BigInt(new bytes(0), false); 143 | } 144 | 145 | (ret.meets_consensus_minimum, byteIdx) = rawResp.readBool(byteIdx); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/types/AccountTypes.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "./CommonTypes.sol"; 23 | 24 | /// @title Filecoin account actor types for Solidity. 25 | /// @author Zondax AG 26 | library AccountTypes { 27 | uint constant AuthenticateMessageMethodNum = 2643134072; 28 | uint constant UniversalReceiverHookMethodNum = 3726118371; 29 | 30 | struct AuthenticateMessageParams { 31 | bytes signature; 32 | bytes message; 33 | } 34 | 35 | struct UniversalReceiverParams { 36 | /// Asset type 37 | uint32 type_; 38 | /// Payload corresponding to asset type 39 | bytes payload; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/types/DataCapTypes.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "../cbor/BigIntCbor.sol"; 23 | 24 | /// @title Filecoin datacap actor types for Solidity. 25 | /// @author Zondax AG 26 | library DataCapTypes { 27 | bytes constant ActorCode = hex"0007"; 28 | uint constant NameMethodNum = 48890204; 29 | uint constant SymbolMethodNum = 2061153854; 30 | uint constant TotalSupplyMethodNum = 114981429; 31 | uint constant BalanceOfMethodNum = 3261979605; 32 | uint constant TransferMethodNum = 80475954; 33 | uint constant TransferFromMethodNum = 3621052141; 34 | uint constant IncreaseAllowanceMethodNum = 1777121560; 35 | uint constant DecreaseAllowanceMethodNum = 1529376545; 36 | uint constant RevokeAllowanceMethodNum = 2765635761; 37 | uint constant BurnMethodNum = 1434719642; 38 | uint constant BurnFromMethodNum = 2979674018; 39 | uint constant AllowanceMethodNum = 4205072950; 40 | uint constant ReceiverHookMethodNum = 3726118371; 41 | 42 | struct GetAllowanceParams { 43 | bytes owner; 44 | bytes operator; 45 | } 46 | 47 | struct TransferParams { 48 | bytes to; 49 | /// A non-negative amount to transfer 50 | BigInt amount; 51 | /// Arbitrary data to pass on via the receiver hook 52 | bytes operator_data; 53 | } 54 | 55 | struct TransferReturn { 56 | BigInt from_balance; 57 | /// The new balance of the `to` address 58 | BigInt to_balance; 59 | /// (Optional) data returned from receiver hook 60 | bytes recipient_data; 61 | } 62 | 63 | struct TransferFromParams { 64 | bytes from; 65 | bytes to; 66 | /// A non-negative amount to transfer 67 | BigInt amount; 68 | /// Arbitrary data to pass on via the receiver hook 69 | bytes operator_data; 70 | } 71 | 72 | struct TransferFromReturn { 73 | BigInt from_balance; 74 | /// The new balance of the `to` address 75 | BigInt to_balance; 76 | /// The new remaining allowance between `owner` and `operator` (caller) 77 | BigInt allowance; 78 | /// (Optional) data returned from receiver hook 79 | bytes recipient_data; 80 | } 81 | 82 | struct IncreaseAllowanceParams { 83 | bytes operator; 84 | /// A non-negative amount to increase the allowance by 85 | BigInt increase; 86 | } 87 | struct DecreaseAllowanceParams { 88 | bytes operator; 89 | /// A non-negative amount to decrease the allowance by 90 | BigInt decrease; 91 | } 92 | struct RevokeAllowanceParams { 93 | bytes operator; 94 | } 95 | 96 | struct BurnParams { 97 | /// A non-negative amount to burn 98 | BigInt amount; 99 | } 100 | 101 | struct BurnReturn { 102 | /// New balance in the account after the successful burn 103 | BigInt balance; 104 | } 105 | 106 | struct BurnFromParams { 107 | bytes owner; 108 | /// A non-negative amount to burn 109 | BigInt amount; 110 | } 111 | 112 | struct BurnFromReturn { 113 | /// New balance in the account after the successful burn 114 | BigInt balance; 115 | /// New remaining allowance between the owner and operator (caller) 116 | BigInt allowance; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/types/InitTypes.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | /// @title Filecoin init actor types for Solidity. 23 | /// @author Zondax AG 24 | library InitTypes { 25 | bytes constant ActorCode = hex"0001"; 26 | uint constant ExecMethodNum = 81225168; 27 | uint constant Exec4MethodNum = 3; 28 | 29 | struct ExecParams { 30 | bytes code_cid; 31 | bytes constructor_params; 32 | } 33 | 34 | struct ExecReturn { 35 | /// ID based address for created actor 36 | bytes id_address; 37 | /// Reorg safe address for actor 38 | bytes robust_address; 39 | } 40 | 41 | struct Exec4Params { 42 | bytes code_cid; 43 | bytes constructor_params; 44 | bytes subaddress; 45 | } 46 | 47 | struct Exec4Return { 48 | /// ID based address for created actor 49 | bytes id_address; 50 | /// Reorg safe address for actor 51 | bytes robust_address; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/types/MarketTypes.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "../cbor/BigIntCbor.sol"; 23 | import "./CommonTypes.sol"; 24 | 25 | /// @title Filecoin market actor types for Solidity. 26 | /// @author Zondax AG 27 | library MarketTypes { 28 | bytes constant ActorCode = hex"0005"; 29 | uint constant AddBalanceMethodNum = 822473126; 30 | uint constant WithdrawBalanceMethodNum = 2280458852; 31 | uint constant GetBalanceMethodNum = 726108461; 32 | uint constant GetDealDataCommitmentMethodNum = 1157985802; 33 | uint constant GetDealClientMethodNum = 128053329; 34 | uint constant GetDealProviderMethodNum = 935081690; 35 | uint constant GetDealLabelMethodNum = 46363526; 36 | uint constant GetDealTermMethodNum = 163777312; 37 | uint constant GetDealEpochPriceMethodNum = 4287162428; 38 | uint constant GetDealClientCollateralMethodNum = 200567895; 39 | uint constant GetDealProviderCollateralMethodNum = 2986712137; 40 | uint constant GetDealVerifiedMethodNum = 2627389465; 41 | uint constant GetDealActivationMethodNum = 2567238399; 42 | uint constant PublishStorageDealsMethodNum = 2236929350; 43 | 44 | struct WithdrawBalanceParams { 45 | bytes provider_or_client; 46 | BigInt tokenAmount; 47 | } 48 | 49 | struct WithdrawBalanceReturn { 50 | BigInt amount_withdrawn; 51 | } 52 | 53 | struct GetBalanceReturn { 54 | BigInt balance; 55 | BigInt locked; 56 | } 57 | 58 | struct GetDealDataCommitmentParams { 59 | uint64 id; 60 | } 61 | 62 | struct GetDealDataCommitmentReturn { 63 | bytes data; 64 | uint64 size; 65 | } 66 | 67 | struct GetDealClientParams { 68 | uint64 id; 69 | } 70 | 71 | struct GetDealClientReturn { 72 | uint64 client; 73 | } 74 | 75 | struct GetDealProviderParams { 76 | uint64 id; 77 | } 78 | 79 | struct GetDealProviderReturn { 80 | uint64 provider; 81 | } 82 | 83 | struct GetDealLabelParams { 84 | uint64 id; 85 | } 86 | 87 | struct GetDealLabelReturn { 88 | string label; 89 | } 90 | 91 | struct GetDealTermParams { 92 | uint64 id; 93 | } 94 | 95 | struct GetDealTermReturn { 96 | int64 start; 97 | int64 end; 98 | } 99 | 100 | struct GetDealEpochPriceParams { 101 | uint64 id; 102 | } 103 | 104 | struct GetDealEpochPriceReturn { 105 | BigInt price_per_epoch; 106 | } 107 | 108 | struct GetDealClientCollateralParams { 109 | uint64 id; 110 | } 111 | 112 | struct GetDealClientCollateralReturn { 113 | BigInt collateral; 114 | } 115 | 116 | struct GetDealProviderCollateralParams { 117 | uint64 id; 118 | } 119 | 120 | struct GetDealProviderCollateralReturn { 121 | BigInt collateral; 122 | } 123 | 124 | struct GetDealVerifiedParams { 125 | uint64 id; 126 | } 127 | 128 | struct GetDealVerifiedReturn { 129 | bool verified; 130 | } 131 | 132 | struct GetDealActivationParams { 133 | uint64 id; 134 | } 135 | 136 | struct GetDealActivationReturn { 137 | int64 activated; 138 | int64 terminated; 139 | } 140 | 141 | struct PublishStorageDealsParams { 142 | CommonTypes.ClientDealProposal[] deals; 143 | } 144 | 145 | struct PublishStorageDealsReturn { 146 | uint64[] ids; 147 | bytes valid_deals; 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/types/MinerTypes.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "../cbor/BigIntCbor.sol"; 23 | import "./CommonTypes.sol"; 24 | 25 | /// @title Filecoin miner actor types for Solidity. 26 | /// @author Zondax AG 27 | library MinerTypes { 28 | uint constant GetOwnerMethodNum = 3275365574; 29 | uint constant ChangeOwnerAddressMethodNum = 1010589339; 30 | uint constant IsControllingAddressMethodNum = 348244887; 31 | uint constant GetSectorSizeMethodNum = 3858292296; 32 | uint constant GetAvailableBalanceMethodNum = 4026106874; 33 | uint constant GetVestingFundsMethodNum = 1726876304; 34 | uint constant ChangeBeneficiaryMethodNum = 1570634796; 35 | uint constant GetBeneficiaryMethodNum = 4158972569; 36 | uint constant ChangeWorkerAddressMethodNum = 3302309124; 37 | uint constant ChangePeerIDMethodNum = 1236548004; 38 | uint constant ChangeMultiaddrsMethodNum = 1063480576; 39 | uint constant RepayDebtMethodNum = 3665352697; 40 | uint constant ConfirmChangeWorkerAddressMethodNum = 2354970453; 41 | uint constant GetPeerIDMethodNum = 2812875329; 42 | uint constant GetMultiaddrsMethodNum = 1332909407; 43 | uint constant WithdrawBalanceMethodNum = 2280458852; 44 | 45 | struct GetOwnerReturn { 46 | bytes owner; 47 | bytes proposed; 48 | } 49 | 50 | struct IsControllingAddressParam { 51 | bytes addr; 52 | } 53 | 54 | struct IsControllingAddressReturn { 55 | bool is_controlling; 56 | } 57 | 58 | struct GetSectorSizeReturn { 59 | uint64 sector_size; 60 | } 61 | struct GetAvailableBalanceReturn { 62 | BigInt available_balance; 63 | } 64 | 65 | struct GetVestingFundsReturn { 66 | CommonTypes.VestingFunds[] vesting_funds; 67 | } 68 | 69 | struct ChangeBeneficiaryParams { 70 | bytes new_beneficiary; 71 | BigInt new_quota; 72 | uint64 new_expiration; 73 | } 74 | 75 | struct GetBeneficiaryReturn { 76 | CommonTypes.ActiveBeneficiary active; 77 | CommonTypes.PendingBeneficiaryChange proposed; 78 | } 79 | 80 | struct ChangeWorkerAddressParams { 81 | bytes new_worker; 82 | bytes[] new_control_addresses; 83 | } 84 | 85 | struct ChangePeerIDParams { 86 | bytes new_id; 87 | } 88 | 89 | struct ChangeMultiaddrsParams { 90 | bytes[] new_multi_addrs; 91 | } 92 | 93 | struct GetPeerIDReturn { 94 | bytes peer_id; 95 | } 96 | 97 | struct GetMultiaddrsReturn { 98 | bytes[] multi_addrs; 99 | } 100 | 101 | struct WithdrawBalanceParams { 102 | bytes amount_requested; 103 | } 104 | 105 | struct WithdrawBalanceReturn { 106 | bytes amount_withdrawn; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/types/MultisigTypes.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "../cbor/BigIntCbor.sol"; 23 | import "./CommonTypes.sol"; 24 | 25 | /// @title Filecoin multisig actor types for Solidity. 26 | /// @author Zondax AG 27 | library MultisigTypes { 28 | uint constant ProposeMethodNum = 1696838335; 29 | uint constant ApproveMethodNum = 1289044053; 30 | uint constant CancelMethodNum = 3365893656; 31 | uint constant AddSignerMethodNum = 3028530033; 32 | uint constant RemoveSignerMethodNum = 21182899; 33 | uint constant SwapSignerMethodNum = 3968117037; 34 | uint constant ChangeNumApprovalsThresholdMethodNum = 3375931653; 35 | uint constant LockBalanceMethodNum = 1999470977; 36 | uint constant UniversalReceiverHookMethodNum = 3726118371; 37 | 38 | struct ProposeParams { 39 | bytes to; 40 | BigInt value; 41 | uint64 method; 42 | bytes params; 43 | } 44 | 45 | struct ProposeReturn { 46 | /// TxnID is the ID of the proposed transaction. 47 | int64 txn_id; 48 | /// Applied indicates if the transaction was applied as opposed to proposed but not applied 49 | /// due to lack of approvals. 50 | bool applied; 51 | /// Code is the exitcode of the transaction, if Applied is false this field should be ignored. 52 | uint32 code; 53 | /// Ret is the return value of the transaction, if Applied is false this field should 54 | /// be ignored. 55 | bytes ret; 56 | } 57 | 58 | struct TxnIDParams { 59 | int64 id; 60 | /// Optional hash of proposal to ensure an operation can only apply to a 61 | /// specific proposal. 62 | bytes proposal_hash; 63 | } 64 | 65 | struct ApproveReturn { 66 | /// Applied indicates if the transaction was applied as opposed to proposed but not applied 67 | /// due to lack of approvals 68 | bool applied; 69 | /// Code is the exitcode of the transaction, if Applied is false this field should be ignored. 70 | uint32 code; 71 | /// Ret is the return value of the transaction, if Applied is false this field should 72 | /// be ignored. 73 | bytes ret; 74 | } 75 | 76 | struct AddSignerParams { 77 | bytes signer; 78 | bool increase; 79 | } 80 | 81 | struct RemoveSignerParams { 82 | bytes signer; 83 | bool decrease; 84 | } 85 | 86 | struct SwapSignerParams { 87 | bytes from; 88 | bytes to; 89 | } 90 | 91 | struct ChangeNumApprovalsThresholdParams { 92 | uint64 new_threshold; 93 | } 94 | 95 | struct LockBalanceParams { 96 | int64 start_epoch; 97 | int64 unlock_duration; 98 | BigInt amount; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/types/PowerTypes.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "../cbor/BigIntCbor.sol"; 23 | import "./CommonTypes.sol"; 24 | 25 | /// @title Filecoin power actor types for Solidity. 26 | /// @author Zondax AG 27 | library PowerTypes { 28 | bytes constant ActorCode = hex"0004"; 29 | uint constant CreateMinerMethodNum = 1173380165; 30 | uint constant MinerCountMethodNum = 1987646258; 31 | uint constant MinerConsensusCountMethodNum = 196739875; 32 | uint constant NetworkRawPowerMethodNum = 931722534; 33 | uint constant MinerRawPowerMethodNum = 3753401894; 34 | 35 | struct CreateMinerParams { 36 | bytes owner; 37 | bytes worker; 38 | CommonTypes.RegisteredPoStProof window_post_proof_type; 39 | bytes peer; 40 | bytes[] multiaddrs; 41 | } 42 | struct CreateMinerReturn { 43 | /// Canonical ID-based address for the actor. 44 | bytes id_address; 45 | /// Re-org safe address for created actor. 46 | bytes robust_address; 47 | } 48 | struct MinerCountReturn { 49 | uint64 miner_count; 50 | } 51 | struct MinerConsensusCountReturn { 52 | int64 miner_consensus_count; 53 | } 54 | struct NetworkRawPowerReturn { 55 | BigInt raw_byte_power; 56 | } 57 | struct MinerRawPowerParams { 58 | uint64 miner; 59 | } 60 | struct MinerRawPowerReturn { 61 | BigInt raw_byte_power; 62 | bool meets_consensus_minimum; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/types/VerifRegTypes.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // 17 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 18 | 19 | // SPDX-License-Identifier: Apache-2.0 20 | pragma solidity >=0.4.25 <=0.8.17; 21 | 22 | import "../cbor/BigIntCbor.sol"; 23 | import "./CommonTypes.sol"; 24 | 25 | /// @title Filecoin Verified Registry actor types for Solidity. 26 | /// @author Zondax AG 27 | library VerifRegTypes { 28 | bytes constant ActorCode = hex"0006"; 29 | uint constant GetClaimsMethodNum = 2199871187; 30 | uint constant AddVerifierClientMethodNum = 3916220144; 31 | uint constant RemoveExpiredAllocationsMethodNum = 2421068268; 32 | uint constant ExtendClaimTermsMethodNum = 1752273514; 33 | uint constant RemoveExpiredClaimsMethodNum = 2873373899; 34 | uint constant UniversalReceiverMethodNum = 3726118371; 35 | 36 | struct GetClaimsParams { 37 | uint64 provider; 38 | uint64[] claim_ids; 39 | } 40 | struct GetClaimsReturn { 41 | CommonTypes.BatchReturn batch_info; 42 | CommonTypes.Claim[] claims; 43 | } 44 | struct AddVerifierClientParams { 45 | bytes addr; 46 | bytes allowance; 47 | } 48 | struct RemoveExpiredAllocationsParams { 49 | // Client for which to remove expired allocations. 50 | uint64 client; 51 | // Optional list of allocation IDs to attempt to remove. 52 | // Empty means remove all eligible expired allocations. 53 | uint64[] allocation_ids; 54 | } 55 | struct RemoveExpiredAllocationsReturn { 56 | // Ids of the allocations that were either specified by the caller or discovered to be expired. 57 | uint64[] considered; 58 | // Results for each processed allocation. 59 | CommonTypes.BatchReturn results; 60 | // The amount of datacap reclaimed for the client. 61 | BigInt datacap_recovered; 62 | } 63 | struct RemoveExpiredClaimsParams { 64 | // Provider to clean up (need not be the caller) 65 | uint64 provider; 66 | // Optional list of claim IDs to attempt to remove. 67 | // Empty means remove all eligible expired claims. 68 | uint64[] claim_ids; 69 | } 70 | struct RemoveExpiredClaimsReturn { 71 | // Ids of the claims that were either specified by the caller or discovered to be expired. 72 | uint64[] considered; 73 | // Results for each processed claim. 74 | CommonTypes.BatchReturn results; 75 | } 76 | struct ExtendClaimTermsParams { 77 | CommonTypes.ClaimTerm[] terms; 78 | } 79 | struct UniversalReceiverParams { 80 | /// Asset type 81 | uint32 type_; 82 | /// Payload corresponding to asset type 83 | bytes payload; 84 | } 85 | 86 | struct AllocationsResponse { 87 | // Result for each allocation request. 88 | CommonTypes.BatchReturn allocation_results; 89 | // Result for each extension request. 90 | CommonTypes.BatchReturn extension_results; 91 | // IDs of new allocations created. 92 | uint64[] new_allocations; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/filecoin-solidity/contracts/v0.8/utils/Misc.sol: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * (c) 2022 Zondax AG 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ********************************************************************************/ 16 | // DRAFT!! THIS CODE HAS NOT BEEN AUDITED - USE ONLY FOR PROTOTYPING 17 | 18 | // SPDX-License-Identifier: Apache-2.0 19 | pragma solidity >=0.4.25 <=0.8.17; 20 | 21 | library Misc { 22 | uint64 constant CBOR_CODEC = 0x71; 23 | uint64 constant NONE_CODEC = 0x00; 24 | 25 | function toUint256(bytes32 _bytes) internal pure returns (uint256 value) { 26 | return uint256(_bytes); 27 | } 28 | 29 | function toInt256(bytes32 _bytes) internal pure returns (int256 value) { 30 | return int256(uint256(_bytes)); 31 | } 32 | 33 | function toUint256(bytes memory _bytes, uint offset) internal pure returns (uint256 value) { 34 | assembly { 35 | value := mload(add(_bytes, offset)) 36 | } 37 | } 38 | 39 | function toInt256(bytes memory _bytes, uint offset) internal pure returns (int256 value) { 40 | return int256(toUint256(_bytes, offset)); 41 | } 42 | 43 | function toBytes(uint256 x) internal pure returns (bytes memory b) { 44 | b = new bytes(32); 45 | assembly { 46 | mstore(add(b, 32), x) 47 | } 48 | } 49 | 50 | function toBytes(int256 x) internal pure returns (bytes memory b) { 51 | b = new bytes(32); 52 | assembly { 53 | mstore(add(b, 32), x) 54 | } 55 | } 56 | 57 | function copy(uint src, uint dest, uint len) internal pure { 58 | // Copy word-length chunks while possible 59 | for (; len >= 32; len -= 32) { 60 | assembly { 61 | mstore(dest, mload(src)) 62 | } 63 | dest += 32; 64 | src += 32; 65 | } 66 | 67 | if (len == 0) return; 68 | 69 | // Copy remaining bytes 70 | uint mask = 256 ** (32 - len) - 1; 71 | assembly { 72 | let srcpart := and(mload(src), not(mask)) 73 | let destpart := and(mload(dest), mask) 74 | mstore(dest, or(destpart, srcpart)) 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/openzeppelin-contracts/contracts/utils/Strings.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol) 3 | 4 | pragma solidity ^0.8.0; 5 | 6 | import "./math/Math.sol"; 7 | import "./math/SignedMath.sol"; 8 | 9 | /** 10 | * @dev String operations. 11 | */ 12 | library Strings { 13 | bytes16 private constant _SYMBOLS = "0123456789abcdef"; 14 | uint8 private constant _ADDRESS_LENGTH = 20; 15 | 16 | /** 17 | * @dev Converts a `uint256` to its ASCII `string` decimal representation. 18 | */ 19 | function toString(uint256 value) internal pure returns (string memory) { 20 | unchecked { 21 | uint256 length = Math.log10(value) + 1; 22 | string memory buffer = new string(length); 23 | uint256 ptr; 24 | /// @solidity memory-safe-assembly 25 | assembly { 26 | ptr := add(buffer, add(32, length)) 27 | } 28 | while (true) { 29 | ptr--; 30 | /// @solidity memory-safe-assembly 31 | assembly { 32 | mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) 33 | } 34 | value /= 10; 35 | if (value == 0) break; 36 | } 37 | return buffer; 38 | } 39 | } 40 | 41 | /** 42 | * @dev Converts a `int256` to its ASCII `string` decimal representation. 43 | */ 44 | function toString(int256 value) internal pure returns (string memory) { 45 | return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value)))); 46 | } 47 | 48 | /** 49 | * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. 50 | */ 51 | function toHexString(uint256 value) internal pure returns (string memory) { 52 | unchecked { 53 | return toHexString(value, Math.log256(value) + 1); 54 | } 55 | } 56 | 57 | /** 58 | * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. 59 | */ 60 | function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { 61 | bytes memory buffer = new bytes(2 * length + 2); 62 | buffer[0] = "0"; 63 | buffer[1] = "x"; 64 | for (uint256 i = 2 * length + 1; i > 1; --i) { 65 | buffer[i] = _SYMBOLS[value & 0xf]; 66 | value >>= 4; 67 | } 68 | require(value == 0, "Strings: hex length insufficient"); 69 | return string(buffer); 70 | } 71 | 72 | /** 73 | * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. 74 | */ 75 | function toHexString(address addr) internal pure returns (string memory) { 76 | return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); 77 | } 78 | 79 | /** 80 | * @dev Returns true if the two strings are equal. 81 | */ 82 | function equal(string memory a, string memory b) internal pure returns (bool) { 83 | return keccak256(bytes(a)) == keccak256(bytes(b)); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) 3 | 4 | pragma solidity ^0.8.0; 5 | 6 | /** 7 | * @dev Standard signed math utilities missing in the Solidity language. 8 | */ 9 | library SignedMath { 10 | /** 11 | * @dev Returns the largest of two signed numbers. 12 | */ 13 | function max(int256 a, int256 b) internal pure returns (int256) { 14 | return a > b ? a : b; 15 | } 16 | 17 | /** 18 | * @dev Returns the smallest of two signed numbers. 19 | */ 20 | function min(int256 a, int256 b) internal pure returns (int256) { 21 | return a < b ? a : b; 22 | } 23 | 24 | /** 25 | * @dev Returns the average of two signed numbers without overflow. 26 | * The result is rounded towards zero. 27 | */ 28 | function average(int256 a, int256 b) internal pure returns (int256) { 29 | // Formula from the book "Hacker's Delight" 30 | int256 x = (a & b) + ((a ^ b) >> 1); 31 | return x + (int256(uint256(x) >> 255) & (a ^ b)); 32 | } 33 | 34 | /** 35 | * @dev Returns the absolute unsigned value of a signed value. 36 | */ 37 | function abs(int256 n) internal pure returns (uint256) { 38 | unchecked { 39 | // must be unchecked in order to support `n = type(int256).min` 40 | return uint256(n >= 0 ? n : -n); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/openzeppelin-contracts/contracts/utils/math/SignedSafeMath.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // OpenZeppelin Contracts v4.4.1 (utils/math/SignedSafeMath.sol) 3 | 4 | pragma solidity ^0.8.0; 5 | 6 | /** 7 | * @dev Wrappers over Solidity's arithmetic operations. 8 | * 9 | * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler 10 | * now has built in overflow checking. 11 | */ 12 | library SignedSafeMath { 13 | /** 14 | * @dev Returns the multiplication of two signed integers, reverting on 15 | * overflow. 16 | * 17 | * Counterpart to Solidity's `*` operator. 18 | * 19 | * Requirements: 20 | * 21 | * - Multiplication cannot overflow. 22 | */ 23 | function mul(int256 a, int256 b) internal pure returns (int256) { 24 | return a * b; 25 | } 26 | 27 | /** 28 | * @dev Returns the integer division of two signed integers. Reverts on 29 | * division by zero. The result is rounded towards zero. 30 | * 31 | * Counterpart to Solidity's `/` operator. 32 | * 33 | * Requirements: 34 | * 35 | * - The divisor cannot be zero. 36 | */ 37 | function div(int256 a, int256 b) internal pure returns (int256) { 38 | return a / b; 39 | } 40 | 41 | /** 42 | * @dev Returns the subtraction of two signed integers, reverting on 43 | * overflow. 44 | * 45 | * Counterpart to Solidity's `-` operator. 46 | * 47 | * Requirements: 48 | * 49 | * - Subtraction cannot overflow. 50 | */ 51 | function sub(int256 a, int256 b) internal pure returns (int256) { 52 | return a - b; 53 | } 54 | 55 | /** 56 | * @dev Returns the addition of two signed integers, reverting on 57 | * overflow. 58 | * 59 | * Counterpart to Solidity's `+` operator. 60 | * 61 | * Requirements: 62 | * 63 | * - Addition cannot overflow. 64 | */ 65 | function add(int256 a, int256 b) internal pure returns (int256) { 66 | return a + b; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | pull_request: 9 | branches: 10 | - "*" 11 | 12 | jobs: 13 | build: 14 | name: Unit Tests 15 | 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | - name: Install Node.js 21 | uses: actions/setup-node@v1 22 | with: 23 | node-version: 10.x 24 | - run: npm install -g yarn 25 | - run: yarn install --frozen-lockfile 26 | - run: yarn test 27 | 28 | solidity-lint: 29 | name: Linting 30 | 31 | runs-on: ubuntu-latest 32 | 33 | steps: 34 | - uses: actions/checkout@v2 35 | - name: Install Node.js 36 | uses: actions/setup-node@v1 37 | with: 38 | node-version: 10.x 39 | - run: npm install -g yarn 40 | - run: yarn install --frozen-lockfile 41 | - run: yarn lint:sol 42 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | build 3 | artifacts 4 | cache 5 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/.solhint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solhint:recommended", 3 | "plugins": [], 4 | "rules": { 5 | "quotes": ["error", "double"], 6 | "avoid-suicide": "warn", 7 | "avoid-sha3": "warn", 8 | "avoid-low-level-calls": "warn", 9 | "compiler-version": ["off", "^0.4.24"], 10 | "avoid-throw": false, 11 | "var-name-mixedcase": false, 12 | "mark-callable-contracts": false 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/.soliumignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | test -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/.soliumrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solium:recommended", 3 | "plugins": [ 4 | "security" 5 | ], 6 | "rules": { 7 | "security/no-inline-assembly": "off", 8 | "quotes": ["error", "double"], 9 | "indentation": ["error", 4] 10 | } 11 | } -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 SmartContract ChainLink, Ltd. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/README.md: -------------------------------------------------------------------------------- 1 | # solidity-cborutils [![GitHub workflow changelog](https://img.shields.io/github/workflow/status/smartcontractkit/solidity-cborutils/CI?style=flat-square&label=github-actions)](https://github.com/smartcontractkit/solidity-cborutils/actions?query=workflow%3ACI) 2 | Utilities for encoding [CBOR](http://cbor.io/) data in solidity 3 | 4 | ## Install 5 | 6 | ```bash 7 | $ git clone https://github.com/smartcontractkit/solidity-cborutils.git 8 | $ cd solidity-cborutils 9 | $ yarn install 10 | ``` 11 | ## Usage 12 | 13 | The Buffer library is not intended to be moved to storage. 14 | In order to persist a Buffer in storage from memory, 15 | you must manually copy each of its attributes to storage, 16 | and back out when moving it back to memory. 17 | 18 | ## Test 19 | 20 | ```bash 21 | $ yarn test 22 | ``` -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/hardhat.config.js: -------------------------------------------------------------------------------- 1 | require("@nomiclabs/hardhat-truffle5"); 2 | require("hardhat-gas-reporter"); 3 | 4 | // You need to export an object to set up your config 5 | // Go to https://hardhat.org/config/ to learn more 6 | 7 | /** 8 | * @type import('hardhat/config').HardhatUserConfig 9 | */ 10 | module.exports = { 11 | solidity: { 12 | version: "0.8.7", 13 | settings: { 14 | optimizer: { 15 | enabled: true, 16 | runs: 200 17 | } 18 | } 19 | }, 20 | gasReporter: { 21 | currency: "USD", 22 | gasPrice: 1 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@ensdomains/buffer": "0.1.0" 4 | }, 5 | "homepage": "https://github.com/smartcontractkit/solidity-cborutils", 6 | "license": "MIT", 7 | "name": "solidity-cborutils", 8 | "scripts": { 9 | "test": "hardhat test", 10 | "lint:sol": "solhint -f table **/*.sol" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "https://github.com/smartcontractkit/solidity-cborutils.git" 15 | }, 16 | "version": "2.0.0", 17 | "devDependencies": { 18 | "@nomiclabs/hardhat-truffle5": "^2.0.0", 19 | "@nomiclabs/hardhat-web3": "^2.0.0", 20 | "hardhat": "^2.0.6", 21 | "hardhat-gas-reporter": "^1.0.4", 22 | "cbor": ">=5.0.0", 23 | "solhint": "^3.3.6", 24 | "solium": "^1.2.5", 25 | "truffle": "^5", 26 | "truffle-assertions": "^0.9.2" 27 | }, 28 | "files": [ 29 | "contracts" 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/test/TestCBOR.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >= 0.4.19 < 0.9.0; 3 | 4 | import "../contracts/CBOR.sol"; 5 | 6 | contract TestCBOR { 7 | using CBOR for CBOR.CBORBuffer; 8 | 9 | function getTestData() public pure returns(bytes memory) { 10 | CBOR.CBORBuffer memory buf = CBOR.create(64); 11 | 12 | // Maps 13 | buf.startMap(); 14 | 15 | // Short strings 16 | buf.writeKVString("key1", "value1"); 17 | 18 | // Longer strings 19 | buf.writeKVString("long", "This string is longer than 24 characters."); 20 | 21 | // Bytes 22 | buf.writeKVBytes("bytes", bytes("Test")); 23 | 24 | // Bools, null, undefined 25 | buf.writeKVBool("true", true); 26 | buf.writeKVBool("false", false); 27 | buf.writeKVNull("null"); 28 | buf.writeKVUndefined("undefined"); 29 | 30 | // Arrays 31 | buf.writeKVArray("array"); 32 | buf.writeUInt64(0); 33 | buf.writeUInt64(1); 34 | buf.writeUInt64(23); 35 | buf.writeUInt64(24); 36 | 37 | // 2, 4, and 8 byte numbers. 38 | buf.writeUInt64(0x100); 39 | buf.writeUInt64(0x10000); 40 | buf.writeUInt64(0x100000000); 41 | 42 | // Negative numbers 43 | buf.writeInt64(-42); 44 | 45 | buf.endSequence(); 46 | buf.endSequence(); 47 | 48 | return buf.data(); 49 | } 50 | 51 | function getTestDataBigInt() public pure returns(bytes memory) { 52 | CBOR.CBORBuffer memory buf = CBOR.create(128); 53 | 54 | buf.startArray(); 55 | buf.writeInt256(type(int256).min); 56 | buf.writeInt256(type(int256).min+1); 57 | buf.writeInt256(type(int256).max-1); 58 | buf.writeInt256(type(int256).max); 59 | buf.writeInt64(type(int64).min); 60 | buf.writeInt64(type(int64).min+1); 61 | buf.writeInt64(type(int64).max-1); 62 | buf.writeInt64(type(int64).max); 63 | buf.endSequence(); 64 | 65 | return buf.data(); 66 | } 67 | 68 | function getTestDataBigUint() public pure returns(bytes memory) { 69 | CBOR.CBORBuffer memory buf = CBOR.create(128); 70 | 71 | buf.startArray(); 72 | buf.writeUInt256(type(uint256).min); 73 | buf.writeUInt256(type(uint256).min+1); 74 | buf.writeUInt256(type(uint256).max-1); 75 | buf.writeUInt256(type(uint256).max); 76 | buf.endSequence(); 77 | 78 | return buf.data(); 79 | } 80 | 81 | function getTestDataDefiniteLengthArray() public pure returns(bytes memory) { 82 | CBOR.CBORBuffer memory buf = CBOR.create(128); 83 | 84 | uint64 length = 1024; 85 | buf.startFixedArray(length); 86 | for (uint64 i = 0; i < length; i++) { 87 | buf.writeInt64(int64(i)); 88 | } 89 | 90 | return buf.data(); 91 | } 92 | 93 | function getTestDataDefiniteLengthMap() public pure returns(bytes memory) { 94 | CBOR.CBORBuffer memory buf = CBOR.create(128); 95 | 96 | buf.startFixedMap(3); 97 | buf.writeKVInt64("a", 100); 98 | buf.writeKVInt64("b", 200); 99 | buf.writeKVInt64("c", 300); 100 | 101 | return buf.data(); 102 | } 103 | 104 | function getTestDataInvalidCBOR() public pure returns(bytes memory) { 105 | CBOR.CBORBuffer memory buf = CBOR.create(128); 106 | 107 | buf.startArray(); 108 | buf.startArray(); 109 | buf.startArray(); 110 | buf.writeUInt256(type(uint256).min); 111 | buf.endSequence(); 112 | 113 | return buf.data(); // this would revert() 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /hardhat/contracts/lib/solidity-cborutils/test/testcbor.js: -------------------------------------------------------------------------------- 1 | const TestCBOR = artifacts.require('./TestCBOR.sol'); 2 | const cbor = require('cbor'); 3 | const truffleAssert = require('truffle-assertions'); 4 | 5 | contract('CBOR', function(accounts) { 6 | it('returns valid CBOR-encoded data', async function() { 7 | var test = await TestCBOR.new(); 8 | var result = new Buffer.from((await test.getTestData()).slice(2), 'hex'); 9 | var decoded = await cbor.decodeFirst(result); 10 | assert.deepEqual(decoded, { 11 | 'key1': 'value1', 12 | 'long': 'This string is longer than 24 characters.', 13 | 'bytes': Buffer.from('Test'), 14 | 'true': true, 15 | 'false': false, 16 | 'null': null, 17 | 'undefined': undefined, 18 | 'array': [0, 1, 23, 24, 0x100, 0x10000, 0x100000000, -42] 19 | }); 20 | }); 21 | 22 | it('returns > 8 byte int as bytes', async function() { 23 | var test = await TestCBOR.new(); 24 | var result = cbor.decodeFirstSync(new Buffer.from((await test.getTestDataBigInt()).slice(2), 'hex')); 25 | expect(result.map((x) => x.toFixed())).to.deep.equal([ 26 | '-57896044618658097711785492504343953926634992332820282019728792003956564819968', 27 | '-57896044618658097711785492504343953926634992332820282019728792003956564819967', 28 | '57896044618658097711785492504343953926634992332820282019728792003956564819966', 29 | '57896044618658097711785492504343953926634992332820282019728792003956564819967', 30 | '-9223372036854775808', 31 | '-9223372036854775807', 32 | '9223372036854775806', 33 | '9223372036854775807' 34 | ]); 35 | }); 36 | 37 | it('returns > 8 byte uint as bytes', async function() { 38 | var test = await TestCBOR.new(); 39 | var result = cbor.decodeFirstSync(new Buffer.from((await test.getTestDataBigUint()).slice(2), 'hex')); 40 | expect(result.map((x) => x.toFixed())).to.deep.equal([ 41 | '0', 42 | '1', 43 | '115792089237316195423570985008687907853269984665640564039457584007913129639934', 44 | '115792089237316195423570985008687907853269984665640564039457584007913129639935' 45 | ]); 46 | }); 47 | 48 | function toHexString(byteArray) { 49 | return Array.from(byteArray, function(byte) { 50 | return ('0' + (byte & 0xFF).toString(16)).slice(-2); 51 | }).join('') 52 | } 53 | 54 | it('returns definite-length encoded array', async function() { 55 | var test = await TestCBOR.new(); 56 | var expected = []; 57 | for (let x = 0; x < 1024; x++) { 58 | expected.push(x.toFixed()) 59 | } 60 | var result = cbor.decodeFirstSync(new Buffer.from((await test.getTestDataDefiniteLengthArray()).slice(2), 'hex')); 61 | expect(result.map((x) => x.toFixed())).to.deep.equal(expected); 62 | }); 63 | 64 | it('returns definite-length encoded map', async function() { 65 | var test = await TestCBOR.new(); 66 | var result = cbor.decodeFirstSync(new Buffer.from((await test.getTestDataDefiniteLengthMap()).slice(2), 'hex')); 67 | expect(result).to.deep.equal({ 68 | "a": 100, 69 | "b": 200, 70 | "c": 300 71 | }); 72 | }); 73 | 74 | it('reverts for invalid CBOR', async function() { 75 | var test = await TestCBOR.new(); 76 | await truffleAssert.reverts( 77 | test.getTestDataInvalidCBOR(), 78 | "Invalid CBOR" 79 | ); 80 | }); 81 | }); 82 | -------------------------------------------------------------------------------- /hardhat/deploy/00_deploy.js: -------------------------------------------------------------------------------- 1 | require("hardhat-deploy") 2 | require("hardhat-deploy-ethers") 3 | 4 | const ethers = require("ethers") 5 | const util = require("util") 6 | const request = util.promisify(require("request")) 7 | const { networkConfig } = require("../helper-hardhat-config") 8 | 9 | const DEPLOYER_PRIVATE_KEY = network.config.accounts[0] 10 | 11 | async function callRpc(method, params) { 12 | var options = { 13 | method: "POST", 14 | url: "https://api.hyperspace.node.glif.io/rpc/v1", 15 | // url: "http://localhost:1234/rpc/v0", 16 | headers: { 17 | "Content-Type": "application/json", 18 | }, 19 | body: JSON.stringify({ 20 | jsonrpc: "2.0", 21 | method: method, 22 | params: params, 23 | id: 1, 24 | }), 25 | } 26 | const res = await request(options) 27 | return JSON.parse(res.body).result 28 | } 29 | 30 | const deployer = new ethers.Wallet(DEPLOYER_PRIVATE_KEY) 31 | 32 | module.exports = async ({ deployments }) => { 33 | const { deploy } = deployments 34 | 35 | const priorityFee = await callRpc("eth_maxPriorityFeePerGas") 36 | 37 | // Wraps Hardhat's deploy, logging errors to console. 38 | const deployLogError = async (title, obj) => { 39 | let ret; 40 | try { 41 | ret = await deploy(title, obj); 42 | } catch (error) { 43 | console.log(error.toString()) 44 | process.exit(1) 45 | } 46 | return ret; 47 | } 48 | 49 | console.log("Wallet Ethereum Address:", deployer.address) 50 | 51 | await deployLogError("BountyFactory", { 52 | from: deployer.address, 53 | args: [], 54 | // maxPriorityFeePerGas to instruct hardhat to use EIP-1559 tx format 55 | maxPriorityFeePerGas: priorityFee, 56 | log: true, 57 | }) 58 | } 59 | 60 | -------------------------------------------------------------------------------- /hardhat/hardhat.config.js: -------------------------------------------------------------------------------- 1 | require("@nomicfoundation/hardhat-toolbox") 2 | require("hardhat-deploy") 3 | require("hardhat-deploy-ethers") 4 | require("./tasks") 5 | require("dotenv").config() 6 | 7 | const PRIVATE_KEY = process.env.PRIVATE_KEY 8 | /** @type import('hardhat/config').HardhatUserConfig */ 9 | module.exports = { 10 | solidity: "0.8.17", 11 | defaultNetwork: "hyperspace", 12 | networks: { 13 | hyperspace: { 14 | chainId: 3141, 15 | url: "https://api.hyperspace.node.glif.io/rpc/v1", 16 | accounts: [PRIVATE_KEY], 17 | }, 18 | }, 19 | paths: { 20 | sources: "./contracts", 21 | tests: "./test", 22 | cache: "./cache", 23 | artifacts: "./artifacts", 24 | }, 25 | mocha: { 26 | timeout: 1000000 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /hardhat/helper-hardhat-config.js: -------------------------------------------------------------------------------- 1 | const { ethers } = require("hardhat") 2 | 3 | const networkConfig = { 4 | 3141: { 5 | name: "hyperspace", 6 | tokenToBeMinted: 12000, 7 | }, 8 | } 9 | 10 | // const developmentChains = ["hardhat", "localhost"] 11 | 12 | module.exports = { 13 | networkConfig, 14 | // developmentChains, 15 | } 16 | -------------------------------------------------------------------------------- /hardhat/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "FVM-Hardhat-Kit", 3 | "version": "1.0.0", 4 | "description": "", 5 | "scripts": { 6 | "compile": "hardhat compile --force", 7 | "test": "hardhat test --network hardhat", 8 | "lint": "solhint 'contracts/*.sol'", 9 | "lint:fix": "solhint 'contracts/**/*.sol' --fix", 10 | "format": "prettier --write .", 11 | "coverage": "hardhat coverage --solcoverjs ./.solcover.js", 12 | "fuzzing": "docker run -it --rm -v $PWD:/src trailofbits/eth-security-toolbox", 13 | "setup": "bash scripts/setup.sh", 14 | "compile:circuits": "bash scripts/compile-circuits.sh", 15 | "version:fix": "node scripts/bump-solidity.js", 16 | "test:full": "yarn compile:circuits && yarn version:fix && yarn compile && yarn test" 17 | }, 18 | "license": "MIT", 19 | "devDependencies": { 20 | "@lighthouse-web3/sdk": "https://github.com/socathie/lighthouse-package.git#5d7d12401ef9e8b041b43a4b3958b53361205888", 21 | "@nomiclabs/hardhat-ethers": "npm:hardhat-deploy-ethers@^0.3.0-beta.13", 22 | "@nomiclabs/hardhat-etherscan": "^3.0.0", 23 | "@nomiclabs/hardhat-waffle": "^2.0.1", 24 | "@openzeppelin/contracts-upgradeable": "^4.8.1", 25 | "@types/chai": "^4.3.4", 26 | "@types/mocha": "^10.0.1", 27 | "@types/node": "^18.11.15", 28 | "base32.js": "^0.1.0", 29 | "chai": "^4.3.7", 30 | "circom_tester": "^0.0.19", 31 | "circomlib": "^2.0.5", 32 | "circomlib-ml": "^1.4.4", 33 | "ethereum-waffle": "^3.4.0", 34 | "ethers": "^5.5.1", 35 | "hardhat": "^2.11.2", 36 | "hardhat-contract-sizer": "^2.4.0", 37 | "hardhat-deploy": "^0.9.29", 38 | "hardhat-gas-reporter": "^1.0.7", 39 | "prettier": "^2.4.1", 40 | "prettier-plugin-solidity": "^1.0.0-beta.19", 41 | "snarkjs": "^0.5.0", 42 | "solhint": "^3.3.6", 43 | "solidity-coverage": "^0.7.13" 44 | }, 45 | "dependencies": { 46 | "@glif/filecoin-address": "^2.0.18", 47 | "@nomicfoundation/hardhat-chai-matchers": "^1.0.0", 48 | "@nomicfoundation/hardhat-network-helpers": "^1.0.0", 49 | "@nomicfoundation/hardhat-toolbox": "^2.0.0", 50 | "@openzeppelin/contracts": "^4.8.0", 51 | "@typechain/hardhat": "^6.1.2", 52 | "@zondax/filecoin-solidity": "^0.4.0-beta.1", 53 | "@zondax/filecoin-solidity-mock-api": "^0.2.0", 54 | "babel-eslint": "^10.1.0", 55 | "dotenv": "^10.0.0", 56 | "hardhat-deploy-ethers": "^0.3.0-beta.13", 57 | "ts-node": "^10.9.1", 58 | "typescript": "^4.9.4" 59 | }, 60 | "mocha": { 61 | "timeout": 10000000 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /hardhat/sample_calldata/claimBounty.json: -------------------------------------------------------------------------------- 1 | { 2 | "_input": ["5", "123456789"] 3 | } -------------------------------------------------------------------------------- /hardhat/sample_calldata/createBounty.json: -------------------------------------------------------------------------------- 1 | { 2 | "_name": "Bounty 1", 3 | "_description": "This is the first bounty", 4 | "_dataCID": "0x01551220dcd270805a674a9925641ff74edf2a2684bf457c4c9a586307cc335305fc7049" 5 | } -------------------------------------------------------------------------------- /hardhat/sample_calldata/submitBounty.json: -------------------------------------------------------------------------------- 1 | { 2 | "_zkeyCID": "0x00", 3 | "_circomCID": "0x00", 4 | "_verifier": "0xc711BaB4132EbDB5705beB50BCE62DdA48Cb7981", 5 | "_a": ["14172240044072774793844585011288753813118894742160860643730950726212424123780","11912368533860691264480209638201808334931774619536068060919407784292566921480"], 6 | "_b": [["11411885995891681770933762130690794053958102525507494895118843861091413717287","7514027573924792970367948792849771893519377166975206263298024904704725939985"],["5949228699588289784664917744103034867580028000018518102143426265478680408244","17579777658583367220167198373765417117912874207070998193384018557556893485922"]], 7 | "_c": ["3958312370074787282691478032108295537241594154559458688467820175581595625926","11807315541273777388714640803711076075133845622319539789595138441286554957180"], 8 | "_hashInputs": ["18383848545176925895656022227321129305","20470626237853968335761818307704869799","293522823212032739177258903802228976166","176451233477851303752071885142877827145"] 9 | } -------------------------------------------------------------------------------- /hardhat/scripts/bump-solidity.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | const solidityRegex = /pragma solidity \^\d+\.\d+\.\d+/ 3 | const inputRegex = /uint\[\d+\] memory input(?!;)/ 4 | const contentRegex = /proof\.C = Pairing\.G1Point\(c\[0\], c\[1\]\);([\s\S]*?)if \(verify\(inputValues, proof\) == 0\)/ 5 | 6 | let content = fs.readFileSync("./contracts/verifier.sol", { encoding: 'utf-8' }); 7 | let bumped = content.replace(solidityRegex, 'pragma solidity ^0.8.17'); 8 | bumped = bumped.replace(inputRegex, 'uint[] memory input'); 9 | bumped = bumped.replace(contentRegex, 'proof.C = Pairing.G1Point(c[0], c[1]);\n\n if (verify(input, proof) == 0)'); 10 | 11 | fs.writeFileSync("./contracts/verifier.sol", bumped); 12 | -------------------------------------------------------------------------------- /hardhat/scripts/compile-circuits.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #export NODE_OPTIONS="--max-old-space-size=16384" 4 | 5 | cd circuits 6 | mkdir -p build 7 | 8 | if [ -f ./powersOfTau28_hez_final_22.ptau ]; then 9 | echo "powersOfTau28_hez_final_22.ptau already exists. Skipping." 10 | else 11 | echo 'Downloading powersOfTau28_hez_final_22.ptau' 12 | wget https://hermez.s3-eu-west-1.amazonaws.com/powersOfTau28_hez_final_22.ptau 13 | fi 14 | 15 | echo "Compiling: circuit..." 16 | 17 | # compile circuit 18 | circom circuit.circom --r1cs --wasm --sym -o build 19 | snarkjs r1cs info build/circuit.r1cs 20 | 21 | # Start a new zkey and make a contribution 22 | snarkjs groth16 setup build/circuit.r1cs powersOfTau28_hez_final_22.ptau build/circuit_0000.zkey 23 | snarkjs zkey contribute build/circuit_0000.zkey build/circuit_final.zkey --name="1st Contributor Name" -v -e="random text" 24 | snarkjs zkey export verificationkey build/circuit_final.zkey build/verification_key.json 25 | 26 | # generate solidity contract 27 | snarkjs zkey export solidityverifier build/circuit_final.zkey ../contracts/verifier.sol -------------------------------------------------------------------------------- /hardhat/scripts/setup-circom.sh: -------------------------------------------------------------------------------- 1 | curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh 2 | 3 | git clone https://github.com/iden3/circom.git 4 | 5 | cd circom 6 | 7 | cargo build --release 8 | cargo install --path circom 9 | 10 | npm install -g snarkjs@latest 11 | -------------------------------------------------------------------------------- /hardhat/tasks/deal-rewarder/add-cid.js: -------------------------------------------------------------------------------- 1 | const util = require("util"); 2 | const request = util.promisify(require("request")); 3 | 4 | task( 5 | "add-cid", 6 | "Adds a CID (should be a piece ID) of data that you would like to put a storage bounty on." 7 | ) 8 | .addParam("contract", "The address of the FilecoinMarketConsumer contract") 9 | .addParam("cid", "The piece CID of the data you want to put up a bounty for") 10 | .addParam("size", "Size of the data you are putting a bounty on") 11 | .setAction(async (taskArgs) => { 12 | const contractAddr = taskArgs.contract 13 | const account = taskArgs.account 14 | const networkId = network.name 15 | console.log("Adding CID as a bounty", networkId) 16 | const DealRewarder = await ethers.getContractFactory("DealRewarder") 17 | 18 | //Get signer information 19 | const accounts = await ethers.getSigners() 20 | const signer = accounts[0] 21 | 22 | const priorityFee = await callRpc("eth_maxPriorityFeePerGas") 23 | 24 | async function callRpc(method, params) { 25 | var options = { 26 | method: "POST", 27 | url: "https://api.hyperspace.node.glif.io/rpc/v1", 28 | // url: "http://localhost:1234/rpc/v0", 29 | headers: { 30 | "Content-Type": "application/json", 31 | }, 32 | body: JSON.stringify({ 33 | jsonrpc: "2.0", 34 | method: method, 35 | params: params, 36 | id: 1, 37 | }), 38 | }; 39 | const res = await request(options); 40 | return JSON.parse(res.body).result; 41 | } 42 | 43 | 44 | const dealRewarder = new ethers.Contract(contractAddr, DealRewarder.interface, signer) 45 | const cid = taskArgs.cid 46 | const size = taskArgs.size 47 | await dealRewarder.addCID(cid, size, { 48 | gasLimit: 1000000000, 49 | maxPriorityFeePerGas: priorityFee 50 | }) 51 | console.log("Complete! Please wait about a minute before reading state!" ) 52 | }) 53 | 54 | module.exports = {} 55 | -------------------------------------------------------------------------------- /hardhat/tasks/filecoin-market-consumer/store-all.js: -------------------------------------------------------------------------------- 1 | const util = require("util"); 2 | const request = util.promisify(require("request")); 3 | 4 | task( 5 | "store-all", 6 | "Calls all the getter functions in the Filecoin Market API to store data from a specific deal." 7 | ) 8 | .addParam("contract", "The address of the FilecoinMarketConsumer contract") 9 | .addParam("dealid", "The id of the deal who's data you want to store") 10 | .setAction(async (taskArgs) => { 11 | const contractAddr = taskArgs.contract 12 | const account = taskArgs.account 13 | const networkId = network.name 14 | console.log("Storing data from FilecoinMarketAPI Getter Functions on network", networkId) 15 | const FilecoinMarketConsumer = await ethers.getContractFactory("FilecoinMarketConsumer") 16 | 17 | //Get signer information 18 | const accounts = await ethers.getSigners() 19 | const signer = accounts[0] 20 | 21 | const priorityFee = await callRpc("eth_maxPriorityFeePerGas") 22 | 23 | async function callRpc(method, params) { 24 | var options = { 25 | method: "POST", 26 | url: "https://api.hyperspace.node.glif.io/rpc/v1", 27 | // url: "http://localhost:1234/rpc/v0", 28 | headers: { 29 | "Content-Type": "application/json", 30 | }, 31 | body: JSON.stringify({ 32 | jsonrpc: "2.0", 33 | method: method, 34 | params: params, 35 | id: 1, 36 | }), 37 | }; 38 | const res = await request(options); 39 | return JSON.parse(res.body).result; 40 | } 41 | 42 | 43 | const filecoinMarketConsumer = new ethers.Contract(contractAddr, FilecoinMarketConsumer.interface, signer) 44 | const dealID = taskArgs.dealid 45 | await filecoinMarketConsumer.storeAll(dealID, { 46 | gasLimit: 1000000000, 47 | maxPriorityFeePerGas: priorityFee 48 | }) 49 | 50 | console.log("Complete! Please wait about a minute before reading state!" ) 51 | }) 52 | 53 | module.exports = {} 54 | -------------------------------------------------------------------------------- /hardhat/tasks/get-address.js: -------------------------------------------------------------------------------- 1 | const fa = require("@glif/filecoin-address"); 2 | const util = require("util"); 3 | const request = util.promisify(require("request")); 4 | 5 | task("get-address", "Gets Filecoin f4 address and corresponding Ethereum address.") 6 | .setAction(async (taskArgs) => { 7 | 8 | const DEPLOYER_PRIVATE_KEY = network.config.accounts[0] 9 | 10 | function hexToBytes(hex) { 11 | for (var bytes = [], c = 0; c < hex.length; c += 2) 12 | bytes.push(parseInt(hex.substr(c, 2), 16)); 13 | return new Uint8Array(bytes); 14 | } 15 | 16 | async function callRpc(method, params) { 17 | var options = { 18 | method: "POST", 19 | url: "https://api.hyperspace.node.glif.io/rpc/v1", 20 | // url: "http://localhost:1234/rpc/v0", 21 | headers: { 22 | "Content-Type": "application/json", 23 | }, 24 | body: JSON.stringify({ 25 | jsonrpc: "2.0", 26 | method: method, 27 | params: params, 28 | id: 1, 29 | }), 30 | }; 31 | const res = await request(options); 32 | return JSON.parse(res.body).result; 33 | } 34 | 35 | const deployer = new ethers.Wallet(DEPLOYER_PRIVATE_KEY); 36 | 37 | 38 | const pubKey = hexToBytes(deployer.publicKey.slice(2)); 39 | 40 | const priorityFee = await callRpc("eth_maxPriorityFeePerGas"); 41 | 42 | const f4Address = fa.newDelegatedEthAddress(deployer.address).toString(); 43 | const nonce = await callRpc("Filecoin.MpoolGetNonce", [f4Address]); 44 | console.log("Ethereum address (this addresss should work for most tools):", deployer.address); 45 | console.log("f4address (informational only):", f4Address); 46 | }) 47 | 48 | 49 | module.exports = {} -------------------------------------------------------------------------------- /hardhat/tasks/index.js: -------------------------------------------------------------------------------- 1 | exports.getBalance = require("./simple-coin/get-balance") 2 | exports.getAddress = require("./get-address") 3 | exports.sendCoin = require("./simple-coin/send-coin") 4 | exports.storeAll = require("./filecoin-market-consumer/store-all") 5 | exports.addCID = require("./deal-rewarder/add-cid") 6 | -------------------------------------------------------------------------------- /hardhat/tasks/simple-coin/get-balance.js: -------------------------------------------------------------------------------- 1 | task( 2 | "get-balance", 3 | "Calls the simple coin Contract to read the amount of SimpleCoins owned by the account." 4 | ) 5 | .addParam("contract", "The address the SimpleCoin contract") 6 | .addParam("account", "The address of the account you want the balance for") 7 | .setAction(async (taskArgs) => { 8 | const contractAddr = taskArgs.contract 9 | const account = taskArgs.account 10 | const networkId = network.name 11 | console.log("Reading SimpleCoin owned by", account, " on network ", networkId) 12 | const SimpleCoin = await ethers.getContractFactory("SimpleCoin") 13 | 14 | //Get signer information 15 | const accounts = await ethers.getSigners() 16 | const signer = accounts[0] 17 | 18 | const simpleCoinContract = new ethers.Contract(contractAddr, SimpleCoin.interface, signer) 19 | let result = BigInt(await simpleCoinContract.getBalance(account)).toString() 20 | console.log("Data is: ", result) 21 | let mintedToken = await simpleCoinContract.getMintedTokenBalance() 22 | console.log(`Total amount of Minted tokens is ${mintedToken}`) 23 | }) 24 | 25 | module.exports = {} 26 | -------------------------------------------------------------------------------- /hardhat/tasks/simple-coin/send-coin.js: -------------------------------------------------------------------------------- 1 | const util = require("util"); 2 | const request = util.promisify(require("request")); 3 | 4 | task("send-coin", "Sends SimpleCoin") 5 | .addParam("contractaddress", "The SimpleCoin address") 6 | .addParam("amount", "The amount to send") 7 | .addParam("toaccount", "The account to send to") 8 | .setAction(async (taskArgs) => { 9 | const contractAddr = taskArgs.contractaddress 10 | const amount = taskArgs.amount 11 | const toAccount = taskArgs.toaccount 12 | const networkId = network.name 13 | const SimpleCoin = await ethers.getContractFactory("SimpleCoin") 14 | //Get signer information 15 | const accounts = await ethers.getSigners() 16 | const signer = accounts[0] 17 | const priorityFee = await callRpc("eth_maxPriorityFeePerGas") 18 | 19 | async function callRpc(method, params) { 20 | var options = { 21 | method: "POST", 22 | url: "https://api.hyperspace.node.glif.io/rpc/v1", 23 | // url: "http://localhost:1234/rpc/v0", 24 | headers: { 25 | "Content-Type": "application/json", 26 | }, 27 | body: JSON.stringify({ 28 | jsonrpc: "2.0", 29 | method: method, 30 | params: params, 31 | id: 1, 32 | }), 33 | }; 34 | const res = await request(options); 35 | return JSON.parse(res.body).result; 36 | } 37 | 38 | const simpleCoinContract = new ethers.Contract(contractAddr, SimpleCoin.interface, signer) 39 | console.log("Sending:", amount, "SimpleCoin to", toAccount) 40 | await simpleCoinContract.sendCoin(toAccount, amount, { 41 | gasLimit: 1000000000, 42 | maxPriorityFeePerGas: priorityFee 43 | }) 44 | let result = BigInt(await simpleCoinContract.getBalance(toAccount)).toString() 45 | console.log("Total SimpleCoin at:", toAccount, "is", result) 46 | }) 47 | 48 | module.exports = {} -------------------------------------------------------------------------------- /hardhat/test/circuit.test.js: -------------------------------------------------------------------------------- 1 | const { expect, assert } = require("chai"); 2 | const { ethers } = require("hardhat"); 3 | const { groth16 } = require("snarkjs"); 4 | const wasm_tester = require("circom_tester").wasm; 5 | 6 | const fs = require("fs"); 7 | const crypto = require("crypto"); 8 | const base32 = require("base32.js"); 9 | 10 | const F1Field = require("ffjavascript").F1Field; 11 | const Scalar = require("ffjavascript").Scalar; 12 | exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); 13 | const Fr = new F1Field(exports.p); 14 | 15 | const json = require("./mnist_latest_input.json"); 16 | 17 | describe("SHA256 MNIST test", function () { 18 | let INPUT = {}; 19 | 20 | for (const [key, value] of Object.entries(json)) { 21 | if (Array.isArray(value)) { 22 | let tmpArray = []; 23 | for (let i = 0; i < value.flat().length; i++) { 24 | tmpArray.push(Fr.e(value.flat()[i])); 25 | } 26 | INPUT[key] = tmpArray; 27 | } else { 28 | INPUT[key] = Fr.e(value); 29 | } 30 | } 31 | 32 | let Verifier; 33 | let verifier; 34 | 35 | let digest; 36 | let a, b, c, Input; 37 | 38 | let digest2; 39 | 40 | before(async function () { 41 | Verifier = await ethers.getContractFactory("Verifier"); 42 | verifier = await Verifier.deploy(); 43 | await verifier.deployed(); 44 | 45 | const bytes = fs.readFileSync("assets/mnist_image.pgm"); 46 | 47 | const hash = crypto.createHash('sha256'); 48 | hash.update(bytes); 49 | 50 | digest = hash.digest('hex'); 51 | 52 | const binary = [...bytes].map((b) => b.toString(2).padStart(8, "0").split("")).flat(); 53 | // console.log(binary); 54 | 55 | INPUT["in"] = binary; 56 | 57 | // compute hash from salt and expected output 58 | INPUT["salt"] = "123456789"; 59 | 60 | const hash2 = crypto.createHash('sha256'); 61 | const preimage = (5).toString(16).padStart(64, "0") + (123456789).toString(16).padStart(64, "0"); 62 | hash2.update(preimage, 'hex'); 63 | digest2 = hash2.digest('hex'); 64 | // console.log(digest2); 65 | 66 | const { proof, publicSignals } = await groth16.fullProve(INPUT, "circuits/build/circuit_js/circuit.wasm","circuits/build/circuit_final.zkey"); 67 | 68 | const calldata = await groth16.exportSolidityCallData(proof, publicSignals); 69 | 70 | const argv = calldata.replace(/["[\]\s]/g, "").split(',').map(x => BigInt(x).toString()); 71 | 72 | a = [argv[0], argv[1]]; 73 | b = [[argv[2], argv[3]], [argv[4], argv[5]]]; 74 | c = [argv[6], argv[7]]; 75 | Input = argv.slice(8); 76 | }); 77 | 78 | it("Check circuit output", async () => { 79 | const circuit = await wasm_tester("circuits/circuit.circom"); 80 | // split digest into two slices and convert to BigNumber 81 | const digest11 = Fr.e(digest.slice(0, 32), 16); 82 | const digest12 = Fr.e(digest.slice(32, 64), 16); 83 | 84 | const digest21 = Fr.e(digest2.slice(0, 32), 16); 85 | const digest22 = Fr.e(digest2.slice(32, 64), 16); 86 | 87 | const witness = await circuit.calculateWitness(INPUT, true); 88 | 89 | assert(Fr.eq(Fr.e(witness[0]),Fr.e(1))); 90 | assert(Fr.eq(Fr.e(witness[1]), Fr.e(digest21))); 91 | assert(Fr.eq(Fr.e(witness[2]), Fr.e(digest22))); 92 | assert(Fr.eq(Fr.e(witness[3]), Fr.e(digest11))); 93 | assert(Fr.eq(Fr.e(witness[4]), Fr.e(digest12))); 94 | 95 | }); 96 | 97 | it("Verifier should return true for correct proofs", async function () { 98 | expect(await verifier.verifyProof(a, b, c, Input)).to.be.true; 99 | }); 100 | 101 | it("Verifier should return false for invalid proof", async function () { 102 | let a = [0, 0]; 103 | let b = [[0, 0], [0, 0]]; 104 | let c = [0, 0]; 105 | let d = [0, 0, 0, 0]; 106 | expect(await verifier.verifyProof(a, b, c, d)).to.be.false; 107 | }); 108 | 109 | let cidraw; 110 | 111 | it("CIDv1 should match that from IPFS", async function () { 112 | const cid_version = 1; 113 | const cid_codec = 85; // raw 0x55 114 | const hash_function_code = 18; // SHA-256 0x12 115 | const length = 32; 116 | 117 | cidraw = cid_version.toString(16).padStart(2, "0") + cid_codec.toString(16).padStart(2, "0") + hash_function_code.toString(16).padStart(2, "0") + length.toString(16).padStart(2, "0") + digest; 118 | const buf = Buffer.from(cidraw, 'hex'); 119 | 120 | const encoder = new base32.Encoder(); 121 | const cid = encoder.write(buf).finalize().toLowerCase(); 122 | 123 | expect("b"+cid).equal("bafkreig42jyiawthjkmskza765hn6krgqs7uk7cmtjmggb6mgnjql7dqje"); 124 | }); 125 | 126 | it("Payload CID should match that from Lotus", async function () { 127 | const buf = Buffer.from(cidraw, 'hex'); 128 | const cid = buf.toString('base64'); 129 | 130 | expect("m"+cid).equal("mAVUSINzScIBaZ0qZJWQf907fKiaEv0V8TJpYYwfMM1MF/HBJ"); 131 | }); 132 | 133 | it("CID contract should compute correct CID", async function () { 134 | const Cid = await ethers.getContractFactory("CID"); 135 | const cid = await Cid.deploy(verifier.address); 136 | 137 | expect(await cid.computeCID(a, b, c, Input)).equal("0x"+cidraw); 138 | }); 139 | 140 | }); 141 | -------------------------------------------------------------------------------- /hardhat/test/circuit2.test.js: -------------------------------------------------------------------------------- 1 | const { expect, assert } = require("chai"); 2 | const { ethers } = require("hardhat"); 3 | const { groth16 } = require("snarkjs"); 4 | const wasm_tester = require("circom_tester").wasm; 5 | 6 | const fs = require("fs"); 7 | const crypto = require("crypto"); 8 | 9 | const F1Field = require("ffjavascript").F1Field; 10 | const Scalar = require("ffjavascript").Scalar; 11 | exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); 12 | const Fr = new F1Field(exports.p); 13 | 14 | // TODO: write all the tests in this file 15 | 16 | describe("Mean+Variance test", function () { 17 | // let INPUT = {}; 18 | 19 | // for (const [key, value] of Object.entries(json)) { 20 | // if (Array.isArray(value)) { 21 | // let tmpArray = []; 22 | // for (let i = 0; i < value.flat().length; i++) { 23 | // tmpArray.push(Fr.e(value.flat()[i])); 24 | // } 25 | // INPUT[key] = tmpArray; 26 | // } else { 27 | // INPUT[key] = Fr.e(value); 28 | // } 29 | // } 30 | 31 | // let Verifier; 32 | // let verifier; 33 | 34 | // let bytes; 35 | 36 | // before(async function () { 37 | // Verifier = await ethers.getContractFactory("Verifier"); 38 | // verifier = await Verifier.deploy(); 39 | // await verifier.deployed(); 40 | 41 | // bytes = fs.readFileSync("assets/mnist_image.pgm"); 42 | 43 | // const binary = [...bytes].map((b) => b.toString(2).padStart(8, "0").split("")).flat(); 44 | // // console.log(binary); 45 | 46 | // INPUT["in"] = binary; 47 | // }); 48 | 49 | 50 | it("Circuit test", async () => { 51 | const circuit = await wasm_tester("circuits/circuit2.circom"); 52 | 53 | const INPUT = {"in": ["1", "2", "4", "5"]}; 54 | 55 | const witness = await circuit.calculateWitness(INPUT, true); 56 | console.log(witness); 57 | 58 | assert(Fr.eq(Fr.e(witness[0]),Fr.e(1))); 59 | assert(Fr.eq(Fr.e(witness[1]),Fr.e(3))); 60 | assert(Fr.eq(Fr.e(witness[2]),Fr.e(3))); 61 | }); 62 | 63 | // it("Verifier should return true for correct proofs", async function () { 64 | 65 | // const { proof, publicSignals } = await groth16.fullProve(INPUT, "circuits/build/circuit_js/circuit.wasm","circuits/build/circuit_final.zkey"); 66 | 67 | // const calldata = await groth16.exportSolidityCallData(proof, publicSignals); 68 | 69 | // const argv = calldata.replace(/["[\]\s]/g, "").split(',').map(x => BigInt(x).toString()); 70 | 71 | // const a = [argv[0], argv[1]]; 72 | // const b = [[argv[2], argv[3]], [argv[4], argv[5]]]; 73 | // const c = [argv[6], argv[7]]; 74 | // const Input = argv.slice(8); 75 | 76 | // expect(await verifier.verifyProof(a, b, c, Input)).to.be.true; 77 | // }); 78 | 79 | // it("Verifier should return false for invalid proof", async function () { 80 | // let a = [0, 0]; 81 | // let b = [[0, 0], [0, 0]]; 82 | // let c = [0, 0]; 83 | // let d = [0, 0, 0, 0]; 84 | // expect(await verifier.verifyProof(a, b, c, d)).to.be.false; 85 | // }); 86 | 87 | }); 88 | -------------------------------------------------------------------------------- /hardhat/test/factory.test.js: -------------------------------------------------------------------------------- 1 | const { expect } = require("chai"); 2 | const { ethers } = require("hardhat"); 3 | 4 | describe("BountyFactory test", function () { 5 | let factory; 6 | let Bounty; 7 | 8 | before(async function () { 9 | const BountyFactory = await ethers.getContractFactory("BountyFactory"); 10 | factory = await BountyFactory.deploy(); 11 | await factory.deployed(); 12 | 13 | Bounty = await ethers.getContractFactory("Bounty"); 14 | }); 15 | 16 | it("Should create a new bounty", async function () { 17 | const tx = await factory.createBounty( 18 | "Bounty 1", 19 | "This is the first bounty", 20 | 0x00, 21 | { value: ethers.utils.parseEther("1") } 22 | ); 23 | await tx.wait(); 24 | 25 | const bounty = await Bounty.attach(await factory.bounties(0)); 26 | 27 | expect(await bounty.owner()).to.equal(await ethers.provider.getSigner(0).getAddress()); 28 | expect(await ethers.provider.getBalance(bounty.address)).to.equal(ethers.utils.parseEther("1")); 29 | 30 | expect(await bounty.name()).to.equal("Bounty 1"); 31 | expect(await bounty.description()).to.equal("This is the first bounty"); 32 | expect(await bounty.dataCID()).to.equal("0x00"); 33 | expect(await factory.bountyCount()).to.equal(1); 34 | }); 35 | 36 | it("Should calculate future bounty address", async function () { 37 | const nonce = await ethers.provider.getTransactionCount(factory.address); 38 | const futureAddress = ethers.utils.getContractAddress({ from: factory.address, nonce: nonce }); 39 | 40 | await expect(factory.createBounty( 41 | "Bounty 2", 42 | "This is the second bounty", 43 | 0x00, 44 | { value: ethers.utils.parseEther("1") } 45 | )).to.emit(factory, "BountyCreated").withArgs(futureAddress); 46 | expect(await factory.bountyCount()).to.equal(2); 47 | }); 48 | }); -------------------------------------------------------------------------------- /hardhat/test/lighthouse.test.js: -------------------------------------------------------------------------------- 1 | const { expect } = require("chai"); 2 | const { ethers } = require("hardhat"); 3 | 4 | require("dotenv").config(); 5 | const lighthouse = require('@lighthouse-web3/sdk'); 6 | const { recoverShards } = require("@lighthouse-web3/kavach"); 7 | const fs = require("fs"); 8 | 9 | const privateKey = process.env.PRIVATE_KEY; 10 | const publicKey = process.env.PUBLIC_KEY; 11 | const privateKeyBob = process.env.PRIVATE_KEY_BOB; 12 | const publicKeyBob = process.env.PUBLIC_KEY_BOB; 13 | 14 | const apiKey = process.env.API_KEY; 15 | const path = "assets/mnist_image.pgm"; //Give path to the file 16 | 17 | const sign_auth_message = async (publicKey, privateKey) => { 18 | const provider = new ethers.providers.JsonRpcProvider(); 19 | const signer = new ethers.Wallet(privateKey, provider); 20 | const messageRequested = (await lighthouse.getAuthMessage(publicKey)).data.message; 21 | const signedMessage = await signer.signMessage(messageRequested); 22 | return (signedMessage) 23 | } 24 | 25 | describe("Lighthouse SDK test", function () { 26 | 27 | it("Should upload file in raw to lighthouse", async function () { 28 | const response = await lighthouse.uploadFileRaw(path, apiKey); 29 | expect(response.data.Name).equal("mnist_image.pgm"); 30 | expect(response.data.Hash).equal("bafkreig42jyiawthjkmskza765hn6krgqs7uk7cmtjmggb6mgnjql7dqje"); 31 | expect(response.data.Size).equal("797") 32 | }); 33 | 34 | it("Should upload file to lighthouse", async function () { 35 | const response = await lighthouse.upload(path, apiKey); 36 | expect(response.data.Name).equal("mnist_image.pgm"); 37 | expect(response.data.Hash).equal("QmevD3vQfg6Nf9RYWGCrNdfmT49BhLS714sxGkVifqmYg9"); 38 | expect(response.data.Size).equal("808") 39 | }); 40 | 41 | let cid; 42 | 43 | it("Should upload encrypted file to lighthouse", async function () { 44 | const signed_message = await sign_auth_message(publicKey, privateKey); 45 | 46 | const response = await lighthouse.uploadEncrypted( 47 | path, 48 | apiKey, 49 | publicKey, 50 | signed_message, 51 | ); 52 | 53 | expect(response.data.Name).equal("mnist_image.pgm"); 54 | // expect(response.data.Hash).equal("QmeakAMwVmYerw8DgZ5jyNHMV8G1fe6cNMvViezzM6bRqt"); 55 | expect(response.data.Size).equal("852"); 56 | 57 | cid = response.data.Hash; 58 | }); 59 | 60 | it("Should download decrypted file from lighthouse", async function () { 61 | const signed_message = await sign_auth_message(publicKey, privateKey); 62 | const fileEncryptionKey = await lighthouse.fetchEncryptionKey( 63 | cid, 64 | publicKey, 65 | signed_message 66 | ); 67 | const decrypted = await lighthouse.decryptFile( 68 | cid, 69 | fileEncryptionKey.data.key 70 | ); 71 | expect(decrypted.byteLength).equal(797); 72 | }); 73 | 74 | it("Should share private file with another user", async function () { 75 | const signed_message = await sign_auth_message(publicKey, privateKey); 76 | 77 | const response = await lighthouse.shareFile( 78 | publicKey, 79 | [publicKeyBob], 80 | cid, 81 | signed_message, 82 | ); 83 | 84 | expect(response.data.cid).equal(cid); 85 | expect(response.data.status).equal("Success"); 86 | expect(response.data.shareTo[0]).equal(publicKeyBob); 87 | }); 88 | 89 | it("Should download decrypted file from lighthouse shared with another user", async function () { 90 | const signed_message = await sign_auth_message(publicKeyBob, privateKeyBob); 91 | const fileEncryptionKey = await lighthouse.fetchEncryptionKey( 92 | cid, 93 | publicKeyBob, 94 | signed_message 95 | ); 96 | const decrypted = await lighthouse.decryptFile( 97 | cid, 98 | fileEncryptionKey.data.key 99 | ); 100 | expect(decrypted.byteLength).equal(797); 101 | }); 102 | 103 | it("Should revoke access to private file from another user", async function () { 104 | const signed_message = await sign_auth_message(publicKey, privateKey); 105 | 106 | const response = await lighthouse.revokeFileAccess( 107 | publicKey, 108 | [publicKeyBob], 109 | cid, 110 | signed_message, 111 | ); 112 | 113 | expect(response.data.cid).equal(cid); 114 | expect(response.data.status).equal("Success"); 115 | expect(response.data.revokeTo[0]).equal(publicKeyBob); 116 | 117 | }); 118 | 119 | it("Should not be able to download decrypted file from lighthouse shared with another user", async function () { 120 | const signed_message = await sign_auth_message(publicKeyBob, privateKeyBob); 121 | 122 | const { error, shards } = await recoverShards( 123 | publicKeyBob, 124 | cid, 125 | signed_message, 126 | 5 127 | ); 128 | 129 | expect(shards.length).equal(0); 130 | expect(error?.message).equal("you don't have access"); 131 | }); 132 | }); -------------------------------------------------------------------------------- /ui/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "next/babel", 5 | { 6 | "preset-react": { 7 | "runtime": "automatic", 8 | "importSource": "@emotion/react" 9 | } 10 | } 11 | ] 12 | ], 13 | "plugins": ["@emotion/babel-plugin"] 14 | } -------------------------------------------------------------------------------- /ui/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es2021: true, 5 | node: true, 6 | }, 7 | extends: [ 8 | "next/core-web-vitals", 9 | "prettier", 10 | "eslint:recommended", 11 | "plugin:@typescript-eslint/recommended", 12 | ], 13 | parser: "@typescript-eslint/parser", 14 | plugins: ["@typescript-eslint", "simple-import-sort"], 15 | root: true, 16 | rules: { 17 | //#region //*=========== Import Sort =========== 18 | "simple-import-sort/exports": "warn", 19 | "simple-import-sort/imports": [ 20 | "warn", 21 | { 22 | groups: [ 23 | // ext library & side effect imports 24 | ["^@?\\w", "^\\u0000"], 25 | // {s}css files 26 | ["^.+\\.s?css$"], 27 | // Lib and hooks 28 | ["^@/lib", "^@/hooks"], 29 | // static data 30 | ["^@/data"], 31 | // components 32 | ["^@/components", "^@/container"], 33 | // zustand store 34 | ["^@/store"], 35 | // Other imports 36 | ["^@/"], 37 | // relative paths up until 3 level 38 | [ 39 | "^\\./?$", 40 | "^\\.(?!/?$)", 41 | "^\\.\\./?$", 42 | "^\\.\\.(?!/?$)", 43 | "^\\.\\./\\.\\./?$", 44 | "^\\.\\./\\.\\.(?!/?$)", 45 | "^\\.\\./\\.\\./\\.\\./?$", 46 | "^\\.\\./\\.\\./\\.\\.(?!/?$)", 47 | ], 48 | ["^@/types"], 49 | // other that didnt fit in 50 | ["^"], 51 | ], 52 | }, 53 | ], 54 | //#endregion //*======== Import Sort =========== 55 | }, 56 | }; 57 | -------------------------------------------------------------------------------- /ui/README.md: -------------------------------------------------------------------------------- 1 | # ZKaggle UI 2 | 3 | 1️⃣ Build with Next.js, MUI and ethers.js.
4 | 2️⃣ Use rainbowkit and wagmi for easier integration.
5 | ❗️ we only support Filecoin and Filecoin Hyperspace testnet right now 6 | 7 | ## Deployment 8 | 9 | https://zkaggle.vercel.app/ 10 | 11 | ## Initialization 12 | 13 | ```bash 14 | nmp install 15 | ``` 16 | 17 | ```bash 18 | npm run dev 19 | ``` 20 | 21 | -------------------------------------------------------------------------------- /ui/base32.d.ts: -------------------------------------------------------------------------------- 1 | declare module "base32.js"; -------------------------------------------------------------------------------- /ui/components/FlowCard.tsx: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/react"; 2 | import { Chip } from "@mui/material"; 3 | import Box from "@mui/material/Box"; 4 | import Card from "@mui/material/Card"; 5 | import CardContent from "@mui/material/CardContent"; 6 | import { useTheme } from "@mui/material/styles"; 7 | import Typography from "@mui/material/Typography"; 8 | import { useRouter } from "next/router"; 9 | import * as React from "react"; 10 | 11 | import { Task } from "../typings"; 12 | 13 | interface FlowCardProps { 14 | task: Task; 15 | expanded: boolean; 16 | } 17 | 18 | export default function FlowCard({ task, expanded }: FlowCardProps) { 19 | const theme = useTheme(); 20 | const taskRouter = useRouter(); 21 | return ( 22 | 31 | taskRouter.push(`/tasks/${task.address}`)} 46 | > 47 | 48 |
54 | 68 | 85 |
86 | 87 | 88 | {task.name} 89 | 90 | {task.description} 91 |
92 |
93 |
94 | ); 95 | } 96 | -------------------------------------------------------------------------------- /ui/components/MainFlow.tsx: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/react"; 2 | import React from "react"; 3 | 4 | interface LayoutProps { 5 | children: React.ReactNode; 6 | } 7 | 8 | const MainFlow = ({ children }: LayoutProps) => { 9 | return ( 10 |
19 | {children} 20 |
21 | ); 22 | }; 23 | 24 | export default MainFlow; 25 | -------------------------------------------------------------------------------- /ui/components/NavBar.tsx: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/react"; 2 | import { Add } from "@mui/icons-material"; 3 | import StarIcon from "@mui/icons-material/Star"; 4 | import { Button } from "@mui/material"; 5 | import { NextComponentType } from "next"; 6 | import Link from "next/link"; 7 | 8 | import NavList from "./NavList"; 9 | 10 | const NavBar: NextComponentType = () => { 11 | return ( 12 |
29 | 39 | 45 |

56 | ZKaggle 57 |

58 | 59 | 60 | 61 | 74 | 75 | 76 |
77 | ); 78 | }; 79 | 80 | export default NavBar; 81 | -------------------------------------------------------------------------------- /ui/components/NavList.tsx: -------------------------------------------------------------------------------- 1 | import AccountCircleIcon from "@mui/icons-material/AccountCircle"; 2 | import AutoAwesomeMosaicIcon from "@mui/icons-material/AutoAwesomeMosaic"; 3 | import Box from "@mui/material/Box"; 4 | import List from "@mui/material/List"; 5 | import ListItem from "@mui/material/ListItem"; 6 | import ListItemButton from "@mui/material/ListItemButton"; 7 | import ListItemIcon from "@mui/material/ListItemIcon"; 8 | import ListItemText from "@mui/material/ListItemText"; 9 | import Link from "next/link"; 10 | import * as React from "react"; 11 | 12 | export default function NavList() { 13 | return ( 14 | 15 | 78 | 79 | ); 80 | } 81 | -------------------------------------------------------------------------------- /ui/components/TopBar.tsx: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/react"; 2 | import { ConnectButton } from "@rainbow-me/rainbowkit"; 3 | import { NextComponentType } from "next"; 4 | 5 | import SearchBar from "./TopSearchBar"; 6 | 7 | const TopBar: NextComponentType = () => { 8 | return ( 9 |
23 |
30 | 31 |
32 | 33 |
40 | 41 |
42 |
43 | ); 44 | }; 45 | 46 | export default TopBar; 47 | -------------------------------------------------------------------------------- /ui/components/TopSearchBar.tsx: -------------------------------------------------------------------------------- 1 | import MenuIcon from "@mui/icons-material/Menu"; 2 | import SearchIcon from "@mui/icons-material/Search"; 3 | import IconButton from "@mui/material/IconButton"; 4 | import InputBase from "@mui/material/InputBase"; 5 | import Paper from "@mui/material/Paper"; 6 | import * as React from "react"; 7 | 8 | export default function SearchBar() { 9 | return ( 10 | 20 | 21 | 22 | 23 | 28 | 29 | 30 | 31 | 32 | ); 33 | } 34 | -------------------------------------------------------------------------------- /ui/local-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | namespace NodeJS { 4 | interface ProcessEnv { 5 | NEXT_PUBLIC_LIGHTHOUSE_API_KEY: string; // this is the line you want 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /ui/next.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | module.exports = { 3 | reactStrictMode: true, 4 | } 5 | -------------------------------------------------------------------------------- /ui/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "dev": "next dev", 5 | "build": "next build", 6 | "start": "next start", 7 | "lint": "next lint" 8 | }, 9 | "dependencies": { 10 | "@emotion/react": "^11.10.5", 11 | "@emotion/styled": "^11.10.5", 12 | "@fontsource/roboto": "^4.5.8", 13 | "@lighthouse-web3/sdk": "github:socathie/lighthouse-package", 14 | "@mui/icons-material": "^5.11.0", 15 | "@mui/material": "^5.11.6", 16 | "@rainbow-me/rainbowkit": "^0.8.1", 17 | "base32.js": "^0.1.0", 18 | "dotenv": "^16.0.3", 19 | "ethers": "^5.7.2", 20 | "next": "latest", 21 | "react": "18.2.0", 22 | "react-dom": "18.2.0", 23 | "swr": "^2.0.1", 24 | "wagmi": "^0.9.6" 25 | }, 26 | "devDependencies": { 27 | "@typechain/ethers-v5": "^10.2.0", 28 | "@types/node": "18.11.3", 29 | "@types/react": "18.0.21", 30 | "@types/react-dom": "18.0.6", 31 | "@typescript-eslint/eslint-plugin": "^5.50.0", 32 | "@typescript-eslint/parser": "^5.50.0", 33 | "eslint": "^8.33.0", 34 | "eslint-config-next": "13.1.6", 35 | "eslint-config-prettier": "^8.6.0", 36 | "eslint-plugin-simple-import-sort": "^10.0.0", 37 | "typechain": "^8.1.1", 38 | "typescript": "^4.9.4" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ui/pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import { createTheme, ThemeOptions, ThemeProvider } from "@mui/material/styles"; 2 | import { 3 | getDefaultWallets, 4 | lightTheme, 5 | RainbowKitProvider, 6 | } from "@rainbow-me/rainbowkit"; 7 | import { jsonRpcProvider } from "@wagmi/core/providers/jsonRpc"; 8 | import type { AppProps } from "next/app"; 9 | import { configureChains, createClient, WagmiConfig } from "wagmi"; 10 | 11 | import "../styles/globals.css"; 12 | import "@fontsource/roboto/300.css"; 13 | import "@fontsource/roboto/400.css"; 14 | import "@fontsource/roboto/500.css"; 15 | import "@fontsource/roboto/700.css"; 16 | import "@rainbow-me/rainbowkit/styles.css"; 17 | 18 | import { filecoin, filecoinHyperspace } from "./api/chain.config"; 19 | 20 | const themeOptions: ThemeOptions = { 21 | palette: { 22 | primary: { 23 | main: "#fffbfe", 24 | contrastText: "#6750a4", 25 | dark: "#d1c4e9", 26 | }, 27 | secondary: { 28 | main: "#6750a4", 29 | contrastText: "#ffffff", 30 | dark: "#d1c4e9", 31 | }, 32 | background: { 33 | default: "#fffbfe", 34 | }, 35 | }, 36 | }; 37 | 38 | const theme = createTheme(themeOptions); 39 | 40 | const { chains, provider } = configureChains( 41 | [filecoinHyperspace, filecoin], 42 | [ 43 | // only endpoint that support Ethereum API requests 44 | jsonRpcProvider({ 45 | priority: 0, 46 | rpc: () => ({ 47 | http: `https://api.hyperspace.node.glif.io/rpc/v1`, 48 | }), 49 | }), 50 | // only support filecoin API requests 51 | jsonRpcProvider({ 52 | priority: 1, 53 | rpc: () => ({ 54 | http: `https://api.hyperspace.node.glif.io/`, 55 | }), 56 | }), 57 | jsonRpcProvider({ 58 | priority: 2, 59 | rpc: () => ({ 60 | http: `https://api.hyperspace.node.glif.io/rpc/v0`, 61 | }), 62 | }), 63 | ] 64 | ); 65 | 66 | const { connectors } = getDefaultWallets({ 67 | appName: "My RainbowKit App", 68 | chains, 69 | }); 70 | 71 | const wagmiClient = createClient({ 72 | autoConnect: true, 73 | connectors, 74 | provider, 75 | }); 76 | 77 | function MyApp({ Component, pageProps }: AppProps) { 78 | return ( 79 | 80 | 87 | 88 | 89 | 90 | 91 | 92 | ); 93 | } 94 | 95 | export default MyApp; 96 | -------------------------------------------------------------------------------- /ui/pages/api/chain.config.ts: -------------------------------------------------------------------------------- 1 | import { Chain } from "wagmi"; 2 | 3 | export const filecoin: Chain = { 4 | id: 314, 5 | name: "Filecoin Mainnet", 6 | network: "filecoin-mainnet", 7 | nativeCurrency: { 8 | decimals: 18, 9 | name: "filecoin", 10 | symbol: "FIL", 11 | }, 12 | rpcUrls: { 13 | default: { http: ["https://api.node.glif.io/"] }, 14 | public: { http: ["https://api.node.glif.io/"] }, 15 | }, 16 | blockExplorers: { 17 | default: { name: "Filfox", url: "https://filfox.info/en" }, 18 | filscan: { name: "Filscan", url: "https://filscan.io" }, 19 | filscout: { name: "Filscout", url: "https://filscout.io/en" }, 20 | }, 21 | }; 22 | 23 | export const filecoinHyperspace: Chain = { 24 | id: 3141, 25 | name: "Filecoin Hyperspace", 26 | network: "filecoin-hyperspace", 27 | nativeCurrency: { 28 | decimals: 18, 29 | name: "testnet filecoin", 30 | symbol: "tFIL", 31 | }, 32 | rpcUrls: { 33 | default: { http: ["https://api.hyperspace.node.glif.io/rpc/v1"] }, 34 | public: { http: ["https://api.hyperspace.node.glif.io/rpc/v1"] }, 35 | }, 36 | blockExplorers: { 37 | default: { name: "FilFox", url: "https://hyperspace.filfox.info/en" }, 38 | gilf: { name: "Gilf", url: "https://explorer.glif.io/?network=hyperspace" }, 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /ui/pages/api/hello.ts: -------------------------------------------------------------------------------- 1 | // Next.js API route support: https://nextjs.org/docs/api-routes/introduction 2 | import type { NextApiRequest, NextApiResponse } from 'next' 3 | 4 | type Data = { 5 | name: string 6 | } 7 | 8 | export default function handler( 9 | req: NextApiRequest, 10 | res: NextApiResponse 11 | ) { 12 | res.status(200).json({ name: 'John Doe' }) 13 | } 14 | -------------------------------------------------------------------------------- /ui/pages/create.tsx: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/react"; 2 | import { Step, StepLabel, Stepper } from "@mui/material"; 3 | import type { NextPage } from "next"; 4 | import React from "react"; 5 | import { useEffect } from "react"; 6 | import { useAccount } from "wagmi"; 7 | 8 | import InitializeStep from "../components/CreateBounty/InitializeStep"; 9 | import MainFlow from "../components/MainFlow"; 10 | import NavBar from "../components/NavBar"; 11 | import TopBar from "../components/TopBar"; 12 | 13 | const stepTitles = ["Initialize", "Processing", "Verify", "Check Out"]; 14 | 15 | const CreateBounty: NextPage = () => { 16 | const { isConnected } = useAccount(); 17 | const [connected, setConnected] = React.useState(false); 18 | 19 | useEffect(() => { 20 | setConnected(isConnected); 21 | }, [isConnected]); 22 | 23 | return ( 24 |
31 | 32 | 33 | 34 |
44 | 45 | {stepTitles.map((label) => ( 46 | 69 | {label} 70 | 71 | ))} 72 | 73 | {connected ? ( 74 | 75 | ) : ( 76 |

🚨Please connect your wallet to continue!

77 | )} 78 |
79 |
80 |
81 | ); 82 | }; 83 | 84 | export default CreateBounty; 85 | -------------------------------------------------------------------------------- /ui/pages/index.tsx: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/react"; 2 | import { Contract, ethers } from "ethers"; 3 | import Head from "next/head"; 4 | import { useRouter } from "next/router"; 5 | import React from "react"; 6 | import { useContractEvent } from "wagmi"; 7 | 8 | import Bounty from "../Bounty.json"; 9 | import BountyFactory from "../BountyFactory.json"; 10 | import FlowCard from "../components/FlowCard"; 11 | import MainFlow from "../components/MainFlow"; 12 | import NavBar from "../components/NavBar"; 13 | import TopBar from "../components/TopBar"; 14 | import { Task } from "../typings"; 15 | 16 | interface Props { 17 | tasks: [Task]; 18 | } 19 | 20 | const Home = ({ tasks }: Props) => { 21 | const taskRouter = useRouter(); 22 | 23 | useContractEvent({ 24 | address: BountyFactory.address, 25 | abi: BountyFactory.abi, 26 | eventName: "BountyCreated", 27 | listener() { 28 | console.log("BountyCreated"); 29 | taskRouter.replace(taskRouter.asPath); 30 | }, 31 | }); 32 | 33 | return ( 34 |
41 | 42 | ZKaggle 43 | 44 | 45 | 46 | 47 | 48 | 49 |
60 | {tasks.map((task, index) => ( 61 | 62 | ))} 63 |
64 |
65 |
66 | ); 67 | }; 68 | 69 | export default Home; 70 | 71 | export const getServerSideProps = async () => { 72 | const provider = new ethers.providers.JsonRpcProvider( 73 | "https://api.hyperspace.node.glif.io/rpc/v1" 74 | ); 75 | const bountyFactory = new Contract( 76 | BountyFactory.address, 77 | BountyFactory.abi, 78 | provider 79 | ); 80 | 81 | // fetching all task address by querying the factory contract 82 | const tasks = []; 83 | const count = Number(await bountyFactory?.bountyCount()); 84 | console.log("count", count); 85 | for (let i = count - 1; i >= 0; i--) { 86 | const address = await bountyFactory?.bounties(i); 87 | tasks.push({ 88 | address: address, 89 | } as Task); 90 | } 91 | 92 | // fetching all task details 93 | const results = tasks.map(async (task: Task) => { 94 | const bounty = new Contract(task.address, Bounty.abi, provider); 95 | task.isCompleted = await bounty?.isComplete(); 96 | task.name = await bounty?.name(); 97 | task.bountyAmount = ethers.utils.formatEther( 98 | await provider.getBalance(task?.address) 99 | ); 100 | task.description = await bounty?.description(); 101 | }); 102 | 103 | await Promise.all(results); 104 | return { 105 | props: { tasks }, 106 | }; 107 | }; 108 | -------------------------------------------------------------------------------- /ui/pages/myspace.tsx: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/react"; 2 | import { Contract, ethers } from "ethers"; 3 | import { useEffect, useState } from "react"; 4 | import { useAccount } from "wagmi"; 5 | 6 | import Bounty from "../Bounty.json"; 7 | import BountyFactory from "../BountyFactory.json"; 8 | import FlowCard from "../components/FlowCard"; 9 | import MainFlow from "../components/MainFlow"; 10 | import NavBar from "../components/NavBar"; 11 | import TopBar from "../components/TopBar"; 12 | import { Task } from "../typings"; 13 | 14 | interface Props { 15 | tasks: Task[]; 16 | } 17 | 18 | const MySpacePage = ({ tasks }: Props) => { 19 | const { address, isConnected } = useAccount(); 20 | const [connected, setConnected] = useState(false); 21 | 22 | useEffect(() => { 23 | setConnected(isConnected); 24 | }, [isConnected]); 25 | 26 | return ( 27 |
34 | 35 | 36 | 37 |
48 | {/* if connected, only show tasks that are created by the connected 49 | address this filter can only be done on client side */} 50 | {connected ? ( 51 | tasks 52 | .filter((task) => task.bountyOwner === address) 53 | .map((task, index) => ( 54 | 55 | )) 56 | ) : ( 57 |

🚨Please connect your wallet to continue!

58 | )} 59 |
60 |
61 |
62 | ); 63 | }; 64 | 65 | export default MySpacePage; 66 | 67 | export const getServerSideProps = async () => { 68 | const provider = new ethers.providers.JsonRpcProvider( 69 | "https://api.hyperspace.node.glif.io/rpc/v1" 70 | ); 71 | const bountyFactory = new Contract( 72 | BountyFactory.address, 73 | BountyFactory.abi, 74 | provider 75 | ); 76 | 77 | // fetching all task address by querying the factory contract 78 | const tasks = []; 79 | const count = Number(await bountyFactory?.bountyCount()); 80 | console.log("count", count); 81 | for (let i = count - 1; i >= 0; i--) { 82 | const address = await bountyFactory?.bounties(i); 83 | tasks.push({ 84 | address: address, 85 | } as Task); 86 | } 87 | 88 | // fetching all task details 89 | const results = tasks.map(async (task: Task) => { 90 | const bounty = new Contract(task.address, Bounty.abi, provider); 91 | task.isCompleted = await bounty?.isComplete(); 92 | task.name = await bounty?.name(); 93 | task.bountyAmount = ethers.utils.formatEther( 94 | await provider.getBalance(task?.address) 95 | ); 96 | task.description = await bounty?.description(); 97 | task.bountyOwner = await bounty?.owner(); 98 | }); 99 | 100 | await Promise.all(results); 101 | return { 102 | props: { tasks }, 103 | }; 104 | }; 105 | -------------------------------------------------------------------------------- /ui/pages/submissions.tsx: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/react"; 2 | import { Contract, ethers } from "ethers"; 3 | import { useEffect, useState } from "react"; 4 | import { useAccount } from "wagmi"; 5 | 6 | import Bounty from "../Bounty.json"; 7 | import BountyFactory from "../BountyFactory.json"; 8 | import FlowCard from "../components/FlowCard"; 9 | import MainFlow from "../components/MainFlow"; 10 | import NavBar from "../components/NavBar"; 11 | import TopBar from "../components/TopBar"; 12 | import { Task } from "../typings"; 13 | 14 | interface Props { 15 | tasks: Task[]; 16 | } 17 | 18 | const SubmissionsPage = ({ tasks }: Props) => { 19 | const { address, isConnected } = useAccount(); 20 | const [connected, setConnected] = useState(false); 21 | 22 | useEffect(() => { 23 | setConnected(isConnected); 24 | }, [isConnected]); 25 | 26 | return ( 27 |
34 | 35 | 36 | 37 |
48 | {/* if connected, only show tasks that are created by the connected 49 | address this filter can only be done on client side */} 50 | {connected ? ( 51 | tasks 52 | .filter((task) => task.bountyHunter === address) 53 | .map((task, index) => ( 54 | 55 | )) 56 | ) : ( 57 |

🚨Please connect your wallet to continue!

58 | )} 59 |
60 |
61 |
62 | ); 63 | }; 64 | 65 | export default SubmissionsPage; 66 | 67 | export const getServerSideProps = async () => { 68 | const provider = new ethers.providers.JsonRpcProvider( 69 | "https://api.hyperspace.node.glif.io/rpc/v1" 70 | ); 71 | const bountyFactory = new Contract( 72 | BountyFactory.address, 73 | BountyFactory.abi, 74 | provider 75 | ); 76 | 77 | // fetching all task address by querying the factory contract 78 | const tasks = []; 79 | const count = Number(await bountyFactory?.bountyCount()); 80 | console.log("count", count); 81 | for (let i = count - 1; i >= 0; i--) { 82 | const address = await bountyFactory?.bounties(i); 83 | tasks.push({ 84 | address: address, 85 | } as Task); 86 | } 87 | 88 | // fetching all task details 89 | const results = tasks.map(async (task: Task) => { 90 | const bounty = new Contract(task.address, Bounty.abi, provider); 91 | task.isCompleted = await bounty?.isComplete(); 92 | task.name = await bounty?.name(); 93 | task.bountyAmount = ethers.utils.formatEther( 94 | await provider.getBalance(task?.address) 95 | ); 96 | task.description = await bounty?.description(); 97 | task.bountyHunter = await bounty?.bountyHunter(); 98 | }); 99 | 100 | await Promise.all(results); 101 | return { 102 | props: { tasks }, 103 | }; 104 | }; 105 | -------------------------------------------------------------------------------- /ui/public/staricon.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ui/styles/globals.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | padding: 0; 4 | margin: 0; 5 | font-family: Roboto, -apple-system, BlinkMacSystemFont, Segoe UI, Oxygen, 6 | Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; 7 | } 8 | 9 | a { 10 | color: inherit; 11 | text-decoration: none; 12 | } 13 | 14 | * { 15 | box-sizing: border-box; 16 | } 17 | 18 | h1 { 19 | margin-top: 40px; 20 | margin-bottom: 0; 21 | font-weight: 200; 22 | } 23 | 24 | h2 { 25 | margin-top: 40px; 26 | margin-bottom: 20px; 27 | font-weight: 200; 28 | } 29 | 30 | h5 { 31 | margin-top: 10px; 32 | margin-bottom: 0; 33 | font-weight: 200; 34 | } 35 | 36 | .Mui-completed, .Mui-active{ 37 | color: #6750A4 !important; 38 | } 39 | 40 | .MuiStepIcon-text{ 41 | color: white; 42 | fill: white; 43 | } 44 | -------------------------------------------------------------------------------- /ui/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "preserve", 16 | "incremental": true 17 | }, 18 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "base32.d.ts"], 19 | "exclude": ["node_modules"] 20 | } 21 | -------------------------------------------------------------------------------- /ui/typings.d.ts: -------------------------------------------------------------------------------- 1 | export interface Task { 2 | address: string; 3 | 4 | bountyAmount: string; 5 | bountyOwner: string; 6 | 7 | completedStep: number; 8 | 9 | // tx 1 10 | name: string; 11 | description: string; 12 | dataCID: string; 13 | 14 | // tx 2 15 | bountyHunter: string; 16 | zkeyCID: string; 17 | circomCID: string; 18 | verifierCID: string; 19 | verifier: string; 20 | 21 | // a: [string, string]; 22 | // b: [[string, string], [string, string]]; 23 | // c: [string, string]; 24 | hashedInput: string; 25 | 26 | // tx 3 27 | isCompleted: boolean; 28 | 29 | // tx 4 30 | input0: string; 31 | input1: string; 32 | } 33 | -------------------------------------------------------------------------------- /ui/utils.tsx: -------------------------------------------------------------------------------- 1 | export function formatBytes(bytes: number, decimals = 2) { 2 | if (!+bytes) return "0 Bytes"; 3 | 4 | const k = 1024; 5 | const dm = decimals < 0 ? 0 : decimals; 6 | const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; 7 | 8 | const i = Math.floor(Math.log(bytes) / Math.log(k)); 9 | 10 | return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`; 11 | } 12 | --------------------------------------------------------------------------------