├── .env.example ├── .gitignore ├── .gitmodules ├── .npmignore ├── .prettierignore ├── .prettierrc ├── .solcover.js ├── .solhint.json ├── .solhintignore ├── LICENSE ├── README.md ├── contracts └── DealClient.sol ├── deploy └── 0_deploy.js ├── frontend ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src │ ├── App.css │ ├── App.jsx │ ├── assets │ └── logo.svg │ ├── components │ └── Inputs.js │ ├── contracts │ └── DealClient.json │ ├── index.css │ ├── index.js │ ├── reportWebVitals.js │ └── setupTests.js ├── hardhat.config.js ├── helper-hardhat-config.js ├── package.json ├── tasks ├── cid-to-bytes.js ├── deal-client │ ├── get-deal-proposal.js │ └── make-deal-proposal.js ├── get-address.js └── index.js └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | PRIVATE_KEY="abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc1" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # vscode 2 | .vscode 3 | 4 | # hardhat 5 | artifacts 6 | cache 7 | deployments 8 | node_modules 9 | coverage 10 | coverage.json 11 | 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 | gas-report.txt 102 | 103 | contracts/test/fuzzing/crytic-export -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "generate-car"] 2 | path = generate-car 3 | url = https://github.com/tech-greedy/generate-car 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | hardhat.config.js 2 | scripts 3 | test 4 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "useTabs": false, 4 | "semi": false, 5 | "singleQuote": false, 6 | "printWidth": 100 7 | } 8 | -------------------------------------------------------------------------------- /.solcover.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | skipFiles: ['test/fuzzing/KeepersCounterEchidnaTest.sol', 'test/LinkToken.sol', 'test/MockOracle.sol', 'test/MockV3Aggregator.sol', 'test/VRFCoordinatorV2Mock.sol'], 3 | }; -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.solhintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | contracts/test -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | Welcome to the fevm deal making kit! This kit has several tools to help enable you make storage deals on the Filecoin network via Solidity smart contracts. This kit assumes some knowledge at interacting with the Filecoin Virtual Machine (FVM). If you are new to the FVM, you may want to start with these starter kits instead: 3 | 4 | * [FEVM Hardhat Starter Kit](https://github.com/filecoin-project/fevm-hardhat-kit) 5 | * [FEVM Foundry Starter Kit](https://github.com/filecoin-project/fevm-foundry-kit) 6 | 7 | Also have a look at this accompanying [Quickstart](https://pl-strflt.notion.site/Data-FVM-Getting-Started-with-the-Client-Contract-745e307f48a147148293aebace746c7f) that dives a bit deeper with the resources described in this repo. 8 | 9 | The whole flow for deal making (from file upload to making a deal on FVM) is described here: 10 | 11 | ![shapes (6) copy](https://user-images.githubusercontent.com/782153/224225887-1a546129-62b5-41e8-b98d-eb52fe35fac8.png) 12 | 13 | ## Table of Contents 14 | + [Using this Repo](#using-this-repo) 15 | + [Data Prep](#1-data-prep) 16 | - [Option A: Use FVM Tooling](#option-a-use-fvm-tooling) 17 | - [Option B: Use the generate-car tool locally](#option-b-use-the-generate-car-tool-locally) 18 | + [Creating a Deal Proposal Payload](#2-creating-a-deal-proposal-payload) 19 | + [Calling the makeDealProposal method](#3-calling-the-makedealproposal-method) 20 | - [Option A: Use the dapp frontend](#option-a-use-the-dapp-frontend) 21 | - [Option B: Use the hardhat task](#option-b-use-the-hardhat-task) 22 | + [Boost Provider Picks up Deal](#4-boost-provider-picks-up-deal) 23 | 24 | ## Using this Repo 25 | 26 | Get started by typing in the following commands into your terminal/command prompt. This will clone the repo and all submodules, switch into the hardhat kit, and install packages: 27 | 28 | ```bash 29 | git clone https://github.com/filecoin-project/fvm-starter-kit-deal-making.git 30 | cd fvm-starter-kit-deal-making 31 | yarn install 32 | ``` 33 | 34 | Add your private key as an environment variable by running this command, replacing the text *abcdef* with your private key: 35 | 36 | ```bash 37 | export PRIVATE_KEY='abcdef' 38 | ``` 39 | 40 | Now type in the following command to deploy the contracts in the kit: 41 | 42 | ```bash 43 | yarn hardhat deploy 44 | ``` 45 | Make sure to record the address of where the `DealClient.sol` is deployed for later use. 46 | 47 | Now, edit the contract address for your frontend in [Input.js here](https://github.com/filecoin-project/fvm-starter-kit-deal-making/blob/main/frontend/src/components/Inputs.js#L11). 48 | 49 | ## (1) Data Prep 50 | 51 | Files need to be converted and prepped for storage on Filecoin. 52 | 53 | For any file you want to upload you need to convert it to a .car file and obtain four pieces of information about this file. These are: 54 | 55 | * An https URL to the .car file so storage providers can download it. This is the `carLink`. 56 | 57 | * The size of the piece in bytes. This is the `piecesize`. 58 | 59 | * The DataCID of the original raw file. This is essentially a hash that represents the original file. This is known as the `commD` or sometimes the `label`. 60 | 61 | * The size of the CAR file that represents the file in bytes. This is known as the `carSize`. 62 | 63 | * The PieceCID of the file. This is essentially a hash that represents the .car file. This is also known as the `commP`. 64 | 65 | 66 | ### Option A: Use FVM Tooling 67 | 68 | One option is to go to the [FVM Data Depot](https://data.lighthouse.storage/), upload the file you want to store on Filecoin, and the tool will generate all the information we discussed. 69 | 70 | **Note**: The data depot is only meant as an intermediate step to get your data to the storage providers. It will hold your files for 30 days before the link to your car file expires. After this, storage providers will not be able to retrieve your file to store it more permanentaly. 71 | 72 | ### Option B: Use the generate-car tool locally 73 | 74 | Another option is to use the [`generate-car`](https://github.com/tech-greedy/generate-car) tool, written in the language Go, and included as a submodule within this repo. 75 | 76 | If you are currently in this repo's directory, run these commands to switch into the proper directory and build the tool: 77 | 78 | ```bash 79 | cd generate-car 80 | make build 81 | ``` 82 | 83 | Now you can create a directory for the tools output and use the utility as follows: 84 | 85 | ```bash 86 | $ mkdir out 87 | $ ./generate-car --single -i /path/to/file/A.txt -o out -p /path/to/file/ 88 | ``` 89 | 90 | You should get a json file that looks like this: 91 | ```json 92 | {"Ipld":{"Name":"","Hash":"bafybeieawlmgtnb455ynra7kxyzipvhfxrms5yeuylr4w7dbpx7w4e6tqe","Size":0,"Link":[{"Name":"shapes.png","Hash":"bafybeigeisbcozxm7xyuf6vviijjg5fm2ptha2ciuyvjfdaedunhdfwsee","Size":1687130,"Link":null}]},"DataCid":"bafybeieawlmgtnb455ynra7kxyzipvhfxrms5yeuylr4w7dbpx7w4e6tqe","PieceCid":"baga6ea4seaqesm5ghdwocotmdavlrrzssfl33xho6xtrr5grwyi5gj3vtairaoq","PieceSize":2097152,"CidMap":{"":{"IsDir":true,"Cid":"bafybeieawlmgtnb455ynra7kxyzipvhfxrms5yeuylr4w7dbpx7w4e6tqe"},"shapes.png":{"IsDir":false,"Cid":"bafybeigeisbcozxm7xyuf6vviijjg5fm2ptha2ciuyvjfdaedunhdfwsee"}}} 93 | ``` 94 | 95 | Note that this results in a `PieceSize`, `PieceCID`, `DataCID` and `Size` is the `CarSize`. 96 | 97 | As a result of the above, you should also get a `.car` file. You can upload this file to any http endpoint of your choice. Any example is using [Web3.storage](https://web3.storage/). Sign in, upload the `.car` file, click on the CID column, and once you get to the IPFS portal right click on the `Copy Link Location`. You should get a link that looks something like this: https://bafybeif74tokne4wvxsrcsxh6dhrzv6ys7mtifhwzaen7jfjuvltean32a.ipfs.w3s.link/ipfs/bafybeif74tokne4wvxsrcsxh6dhrzv6ys7mtifhwzaen7jfjuvltean32a/baga6ea4seaqesm5ghdwocotmdavlrrzssfl33xho6xtrr5grwyi5gj3vtairaoq.car 98 | 99 | This link is `carLink` for your file. 100 | 101 | 102 | ## (2) Creating a Deal Proposal Payload 103 | 104 | Because of the way the client contract is set up, you need to prepare a deal proposal payload and call `makeDealProposal` with this payload. The payload consists of these solidity structs (which can be found [here in the Client Contract](https://github.com/filecoin-project/fevm-hardhat-kit/blob/main/contracts/basic-deal-client/DealClient.sol#L38)): 105 | 106 | 107 | Here is an example with these fields initialized: 108 | 109 | ```javascript 110 | const DealRequestStruct = [ 111 | "baga6ea4seaqesm5ghdwocotmdavlrrzssfl33xho6xtrr5grwyi5gj3vtairaoq", // pieceCID (Generated in previous step) 112 | 262144, // pieceSize (Generated in previous step) 113 | false, // verifiedDeal (whether the deal has datacap or not) 114 | "baga6ea4seaqesm5ghdwocotmdavlrrzssfl33xho6xtrr5grwyi5gj3vtairaoq", // DataCID (generated in previous step) 115 | 520000, // startEpoch (when you want the storage to start) 116 | 1555200, // endEpoch (when you want the storage to end) 117 | 0, // storagePricePerEpoch (how much attoFIL per GiB per 30s you are offering for this deal, set to 0 for a free deal) 118 | 0, // providerCollateral (how much collateral the provider must put up for the deal) 119 | 0, // clientCollateral (how much collateral you, the client, must put up for the deal) 120 | 1, // extraParamsVersion (set to 1) 121 | extraParamsV1, // see below 122 | ]; 123 | 124 | const extraParamsV1 = [ 125 | "https://bafybeif74tokne4wvxsrcsxh6dhrzv6ys7mtifhwzaen7jfjuvltean32a.ipfs.w3s.link/ipfs/bafybeif74tokne4wvxsrcsxh6dhrzv6ys7mtifhwzaen7jfjuvltean32a/baga6ea4seaqesm5ghdwocotmdavlrrzssfl33xho6xtrr5grwyi5gj3vtairaoq.car", // carLink (Generated in previous step) 126 | 236445, // carSize (Generated in previous step). 127 | false, // skipIpniAnnounce (whether or not the deal should be announced to IPNI indexers, set to false) 128 | false, // removeUnsealedCopy (whether or not the storage provider should remove an unsealed copy. Set to false) 129 | ]; 130 | ``` 131 | 132 | ## (3) Calling the makeDealProposal method 133 | 134 | 135 | 136 | ### Option A: Use the dapp frontend 137 | 138 | Take the four outputs of part (I) and put each into the four fields of the [frontend in this repo](https://github.com/filecoin-project/fvm-starter-kit-deal-making/tree/main/frontend). 139 | 140 | Once the deal handshake is completed (described more in part III), you should be able to see the deal ID for this transaction in Filfox on the frontend. Here is a previous example of a DealID submitted through the frontend: https://calibration.filfox.info/en/deal/1016 141 | 142 | ### Option B: Use the hardhat task 143 | 144 | You can also call the method by running the make-deal-proposal task. Below is an example of how to run the task. Make sure to replace any values with your own. 145 | 146 | ```bash 147 | yarn hardhat make-deal-proposal --contract 0xD4aac4D8fBc7575bDf5C19f900634d6c61a00a79 --piece-cid baga6ea4seaqayn6kwvhnajfgec2qakj7vb5aeqisbbnojunowdyapkdfcyhzcpy --piece-size 262144 --verified-deal false --label "baga6ea4seaqayn6kwvhnajfgec2qakj7vb5aeqisbbnojunowdyapkdfcyhzcpy" --start-epoch 520000 --end-epoch 1555200 --storage-price-per-epoch 0 --provider-collateral 0 --client-collateral 0 --extra-params-version 1 --location-ref "https://data-depot.lighthouse.storage/api/download/download_car?fileId=005b377e-89a6-44c6-aa04-871509019bec.car" --car-size 194875 --skip-ipni-announce false --remove-unsealed-copy false 148 | ``` 149 | 150 | ## (4) Boost Provider Picks up Deal 151 | 152 | The Client Contract (CC) is built to interact with Boost SPs and generate deals on behalf of a client, entirely on-chain. 153 | 154 | The CC primarily interacts with the Boost SPs through an event known as `DealProposalCreate`, which looks like this: 155 | 156 | ```solidity 157 | event DealProposalCreate( 158 | bytes32 indexed id, 159 | uint64 size, 160 | bool indexed verified, 161 | uint256 price 162 | ); 163 | ``` 164 | 165 | The payload we generated earlier is then picked up by the storage provider. 166 | 167 | The overall flow is a push-pull mechanism. The CC "pushes" a `DealProposalCreate` event onto the FVM event log, which is watched by Boost SPs. SPs look for `DealProposalCreate` events that interest them (they can filter by price, verified state and size). They then ask the CC to provide them the `DealProposal` payload. Data transfer can begin. SPs can also publish the deal by submitting a PublishStorageDeal message on-chain with the fields in the DealProposal payload. 168 | 169 | See the diagram of this information here: 170 | 171 | ![shapes (6) copy](https://user-images.githubusercontent.com/782153/224235188-f1b2ecfc-c88b-4efb-9896-b90ec5c3152f.png) 172 | 173 | In summary, the "front-end" of the CC interacts with the contract, and takes in a deal proposal payload. The "back-end" of the CC interacts with the Boost SP in order to generate the deal, as well as in order to authenticate the deal. 174 | 175 | Note that we have a few active threads and FRCs where the client contract is being discussed: 176 | - [Our latest FRC draft, WIP](https://www.notion.so/WIP-Deal-Client-Contract-FRC-458e625f13b14c70bfdfe7ed64007b6c) 177 | - [FIP discussion 604](https://github.com/filecoin-project/FIPs/discussions/604) 178 | - [Boost discussion 1160](https://github.com/filecoin-project/boost/discussions/1160) 179 | -------------------------------------------------------------------------------- /contracts/DealClient.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.23; 3 | 4 | import {MarketAPI} from "filecoin-solidity-api/contracts/v0.8/MarketAPI.sol"; 5 | import {CommonTypes} from "filecoin-solidity-api/contracts/v0.8/types/CommonTypes.sol"; 6 | import {MarketTypes} from "filecoin-solidity-api/contracts/v0.8/types/MarketTypes.sol"; 7 | import {AccountTypes} from "filecoin-solidity-api/contracts/v0.8/types/AccountTypes.sol"; 8 | import {CommonTypes} from "filecoin-solidity-api/contracts/v0.8/types/CommonTypes.sol"; 9 | import {AccountCBOR} from "filecoin-solidity-api/contracts/v0.8/cbor/AccountCbor.sol"; 10 | import {MarketCBOR} from "filecoin-solidity-api/contracts/v0.8/cbor/MarketCbor.sol"; 11 | import {BytesCBOR} from "filecoin-solidity-api/contracts/v0.8/cbor/BytesCbor.sol"; 12 | import {BigInts} from "filecoin-solidity-api/contracts/v0.8/utils/BigInts.sol"; 13 | import {CBOR} from "solidity-cborutils/contracts/CBOR.sol"; 14 | import {Misc} from "filecoin-solidity-api/contracts/v0.8/utils/Misc.sol"; 15 | import {FilAddresses} from "filecoin-solidity-api/contracts/v0.8/utils/FilAddresses.sol"; 16 | 17 | using CBOR for CBOR.CBORBuffer; 18 | 19 | struct RequestId { 20 | bytes32 requestId; 21 | bool valid; 22 | } 23 | 24 | struct RequestIdx { 25 | uint256 idx; 26 | bool valid; 27 | } 28 | 29 | struct ProviderSet { 30 | bytes provider; 31 | bool valid; 32 | } 33 | 34 | // User request for this contract to make a deal. This structure is modelled after Filecoin's Deal 35 | // Proposal, but leaves out the provider, since any provider can pick up a deal broadcast by this 36 | // contract. 37 | struct DealRequest { 38 | bytes piece_cid; 39 | uint64 piece_size; 40 | bool verified_deal; 41 | string label; 42 | int64 start_epoch; 43 | int64 end_epoch; 44 | uint256 storage_price_per_epoch; 45 | uint256 provider_collateral; 46 | uint256 client_collateral; 47 | uint64 extra_params_version; 48 | ExtraParamsV1 extra_params; 49 | } 50 | 51 | // Extra parameters associated with the deal request. These are off-protocol flags that 52 | // the storage provider will need. 53 | struct ExtraParamsV1 { 54 | string location_ref; 55 | uint64 car_size; 56 | bool skip_ipni_announce; 57 | bool remove_unsealed_copy; 58 | } 59 | 60 | function serializeExtraParamsV1(ExtraParamsV1 memory params) pure returns (bytes memory) { 61 | CBOR.CBORBuffer memory buf = CBOR.create(64); 62 | buf.startFixedArray(4); 63 | buf.writeString(params.location_ref); 64 | buf.writeUInt64(params.car_size); 65 | buf.writeBool(params.skip_ipni_announce); 66 | buf.writeBool(params.remove_unsealed_copy); 67 | return buf.data(); 68 | } 69 | 70 | contract DealClient { 71 | using AccountCBOR for *; 72 | using MarketCBOR for *; 73 | 74 | uint64 public constant AUTHENTICATE_MESSAGE_METHOD_NUM = 2643134072; 75 | uint64 public constant DATACAP_RECEIVER_HOOK_METHOD_NUM = 3726118371; 76 | uint64 public constant MARKET_NOTIFY_DEAL_METHOD_NUM = 4186741094; 77 | address public constant MARKET_ACTOR_ETH_ADDRESS = 78 | address(0xff00000000000000000000000000000000000005); 79 | address public constant DATACAP_ACTOR_ETH_ADDRESS = 80 | address(0xfF00000000000000000000000000000000000007); 81 | 82 | enum Status { 83 | None, 84 | RequestSubmitted, 85 | DealPublished, 86 | DealActivated, 87 | DealTerminated 88 | } 89 | 90 | mapping(bytes32 => RequestIdx) public dealRequestIdx; // contract deal id -> deal index 91 | DealRequest[] public dealRequests; 92 | 93 | mapping(bytes => RequestId) public pieceRequests; // commP -> dealProposalID 94 | mapping(bytes => ProviderSet) public pieceProviders; // commP -> provider 95 | mapping(bytes => uint64) public pieceDeals; // commP -> deal ID 96 | mapping(bytes => Status) public pieceStatus; 97 | 98 | event ReceivedDataCap(string received); 99 | event DealProposalCreate(bytes32 indexed id, uint64 size, bool indexed verified, uint256 price); 100 | 101 | address public owner; 102 | 103 | constructor() { 104 | owner = msg.sender; 105 | } 106 | 107 | function getProviderSet(bytes calldata cid) public view returns (ProviderSet memory) { 108 | return pieceProviders[cid]; 109 | } 110 | 111 | function getProposalIdSet(bytes calldata cid) public view returns (RequestId memory) { 112 | return pieceRequests[cid]; 113 | } 114 | 115 | function dealsLength() public view returns (uint256) { 116 | return dealRequests.length; 117 | } 118 | 119 | function getDealByIndex(uint256 index) public view returns (DealRequest memory) { 120 | return dealRequests[index]; 121 | } 122 | 123 | function makeDealProposal(DealRequest calldata deal) public returns (bytes32) { 124 | require(msg.sender == owner); 125 | 126 | if ( 127 | pieceStatus[deal.piece_cid] == Status.DealPublished || 128 | pieceStatus[deal.piece_cid] == Status.DealActivated 129 | ) { 130 | revert("deal with this pieceCid already published"); 131 | } 132 | 133 | uint256 index = dealRequests.length; 134 | dealRequests.push(deal); 135 | 136 | // creates a unique ID for the deal proposal -- there are many ways to do this 137 | bytes32 id = keccak256(abi.encodePacked(block.timestamp, msg.sender, index)); 138 | dealRequestIdx[id] = RequestIdx(index, true); 139 | 140 | pieceRequests[deal.piece_cid] = RequestId(id, true); 141 | pieceStatus[deal.piece_cid] = Status.RequestSubmitted; 142 | 143 | // writes the proposal metadata to the event log 144 | emit DealProposalCreate( 145 | id, 146 | deal.piece_size, 147 | deal.verified_deal, 148 | deal.storage_price_per_epoch 149 | ); 150 | 151 | return id; 152 | } 153 | 154 | // helper function to get deal request based from id 155 | function getDealRequest(bytes32 requestId) internal view returns (DealRequest memory) { 156 | RequestIdx memory ri = dealRequestIdx[requestId]; 157 | require(ri.valid, "proposalId not available"); 158 | return dealRequests[ri.idx]; 159 | } 160 | 161 | // Returns a CBOR-encoded DealProposal. 162 | function getDealProposal(bytes32 proposalId) public view returns (bytes memory) { 163 | DealRequest memory deal = getDealRequest(proposalId); 164 | 165 | MarketTypes.DealProposal memory ret; 166 | ret.piece_cid = CommonTypes.Cid(deal.piece_cid); 167 | ret.piece_size = deal.piece_size; 168 | ret.verified_deal = deal.verified_deal; 169 | ret.client = FilAddresses.fromEthAddress(address(this)); 170 | // Set a dummy provider. The provider that picks up this deal will need to set its own address. 171 | ret.provider = FilAddresses.fromActorID(0); 172 | ret.label = CommonTypes.DealLabel(bytes(deal.label), true); 173 | ret.start_epoch = CommonTypes.ChainEpoch.wrap(deal.start_epoch); 174 | ret.end_epoch = CommonTypes.ChainEpoch.wrap(deal.end_epoch); 175 | ret.storage_price_per_epoch = BigInts.fromUint256(deal.storage_price_per_epoch); 176 | ret.provider_collateral = BigInts.fromUint256(deal.provider_collateral); 177 | ret.client_collateral = BigInts.fromUint256(deal.client_collateral); 178 | 179 | return MarketCBOR.serializeDealProposal(ret); 180 | } 181 | 182 | function getExtraParams(bytes32 proposalId) public view returns (bytes memory extra_params) { 183 | DealRequest memory deal = getDealRequest(proposalId); 184 | return serializeExtraParamsV1(deal.extra_params); 185 | } 186 | 187 | // authenticateMessage is the callback from the market actor into the contract 188 | // as part of PublishStorageDeals. This message holds the deal proposal from the 189 | // miner, which needs to be validated by the contract in accordance with the 190 | // deal requests made and the contract's own policies 191 | // @params - cbor byte array of AccountTypes.AuthenticateMessageParams 192 | function authenticateMessage(bytes memory params) internal view { 193 | require(msg.sender == MARKET_ACTOR_ETH_ADDRESS, "msg.sender needs to be market actor f05"); 194 | 195 | AccountTypes.AuthenticateMessageParams memory amp = params 196 | .deserializeAuthenticateMessageParams(); 197 | MarketTypes.DealProposal memory proposal = MarketCBOR.deserializeDealProposal(amp.message); 198 | 199 | bytes memory pieceCid = proposal.piece_cid.data; 200 | require(pieceRequests[pieceCid].valid, "piece cid must be added before authorizing"); 201 | require( 202 | !pieceProviders[pieceCid].valid, 203 | "deal failed policy check: provider already claimed this cid" 204 | ); 205 | 206 | DealRequest memory req = getDealRequest(pieceRequests[pieceCid].requestId); 207 | require(proposal.verified_deal == req.verified_deal, "verified_deal param mismatch"); 208 | (uint256 proposalStoragePricePerEpoch, bool storagePriceConverted) = BigInts.toUint256( 209 | proposal.storage_price_per_epoch 210 | ); 211 | require( 212 | !storagePriceConverted, 213 | "Issues converting uint256 to BigInt, may not have accurate values" 214 | ); 215 | (uint256 proposalClientCollateral, bool collateralConverted) = BigInts.toUint256( 216 | proposal.client_collateral 217 | ); 218 | require( 219 | !collateralConverted, 220 | "Issues converting uint256 to BigInt, may not have accurate values" 221 | ); 222 | require( 223 | proposalStoragePricePerEpoch <= req.storage_price_per_epoch, 224 | "storage price greater than request amount" 225 | ); 226 | require( 227 | proposalClientCollateral <= req.client_collateral, 228 | "client collateral greater than request amount" 229 | ); 230 | } 231 | 232 | // dealNotify is the callback from the market actor into the contract at the end 233 | // of PublishStorageDeals. This message holds the previously approved deal proposal 234 | // and the associated dealID. The dealID is stored as part of the contract state 235 | // and the completion of this call marks the success of PublishStorageDeals 236 | // @params - cbor byte array of MarketDealNotifyParams 237 | function dealNotify(bytes memory params) internal { 238 | require(msg.sender == MARKET_ACTOR_ETH_ADDRESS, "msg.sender needs to be market actor f05"); 239 | 240 | MarketTypes.MarketDealNotifyParams memory mdnp = MarketCBOR 241 | .deserializeMarketDealNotifyParams(params); 242 | MarketTypes.DealProposal memory proposal = MarketCBOR.deserializeDealProposal( 243 | mdnp.dealProposal 244 | ); 245 | 246 | // These checks prevent race conditions between the authenticateMessage and 247 | // marketDealNotify calls where someone could have 2 of the same deal proposals 248 | // within the same PSD msg, which would then get validated by authenticateMessage 249 | // However, only one of those deals should be allowed 250 | require( 251 | pieceRequests[proposal.piece_cid.data].valid, 252 | "piece cid must be added before authorizing" 253 | ); 254 | require( 255 | !pieceProviders[proposal.piece_cid.data].valid, 256 | "deal failed policy check: provider already claimed this cid" 257 | ); 258 | 259 | pieceProviders[proposal.piece_cid.data] = ProviderSet(proposal.provider.data, true); 260 | pieceDeals[proposal.piece_cid.data] = mdnp.dealId; 261 | pieceStatus[proposal.piece_cid.data] = Status.DealPublished; 262 | } 263 | 264 | // This function can be called/smartly polled to retrieve the deal activation status 265 | // associated with provided pieceCid and update the contract state based on that 266 | // info 267 | // @pieceCid - byte representation of pieceCid 268 | function updateActivationStatus(bytes memory pieceCid) public { 269 | require(pieceDeals[pieceCid] > 0, "no deal published for this piece cid"); 270 | 271 | (int256 exit_code, MarketTypes.GetDealActivationReturn memory ret) = MarketAPI 272 | .getDealActivation(pieceDeals[pieceCid]); 273 | if (exit_code != 0) { 274 | revert("Get deal activation failed with non zero exit code"); 275 | } 276 | if (CommonTypes.ChainEpoch.unwrap(ret.terminated) > 0) { 277 | pieceStatus[pieceCid] = Status.DealTerminated; 278 | } else if (CommonTypes.ChainEpoch.unwrap(ret.activated) > 0) { 279 | pieceStatus[pieceCid] = Status.DealActivated; 280 | } 281 | } 282 | 283 | // addBalance funds the builtin storage market actor's escrow 284 | // with funds from the contract's own balance 285 | // @value - amount to be added in escrow in attoFIL 286 | function addBalance(uint256 value) public { 287 | require(msg.sender == owner); 288 | MarketAPI.addBalance(FilAddresses.fromEthAddress(address(this)), value); 289 | } 290 | 291 | // This function attempts to withdraw the specified amount from the contract addr's escrow balance 292 | // If less than the given amount is available, the full escrow balance is withdrawn 293 | // @client - Eth address where the balance is withdrawn to. This can be the contract address or an external address 294 | // @value - amount to be withdrawn in escrow in attoFIL 295 | function withdrawBalance(address client, uint256 value) public returns (uint) { 296 | require(msg.sender == owner); 297 | 298 | MarketTypes.WithdrawBalanceParams memory params = MarketTypes.WithdrawBalanceParams( 299 | FilAddresses.fromEthAddress(client), 300 | BigInts.fromUint256(value) 301 | ); 302 | (int256 exit_code, CommonTypes.BigInt memory ret) = MarketAPI.withdrawBalance(params); 303 | if (exit_code != 0) { 304 | revert("Withdraw balance failed with non zero exit code"); 305 | } 306 | 307 | (uint256 withdrawBalanceAmount, bool withdrawBalanceConverted) = BigInts.toUint256(ret); 308 | require( 309 | withdrawBalanceConverted, 310 | "Problems converting withdraw balance into Big Int, may cause an overflow" 311 | ); 312 | 313 | return withdrawBalanceAmount; 314 | } 315 | 316 | function receiveDataCap(bytes memory) internal { 317 | require( 318 | msg.sender == DATACAP_ACTOR_ETH_ADDRESS, 319 | "msg.sender needs to be datacap actor f07" 320 | ); 321 | emit ReceivedDataCap("DataCap Received!"); 322 | // Add get datacap balance api and store datacap amount 323 | } 324 | 325 | // handle_filecoin_method is the universal entry point for any evm based 326 | // actor for a call coming from a builtin filecoin actor 327 | // @method - FRC42 method number for the specific method hook 328 | // @params - CBOR encoded byte array params 329 | function handle_filecoin_method( 330 | uint64 method, 331 | uint64, 332 | bytes memory params 333 | ) public returns (uint32, uint64, bytes memory) { 334 | bytes memory ret; 335 | uint64 codec; 336 | // dispatch methods 337 | if (method == AUTHENTICATE_MESSAGE_METHOD_NUM) { 338 | authenticateMessage(params); 339 | // If we haven't reverted, we should return a CBOR true to indicate that verification passed. 340 | CBOR.CBORBuffer memory buf = CBOR.create(1); 341 | buf.writeBool(true); 342 | ret = buf.data(); 343 | codec = Misc.CBOR_CODEC; 344 | } else if (method == MARKET_NOTIFY_DEAL_METHOD_NUM) { 345 | dealNotify(params); 346 | } else if (method == DATACAP_RECEIVER_HOOK_METHOD_NUM) { 347 | receiveDataCap(params); 348 | } else { 349 | revert("the filecoin method that was called is not handled"); 350 | } 351 | return (0, codec, ret); 352 | } 353 | } 354 | -------------------------------------------------------------------------------- /deploy/0_deploy.js: -------------------------------------------------------------------------------- 1 | require("hardhat-deploy") 2 | require("hardhat-deploy-ethers") 3 | 4 | const { networkConfig } = require("../helper-hardhat-config") 5 | 6 | 7 | const private_key = network.config.accounts[0] 8 | const wallet = new ethers.Wallet(private_key, ethers.provider) 9 | 10 | module.exports = async ({ deployments }) => { 11 | console.log("Wallet Ethereum Address:", wallet.address) 12 | 13 | //deploy DealClient 14 | const DealClient = await ethers.getContractFactory('DealClient', wallet); 15 | console.log('Deploying DealClient...'); 16 | const dc = await DealClient.deploy(); 17 | await dc.deployed() 18 | console.log('DealClient deployed to:', dc.address); 19 | } -------------------------------------------------------------------------------- /frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # Dapp Frontend 2 | 3 | The frontend looks like the the following on launch and successful deal submission: 4 | 5 | Screen Shot 2023-03-13 at 10 22 54 AM 6 | 7 | 8 | ## Scripts 9 | 10 | In the project directory, you can run: 11 | 12 | ### `npm start` 13 | 14 | Runs the app in the development mode.\ 15 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 16 | 17 | The page will reload when you make changes.\ 18 | You may also see any lint errors in the console. 19 | 20 | ### `npm test` 21 | 22 | Launches the test runner in the interactive watch mode.\ 23 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 24 | 25 | ### `npm run build` 26 | 27 | Builds the app for production to the `build` folder.\ 28 | It correctly bundles React in production mode and optimizes the build for the best performance. 29 | 30 | The build is minified and the filenames include the hashes.\ 31 | Your app is ready to be deployed! 32 | 33 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 34 | 35 | ### `npm run eject` 36 | 37 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 38 | 39 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 40 | 41 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. 42 | 43 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. 44 | 45 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client-contracts-frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.16.5", 7 | "@testing-library/react": "^14.0.0", 8 | "@testing-library/user-event": "^14.4.3", 9 | "bootstrap": "^5.2.3", 10 | "cids": "^1.1.9", 11 | "eth-hooks": "^4.6.2", 12 | "ethers": "^6.1.0", 13 | "react": "^18.2.0", 14 | "react-bootstrap": "^2.7.2", 15 | "react-dom": "^18.2.0", 16 | "react-icons": "^4.8.0", 17 | "react-tooltip": "^5.10.0", 18 | "web-vitals": "^3.3.0" 19 | }, 20 | "devDependencies": { 21 | "react-scripts": "^5.0.1" 22 | }, 23 | "scripts": { 24 | "start": "react-scripts start", 25 | "build": "react-scripts build", 26 | "test": "react-scripts test", 27 | "eject": "react-scripts eject" 28 | }, 29 | "eslintConfig": { 30 | "extends": [ 31 | "react-app", 32 | "react-app/jest" 33 | ] 34 | }, 35 | "browserslist": { 36 | "production": [ 37 | ">0.2%", 38 | "not dead", 39 | "not op_mini all" 40 | ], 41 | "development": [ 42 | "last 1 chrome version", 43 | "last 1 firefox version", 44 | "last 1 safari version" 45 | ] 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/filecoin-project/fvm-starter-kit-deal-making/bbe2815ee7b8a2ba2ef43ed8b1b1eaee90e05a7c/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | Client Contract 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /frontend/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/filecoin-project/fvm-starter-kit-deal-making/bbe2815ee7b8a2ba2ef43ed8b1b1eaee90e05a7c/frontend/public/logo192.png -------------------------------------------------------------------------------- /frontend/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/filecoin-project/fvm-starter-kit-deal-making/bbe2815ee7b8a2ba2ef43ed8b1b1eaee90e05a7c/frontend/public/logo512.png -------------------------------------------------------------------------------- /frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "Client Contract", 3 | "name": "FVM Client Contract Frontend", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /frontend/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | display: flex; 3 | flex-direction: column; 4 | align-items: center; 5 | margin: 2rem; 6 | height: 100vh; 7 | } 8 | 9 | body { 10 | font-family: sans-serif; 11 | } 12 | 13 | .input-elem { 14 | font-size:20px;padding:10px; 15 | margin:10px; 16 | margin-left: 0px; 17 | } 18 | 19 | #container { 20 | position: absolute; 21 | top: 0; 22 | right: 0; 23 | left: 0; 24 | bottom: 0; 25 | margin: 20px; 26 | display: flex; 27 | flex-flow: column 28 | } 29 | 30 | 31 | .child-1 { 32 | display: flex; 33 | flex-flow:column nowrap; 34 | width:100%; 35 | max-width: 800px; 36 | margin-left: auto; 37 | margin-right: auto; 38 | } 39 | 40 | .child-1-cw { 41 | margin:auto; 42 | margin-top: 10px; 43 | margin-right: 10px; 44 | } 45 | 46 | .child-1-hg { 47 | display:flex; 48 | flex-flow: row; 49 | } 50 | 51 | .tooltip { margin-left:3px; } 52 | 53 | button { 54 | padding: 1rem; 55 | border-radius: 12px; 56 | outline: none; 57 | background-color: #f1f3f5; 58 | border-radius: 0.25rem; 59 | border: 0; 60 | cursor: pointer; 61 | transition: opacity 0.3s ease; 62 | } 63 | 64 | .center { 65 | position: absolute; 66 | top: 50%; 67 | left: 50%; 68 | transform: translate(-50%, -50%); 69 | } 70 | 71 | .connect-wallet-btn { 72 | position: absolute; 73 | top: 0; 74 | right: 0; 75 | } 76 | 77 | button:hover { 78 | opacity: 0.8; 79 | } 80 | 81 | button:active { 82 | opacity: 0.6; 83 | } 84 | 85 | button + button { 86 | margin-top: 1rem; 87 | } 88 | 89 | button { 90 | border:none; 91 | margin-left:auto; 92 | margin-right:auto; 93 | padding: 10px; 94 | } 95 | 96 | .text-error { 97 | color: #ff6b6b; 98 | } 99 | -------------------------------------------------------------------------------- /frontend/src/App.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Inputs from './components/Inputs'; 3 | import "./App.css"; 4 | 5 | function App() { 6 | 7 | return ( 8 |
9 | 10 |
11 | ); 12 | } 13 | 14 | export default App; -------------------------------------------------------------------------------- /frontend/src/assets/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/components/Inputs.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | import contract from "../contracts/DealClient.json"; 3 | import "react-tooltip/dist/react-tooltip.css"; 4 | import { Tooltip } from "react-tooltip"; 5 | import { ethers } from "ethers"; 6 | import { AiOutlineQuestionCircle } from "react-icons/ai"; 7 | import Spinner from 'react-bootstrap/Spinner'; 8 | const CID = require("cids"); 9 | 10 | // Replace this address with the address of own instance of the deal client contract 11 | const contractAddress = "0xf4E0C74D76Bf324293bB3B3DA184d164d06F7664"; 12 | const contractABI = contract.abi; 13 | let dealClient; 14 | let cid; 15 | 16 | function Inputs() { 17 | // Initialize with some dummy working default values 18 | const [commP, setCommP] = useState( 19 | "baga6ea4seaqkp2pjlh6avlvee6ib2maanav5sc35l5glf3zm6rd6hmfgcx5xeji" 20 | ); 21 | const [carLink, setCarLink] = useState( 22 | "https://data-depot.lighthouse.storage/api/download/download_car?fileId=862fb115-d24a-4ff1-a1c8-eadbbbfd19cf.car" 23 | ); 24 | const [errorMessageSubmit, setErrorMessageSubmit] = useState(""); 25 | const [pieceSize, setPieceSize] = useState("32768"); 26 | const [carSize, setCarSize] = useState("18445"); 27 | const [txSubmitted, setTxSubmitted] = useState(""); 28 | const [dealID, setDealID] = useState(""); 29 | const [proposingDeal, setProposingDeal] = useState(false); 30 | const [network, setNetwork] = useState(""); 31 | 32 | const handleChangeCommP = (event) => { 33 | setCommP(event.target.value); 34 | }; 35 | 36 | const handleChangeCarLink = (event) => { 37 | // validate input data here 38 | setCarLink(event.target.value); 39 | }; 40 | 41 | const handleChangePieceSize = (event) => { 42 | setPieceSize(event.target.value); 43 | }; 44 | 45 | const handleChangeCarSize = (event) => { 46 | setCarSize(event.target.value); 47 | }; 48 | 49 | /* 50 | const handleChangeStartEpoch = (event) => { 51 | setStartEpoch(event.target.value); 52 | } 53 | 54 | const handleChangeEndEpoch = (event) => { 55 | setEndEpoch(event.target.value); 56 | } 57 | */ 58 | 59 | const handleSubmit = async (event) => { 60 | // This will be handling deal proposal submission sometime in the future. 61 | event.preventDefault(); 62 | // do something with the carLink value, like send it to a backend API 63 | console.log(commP); 64 | console.log(carLink); 65 | console.log(pieceSize); 66 | console.log(carSize); 67 | 68 | try { 69 | setErrorMessageSubmit( 70 | "" 71 | ); 72 | cid = new CID(commP); 73 | const { ethereum } = window; 74 | if (ethereum) { 75 | const provider = new ethers.BrowserProvider(ethereum); 76 | const signer = await provider.getSigner(); 77 | dealClient = new ethers.Contract( 78 | contractAddress, 79 | contractABI, 80 | signer 81 | ); 82 | const extraParamsV1 = [ 83 | carLink, 84 | carSize, 85 | false, // taskArgs.skipIpniAnnounce, 86 | false, // taskArgs.removeUnsealedCopy 87 | ]; 88 | const DealRequestStruct = [ 89 | cid.bytes, //cidHex 90 | pieceSize, //taskArgs.pieceSize, 91 | false, //taskArgs.verifiedDeal, 92 | commP, //taskArgs.label, 93 | 520000, // startEpoch 94 | 1555200, // endEpoch 95 | 0, // taskArgs.storagePricePerEpoch, 96 | 0, // taskArgs.providerCollateral, 97 | 0, // taskArgs.clientCollateral, 98 | 1, //taskArgs.extraParamsVersion, 99 | extraParamsV1, 100 | ]; 101 | // console.log(await provider.getBalance("0x42c930a33280a7218bc924732d67dd84d6247af4")); 102 | console.log(dealClient.interface); 103 | const transaction = await dealClient.makeDealProposal( 104 | DealRequestStruct 105 | ); 106 | console.log("Proposing deal..."); 107 | setProposingDeal(true); 108 | const receipt = await transaction.wait(); 109 | console.log(receipt); 110 | setProposingDeal(false); 111 | setTxSubmitted("Transaction submitted! " + receipt.hash); 112 | 113 | dealClient.on("DealProposalCreate", (id, size, verified, price)=>{ 114 | console.log(id, size, verified, price); 115 | }) 116 | 117 | console.log("Deal proposed! CID: " + cid); 118 | } else { 119 | console.log("Ethereum object doesn't exist!"); 120 | } 121 | } catch (error) { 122 | console.log(error); 123 | setErrorMessageSubmit( 124 | "Something went wrong. " + error.name + " " + error.message 125 | ); 126 | return; 127 | } 128 | }; 129 | 130 | const checkWalletIsConnected = async () => { 131 | const { ethereum } = window; 132 | if (!ethereum) { 133 | console.log("Make sure you have metamask!"); 134 | return; 135 | } else { 136 | console.log("We have the ethereum object", ethereum); 137 | } 138 | const provider = new ethers.BrowserProvider(ethereum); 139 | const network = await provider.getNetwork(); 140 | setNetwork(network.chainId); 141 | console.log(network.chainId); 142 | 143 | ethereum.request({ method: "eth_accounts" }).then((accounts) => { 144 | if (accounts.length !== 0) { 145 | const account = accounts[0]; 146 | console.log("Found an account:", account); 147 | } else { 148 | console.log("No account found"); 149 | } 150 | }); 151 | }; 152 | 153 | const connectWalletHandler = () => { 154 | const { ethereum } = window; 155 | if (!ethereum) { 156 | alert("Get MetaMask!"); 157 | return; 158 | } 159 | ethereum 160 | .request({ method: "eth_requestAccounts" }) 161 | .then((accounts) => { 162 | console.log("Connected", accounts[0]); 163 | }) 164 | .catch((err) => console.log(err)); 165 | }; 166 | 167 | const connectWalletButton = () => { 168 | return ( 169 |
170 | 176 | { window &&
Connected
} 177 | { network &&
Network: Calibration
} 178 |
179 | ); 180 | }; 181 | 182 | const dealIDButton = () => { 183 | return ( 184 | 189 | ); 190 | }; 191 | 192 | const dealIDHandler = async () => { 193 | setDealID("Waiting for acceptance by SP..."); 194 | cid = new CID(commP); 195 | var refresh = setInterval(async () => { 196 | console.log(cid.bytes); 197 | if (cid === undefined) { 198 | setDealID("Error: CID not found"); 199 | clearInterval(refresh); 200 | } 201 | console.log("Checking for deal ID..."); 202 | const dealID = await dealClient.pieceDeals(cid.bytes); 203 | console.log(dealID); 204 | if (dealID !== undefined && dealID !== "0") { 205 | // If your deal has already been submitted, you can get the deal ID by going to https://calibration.filfox.info/en/deal/ 206 | // The link will show up in the frontend: once a deal has been submitted, its deal ID stays constant. It will always have the same deal ID. 207 | setDealID("https://calibration.filfox.info/en/deal/" + dealID); 208 | clearInterval(refresh); 209 | } 210 | }, 5000 211 | ); 212 | }; 213 | 214 | useEffect(() => { 215 | checkWalletIsConnected(); 216 | }, []); 217 | 218 | return ( 219 |
220 |
221 | {connectWalletButton()} 222 |
223 | 224 |
225 | 226 |
227 | 228 | 231 | 232 | 233 |
234 |
239 | 240 |
241 | 242 |
243 | 244 | 245 |
246 | 247 | 248 | 253 | 254 |
255 |
256 | 257 |
258 | 259 | 260 | 261 |
267 | 268 |
269 | 270 | 271 |
272 | 273 | 278 | 279 | 280 |
281 |
282 | 283 |
284 | 285 | 288 | 289 |
295 | 296 |
297 | 298 | 299 | 300 |
301 | 302 | 307 |
308 |
309 | 310 |
311 | 312 | 315 | 316 |
322 | 323 |
324 | 325 | 326 | 327 |
328 | 329 | 330 |
331 |
332 | 338 |
{errorMessageSubmit}
339 | { proposingDeal && 340 | Loading... 341 | } 342 |
{txSubmitted}
343 |
344 | 345 |
346 |
347 |
348 |
349 | {dealIDButton()} 350 |
351 |
352 | {dealID &&
Deal: {dealID}
} 353 | 354 |
355 | ); 356 | } 357 | 358 | export default Inputs; 359 | -------------------------------------------------------------------------------- /frontend/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | const root = ReactDOM.createRoot(document.getElementById('root')); 8 | root.render( 9 | 10 | 11 | 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /frontend/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /frontend/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /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: { 11 | compilers: [ 12 | { 13 | version: "0.8.23", 14 | settings: { 15 | optimizer: { 16 | enabled: true, 17 | runs: 1000, 18 | details: { yul: false }, 19 | }, 20 | }, 21 | }, 22 | ], 23 | }, 24 | defaultNetwork: "Calibration", 25 | networks: { 26 | Calibration: { 27 | chainId: 314159, 28 | url: "https://api.calibration.node.glif.io/rpc/v1", 29 | accounts: [PRIVATE_KEY], 30 | }, 31 | FilecoinMainnet: { 32 | chainId: 314, 33 | url: "https://api.node.glif.io", 34 | accounts: [PRIVATE_KEY], 35 | }, 36 | }, 37 | paths: { 38 | sources: "./contracts", 39 | tests: "./test", 40 | cache: "./cache", 41 | artifacts: "./artifacts", 42 | }, 43 | } 44 | -------------------------------------------------------------------------------- /helper-hardhat-config.js: -------------------------------------------------------------------------------- 1 | const { ethers } = require("hardhat") 2 | 3 | const networkConfig = { 4 | 314159: { 5 | name: "Calibration", 6 | tokensToBeMinted: 12000, 7 | }, 8 | 314: { 9 | name: "FilecoinMainnet", 10 | tokensToBeMinted: 12000, 11 | }, 12 | } 13 | 14 | module.exports = { 15 | networkConfig, 16 | // developmentChains, 17 | } 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fvm-starter-kit-deal-making", 3 | "version": "1.0.0", 4 | "description": "", 5 | "scripts": { 6 | "compile": "hardhat compile", 7 | "test": "hardhat test test/unit/*_test.js --network hardhat", 8 | "test-staging": "hardhat test test/staging/*_test.js --network goerli", 9 | "lint": "solhint 'contracts/*.sol'", 10 | "lint:fix": "solhint 'contracts/**/*.sol' --fix", 11 | "format": "prettier --write .", 12 | "coverage": "hardhat coverage --solcoverjs ./.solcover.js", 13 | "fuzzing": "docker run -it --rm -v $PWD:/src trailofbits/eth-security-toolbox" 14 | }, 15 | "license": "MIT", 16 | "devDependencies": { 17 | "@nomiclabs/hardhat-ethers": "^2.2.3", 18 | "@nomiclabs/hardhat-etherscan": "^3.0.0", 19 | "@nomiclabs/hardhat-waffle": "^2.0.1", 20 | "@types/chai": "^4.3.4", 21 | "@types/mocha": "^10.0.1", 22 | "@types/node": "^18.11.15", 23 | "chai": "^4.3.7", 24 | "cids": "^1.1.9", 25 | "ethereum-waffle": "^3.4.0", 26 | "ethers": "^5.5.1", 27 | "hardhat": "^2.22.4", 28 | "hardhat-contract-sizer": "^2.4.0", 29 | "hardhat-deploy": "^0.9.29", 30 | "hardhat-gas-reporter": "^1.0.7", 31 | "prettier": "^2.4.1", 32 | "prettier-plugin-solidity": "^1.0.0-beta.19", 33 | "solhint": "^3.3.6", 34 | "solidity-coverage": "^0.8.12" 35 | }, 36 | "dependencies": { 37 | "@glif/filecoin-address": "^2.0.18", 38 | "@nomicfoundation/hardhat-chai-matchers": "^1.0.0", 39 | "@nomicfoundation/hardhat-network-helpers": "^1.0.0", 40 | "@nomicfoundation/hardhat-toolbox": "^2.0.0", 41 | "@openzeppelin/contracts": "^4.9.2", 42 | "@typechain/hardhat": "^6.1.2", 43 | "babel-eslint": "^10.1.0", 44 | "dotenv": "^10.0.0", 45 | "filecoin-solidity-api": "^1.1.3", 46 | "hardhat-deploy-ethers": "^0.3.0-beta.13", 47 | "ts-node": "^10.9.1", 48 | "typescript": "^4.9.4" 49 | }, 50 | "mocha": { 51 | "timeout": 10000000 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /tasks/cid-to-bytes.js: -------------------------------------------------------------------------------- 1 | const CID = require('cids') 2 | 3 | task( 4 | "cid-to-bytes", 5 | "Converts CID to EVM compatible hex bytes." 6 | ) 7 | .addParam("cid", "The piece CID of the data you want to put up a bounty for") 8 | .setAction(async (taskArgs) => { 9 | //store taskargs as useable variables 10 | const cid = taskArgs.cid 11 | 12 | //convert piece CID string to hex bytes 13 | const cidHexRaw = new CID(cid).toString('base16').substring(1) 14 | const cidHex = "0x00" + cidHexRaw 15 | console.log("Hex bytes are:", cidHex) 16 | console.log("Complete!") 17 | }) -------------------------------------------------------------------------------- /tasks/deal-client/get-deal-proposal.js: -------------------------------------------------------------------------------- 1 | task( 2 | "get-deal-proposal", 3 | "Gets a deal proposal from the proposal id" 4 | ) 5 | .addParam("contract", "The address of the deal client solidity") 6 | .addParam("proposalId", "The proposal ID") 7 | .setAction(async (taskArgs) => { 8 | const contractAddr = taskArgs.contract 9 | const proposalID = taskArgs.proposalId 10 | const networkId = network.name 11 | console.log("Getting deal proposal on network", networkId) 12 | 13 | //create a new wallet instance 14 | const wallet = new ethers.Wallet(network.config.accounts[0], ethers.provider) 15 | 16 | //create a DealClient contract factory 17 | const DealClient = await ethers.getContractFactory("DealClient", wallet) 18 | //create a DealClient contract instance 19 | //this is what you will call to interact with the deployed contract 20 | const dealClient = await DealClient.attach(contractAddr) 21 | 22 | //send a transaction to call makeDealProposal() method 23 | //transaction = await dealClient.getDealProposal(proposalID) 24 | let result = await dealClient.getDealProposal(proposalID) 25 | console.log("The deal proposal is:", result) 26 | }) -------------------------------------------------------------------------------- /tasks/deal-client/make-deal-proposal.js: -------------------------------------------------------------------------------- 1 | const CID = require('cids') 2 | 3 | task( 4 | "make-deal-proposal", 5 | "Makes a deal proposal via the client contract. This will ultimately emit an event that storage providers can listen too and choose to accept your deal." 6 | ) 7 | .addParam("contract", "The address of the deal client solidity") 8 | .addParam("pieceCid", "The address of the DealRewarder contract") 9 | .addParam("pieceSize", "The piece CID of the data you want to put up a bounty for") 10 | .addParam("verifiedDeal", "Size of the data you are putting a bounty on") 11 | .addParam("label", "The deal label (typically the raw cid)") 12 | .addParam("startEpoch", "The epoch the deal will start") 13 | .addParam("endEpoch", "The epoch the deal will end") 14 | .addParam("storagePricePerEpoch", "The cost of the deal, in FIL, per epoch") 15 | .addParam("providerCollateral", "The collateral, in FIL, to be put up by the storage provider") 16 | .addParam("clientCollateral", "The collateral, in FIL, to be put up by the the client (which is you)") 17 | .addParam("extraParamsVersion", "") 18 | .addParam("locationRef", "Where the data you want to be stored is located") 19 | .addParam("carSize", "The size of the .car file") 20 | .addParam("skipIpniAnnounce", "") 21 | .addParam("removeUnsealedCopy", "") 22 | .setAction(async (taskArgs) => { 23 | //store taskargs as useable variables 24 | //convert piece CID string to hex bytes 25 | const cid = taskArgs.pieceCid 26 | const cidHexRaw = new CID(cid).toString('base16').substring(1) 27 | const cidHex = "0x" + cidHexRaw 28 | const contractAddr = taskArgs.contract 29 | 30 | const verified = (taskArgs.verifiedDeal === 'true') 31 | const skipIpniAnnounce = (taskArgs.skipIpniAnnounce === 'true') 32 | const removeUnsealedCopy = (taskArgs.removeUnsealedCopy === 'true') 33 | 34 | const extraParamsV1 = [ 35 | taskArgs.locationRef, 36 | taskArgs.carSize, 37 | skipIpniAnnounce, 38 | removeUnsealedCopy, 39 | ] 40 | 41 | const DealRequestStruct = [ 42 | cidHex, 43 | taskArgs.pieceSize, 44 | verified, 45 | taskArgs.label, 46 | taskArgs.startEpoch, 47 | taskArgs.endEpoch, 48 | taskArgs.storagePricePerEpoch, 49 | taskArgs.providerCollateral, 50 | taskArgs.clientCollateral, 51 | taskArgs.extraParamsVersion, 52 | extraParamsV1, 53 | ] 54 | const networkId = network.name 55 | console.log("Making deal proposal on network", networkId) 56 | 57 | //create a new wallet instance 58 | const wallet = new ethers.Wallet(network.config.accounts[0], ethers.provider) 59 | 60 | //create a DealClient contract factory 61 | const DealClient = await ethers.getContractFactory("DealClient", wallet) 62 | //create a DealClient contract instance 63 | //this is what you will call to interact with the deployed contract 64 | const dealClient = await DealClient.attach(contractAddr) 65 | 66 | //send a transaction to call makeDealProposal() method 67 | transaction = await dealClient.makeDealProposal(DealRequestStruct) 68 | transactionReceipt = await transaction.wait() 69 | 70 | //listen for DealProposalCreate event 71 | const event = transactionReceipt.events[0].topics[0] 72 | console.log("Complete! Event Emitted. ProposalId is:", event) 73 | }) -------------------------------------------------------------------------------- /tasks/get-address.js: -------------------------------------------------------------------------------- 1 | const fa = require("@glif/filecoin-address"); 2 | 3 | task("get-address", "Gets Filecoin f4 address and corresponding Ethereum address.") 4 | .setAction(async (taskArgs) => { 5 | 6 | //create new Wallet object from private key 7 | const DEPLOYER_PRIVATE_KEY = network.config.accounts[0] 8 | const deployer = new ethers.Wallet(DEPLOYER_PRIVATE_KEY); 9 | 10 | //Convert Ethereum address to f4 address 11 | const f4Address = fa.newDelegatedEthAddress(deployer.address).toString(); 12 | console.log("Ethereum address (this addresss should work for most tools):", deployer.address); 13 | console.log("f4address (also known as t4 address on testnets):", f4Address); 14 | }) -------------------------------------------------------------------------------- /tasks/index.js: -------------------------------------------------------------------------------- 1 | exports.getAddress = require("./get-address") 2 | exports.cidToBytes = require("./cid-to-bytes") 3 | exports.makeDealProposal = require("./deal-client/make-deal-proposal") 4 | exports.getDealProposal = require("./deal-client/get-deal-proposal") --------------------------------------------------------------------------------