├── .env.example ├── .gitattributes ├── .github └── workflows │ ├── lint.yml │ └── tests.yml ├── .gitignore ├── .mocharc.json ├── .nvmrc ├── .prettierrc ├── .yarnrc ├── LICENSE ├── README.md ├── contracts ├── MerkleDistributor.sol ├── MerkleDistributorWithDeadline.sol ├── interfaces │ └── IMerkleDistributor.sol └── test │ └── TestERC20.sol ├── hardhat.config.ts ├── package.json ├── scripts ├── complex_example.json ├── deployMerkleDistributor.js ├── deployMerkleDistributorWithDeadline.js ├── example.json ├── generate-merkle-root.ts ├── new_example.json ├── result.json ├── to-kv-input.ts └── verify-merkle-root.ts ├── src ├── balance-tree.ts ├── merkle-tree.ts └── parse-balance-map.ts ├── test ├── MerkleDistributor.spec.ts.old └── MerkleDistributor.test.ts ├── tsconfig.json ├── waffle.json └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | ETHERSCAN_API_KEY=XXXX 2 | ROPSTEN_URL=https://eth-ropsten.alchemyapi.io/v2/XXXX 3 | PRIVATE_KEY=XXXX 4 | TENDERLY_FORK_ID=XXXX 5 | INFURA_KEY=XXXX 6 | REPORT_GAS=1 -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | run-linters: 13 | name: Run linters 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - name: Check out Git repository 18 | uses: actions/checkout@v3 19 | 20 | - name: Set up node 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: 16 24 | 25 | - name: Install dependencies 26 | run: yarn 27 | 28 | - name: Run linters 29 | uses: wearerequired/lint-action@v1 30 | with: 31 | github_token: ${{ secrets.github_token }} 32 | prettier: true 33 | auto_fix: true 34 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | unit-tests: 13 | name: Unit Tests 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - uses: actions/setup-node@v3 19 | with: 20 | node-version: 16 21 | 22 | - id: yarn-cache 23 | run: echo "::set-output name=dir::$(yarn cache dir)" 24 | 25 | - uses: actions/cache@v1 26 | with: 27 | path: ${{ steps.yarn-cache.outputs.dir }} 28 | key: yarn-${{ hashFiles('**/yarn.lock') }} 29 | restore-keys: | 30 | yarn- 31 | 32 | - run: yarn 33 | - run: yarn test 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | build/ 3 | wrangler.toml 4 | artifacts/ 5 | .idea 6 | cache/ -------------------------------------------------------------------------------- /.mocharc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extension": ["ts"], 3 | "spec": "./test/**/*.spec.ts", 4 | "require": "ts-node/register", 5 | "timeout": 12000 6 | } 7 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v16 -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "printWidth": 120 5 | } 6 | -------------------------------------------------------------------------------- /.yarnrc: -------------------------------------------------------------------------------- 1 | ignore-scripts true 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # @uniswap/merkle-distributor 2 | 3 | [![Tests](https://github.com/Uniswap/merkle-distributor/workflows/Tests/badge.svg)](https://github.com/Uniswap/merkle-distributor/actions?query=workflow%3ATests) 4 | [![Lint](https://github.com/Uniswap/merkle-distributor/workflows/Lint/badge.svg)](https://github.com/Uniswap/merkle-distributor/actions?query=workflow%3ALint) 5 | 6 | # Local Development 7 | 8 | The following assumes the use of `node@>=10`. 9 | 10 | ## Install Dependencies 11 | 12 | `yarn` 13 | 14 | ## Compile Contracts 15 | 16 | `yarn compile` 17 | 18 | ## Run Tests 19 | 20 | `yarn test` 21 | -------------------------------------------------------------------------------- /contracts/MerkleDistributor.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity =0.8.17; 3 | 4 | import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; 5 | import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; 6 | import {IMerkleDistributor} from "./interfaces/IMerkleDistributor.sol"; 7 | 8 | error AlreadyClaimed(); 9 | error InvalidProof(); 10 | 11 | contract MerkleDistributor is IMerkleDistributor { 12 | using SafeERC20 for IERC20; 13 | 14 | address public immutable override token; 15 | bytes32 public immutable override merkleRoot; 16 | 17 | // This is a packed array of booleans. 18 | mapping(uint256 => uint256) private claimedBitMap; 19 | 20 | constructor(address token_, bytes32 merkleRoot_) { 21 | token = token_; 22 | merkleRoot = merkleRoot_; 23 | } 24 | 25 | function isClaimed(uint256 index) public view override returns (bool) { 26 | uint256 claimedWordIndex = index / 256; 27 | uint256 claimedBitIndex = index % 256; 28 | uint256 claimedWord = claimedBitMap[claimedWordIndex]; 29 | uint256 mask = (1 << claimedBitIndex); 30 | return claimedWord & mask == mask; 31 | } 32 | 33 | function _setClaimed(uint256 index) private { 34 | uint256 claimedWordIndex = index / 256; 35 | uint256 claimedBitIndex = index % 256; 36 | claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); 37 | } 38 | 39 | function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) 40 | public 41 | virtual 42 | override 43 | { 44 | if (isClaimed(index)) revert AlreadyClaimed(); 45 | 46 | // Verify the merkle proof. 47 | bytes32 node = keccak256(abi.encodePacked(index, account, amount)); 48 | if (!MerkleProof.verify(merkleProof, merkleRoot, node)) revert InvalidProof(); 49 | 50 | // Mark it claimed and send the token. 51 | _setClaimed(index); 52 | IERC20(token).safeTransfer(account, amount); 53 | 54 | emit Claimed(index, account, amount); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /contracts/MerkleDistributorWithDeadline.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity =0.8.17; 3 | 4 | import {MerkleDistributor} from "./MerkleDistributor.sol"; 5 | import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; 6 | import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; 7 | 8 | error EndTimeInPast(); 9 | error ClaimWindowFinished(); 10 | error NoWithdrawDuringClaim(); 11 | 12 | contract MerkleDistributorWithDeadline is MerkleDistributor, Ownable { 13 | using SafeERC20 for IERC20; 14 | 15 | uint256 public immutable endTime; 16 | 17 | constructor(address token_, bytes32 merkleRoot_, uint256 endTime_) MerkleDistributor(token_, merkleRoot_) { 18 | if (endTime_ <= block.timestamp) revert EndTimeInPast(); 19 | endTime = endTime_; 20 | } 21 | 22 | function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) public override { 23 | if (block.timestamp > endTime) revert ClaimWindowFinished(); 24 | super.claim(index, account, amount, merkleProof); 25 | } 26 | 27 | function withdraw() external onlyOwner { 28 | if (block.timestamp < endTime) revert NoWithdrawDuringClaim(); 29 | IERC20(token).safeTransfer(msg.sender, IERC20(token).balanceOf(address(this))); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /contracts/interfaces/IMerkleDistributor.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity >=0.5.0; 3 | 4 | // Allows anyone to claim a token if they exist in a merkle root. 5 | interface IMerkleDistributor { 6 | // Returns the address of the token distributed by this contract. 7 | function token() external view returns (address); 8 | // Returns the merkle root of the merkle tree containing account balances available to claim. 9 | function merkleRoot() external view returns (bytes32); 10 | // Returns true if the index has been marked claimed. 11 | function isClaimed(uint256 index) external view returns (bool); 12 | // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. 13 | function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; 14 | 15 | // This event is triggered whenever a call to #claim succeeds. 16 | event Claimed(uint256 index, address account, uint256 amount); 17 | } 18 | -------------------------------------------------------------------------------- /contracts/test/TestERC20.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity =0.8.17; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 5 | 6 | contract TestERC20 is ERC20 { 7 | constructor(string memory name_, string memory symbol_, uint256 amountToMint) ERC20(name_, symbol_) { 8 | setBalance(msg.sender, amountToMint); 9 | } 10 | 11 | // sets the balance of the address 12 | // this mints/burns the amount depending on the current balance 13 | function setBalance(address to, uint256 amount) public { 14 | uint256 old = balanceOf(to); 15 | if (old < amount) { 16 | _mint(to, amount - old); 17 | } else if (old > amount) { 18 | _burn(to, old - amount); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /hardhat.config.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @type import('hardhat/config').HardhatUserConfig 3 | */ 4 | require('dotenv').config() 5 | import '@nomiclabs/hardhat-ethers' 6 | import '@nomiclabs/hardhat-waffle' 7 | 8 | module.exports = { 9 | solidity: { 10 | compilers: [ 11 | { 12 | version: '0.8.17', 13 | settings: { 14 | optimizer: { 15 | enabled: true, 16 | runs: 5000, 17 | }, 18 | }, 19 | }, 20 | ], 21 | }, 22 | networks: { 23 | hardhat: { 24 | settings: { 25 | debug: { 26 | revertStrings: 'debug', 27 | }, 28 | }, 29 | }, 30 | tenderly: { 31 | chainId: 1, 32 | url: `https://rpc.tenderly.co/fork/${process.env.TENDERLY_FORK_ID}`, 33 | accounts: process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [], 34 | }, 35 | mainnet: { 36 | url: `https://mainnet.infura.io/v3/${process.env.INFURA_KEY}`, // or any other JSON-RPC provider 37 | accounts: process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [], 38 | }, 39 | }, 40 | } 41 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@uniswap/merkle-distributor", 3 | "version": "1.0.1", 4 | "description": "📦 A smart contract that distributes a balance of tokens according to a merkle root", 5 | "keywords": [ 6 | "uniswap", 7 | "erc20" 8 | ], 9 | "homepage": "https://uniswap.org", 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/Uniswap/merkle-distributor" 13 | }, 14 | "author": { 15 | "name": "Moody Salem" 16 | }, 17 | "files": [ 18 | "build" 19 | ], 20 | "scripts": { 21 | "precompile": "rimraf ./build/", 22 | "compile": "npx hardhat compile", 23 | "generate-merkle-root": "ts-node scripts/generate-merkle-root.ts", 24 | "generate-merkle-root:example": "ts-node scripts/generate-merkle-root.ts --input scripts/example.json", 25 | "prepublishOnly": "yarn test", 26 | "pretest": "yarn compile", 27 | "test": "npx hardhat test" 28 | }, 29 | "dependencies": { 30 | "@openzeppelin/contracts": "4.7.0" 31 | }, 32 | "devDependencies": { 33 | "@nomiclabs/hardhat-ethers": "^2.0.6", 34 | "@nomiclabs/hardhat-waffle": "^2.0.3", 35 | "@types/chai": "^4.2.6", 36 | "@types/mocha": "^5.2.7", 37 | "axios": "^0.20.0", 38 | "chai": "^4.2.0", 39 | "commander": "^6.1.0", 40 | "dotenv": "^16.0.1", 41 | "ethereum-waffle": "^3.0.0", 42 | "ethereumjs-util": "^7.0.4", 43 | "ethers": "5.6.9", 44 | "hardhat": "^2.9.9", 45 | "mocha": "^6.2.2", 46 | "prettier": "^2.0.5", 47 | "rimraf": "^3.0.0", 48 | "solc": "0.6.11", 49 | "ts-node": "^8.5.4", 50 | "typescript": "^3.7.3" 51 | }, 52 | "engines": { 53 | "node": ">=16" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /scripts/complex_example.json: -------------------------------------------------------------------------------- 1 | { 2 | "0xF3c6F5F265F503f53EAD8aae90FC257A5aa49AC1": 1, 3 | "0xB9CcDD7Bedb7157798e10Ff06C7F10e0F37C6BdD": 2, 4 | "0xf94DbB18cc2a7852C9CEd052393d517408E8C20C": 3, 5 | "0xf0591a60b8dBa2420408Acc5eDFA4f8A15d87308": 4, 6 | "0x6A2dE67981CbE91209c1046D67eF7a45631d0666": 5, 7 | "0x7C262baf13794f54e3514539c411f92716996C38": 6, 8 | "0x57E7c6B647C004CFB7A38E08fDDef09Af5Ea55eD": 7, 9 | "0x05fc93DeFFFe436822100E795F376228470FB514": 8, 10 | "0x6b6C7139B48156d7EC90eD4c55C56bDFCB1C19D2": 9, 11 | "0x7D13f07889F04a593a3E12f5d3f8Bf850d07465B": 10, 12 | "0xb86739476a4820FcC39Ff1C413d9af0b96c1589F": 11, 13 | "0xf66705E0Ae4e5DfC02b2633356f5305662F00d3b": 12, 14 | "0xC7AA922f0823DeE2eD721E61ebCCF2F9596017Fb": 13, 15 | "0x6E9Ead46916950088E236A77bb7b6309170827CA": 14, 16 | "0x656231095A6700620062B308C900E124461C48B6": 15, 17 | "0xCb73bE1851f2133895C05D408666475bA8Da351e": 16, 18 | "0x6FCBCB45deE6649450932f7FF142C7c434CED9a6": 17, 19 | "0xB34bf945E5a5698087820812e9CCBA0686D2a783": 18, 20 | "0x31f161a781a30AB4bF4Bf11175e3098204FB5235": 19, 21 | "0xde03a8041B40FF95F7F6b6ca0d1Da80fbBD07925": 20, 22 | "0xdc7B752019AC5eFA067Bd3dE17Fc2D2c7C8d881e": 21, 23 | "0xcB4A9ae3d5C4c9BF3c688d387230559018FB90C3": 22, 24 | "0x97Ac383e64d5a1A2A08c646C87B6e0546F7c164B": 23, 25 | "0xc0B7C64d370A9ffcFb9ef675809126c5cAfA9619": 24, 26 | "0xC910240362A5dda9e6cE8fAc86C329864d9Da15d": 25, 27 | "0x7e72833a9D8Da5458470f2B226f1c095ef335e86": 26, 28 | "0x40DeF14b2793e99f1f453FbD98A0f251a1D19f4f": 27, 29 | "0xBC61c73CFc191321DA837def848784c002279a01": 28, 30 | "0x32Cc3F29cde7ac9c000FEbf0D8F28B94F1A34441": 29, 31 | "0x538F43872aC14d3130721Df4F02a3Ff05053A2d9": 30, 32 | "0xDE78e3462c9F976257E5E4Ed821BE7B306B23450": 31, 33 | "0xF1079DD1048A65cA9f9153246164758203d1aEd5": 32, 34 | "0xAb7Fb5958785b20bdccd2A65d15F139B60080fAc": 33, 35 | "0xc6b467aCAa5B07b8182749524385B79DBb909B14": 34, 36 | "0xE7fA80757FeAb870E0bF3b3dc8d4647f403A65ac": 35, 37 | "0x72381936D8e22a52F9a6ea62e23628084085D05b": 36, 38 | "0x3fC98BAD7384a354f8b083Fc5A7D621DF5fB9F41": 37, 39 | "0x5e471D67A610f541B63a8789A9BE1F0fAcd9E244": 38, 40 | "0x5a693Fc88b80Bd7e57f676Bd5e0945995f68bC47": 39, 41 | "0x69eA0b9B0b489B87E061e3e85886D668b24157Ad": 40, 42 | "0x7D0Fe663D9488F6793D813e51EC1DC600F289ad3": 41, 43 | "0x162F49fE6F365d04Db07F77377699aeFE2E8A2cf": 42, 44 | "0x8A1F2B46A35D10F0EafbE6c7f0671d8DB847dcA2": 43, 45 | "0x4aA6E2Fe3f306CB777dFeA344daaAd33eB50f972": 44, 46 | "0x1fCBa490902B2BD44ba98359C7075e2C8a2b9F15": 45, 47 | "0xdd1f7Ea709BD594D834411AE22D81a5B6a91008F": 46, 48 | "0x406b7968735b79688C6694634f2Ef5CF01c386F5": 47, 49 | "0x7152dc7a0eC646A7bCD3b00EF4Ca984E337da2B3": 48, 50 | "0xdf9424b7563A00386217471cfAC8944185505c56": 49, 51 | "0xaDF30D969b396DFC5035Cb3921034Bfb86CC055d": 50, 52 | "0xf970e1f7e89a57485E139F9EB4652181Ef270515": 51, 53 | "0xBd8BcBdF78205590FD576acaf110d70069eE7125": 52, 54 | "0xd7663Ca75082939012A9b5DCaFaDABEA51352F70": 53, 55 | "0x75662678a74C6aD63501519F656CE4Db04e1EF49": 54, 56 | "0xC1f94BCA2146B462685FC04Bf10f8b8CB7a305a3": 55, 57 | "0x7DD3A4cCf156475AE927E9aedc91E9f33AABc79d": 56, 58 | "0x85c5EE48A6687c9D903052a22f5764Bed2B4A6A8": 57, 59 | "0x73f24B3cB7FDAf629d2DC44f67ADaA99005719B0": 58, 60 | "0x9Cce64165E28dEA01a8b9c977F4dbD9D791EbcFf": 59, 61 | "0xcB667d9F540E721858e77E6667e281Aa6fFD5C17": 60, 62 | "0x0f39bceBE74751D89c37a2671DE0c750b71cA152": 61, 63 | "0xC0CDEE637cd0Ef7Ef7ab2696ffADc9C78F4daa0B": 62, 64 | "0x0cF605Ad65B1A541Ca6390606F944D176D5B9950": 63, 65 | "0x614de94D2E18c174bc0155EFef55bAa9cB55bAf2": 64, 66 | "0xa47A8fa265bf540184fA3499566761A608Be84EE": 65, 67 | "0xD2ED9f212c6f5d127757fA700cc55235F5cBc167": 66, 68 | "0xfA4563612C9De62302364ee8042635e44c8327fF": 67, 69 | "0x0350D208F3D94Af84724e437fAa7ebe5A3C35aC7": 68, 70 | "0x31de7522f31322081516703F78ce8eA128d9D6f7": 69, 71 | "0x3e51a90d40F8dC43d2b8720B3671aa208b0316ac": 70, 72 | "0x9BDFE65726326c104a302B172e49c4946E481306": 71, 73 | "0xe7B6bdA3990D0F6892cB1c37F4f2867a8Df4Fe5e": 72, 74 | "0x42B6cC78074eF1C5eC4AEe844B4B9c27b199831F": 73, 75 | "0x1E5eF4320142B6721C27846c9Ab4D6F0a0aFD2CE": 74, 76 | "0xA998c01B7c9674490480ec68bCf27C836CF9B495": 75, 77 | "0xa087344Bc4A05D2885aa9531ae6694e0C5dEb728": 76, 78 | "0x8874a8B06bd074953a9b22CaaC0Ce3bCf1260fB4": 77, 79 | "0x8943b759EaAa0e51b93ddB12B19e9EB71A361c69": 78, 80 | "0x4540e3Ef6dC7a420cd44767F98EF15BEEA28606D": 79, 81 | "0x4d9366B189AA78B9764Bd50B22F9398ABB4AcFbD": 80, 82 | "0x250fC1677986e6c3CEb348a378919f5b0Eb487ea": 81, 83 | "0x1668395E2FDEC223E175111ff8bDce4180A3B680": 82, 84 | "0x904dac1641aC5DAB76B7b2B2AB2779E98ac6BC74": 83, 85 | "0x169D0Cc3e36D3C9253Dd8418421Af5F84a75EC76": 84, 86 | "0x012ed55a0876Ea9e58277197DC14CbA47571CE28": 85, 87 | "0xc07b1400fB950253fbfC5484601036f18c8A91CC": 86, 88 | "0x3741c4751bBff7ba5D58BDA8F1c25Cb71b6b95D2": 87, 89 | "0x01dC7F8C928CeA27D8fF928363111c291bEB20b1": 88, 90 | "0x41560a0CC92C4267614721140a031aE20051Bb65": 89, 91 | "0xF1d322d48E47eb4A806bAB843B5C79Af641bb8cD": 90, 92 | "0x332BC77780057942cAa2c7bad21a04E91B5Ed687": 91, 93 | "0x8519E69FfaF870479534b362ce34F666533aE758": 92, 94 | "0xBF134F1BD442c77F01d4784D991F3c191ce700cf": 93, 95 | "0xb7649E4000AD4748dc2907eCdcAC4ae3d59da0D5": 94, 96 | "0x84664986ad6D1237010be3BFC0F88555edc6987f": 95, 97 | "0x983a9ed0e4A274314231BFce58Ec973f0D298c9d": 96, 98 | "0x9F0A64c6956D7205E883ae8A3C19577f1cadD78F": 97, 99 | "0xB96cE59522314ACB1502Dc8d3e192995e36439c1": 98, 100 | "0x5A553d59435Df0688fd5dEa1aa66C7430541ffB3": 99 101 | } 102 | -------------------------------------------------------------------------------- /scripts/deployMerkleDistributor.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config() 2 | require('@nomiclabs/hardhat-ethers') 3 | const { ethers } = require('hardhat') 4 | 5 | async function main() { 6 | const MerkleDistributor = await ethers.getContractFactory('MerkleDistributor') 7 | const merkleDistributor = await MerkleDistributor.deploy( 8 | // USDC 9 | '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', 10 | '0x525df38ec587d18df62b7e004e44c6cb4c3af6981d1d3f156e73eeafb1a128a5' 11 | ) 12 | await merkleDistributor.deployed() 13 | console.log(`merkleDistributor deployed at ${merkleDistributor.address}`) 14 | } 15 | 16 | main() 17 | // eslint-disable-next-line no-process-exit 18 | .then(() => process.exit(0)) 19 | .catch((error) => { 20 | console.error(error) 21 | // eslint-disable-next-line no-process-exit 22 | process.exit(1) 23 | }) 24 | -------------------------------------------------------------------------------- /scripts/deployMerkleDistributorWithDeadline.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config() 2 | require('@nomiclabs/hardhat-ethers') 3 | const { ethers } = require('hardhat') 4 | 5 | async function main() { 6 | const MerkleDistributorWithDeadline = await ethers.getContractFactory('MerkleDistributorWithDeadline') 7 | const merkleDistributorWithDeadline = await MerkleDistributorWithDeadline.deploy( 8 | // USDC 9 | '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', 10 | '0xbe154afea9ba1e08729654a19c53952a892d6b37fe0b5d1bdf8ac4f51d03a426', 11 | 1688493524 12 | ) 13 | await merkleDistributorWithDeadline.deployed() 14 | console.log(`merkleDistributorWithDeadline deployed at ${merkleDistributorWithDeadline.address}`) 15 | } 16 | 17 | main() 18 | // eslint-disable-next-line no-process-exit 19 | .then(() => process.exit(0)) 20 | .catch((error) => { 21 | console.error(error) 22 | // eslint-disable-next-line no-process-exit 23 | process.exit(1) 24 | }) 25 | -------------------------------------------------------------------------------- /scripts/example.json: -------------------------------------------------------------------------------- 1 | { 2 | "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f": "100" 3 | } 4 | -------------------------------------------------------------------------------- /scripts/generate-merkle-root.ts: -------------------------------------------------------------------------------- 1 | import { program } from 'commander' 2 | import fs from 'fs' 3 | import { parseBalanceMap } from '../src/parse-balance-map' 4 | 5 | program 6 | .version('0.0.0') 7 | .requiredOption( 8 | '-i, --input ', 9 | 'input JSON file location containing a map of account addresses to string balances' 10 | ) 11 | 12 | program.parse(process.argv) 13 | 14 | const json = JSON.parse(fs.readFileSync(program.input, { encoding: 'utf8' })) 15 | 16 | if (typeof json !== 'object') throw new Error('Invalid JSON') 17 | 18 | console.log(JSON.stringify(parseBalanceMap(json))) 19 | -------------------------------------------------------------------------------- /scripts/new_example.json: -------------------------------------------------------------------------------- 1 | [ 2 | { "address": "0x097a3a6ce1d77a11bda1ac40c08fdf9f6202103f", "earnings": "0x2086ac351052600000", "reasons": "socks" }, 3 | { 4 | "address": "0xfa6863a6507c94ed52e9276f8a72479924e77a36", 5 | "earnings": "0x30ca024f987b900000", 6 | "reasons": "socks,user" 7 | }, 8 | { 9 | "address": "0xef6fe9c9b351824c96e5c7a478c1e52badcbaee0", 10 | "earnings": "0x30ca024f987b900000", 11 | "reasons": "socks,user" 12 | }, 13 | { 14 | "address": "0x397aca36ab63dbc1bdafc65a9916dcaee6c94e60", 15 | "earnings": "0x30ca024f987b900000", 16 | "reasons": "socks,user" 17 | }, 18 | { 19 | "address": "0x08d816526bdc9d077dd685bd9fa49f58a5ab8e48", 20 | "earnings": "0x30ca024f987b900000", 21 | "reasons": "socks,user" 22 | }, 23 | { 24 | "address": "0x3b16821a5dbbff86e4a88ea0621ec6be016cd79a", 25 | "earnings": "0x30ca024f987b900000", 26 | "reasons": "socks,user" 27 | }, 28 | { 29 | "address": "0xa1d3c765e9a9655e8838bc4a9b16d5e6af024321", 30 | "earnings": "0x30ca024f987b900000", 31 | "reasons": "socks,user" 32 | }, 33 | { 34 | "address": "0x3605780992537dcaae52a8da39238d6d883b7009", 35 | "earnings": "0x30ca024f987b900000", 36 | "reasons": "socks,user" 37 | }, 38 | { 39 | "address": "0x6561155263438064ffdd5fe2481d872f7dba95e7", 40 | "earnings": "0x30ca024f987b900000", 41 | "reasons": "socks,user" 42 | }, 43 | { 44 | "address": "0x54626c49ecd78b2ea5aeecaec82049ca26a04028", 45 | "earnings": "0x30ca024f987b900000", 46 | "reasons": "socks,user" 47 | }, 48 | { 49 | "address": "0xacf4c2950107ef9b1c37faa1f9a866c8f0da88b9", 50 | "earnings": "0x30ca024f987b900000", 51 | "reasons": "socks,user" 52 | }, 53 | { 54 | "address": "0xa289364347bfc1912ab672425abe593ec01ca56e", 55 | "earnings": "0x30ca024f987b900000", 56 | "reasons": "socks,user" 57 | }, 58 | { 59 | "address": "0x97209d58e75a799d41e4f5f7acf3aa675c9053f2", 60 | "earnings": "0x30ca024f987b900000", 61 | "reasons": "socks,user" 62 | }, 63 | { 64 | "address": "0xb262fa34e8fe3b664689945c9f3830a35d30e44b", 65 | "earnings": "0x30ca024f987b900000", 66 | "reasons": "socks,user" 67 | }, 68 | { 69 | "address": "0xea271b7dc328b43a9af9d406484d1e79613f7127", 70 | "earnings": "0x30ca024f987b900000", 71 | "reasons": "socks,user" 72 | }, 73 | { 74 | "address": "0xe248bf601aaf6dd25532e92e72630c4f9cdb0ed7", 75 | "earnings": "0x30ca024f987b900000", 76 | "reasons": "socks,user" 77 | }, 78 | { 79 | "address": "0x60e7ba91afd79ce71635b9249072bd43a63ea390", 80 | "earnings": "0x30ca024f987b900000", 81 | "reasons": "socks,user" 82 | }, 83 | { 84 | "address": "0x3f3b4c780dcfc39b24b0d09b1f1f1cf133b733d5", 85 | "earnings": "0x30ca024f987b900000", 86 | "reasons": "socks,user" 87 | }, 88 | { 89 | "address": "0xb9b8de4b0b7020920c0476ff1d74d6c51aec7796", 90 | "earnings": "0x30ca024f987b900000", 91 | "reasons": "socks,user" 92 | }, 93 | { 94 | "address": "0xfde5cff51e4ec5495a86cf8d1b1f7b915eca02e0", 95 | "earnings": "0x30ca024f987b900000", 96 | "reasons": "socks,user" 97 | }, 98 | { 99 | "address": "0xf8f0cb8b06b2ba827ae8e7915deb0cf796aec53b", 100 | "earnings": "0x30ca024f987b900000", 101 | "reasons": "socks,user" 102 | }, 103 | { 104 | "address": "0x110f1c53c546fb83fba121033ea22551e5e07193", 105 | "earnings": "0x30ca024f987b900000", 106 | "reasons": "socks,user" 107 | }, 108 | { 109 | "address": "0xdc2cf5cbfa31958ed32c3ace696ee6bf1a6a19f4", 110 | "earnings": "0x30ca024f987b900000", 111 | "reasons": "socks,user" 112 | }, 113 | { 114 | "address": "0x217ba130ce2452d3793fd524c11ddee63898aff7", 115 | "earnings": "0x30ca024f987b900000", 116 | "reasons": "socks,user" 117 | }, 118 | { 119 | "address": "0xb827037835778e750b3ee18bc207c4830888140a", 120 | "earnings": "0x30ca024f987b900000", 121 | "reasons": "socks,user" 122 | }, 123 | { 124 | "address": "0x9f2942ff27e40445d3cb2aad90f84c3a03574f26", 125 | "earnings": "0x30ca024f987b900000", 126 | "reasons": "socks,user" 127 | }, 128 | { 129 | "address": "0x4a21fa249086f1227f4005398035340cdb318c20", 130 | "earnings": "0x30ca024f987b900000", 131 | "reasons": "socks,user" 132 | }, 133 | { 134 | "address": "0xd1edec711d5ea0b4b064b678ff4a13b2c2a5ce8b", 135 | "earnings": "0x30ca024f987b900000", 136 | "reasons": "socks,user" 137 | }, 138 | { 139 | "address": "0x9a3e204bd2f012122b228fa68bf97539da965d3b", 140 | "earnings": "0x30ca024f987b900000", 141 | "reasons": "socks,user" 142 | }, 143 | { 144 | "address": "0x7f46bb25460dd7dae4211ca7f15ad312fc7dc75c", 145 | "earnings": "0x30ca024f987b900000", 146 | "reasons": "socks,user" 147 | }, 148 | { 149 | "address": "0x5d509f653d7e4914af9da434bf25c53cd122763d", 150 | "earnings": "0x30ca024f987b900000", 151 | "reasons": "socks,user" 152 | }, 153 | { 154 | "address": "0xf7dbfe7dcfba501464008554e7c5edde8ab7b0ff", 155 | "earnings": "0x30ca024f987b900000", 156 | "reasons": "socks,user" 157 | }, 158 | { 159 | "address": "0x1db3439a222c519ab44bb1144fc28167b4fa6ee6", 160 | "earnings": "0x30ca024f987b900000", 161 | "reasons": "socks,user" 162 | }, 163 | { 164 | "address": "0xd1f55571cbb04139716a9a5076aa69626b6df009", 165 | "earnings": "0x30ca1208d69308723c", 166 | "reasons": "socks,lp,user" 167 | } 168 | ] 169 | -------------------------------------------------------------------------------- /scripts/result.json: -------------------------------------------------------------------------------- 1 | { 2 | "merkleRoot": "0xdefa96435aec82d201dbd2e5f050fb4e1fef5edac90ce1e03953f916a5e1132d", 3 | "tokenTotal": "0x64", 4 | "numDrops": 1, 5 | "claims": { "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f": { "index": 0, "amount": "0x64", "proof": [] } } 6 | } 7 | -------------------------------------------------------------------------------- /scripts/to-kv-input.ts: -------------------------------------------------------------------------------- 1 | import { program } from 'commander' 2 | import fs from 'fs' 3 | import axios from 'axios' 4 | 5 | const BATCH_SIZE = 10_000 6 | 7 | program 8 | .version('0.0.0') 9 | .requiredOption('-i, --input ', 'input JSON file location containing a claims tree') 10 | .requiredOption('-c, --chain-id ', 'chain ID of the merkle kv root') 11 | .requiredOption('-t, --token ', 'Cloudflare API token') 12 | .requiredOption('-a, --account-identifier ', 'Cloudflare account identifier') 13 | .requiredOption('-n, --namespace-identifier ', 'Cloudflare KV namespace identifier') 14 | 15 | program.parse(process.argv) 16 | 17 | const json = JSON.parse(fs.readFileSync(program.input, { encoding: 'utf8' })) 18 | 19 | if (typeof json !== 'object') throw new Error('Invalid JSON') 20 | 21 | async function main() { 22 | const KV = Object.keys(json.claims).map((account) => { 23 | const claim = json.claims[account] 24 | return { 25 | key: `${program.chainId}:${account}`, 26 | value: JSON.stringify(claim), 27 | } 28 | }) 29 | 30 | let i = 0 31 | while (i < KV.length) { 32 | await axios 33 | .put( 34 | `https://api.cloudflare.com/client/v4/accounts/${program.accountIdentifier}/storage/kv/namespaces/${program.namespaceIdentifier}/bulk`, 35 | JSON.stringify(KV.slice(i, (i += BATCH_SIZE))), 36 | { 37 | maxBodyLength: Infinity, 38 | headers: { Authorization: `Bearer ${program.token}`, 'Content-Type': 'application/json' }, 39 | } 40 | ) 41 | .then((response) => { 42 | if (!response.data.success) { 43 | throw Error(response.data.errors) 44 | } 45 | }) 46 | 47 | console.log(`Uploaded ${i} records in total`) 48 | } 49 | } 50 | 51 | main() 52 | -------------------------------------------------------------------------------- /scripts/verify-merkle-root.ts: -------------------------------------------------------------------------------- 1 | import { program } from 'commander' 2 | import fs from 'fs' 3 | import { BigNumber, utils } from 'ethers' 4 | 5 | program 6 | .version('0.0.0') 7 | .requiredOption( 8 | '-i, --input ', 9 | 'input JSON file location containing the merkle proofs for each account and the merkle root' 10 | ) 11 | 12 | program.parse(process.argv) 13 | const json = JSON.parse(fs.readFileSync(program.input, { encoding: 'utf8' })) 14 | 15 | const combinedHash = (first: Buffer, second: Buffer): Buffer => { 16 | if (!first) { 17 | return second 18 | } 19 | if (!second) { 20 | return first 21 | } 22 | 23 | return Buffer.from( 24 | utils.solidityKeccak256(['bytes32', 'bytes32'], [first, second].sort(Buffer.compare)).slice(2), 25 | 'hex' 26 | ) 27 | } 28 | 29 | const toNode = (index: number | BigNumber, account: string, amount: BigNumber): Buffer => { 30 | const pairHex = utils.solidityKeccak256(['uint256', 'address', 'uint256'], [index, account, amount]) 31 | return Buffer.from(pairHex.slice(2), 'hex') 32 | } 33 | 34 | const verifyProof = ( 35 | index: number | BigNumber, 36 | account: string, 37 | amount: BigNumber, 38 | proof: Buffer[], 39 | root: Buffer 40 | ): boolean => { 41 | let pair = toNode(index, account, amount) 42 | for (const item of proof) { 43 | pair = combinedHash(pair, item) 44 | } 45 | 46 | return pair.equals(root) 47 | } 48 | 49 | const getNextLayer = (elements: Buffer[]): Buffer[] => { 50 | return elements.reduce((layer, el, idx, arr) => { 51 | if (idx % 2 === 0) { 52 | // Hash the current element with its pair element 53 | layer.push(combinedHash(el, arr[idx + 1])) 54 | } 55 | 56 | return layer 57 | }, []) 58 | } 59 | 60 | const getRoot = (balances: { account: string; amount: BigNumber; index: number }[]): Buffer => { 61 | let nodes = balances 62 | .map(({ account, amount, index }) => toNode(index, account, amount)) 63 | // sort by lexicographical order 64 | .sort(Buffer.compare) 65 | 66 | // deduplicate any eleents 67 | nodes = nodes.filter((el, idx) => { 68 | return idx === 0 || !nodes[idx - 1].equals(el) 69 | }) 70 | 71 | const layers = [] 72 | layers.push(nodes) 73 | 74 | // Get next layer until we reach the root 75 | while (layers[layers.length - 1].length > 1) { 76 | layers.push(getNextLayer(layers[layers.length - 1])) 77 | } 78 | 79 | return layers[layers.length - 1][0] 80 | } 81 | 82 | if (typeof json !== 'object') throw new Error('Invalid JSON') 83 | 84 | const merkleRootHex = json.merkleRoot 85 | const merkleRoot = Buffer.from(merkleRootHex.slice(2), 'hex') 86 | 87 | let balances: { index: number; account: string; amount: BigNumber }[] = [] 88 | let valid = true 89 | 90 | Object.keys(json.claims).forEach((address) => { 91 | const claim = json.claims[address] 92 | const proof = claim.proof.map((p: string) => Buffer.from(p.slice(2), 'hex')) 93 | balances.push({ index: claim.index, account: address, amount: BigNumber.from(claim.amount) }) 94 | if (verifyProof(claim.index, address, claim.amount, proof, merkleRoot)) { 95 | console.log('Verified proof for', claim.index, address) 96 | } else { 97 | console.log('Verification for', address, 'failed') 98 | valid = false 99 | } 100 | }) 101 | 102 | if (!valid) { 103 | console.error('Failed validation for 1 or more proofs') 104 | process.exit(1) 105 | } 106 | console.log('Done!') 107 | 108 | // Root 109 | const root = getRoot(balances).toString('hex') 110 | console.log('Reconstructed merkle root', root) 111 | console.log('Root matches the one read from the JSON?', root === merkleRootHex.slice(2)) 112 | -------------------------------------------------------------------------------- /src/balance-tree.ts: -------------------------------------------------------------------------------- 1 | import MerkleTree from './merkle-tree' 2 | import { BigNumber, utils } from 'ethers' 3 | 4 | export default class BalanceTree { 5 | private readonly tree: MerkleTree 6 | constructor(balances: { account: string; amount: BigNumber }[]) { 7 | this.tree = new MerkleTree( 8 | balances.map(({ account, amount }, index) => { 9 | return BalanceTree.toNode(index, account, amount) 10 | }) 11 | ) 12 | } 13 | 14 | public static verifyProof( 15 | index: number | BigNumber, 16 | account: string, 17 | amount: BigNumber, 18 | proof: Buffer[], 19 | root: Buffer 20 | ): boolean { 21 | let pair = BalanceTree.toNode(index, account, amount) 22 | for (const item of proof) { 23 | pair = MerkleTree.combinedHash(pair, item) 24 | } 25 | 26 | return pair.equals(root) 27 | } 28 | 29 | // keccak256(abi.encode(index, account, amount)) 30 | public static toNode(index: number | BigNumber, account: string, amount: BigNumber): Buffer { 31 | return Buffer.from( 32 | utils.solidityKeccak256(['uint256', 'address', 'uint256'], [index, account, amount]).substr(2), 33 | 'hex' 34 | ) 35 | } 36 | 37 | public getHexRoot(): string { 38 | return this.tree.getHexRoot() 39 | } 40 | 41 | // returns the hex bytes32 values of the proof 42 | public getProof(index: number | BigNumber, account: string, amount: BigNumber): string[] { 43 | return this.tree.getHexProof(BalanceTree.toNode(index, account, amount)) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/merkle-tree.ts: -------------------------------------------------------------------------------- 1 | import { bufferToHex, keccak256 } from 'ethereumjs-util' 2 | 3 | export default class MerkleTree { 4 | private readonly elements: Buffer[] 5 | private readonly bufferElementPositionIndex: { [hexElement: string]: number } 6 | private readonly layers: Buffer[][] 7 | 8 | constructor(elements: Buffer[]) { 9 | this.elements = [...elements] 10 | // Sort elements 11 | this.elements.sort(Buffer.compare) 12 | // Deduplicate elements 13 | this.elements = MerkleTree.bufDedup(this.elements) 14 | 15 | this.bufferElementPositionIndex = this.elements.reduce<{ [hexElement: string]: number }>((memo, el, index) => { 16 | memo[bufferToHex(el)] = index 17 | return memo 18 | }, {}) 19 | 20 | // Create layers 21 | this.layers = this.getLayers(this.elements) 22 | } 23 | 24 | getLayers(elements: Buffer[]): Buffer[][] { 25 | if (elements.length === 0) { 26 | throw new Error('empty tree') 27 | } 28 | 29 | const layers = [] 30 | layers.push(elements) 31 | 32 | // Get next layer until we reach the root 33 | while (layers[layers.length - 1].length > 1) { 34 | layers.push(this.getNextLayer(layers[layers.length - 1])) 35 | } 36 | 37 | return layers 38 | } 39 | 40 | getNextLayer(elements: Buffer[]): Buffer[] { 41 | return elements.reduce((layer, el, idx, arr) => { 42 | if (idx % 2 === 0) { 43 | // Hash the current element with its pair element 44 | layer.push(MerkleTree.combinedHash(el, arr[idx + 1])) 45 | } 46 | 47 | return layer 48 | }, []) 49 | } 50 | 51 | static combinedHash(first: Buffer, second: Buffer): Buffer { 52 | if (!first) { 53 | return second 54 | } 55 | if (!second) { 56 | return first 57 | } 58 | 59 | return keccak256(MerkleTree.sortAndConcat(first, second)) 60 | } 61 | 62 | getRoot(): Buffer { 63 | return this.layers[this.layers.length - 1][0] 64 | } 65 | 66 | getHexRoot(): string { 67 | return bufferToHex(this.getRoot()) 68 | } 69 | 70 | getProof(el: Buffer) { 71 | let idx = this.bufferElementPositionIndex[bufferToHex(el)] 72 | 73 | if (typeof idx !== 'number') { 74 | throw new Error('Element does not exist in Merkle tree') 75 | } 76 | 77 | return this.layers.reduce((proof, layer) => { 78 | const pairElement = MerkleTree.getPairElement(idx, layer) 79 | 80 | if (pairElement) { 81 | proof.push(pairElement) 82 | } 83 | 84 | idx = Math.floor(idx / 2) 85 | 86 | return proof 87 | }, []) 88 | } 89 | 90 | getHexProof(el: Buffer): string[] { 91 | const proof = this.getProof(el) 92 | 93 | return MerkleTree.bufArrToHexArr(proof) 94 | } 95 | 96 | private static getPairElement(idx: number, layer: Buffer[]): Buffer | null { 97 | const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1 98 | 99 | if (pairIdx < layer.length) { 100 | return layer[pairIdx] 101 | } else { 102 | return null 103 | } 104 | } 105 | 106 | private static bufDedup(elements: Buffer[]): Buffer[] { 107 | return elements.filter((el, idx) => { 108 | return idx === 0 || !elements[idx - 1].equals(el) 109 | }) 110 | } 111 | 112 | private static bufArrToHexArr(arr: Buffer[]): string[] { 113 | if (arr.some((el) => !Buffer.isBuffer(el))) { 114 | throw new Error('Array is not an array of buffers') 115 | } 116 | 117 | return arr.map((el) => '0x' + el.toString('hex')) 118 | } 119 | 120 | private static sortAndConcat(...args: Buffer[]): Buffer { 121 | return Buffer.concat([...args].sort(Buffer.compare)) 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/parse-balance-map.ts: -------------------------------------------------------------------------------- 1 | import { BigNumber, utils } from 'ethers' 2 | import BalanceTree from './balance-tree' 3 | 4 | const { isAddress, getAddress } = utils 5 | 6 | // This is the blob that gets distributed and pinned to IPFS. 7 | // It is completely sufficient for recreating the entire merkle tree. 8 | // Anyone can verify that all air drops are included in the tree, 9 | // and the tree has no additional distributions. 10 | interface MerkleDistributorInfo { 11 | merkleRoot: string 12 | tokenTotal: string 13 | claims: { 14 | [account: string]: { 15 | index: number 16 | amount: string 17 | proof: string[] 18 | flags?: { 19 | [flag: string]: boolean 20 | } 21 | } 22 | } 23 | } 24 | 25 | type OldFormat = { [account: string]: number | string } 26 | type NewFormat = { address: string; earnings: string; reasons: string } 27 | 28 | export function parseBalanceMap(balances: OldFormat | NewFormat[]): MerkleDistributorInfo { 29 | // if balances are in an old format, process them 30 | const balancesInNewFormat: NewFormat[] = Array.isArray(balances) 31 | ? balances 32 | : Object.keys(balances).map( 33 | (account): NewFormat => ({ 34 | address: account, 35 | earnings: `0x${balances[account].toString(16)}`, 36 | reasons: '', 37 | }) 38 | ) 39 | 40 | const dataByAddress = balancesInNewFormat.reduce<{ 41 | [address: string]: { amount: BigNumber; flags?: { [flag: string]: boolean } } 42 | }>((memo, { address: account, earnings, reasons }) => { 43 | if (!isAddress(account)) { 44 | throw new Error(`Found invalid address: ${account}`) 45 | } 46 | const parsed = getAddress(account) 47 | if (memo[parsed]) throw new Error(`Duplicate address: ${parsed}`) 48 | const parsedNum = BigNumber.from(earnings) 49 | if (parsedNum.lte(0)) throw new Error(`Invalid amount for account: ${account}`) 50 | 51 | const flags = { 52 | isSOCKS: reasons.includes('socks'), 53 | isLP: reasons.includes('lp'), 54 | isUser: reasons.includes('user'), 55 | } 56 | 57 | memo[parsed] = { amount: parsedNum, ...(reasons === '' ? {} : { flags }) } 58 | return memo 59 | }, {}) 60 | 61 | const sortedAddresses = Object.keys(dataByAddress).sort() 62 | 63 | // construct a tree 64 | const tree = new BalanceTree( 65 | sortedAddresses.map((address) => ({ account: address, amount: dataByAddress[address].amount })) 66 | ) 67 | 68 | // generate claims 69 | const claims = sortedAddresses.reduce<{ 70 | [address: string]: { amount: string; index: number; proof: string[]; flags?: { [flag: string]: boolean } } 71 | }>((memo, address, index) => { 72 | const { amount, flags } = dataByAddress[address] 73 | memo[address] = { 74 | index, 75 | amount: amount.toHexString(), 76 | proof: tree.getProof(index, address, amount), 77 | ...(flags ? { flags } : {}), 78 | } 79 | return memo 80 | }, {}) 81 | 82 | const tokenTotal: BigNumber = sortedAddresses.reduce( 83 | (memo, key) => memo.add(dataByAddress[key].amount), 84 | BigNumber.from(0) 85 | ) 86 | 87 | return { 88 | merkleRoot: tree.getHexRoot(), 89 | tokenTotal: tokenTotal.toHexString(), 90 | claims, 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /test/MerkleDistributor.spec.ts.old: -------------------------------------------------------------------------------- 1 | import chai, { expect } from 'chai' 2 | import { solidity, MockProvider, deployContract } from 'ethereum-waffle' 3 | import { Contract, BigNumber, constants } from 'ethers' 4 | import BalanceTree from '../src/balance-tree' 5 | 6 | import Distributor from '../build/MerkleDistributor.json' 7 | import TestERC20 from '../build/TestERC20.json' 8 | import { parseBalanceMap } from '../src/parse-balance-map' 9 | 10 | chai.use(solidity) 11 | 12 | const overrides = { 13 | gasLimit: 9999999, 14 | } 15 | 16 | const ZERO_BYTES32 = '0x0000000000000000000000000000000000000000000000000000000000000000' 17 | 18 | describe('MerkleDistributor', () => { 19 | const provider = new MockProvider({ 20 | ganacheOptions: { 21 | hardfork: 'istanbul', 22 | mnemonic: 'horn horn horn horn horn horn horn horn horn horn horn horn', 23 | gasLimit: 9999999, 24 | }, 25 | }) 26 | 27 | const wallets = provider.getWallets() 28 | const [wallet0, wallet1] = wallets 29 | 30 | let token: Contract 31 | beforeEach('deploy token', async () => { 32 | token = await deployContract(wallet0, TestERC20, ['Token', 'TKN', 0], overrides) 33 | }) 34 | 35 | describe('#token', () => { 36 | it('returns the token address', async () => { 37 | const distributor = await deployContract(wallet0, Distributor, [token.address, ZERO_BYTES32], overrides) 38 | expect(await distributor.token()).to.eq(token.address) 39 | }) 40 | }) 41 | 42 | describe('#merkleRoot', () => { 43 | it('returns the zero merkle root', async () => { 44 | const distributor = await deployContract(wallet0, Distributor, [token.address, ZERO_BYTES32], overrides) 45 | expect(await distributor.merkleRoot()).to.eq(ZERO_BYTES32) 46 | }) 47 | }) 48 | 49 | describe('#claim', () => { 50 | it('fails for empty proof', async () => { 51 | const distributor = await deployContract(wallet0, Distributor, [token.address, ZERO_BYTES32], overrides) 52 | await expect(distributor.claim(0, wallet0.address, 10, [])).to.be.revertedWith( 53 | 'MerkleDistributor: Invalid proof.' 54 | ) 55 | }) 56 | 57 | it('fails for invalid index', async () => { 58 | const distributor = await deployContract(wallet0, Distributor, [token.address, ZERO_BYTES32], overrides) 59 | await expect(distributor.claim(0, wallet0.address, 10, [])).to.be.revertedWith( 60 | 'MerkleDistributor: Invalid proof.' 61 | ) 62 | }) 63 | 64 | describe('two account tree', () => { 65 | let distributor: Contract 66 | let tree: BalanceTree 67 | beforeEach('deploy', async () => { 68 | tree = new BalanceTree([ 69 | { account: wallet0.address, amount: BigNumber.from(100) }, 70 | { account: wallet1.address, amount: BigNumber.from(101) }, 71 | ]) 72 | distributor = await deployContract(wallet0, Distributor, [token.address, tree.getHexRoot()], overrides) 73 | await token.setBalance(distributor.address, 201) 74 | }) 75 | 76 | it('successful claim', async () => { 77 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 78 | await expect(distributor.claim(0, wallet0.address, 100, proof0, overrides)) 79 | .to.emit(distributor, 'Claimed') 80 | .withArgs(0, wallet0.address, 100) 81 | const proof1 = tree.getProof(1, wallet1.address, BigNumber.from(101)) 82 | await expect(distributor.claim(1, wallet1.address, 101, proof1, overrides)) 83 | .to.emit(distributor, 'Claimed') 84 | .withArgs(1, wallet1.address, 101) 85 | }) 86 | 87 | it('transfers the token', async () => { 88 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 89 | expect(await token.balanceOf(wallet0.address)).to.eq(0) 90 | await distributor.claim(0, wallet0.address, 100, proof0, overrides) 91 | expect(await token.balanceOf(wallet0.address)).to.eq(100) 92 | }) 93 | 94 | it('must have enough to transfer', async () => { 95 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 96 | await token.setBalance(distributor.address, 99) 97 | await expect(distributor.claim(0, wallet0.address, 100, proof0, overrides)).to.be.revertedWith( 98 | 'ERC20: transfer amount exceeds balance' 99 | ) 100 | }) 101 | 102 | it('sets #isClaimed', async () => { 103 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 104 | expect(await distributor.isClaimed(0)).to.eq(false) 105 | expect(await distributor.isClaimed(1)).to.eq(false) 106 | await distributor.claim(0, wallet0.address, 100, proof0, overrides) 107 | expect(await distributor.isClaimed(0)).to.eq(true) 108 | expect(await distributor.isClaimed(1)).to.eq(false) 109 | }) 110 | 111 | it('cannot allow two claims', async () => { 112 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 113 | await distributor.claim(0, wallet0.address, 100, proof0, overrides) 114 | await expect(distributor.claim(0, wallet0.address, 100, proof0, overrides)).to.be.revertedWith( 115 | 'MerkleDistributor: Drop already claimed.' 116 | ) 117 | }) 118 | 119 | it('cannot claim more than once: 0 and then 1', async () => { 120 | await distributor.claim( 121 | 0, 122 | wallet0.address, 123 | 100, 124 | tree.getProof(0, wallet0.address, BigNumber.from(100)), 125 | overrides 126 | ) 127 | await distributor.claim( 128 | 1, 129 | wallet1.address, 130 | 101, 131 | tree.getProof(1, wallet1.address, BigNumber.from(101)), 132 | overrides 133 | ) 134 | 135 | await expect( 136 | distributor.claim(0, wallet0.address, 100, tree.getProof(0, wallet0.address, BigNumber.from(100)), overrides) 137 | ).to.be.revertedWith('MerkleDistributor: Drop already claimed.') 138 | }) 139 | 140 | it('cannot claim more than once: 1 and then 0', async () => { 141 | await distributor.claim( 142 | 1, 143 | wallet1.address, 144 | 101, 145 | tree.getProof(1, wallet1.address, BigNumber.from(101)), 146 | overrides 147 | ) 148 | await distributor.claim( 149 | 0, 150 | wallet0.address, 151 | 100, 152 | tree.getProof(0, wallet0.address, BigNumber.from(100)), 153 | overrides 154 | ) 155 | 156 | await expect( 157 | distributor.claim(1, wallet1.address, 101, tree.getProof(1, wallet1.address, BigNumber.from(101)), overrides) 158 | ).to.be.revertedWith('MerkleDistributor: Drop already claimed.') 159 | }) 160 | 161 | it('cannot claim for address other than proof', async () => { 162 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 163 | await expect(distributor.claim(1, wallet1.address, 101, proof0, overrides)).to.be.revertedWith( 164 | 'MerkleDistributor: Invalid proof.' 165 | ) 166 | }) 167 | 168 | it('cannot claim more than proof', async () => { 169 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 170 | await expect(distributor.claim(0, wallet0.address, 101, proof0, overrides)).to.be.revertedWith( 171 | 'MerkleDistributor: Invalid proof.' 172 | ) 173 | }) 174 | 175 | it('gas', async () => { 176 | const proof = tree.getProof(0, wallet0.address, BigNumber.from(100)) 177 | const tx = await distributor.claim(0, wallet0.address, 100, proof, overrides) 178 | const receipt = await tx.wait() 179 | expect(receipt.gasUsed).to.eq(78466) 180 | }) 181 | }) 182 | describe('larger tree', () => { 183 | let distributor: Contract 184 | let tree: BalanceTree 185 | beforeEach('deploy', async () => { 186 | tree = new BalanceTree( 187 | wallets.map((wallet, ix) => { 188 | return { account: wallet.address, amount: BigNumber.from(ix + 1) } 189 | }) 190 | ) 191 | distributor = await deployContract(wallet0, Distributor, [token.address, tree.getHexRoot()], overrides) 192 | await token.setBalance(distributor.address, 201) 193 | }) 194 | 195 | it('claim index 4', async () => { 196 | const proof = tree.getProof(4, wallets[4].address, BigNumber.from(5)) 197 | await expect(distributor.claim(4, wallets[4].address, 5, proof, overrides)) 198 | .to.emit(distributor, 'Claimed') 199 | .withArgs(4, wallets[4].address, 5) 200 | }) 201 | 202 | it('claim index 9', async () => { 203 | const proof = tree.getProof(9, wallets[9].address, BigNumber.from(10)) 204 | await expect(distributor.claim(9, wallets[9].address, 10, proof, overrides)) 205 | .to.emit(distributor, 'Claimed') 206 | .withArgs(9, wallets[9].address, 10) 207 | }) 208 | 209 | it('gas', async () => { 210 | const proof = tree.getProof(9, wallets[9].address, BigNumber.from(10)) 211 | const tx = await distributor.claim(9, wallets[9].address, 10, proof, overrides) 212 | const receipt = await tx.wait() 213 | expect(receipt.gasUsed).to.eq(80960) 214 | }) 215 | 216 | it('gas second down about 15k', async () => { 217 | await distributor.claim( 218 | 0, 219 | wallets[0].address, 220 | 1, 221 | tree.getProof(0, wallets[0].address, BigNumber.from(1)), 222 | overrides 223 | ) 224 | const tx = await distributor.claim( 225 | 1, 226 | wallets[1].address, 227 | 2, 228 | tree.getProof(1, wallets[1].address, BigNumber.from(2)), 229 | overrides 230 | ) 231 | const receipt = await tx.wait() 232 | expect(receipt.gasUsed).to.eq(65940) 233 | }) 234 | }) 235 | 236 | describe('realistic size tree', () => { 237 | let distributor: Contract 238 | let tree: BalanceTree 239 | const NUM_LEAVES = 100_000 240 | const NUM_SAMPLES = 25 241 | const elements: { account: string; amount: BigNumber }[] = [] 242 | for (let i = 0; i < NUM_LEAVES; i++) { 243 | const node = { account: wallet0.address, amount: BigNumber.from(100) } 244 | elements.push(node) 245 | } 246 | tree = new BalanceTree(elements) 247 | 248 | it('proof verification works', () => { 249 | const root = Buffer.from(tree.getHexRoot().slice(2), 'hex') 250 | for (let i = 0; i < NUM_LEAVES; i += NUM_LEAVES / NUM_SAMPLES) { 251 | const proof = tree 252 | .getProof(i, wallet0.address, BigNumber.from(100)) 253 | .map((el) => Buffer.from(el.slice(2), 'hex')) 254 | const validProof = BalanceTree.verifyProof(i, wallet0.address, BigNumber.from(100), proof, root) 255 | expect(validProof).to.be.true 256 | } 257 | }) 258 | 259 | beforeEach('deploy', async () => { 260 | distributor = await deployContract(wallet0, Distributor, [token.address, tree.getHexRoot()], overrides) 261 | await token.setBalance(distributor.address, constants.MaxUint256) 262 | }) 263 | 264 | it('gas', async () => { 265 | const proof = tree.getProof(50000, wallet0.address, BigNumber.from(100)) 266 | const tx = await distributor.claim(50000, wallet0.address, 100, proof, overrides) 267 | const receipt = await tx.wait() 268 | expect(receipt.gasUsed).to.eq(91650) 269 | }) 270 | it('gas deeper node', async () => { 271 | const proof = tree.getProof(90000, wallet0.address, BigNumber.from(100)) 272 | const tx = await distributor.claim(90000, wallet0.address, 100, proof, overrides) 273 | const receipt = await tx.wait() 274 | expect(receipt.gasUsed).to.eq(91586) 275 | }) 276 | it('gas average random distribution', async () => { 277 | let total: BigNumber = BigNumber.from(0) 278 | let count: number = 0 279 | for (let i = 0; i < NUM_LEAVES; i += NUM_LEAVES / NUM_SAMPLES) { 280 | const proof = tree.getProof(i, wallet0.address, BigNumber.from(100)) 281 | const tx = await distributor.claim(i, wallet0.address, 100, proof, overrides) 282 | const receipt = await tx.wait() 283 | total = total.add(receipt.gasUsed) 284 | count++ 285 | } 286 | const average = total.div(count) 287 | expect(average).to.eq(77075) 288 | }) 289 | // this is what we gas golfed by packing the bitmap 290 | it('gas average first 25', async () => { 291 | let total: BigNumber = BigNumber.from(0) 292 | let count: number = 0 293 | for (let i = 0; i < 25; i++) { 294 | const proof = tree.getProof(i, wallet0.address, BigNumber.from(100)) 295 | const tx = await distributor.claim(i, wallet0.address, 100, proof, overrides) 296 | const receipt = await tx.wait() 297 | total = total.add(receipt.gasUsed) 298 | count++ 299 | } 300 | const average = total.div(count) 301 | expect(average).to.eq(62824) 302 | }) 303 | 304 | it('no double claims in random distribution', async () => { 305 | for (let i = 0; i < 25; i += Math.floor(Math.random() * (NUM_LEAVES / NUM_SAMPLES))) { 306 | const proof = tree.getProof(i, wallet0.address, BigNumber.from(100)) 307 | await distributor.claim(i, wallet0.address, 100, proof, overrides) 308 | await expect(distributor.claim(i, wallet0.address, 100, proof, overrides)).to.be.revertedWith( 309 | 'MerkleDistributor: Drop already claimed.' 310 | ) 311 | } 312 | }) 313 | }) 314 | }) 315 | 316 | describe('parseBalanceMap', () => { 317 | let distributor: Contract 318 | let claims: { 319 | [account: string]: { 320 | index: number 321 | amount: string 322 | proof: string[] 323 | } 324 | } 325 | beforeEach('deploy', async () => { 326 | const { claims: innerClaims, merkleRoot, tokenTotal } = parseBalanceMap({ 327 | [wallet0.address]: 200, 328 | [wallet1.address]: 300, 329 | [wallets[2].address]: 250, 330 | }) 331 | expect(tokenTotal).to.eq('0x02ee') // 750 332 | claims = innerClaims 333 | distributor = await deployContract(wallet0, Distributor, [token.address, merkleRoot], overrides) 334 | await token.setBalance(distributor.address, tokenTotal) 335 | }) 336 | 337 | it('check the proofs is as expected', () => { 338 | expect(claims).to.deep.eq({ 339 | [wallet0.address]: { 340 | index: 0, 341 | amount: '0xc8', 342 | proof: ['0x2a411ed78501edb696adca9e41e78d8256b61cfac45612fa0434d7cf87d916c6'], 343 | }, 344 | [wallet1.address]: { 345 | index: 1, 346 | amount: '0x012c', 347 | proof: [ 348 | '0xbfeb956a3b705056020a3b64c540bff700c0f6c96c55c0a5fcab57124cb36f7b', 349 | '0xd31de46890d4a77baeebddbd77bf73b5c626397b73ee8c69b51efe4c9a5a72fa', 350 | ], 351 | }, 352 | [wallets[2].address]: { 353 | index: 2, 354 | amount: '0xfa', 355 | proof: [ 356 | '0xceaacce7533111e902cc548e961d77b23a4d8cd073c6b68ccf55c62bd47fc36b', 357 | '0xd31de46890d4a77baeebddbd77bf73b5c626397b73ee8c69b51efe4c9a5a72fa', 358 | ], 359 | }, 360 | }) 361 | }) 362 | 363 | it('all claims work exactly once', async () => { 364 | for (let account in claims) { 365 | const claim = claims[account] 366 | await expect(distributor.claim(claim.index, account, claim.amount, claim.proof, overrides)) 367 | .to.emit(distributor, 'Claimed') 368 | .withArgs(claim.index, account, claim.amount) 369 | await expect(distributor.claim(claim.index, account, claim.amount, claim.proof, overrides)).to.be.revertedWith( 370 | 'MerkleDistributor: Drop already claimed.' 371 | ) 372 | } 373 | expect(await token.balanceOf(distributor.address)).to.eq(0) 374 | }) 375 | }) 376 | }) 377 | -------------------------------------------------------------------------------- /test/MerkleDistributor.test.ts: -------------------------------------------------------------------------------- 1 | import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers' 2 | import chai, { expect } from 'chai' 3 | import { solidity } from 'ethereum-waffle' 4 | import { BigNumber, constants, Contract, ContractFactory } from 'ethers' 5 | import { ethers } from 'hardhat' 6 | import BalanceTree from '../src/balance-tree' 7 | import { parseBalanceMap } from '../src/parse-balance-map' 8 | 9 | chai.use(solidity) 10 | 11 | const overrides = { 12 | gasLimit: 9999999, 13 | } 14 | const gasUsed = { 15 | MerkleDistributor: { 16 | twoAccountTree: 81970, 17 | largerTreeFirstClaim: 85307, 18 | largerTreeSecondClaim: 68207, 19 | realisticTreeGas: 95256, 20 | realisticTreeGasDeeperNode: 95172, 21 | realisticTreeGasAverageRandom: 78598, 22 | realisticTreeGasAverageFirst25: 62332, 23 | }, 24 | MerkleDistributorWithDeadline: { 25 | twoAccountTree: 82102, 26 | largerTreeFirstClaim: 85439, 27 | largerTreeSecondClaim: 68339, 28 | realisticTreeGas: 95388, 29 | realisticTreeGasDeeperNode: 95304, 30 | realisticTreeGasAverageRandom: 78730, 31 | realisticTreeGasAverageFirst25: 62464, 32 | }, 33 | } 34 | 35 | const ZERO_BYTES32 = '0x0000000000000000000000000000000000000000000000000000000000000000' 36 | 37 | const deployContract = async (factory: ContractFactory, tokenAddress: string, merkleRoot: string, contract: string) => { 38 | let distributor 39 | const currentTimestamp = Math.floor(Date.now() / 1000) 40 | if (contract === 'MerkleDistributorWithDeadline') { 41 | distributor = await factory.deploy(tokenAddress, merkleRoot, currentTimestamp + 31536000, overrides) 42 | } else { 43 | distributor = await factory.deploy(tokenAddress, merkleRoot, overrides) 44 | } 45 | return distributor 46 | } 47 | 48 | for (const contract of ['MerkleDistributor', 'MerkleDistributorWithDeadline']) { 49 | describe(`${contract} tests`, () => { 50 | let token: Contract 51 | let distributorFactory: ContractFactory 52 | let wallet0: SignerWithAddress 53 | let wallet1: SignerWithAddress 54 | let wallets: SignerWithAddress[] 55 | 56 | beforeEach(async () => { 57 | wallets = await ethers.getSigners() 58 | wallet0 = wallets[0] 59 | wallet1 = wallets[1] 60 | const tokenFactory = await ethers.getContractFactory('TestERC20', wallet0) 61 | token = await tokenFactory.deploy('Token', 'TKN', 0, overrides) 62 | distributorFactory = await ethers.getContractFactory(contract, wallet0) 63 | }) 64 | 65 | describe('#token', () => { 66 | it('returns the token address', async () => { 67 | const distributor = await deployContract(distributorFactory, token.address, ZERO_BYTES32, contract) 68 | expect(await distributor.token()).to.eq(token.address) 69 | }) 70 | }) 71 | 72 | describe('#merkleRoot', () => { 73 | it('returns the zero merkle root', async () => { 74 | const distributor = await deployContract(distributorFactory, token.address, ZERO_BYTES32, contract) 75 | expect(await distributor.merkleRoot()).to.eq(ZERO_BYTES32) 76 | }) 77 | }) 78 | 79 | describe('#claim', () => { 80 | it('fails for empty proof', async () => { 81 | const distributor = await deployContract(distributorFactory, token.address, ZERO_BYTES32, contract) 82 | await expect(distributor.claim(0, wallet0.address, 10, [])).to.be.revertedWith('InvalidProof()') 83 | }) 84 | 85 | it('fails for invalid index', async () => { 86 | const distributor = await deployContract(distributorFactory, token.address, ZERO_BYTES32, contract) 87 | await expect(distributor.claim(0, wallet0.address, 10, [])).to.be.revertedWith('InvalidProof()') 88 | }) 89 | 90 | describe('two account tree', () => { 91 | let distributor: Contract 92 | let tree: BalanceTree 93 | beforeEach('deploy', async () => { 94 | tree = new BalanceTree([ 95 | { account: wallet0.address, amount: BigNumber.from(100) }, 96 | { account: wallet1.address, amount: BigNumber.from(101) }, 97 | ]) 98 | distributor = await deployContract(distributorFactory, token.address, tree.getHexRoot(), contract) 99 | await token.setBalance(distributor.address, 201) 100 | }) 101 | 102 | it('successful claim', async () => { 103 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 104 | await expect(distributor.claim(0, wallet0.address, 100, proof0, overrides)) 105 | .to.emit(distributor, 'Claimed') 106 | .withArgs(0, wallet0.address, 100) 107 | const proof1 = tree.getProof(1, wallet1.address, BigNumber.from(101)) 108 | await expect(distributor.claim(1, wallet1.address, 101, proof1, overrides)) 109 | .to.emit(distributor, 'Claimed') 110 | .withArgs(1, wallet1.address, 101) 111 | }) 112 | 113 | it('transfers the token', async () => { 114 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 115 | expect(await token.balanceOf(wallet0.address)).to.eq(0) 116 | await distributor.claim(0, wallet0.address, 100, proof0, overrides) 117 | expect(await token.balanceOf(wallet0.address)).to.eq(100) 118 | }) 119 | 120 | it('must have enough to transfer', async () => { 121 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 122 | await token.setBalance(distributor.address, 99) 123 | await expect(distributor.claim(0, wallet0.address, 100, proof0, overrides)).to.be.revertedWith( 124 | 'ERC20: transfer amount exceeds balance' 125 | ) 126 | }) 127 | 128 | it('sets #isClaimed', async () => { 129 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 130 | expect(await distributor.isClaimed(0)).to.eq(false) 131 | expect(await distributor.isClaimed(1)).to.eq(false) 132 | await distributor.claim(0, wallet0.address, 100, proof0, overrides) 133 | expect(await distributor.isClaimed(0)).to.eq(true) 134 | expect(await distributor.isClaimed(1)).to.eq(false) 135 | }) 136 | 137 | it('cannot allow two claims', async () => { 138 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 139 | await distributor.claim(0, wallet0.address, 100, proof0, overrides) 140 | await expect(distributor.claim(0, wallet0.address, 100, proof0, overrides)).to.be.revertedWith( 141 | 'AlreadyClaimed()' 142 | ) 143 | }) 144 | 145 | it('cannot claim more than once: 0 and then 1', async () => { 146 | await distributor.claim( 147 | 0, 148 | wallet0.address, 149 | 100, 150 | tree.getProof(0, wallet0.address, BigNumber.from(100)), 151 | overrides 152 | ) 153 | await distributor.claim( 154 | 1, 155 | wallet1.address, 156 | 101, 157 | tree.getProof(1, wallet1.address, BigNumber.from(101)), 158 | overrides 159 | ) 160 | 161 | await expect( 162 | distributor.claim( 163 | 0, 164 | wallet0.address, 165 | 100, 166 | tree.getProof(0, wallet0.address, BigNumber.from(100)), 167 | overrides 168 | ) 169 | ).to.be.revertedWith('AlreadyClaimed()') 170 | }) 171 | 172 | it('cannot claim more than once: 1 and then 0', async () => { 173 | await distributor.claim( 174 | 1, 175 | wallet1.address, 176 | 101, 177 | tree.getProof(1, wallet1.address, BigNumber.from(101)), 178 | overrides 179 | ) 180 | await distributor.claim( 181 | 0, 182 | wallet0.address, 183 | 100, 184 | tree.getProof(0, wallet0.address, BigNumber.from(100)), 185 | overrides 186 | ) 187 | 188 | await expect( 189 | distributor.claim( 190 | 1, 191 | wallet1.address, 192 | 101, 193 | tree.getProof(1, wallet1.address, BigNumber.from(101)), 194 | overrides 195 | ) 196 | ).to.be.revertedWith('AlreadyClaimed()') 197 | }) 198 | 199 | it('cannot claim for address other than proof', async () => { 200 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 201 | await expect(distributor.claim(1, wallet1.address, 101, proof0, overrides)).to.be.revertedWith( 202 | 'InvalidProof()' 203 | ) 204 | }) 205 | 206 | it('cannot claim more than proof', async () => { 207 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 208 | await expect(distributor.claim(0, wallet0.address, 101, proof0, overrides)).to.be.revertedWith( 209 | 'InvalidProof()' 210 | ) 211 | }) 212 | 213 | it('gas', async () => { 214 | const proof = tree.getProof(0, wallet0.address, BigNumber.from(100)) 215 | const tx = await distributor.claim(0, wallet0.address, 100, proof, overrides) 216 | const receipt = await tx.wait() 217 | expect(receipt.gasUsed).to.eq(gasUsed[contract as keyof typeof gasUsed].twoAccountTree) 218 | }) 219 | }) 220 | 221 | describe('larger tree', () => { 222 | let distributor: Contract 223 | let tree: BalanceTree 224 | beforeEach('deploy', async () => { 225 | tree = new BalanceTree( 226 | wallets.map((wallet, ix) => { 227 | return { account: wallet.address, amount: BigNumber.from(ix + 1) } 228 | }) 229 | ) 230 | distributor = await deployContract(distributorFactory, token.address, tree.getHexRoot(), contract) 231 | await token.setBalance(distributor.address, 201) 232 | }) 233 | 234 | it('claim index 4', async () => { 235 | const proof = tree.getProof(4, wallets[4].address, BigNumber.from(5)) 236 | await expect(distributor.claim(4, wallets[4].address, 5, proof, overrides)) 237 | .to.emit(distributor, 'Claimed') 238 | .withArgs(4, wallets[4].address, 5) 239 | }) 240 | 241 | it('claim index 9', async () => { 242 | const proof = tree.getProof(9, wallets[9].address, BigNumber.from(10)) 243 | await expect(distributor.claim(9, wallets[9].address, 10, proof, overrides)) 244 | .to.emit(distributor, 'Claimed') 245 | .withArgs(9, wallets[9].address, 10) 246 | }) 247 | 248 | it('gas', async () => { 249 | const proof = tree.getProof(9, wallets[9].address, BigNumber.from(10)) 250 | const tx = await distributor.claim(9, wallets[9].address, 10, proof, overrides) 251 | const receipt = await tx.wait() 252 | expect(receipt.gasUsed).to.eq(gasUsed[contract as keyof typeof gasUsed].largerTreeFirstClaim) 253 | }) 254 | 255 | it('gas second down about 15k', async () => { 256 | await distributor.claim( 257 | 0, 258 | wallets[0].address, 259 | 1, 260 | tree.getProof(0, wallets[0].address, BigNumber.from(1)), 261 | overrides 262 | ) 263 | const tx = await distributor.claim( 264 | 1, 265 | wallets[1].address, 266 | 2, 267 | tree.getProof(1, wallets[1].address, BigNumber.from(2)), 268 | overrides 269 | ) 270 | const receipt = await tx.wait() 271 | expect(receipt.gasUsed).to.eq(gasUsed[contract as keyof typeof gasUsed].largerTreeSecondClaim) 272 | }) 273 | }) 274 | 275 | describe('realistic size tree', () => { 276 | let distributor: Contract 277 | let tree: BalanceTree 278 | const NUM_LEAVES = 100_000 279 | const NUM_SAMPLES = 25 280 | 281 | beforeEach('deploy', async () => { 282 | const elements: { account: string; amount: BigNumber }[] = [] 283 | for (let i = 0; i < NUM_LEAVES; i++) { 284 | const node = { account: wallet0.address, amount: BigNumber.from(100) } 285 | elements.push(node) 286 | } 287 | tree = new BalanceTree(elements) 288 | distributor = await deployContract(distributorFactory, token.address, tree.getHexRoot(), contract) 289 | await token.setBalance(distributor.address, constants.MaxUint256) 290 | }) 291 | 292 | it('proof verification works', () => { 293 | const root = Buffer.from(tree.getHexRoot().slice(2), 'hex') 294 | for (let i = 0; i < NUM_LEAVES; i += NUM_LEAVES / NUM_SAMPLES) { 295 | const proof = tree 296 | .getProof(i, wallet0.address, BigNumber.from(100)) 297 | .map((el) => Buffer.from(el.slice(2), 'hex')) 298 | const validProof = BalanceTree.verifyProof(i, wallet0.address, BigNumber.from(100), proof, root) 299 | expect(validProof).to.be.true 300 | } 301 | }) 302 | 303 | it('gas', async () => { 304 | const proof = tree.getProof(50000, wallet0.address, BigNumber.from(100)) 305 | const tx = await distributor.claim(50000, wallet0.address, 100, proof, overrides) 306 | const receipt = await tx.wait() 307 | expect(receipt.gasUsed).to.eq(gasUsed[contract as keyof typeof gasUsed].realisticTreeGas) 308 | }) 309 | it('gas deeper node', async () => { 310 | const proof = tree.getProof(90000, wallet0.address, BigNumber.from(100)) 311 | const tx = await distributor.claim(90000, wallet0.address, 100, proof, overrides) 312 | const receipt = await tx.wait() 313 | expect(receipt.gasUsed).to.eq(gasUsed[contract as keyof typeof gasUsed].realisticTreeGasDeeperNode) 314 | }) 315 | it('gas average random distribution', async () => { 316 | let total: BigNumber = BigNumber.from(0) 317 | let count: number = 0 318 | for (let i = 0; i < NUM_LEAVES; i += NUM_LEAVES / NUM_SAMPLES) { 319 | const proof = tree.getProof(i, wallet0.address, BigNumber.from(100)) 320 | const tx = await distributor.claim(i, wallet0.address, 100, proof, overrides) 321 | const receipt = await tx.wait() 322 | total = total.add(receipt.gasUsed) 323 | count++ 324 | } 325 | const average = total.div(count) 326 | expect(average).to.eq(gasUsed[contract as keyof typeof gasUsed].realisticTreeGasAverageRandom) 327 | }) 328 | // this is what we gas golfed by packing the bitmap 329 | it('gas average first 25', async () => { 330 | let total: BigNumber = BigNumber.from(0) 331 | let count: number = 0 332 | for (let i = 0; i < 25; i++) { 333 | const proof = tree.getProof(i, wallet0.address, BigNumber.from(100)) 334 | const tx = await distributor.claim(i, wallet0.address, 100, proof, overrides) 335 | const receipt = await tx.wait() 336 | total = total.add(receipt.gasUsed) 337 | count++ 338 | } 339 | const average = total.div(count) 340 | expect(average).to.eq(gasUsed[contract as keyof typeof gasUsed].realisticTreeGasAverageFirst25) 341 | }) 342 | 343 | it('no double claims in random distribution', async () => { 344 | for (let i = 0; i < 25; i += Math.floor(Math.random() * (NUM_LEAVES / NUM_SAMPLES))) { 345 | const proof = tree.getProof(i, wallet0.address, BigNumber.from(100)) 346 | await distributor.claim(i, wallet0.address, 100, proof, overrides) 347 | await expect(distributor.claim(i, wallet0.address, 100, proof, overrides)).to.be.revertedWith( 348 | 'AlreadyClaimed()' 349 | ) 350 | } 351 | }) 352 | }) 353 | 354 | describe('parseBalanceMap', () => { 355 | let distributor: Contract 356 | let claims: { 357 | [account: string]: { 358 | index: number 359 | amount: string 360 | proof: string[] 361 | } 362 | } 363 | beforeEach('deploy', async () => { 364 | const { claims: innerClaims, merkleRoot, tokenTotal } = parseBalanceMap({ 365 | [wallet0.address]: 200, 366 | [wallet1.address]: 300, 367 | [wallets[2].address]: 250, 368 | }) 369 | expect(tokenTotal).to.eq('0x02ee') // 750 370 | claims = innerClaims 371 | distributor = await deployContract(distributorFactory, token.address, merkleRoot, contract) 372 | await token.setBalance(distributor.address, tokenTotal) 373 | }) 374 | 375 | it('check the proofs is as expected', () => { 376 | expect(claims).to.deep.eq({ 377 | [wallet0.address]: { 378 | index: 2, 379 | amount: '0xc8', 380 | proof: [ 381 | '0x0782528e118c4350a2465fbeabec5e72fff06991a29f21c08d37a0d275e38ddd', 382 | '0xf3c5acb53398e1d11dcaa74e37acc33d228f5da944fbdea9a918684074a21cdb', 383 | ], 384 | }, 385 | [wallet1.address]: { 386 | index: 1, 387 | amount: '0x012c', 388 | proof: [ 389 | '0xc86fd316fa3e7b83c2665b5ccb63771e78abcc0429e0105c91dde37cb9b857a4', 390 | '0xf3c5acb53398e1d11dcaa74e37acc33d228f5da944fbdea9a918684074a21cdb', 391 | ], 392 | }, 393 | [wallets[2].address]: { 394 | index: 0, 395 | amount: '0xfa', 396 | proof: ['0x0c9bcaca2a1013557ef7f348b514ab8a8cd6c7051b69e46b1681a2aff22f4a88'], 397 | }, 398 | }) 399 | }) 400 | 401 | it('all claims work exactly once', async () => { 402 | for (let account in claims) { 403 | const claim = claims[account] 404 | await expect(distributor.claim(claim.index, account, claim.amount, claim.proof, overrides)) 405 | .to.emit(distributor, 'Claimed') 406 | .withArgs(claim.index, account, claim.amount) 407 | await expect( 408 | distributor.claim(claim.index, account, claim.amount, claim.proof, overrides) 409 | ).to.be.revertedWith('AlreadyClaimed()') 410 | } 411 | expect(await token.balanceOf(distributor.address)).to.eq(0) 412 | }) 413 | }) 414 | }) 415 | }) 416 | } 417 | 418 | describe('#MerkleDistributorWithDeadline', () => { 419 | let token: Contract 420 | let wallet0: SignerWithAddress 421 | let wallet1: SignerWithAddress 422 | let wallets: SignerWithAddress[] 423 | let distributor: Contract 424 | let tree: BalanceTree 425 | let currentTimestamp = Math.floor(Date.now() / 1000) 426 | 427 | beforeEach('deploy', async () => { 428 | wallets = await ethers.getSigners() 429 | wallet0 = wallets[0] 430 | wallet1 = wallets[1] 431 | const tokenFactory = await ethers.getContractFactory('TestERC20', wallet0) 432 | token = await tokenFactory.deploy('Token', 'TKN', 0, overrides) 433 | tree = new BalanceTree([ 434 | { account: wallet0.address, amount: BigNumber.from(100) }, 435 | { account: wallet1.address, amount: BigNumber.from(101) }, 436 | ]) 437 | const merkleDistributorWithDeadlineFactory = await ethers.getContractFactory( 438 | 'MerkleDistributorWithDeadline', 439 | wallet0 440 | ) 441 | // Set the endTime to be 1 year after currentTimestamp 442 | distributor = await merkleDistributorWithDeadlineFactory.deploy( 443 | token.address, 444 | tree.getHexRoot(), 445 | currentTimestamp + 31536000, 446 | overrides 447 | ) 448 | await token.setBalance(distributor.address, 201) 449 | }) 450 | 451 | it('successful claim', async () => { 452 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 453 | await expect(distributor.claim(0, wallet0.address, 100, proof0, overrides)) 454 | .to.emit(distributor, 'Claimed') 455 | .withArgs(0, wallet0.address, 100) 456 | }) 457 | 458 | it('only owner can withdraw', async () => { 459 | distributor = distributor.connect(wallet1) 460 | await expect(distributor.withdraw(overrides)).to.be.revertedWith('Ownable: caller is not the owner') 461 | }) 462 | 463 | it('cannot withdraw during claim window', async () => { 464 | await expect(distributor.withdraw(overrides)).to.be.revertedWith('NoWithdrawDuringClaim()') 465 | }) 466 | 467 | it('cannot claim after end time', async () => { 468 | const oneSecondAfterEndTime = currentTimestamp + 31536001 469 | await ethers.provider.send('evm_mine', [oneSecondAfterEndTime]) 470 | currentTimestamp = oneSecondAfterEndTime 471 | const proof0 = tree.getProof(0, wallet0.address, BigNumber.from(100)) 472 | await expect(distributor.claim(0, wallet0.address, 100, proof0, overrides)).to.be.revertedWith( 473 | 'ClaimWindowFinished()' 474 | ) 475 | }) 476 | 477 | it('can withdraw after end time', async () => { 478 | const oneSecondAfterEndTime = currentTimestamp + 31536001 479 | await ethers.provider.send('evm_mine', [oneSecondAfterEndTime]) 480 | currentTimestamp = oneSecondAfterEndTime 481 | expect(await token.balanceOf(wallet0.address)).to.eq(0) 482 | await distributor.withdraw(overrides) 483 | expect(await token.balanceOf(wallet0.address)).to.eq(201) 484 | }) 485 | 486 | it('only owner can withdraw even after end time', async () => { 487 | const oneSecondAfterEndTime = currentTimestamp + 31536001 488 | await ethers.provider.send('evm_mine', [oneSecondAfterEndTime]) 489 | distributor = distributor.connect(wallet1) 490 | await expect(distributor.withdraw(overrides)).to.be.revertedWith('Ownable: caller is not the owner') 491 | }) 492 | }) 493 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "strict": true, 6 | "esModuleInterop": true, 7 | "resolveJsonModule": true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /waffle.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerType": "solcjs", 3 | "compilerVersion": "./node_modules/solc", 4 | "outputType": "all", 5 | "compilerOptions": { 6 | "outputSelection": { 7 | "*": { 8 | "*": [ 9 | "evm.bytecode.object", 10 | "evm.deployedBytecode.object", 11 | "abi", 12 | "evm.bytecode.sourceMap", 13 | "evm.deployedBytecode.sourceMap", 14 | "metadata" 15 | ], 16 | "": ["ast"] 17 | } 18 | }, 19 | "evmVersion": "istanbul", 20 | "optimizer": { 21 | "enabled": true, 22 | "runs": 200 23 | } 24 | } 25 | } 26 | --------------------------------------------------------------------------------