├── .env
├── .gitignore
├── .gitmodules
├── Faillapop_diagram_v3.svg
├── LICENSE
├── README.md
├── docs
└── README.md
├── foundry.toml
├── remappings.txt
├── script
└── DeployFaillapop.s.sol
├── src
├── FP_CoolNFT.sol
├── FP_DAO.sol
├── FP_PowersellerNFT.sol
├── FP_Proxy.sol
├── FP_Shop.sol
├── FP_Token.sol
├── FP_Vault.sol
└── interfaces
│ ├── IFP_CoolNFT.sol
│ ├── IFP_DAO.sol
│ ├── IFP_PowersellerNFT.sol
│ ├── IFP_Proxy.sol
│ ├── IFP_Shop.sol
│ └── IFP_Vault.sol
└── test
├── integration
└── FP_Proxy_Shop.t.sol
└── unit
├── FP_CoolNFT.t.sol
├── FP_DAO.t.sol
├── FP_PowersellerNFT.t.sol
├── FP_Proxy.t.sol
├── FP_Shop.t.sol
├── FP_Token.t.sol
└── FP_Vault.t.sol
/.env:
--------------------------------------------------------------------------------
1 | PRIVATE_KEY=0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba
2 | DEPLOYER=0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Faillapop
2 | solutions/
3 | cache/
4 | out/
5 | lib/
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "lib/forge-std"]
2 | path = lib/forge-std
3 | url = https://github.com/foundry-rs/forge-std
4 | branch = v1.5.0
5 | [submodule "lib/openzeppelin-contracts"]
6 | path = lib/openzeppelin-contracts
7 | url = https://github.com/OpenZeppelin/openzeppelin-contracts
8 | branch = v5.0.1
9 | [submodule "lib/openzeppelin-contracts-upgradeable"]
10 | path = lib/openzeppelin-contracts-upgradeable
11 | url = https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable
12 | branch = v5.0.1
--------------------------------------------------------------------------------
/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 | # Faillapop - Solidity mock audit environment!
2 |
3 | We sometimes feel that the jump between being able to identify issues in small snippets of code and auditing a more complex codebase is problematic. There are a loooot of small CTF-like exercises, some easy some really difficult, but feel like there is a lack of a "mock audit contract" for people to practice their skills in a closer to real-life project.
4 |
5 | So we decided to create the Faillapop protocol!
6 |
7 | > [!WARNING]
8 | > The code has been made vulnerable on purpose. Please do not deploy or reuse this codebase in a live environment.
9 |
10 | ---
11 |
12 | ## The Faillapop protocol 🛍️
13 |
14 | The Faillapop protocol is a vulnerable-by-design protocol to help Web3 security students practice their skills in a fun environment. The protocol is composed of multiple contracts that interact with each other to create a decentralized buying and selling platform. Disputes are resolved through a DAO and malicious sellers are checked by forcing a deposit before selling anything... but there have been a lot of bad decisions during this process :mag:.
15 |
16 |
17 | You will find common solidity security issues, dubious centralization and logical loopholes. Do not forget to think about others such as flash loans and Out-Of-Gas exceptions!
18 |
19 | Try to perform a full mock audit! Create your own professional report mimicking those of well-known companies such as Oak Security, Trail of Bits, Hacken, or Halborn. Imagine that you are getting paid for this and trying to do the best job possible! not just finding bugs but also crafting proper paragraphs for your report.
20 |
21 |
22 | Solutions are not provided along this repo but the documentation has been created following the NatSpec format and the following diagram will help you get a grasp of the whole architecture.
23 |
24 |
25 | 
26 |
27 |
28 | > [!TIP]
29 | > Do not forget to run and analyze the testing suite. Sometimes you can spot vulnerabilities just by checking the bits that were neglected during testing and ensuring they behave as expected, or just reviewing failed tests.
30 |
31 | ## Working with the Faillapop Protocol 🛠️
32 |
33 | The Faillapop protocol uses the Foundry framework.
34 |
35 | >**Why Foundry?**
36 | >- It is the fastest framework
37 | >- Allows writing tests and scripts in Solidity, minimising context switches
38 | >- It has a lot of cheatcodes for testing and debugging
39 |
40 | Foundry is composed of four components:
41 | - [**Forge**](https://github.com/foundry-rs/foundry/blob/master/crates/forge): Ethereum Testing Framework
42 | - [**Cast**](https://github.com/foundry-rs/foundry/blob/master/crates/cast): A command line tool for making RPC calls to Ethereum. Allowing to interact with smart contracts, send transactions or retrieve any kind of data from the Blockchain through the console
43 | - [**Anvil**](https://github.com/foundry-rs/foundry/blob/master/crates/anvil): A local Ethereum node, similar to Ganache, which is deployed by default during test execution
44 | - [**Chisel**](https://github.com/foundry-rs/foundry/blob/master/crates/chisel): A solidity REPL, very fast and useful during contract development or testing
45 |
46 | To work with the Faillapop protocol, follow these steps:
47 |
48 | ### 1. Install Foundry Framework
49 |
50 | The recommended way to install it is using the **foundryup** tool. Below we will go through the installation step by step, but if you want to do a dependency-free installation, you can follow the installation instructions from [this repository](https://github.com/hardenerdev/smart-contract-auditor).
51 |
52 | > [!NOTE]
53 | > If you are using Windows, you will need to install and use [Git BASH](https://gitforwindows.org/) or [WSL](https://learn.microsoft.com/en-us/windows/wsl/install) as the terminal, as Foundryup does not support Powershell or Cmd.
54 |
55 | In the terminal run:
56 |
57 | ```Powershell
58 | curl -L https://foundry.paradigm.xyz | bash
59 | ```
60 |
61 | As a result you will get something like this:
62 |
63 | ```shell
64 | consoleDetected your preferred shell is bashrc and added Foundry to Path run:source /home/user/.bashrcStart a new terminal session to use Foundry
65 | ```
66 |
67 | Now simply type `foundryup` in the terminal and press `Enter`. This will install the four Foundry components: *forge*, *cast*, *anvil* and *chisel*.
68 |
69 | To confirm the correct installation, type `forge --version`. You should get the installed version of forge:
70 |
71 | ```shell
72 | Forge version x.x.x
73 | ```
74 | If you have not obtained the version, you may need to add Foundry to your PATH. To do this, you can run the following:
75 |
76 | ```shell
77 | cd ~echo 'source /home/user/.bashrc' >> ~/.bash_profile
78 | ```
79 |
80 | If you still have problems with the installation, you can follow Foundry's installation instructions in their [repository](https://book.getfoundry.sh/getting-started/installation).
81 |
82 | ### 2. Set Up the Project
83 |
84 | Clone the repository to your local machine:
85 |
86 | ```shell
87 | git clone https://github.com/jcsec-security/faillapop.git
88 | cd faillapop
89 | ```
90 |
91 | Install dependencies and compile the project using Foundry:
92 |
93 | ```shell
94 | forge build
95 | ```
96 |
97 | ### 3. Run the Tests
98 |
99 | To run the test suite, use the following command:
100 |
101 | ```shell
102 | forge test
103 | ```
104 |
105 | This will run all the tests in the `tests` directory.
106 |
107 | ---
108 |
109 | For further documentation on the protocol --> [Faillapop Documentation](./docs/README.md)
110 |
111 |
112 | ## Next steps
113 |
114 | The current version is `v1.0`. At the moment we would like to achieve the below in order to upgrade it:
115 |
116 |
117 | :pushpin:`V2.0`
118 |
119 | - Oracle
120 | - Flash loan provider
121 |
122 | ## Contribution and Contact
123 |
124 | We encourage you to make the most of this material. If you find it useful, feel free to share by linking to this repository. Your feedback is invaluable! If you have suggestions, corrections, or would like to contribute in any way, please don't hesitate to reach out:
125 |
126 | - Telegram: @jcr_auditor
127 | - Email: jc@jcsec.io
128 |
129 | Thank you for exploring this repository, and happy bug hunting!
130 |
131 | ## Collaboration
132 |
133 | On September 2023 the [NICS lab](https://www.nics.uma.es/) research group from the [University of Malaga](https://www.uma.es/) agreed to help improving this repository as part of their efforts on Open Source collaboration. In particular, with new versions of the Faillapop mock-audit environment, both improving the initial codebase and extending its features.
134 |
135 | > [!IMPORTANT]
136 | > Special thanks to Marco Lopez ([TW](https://twitter.com/Marcologonz), [LD](https://linkedin.com/in/marcologonz)) who took on this workload as part of his dissertation and to NICS Lab's researcher Isaac Agudo who supported and pushed for the initiative to come to success.
137 |
--------------------------------------------------------------------------------
/foundry.toml:
--------------------------------------------------------------------------------
1 | [profile.default]
2 | src = 'src'
3 | out = 'out'
4 | libs = ['lib']
5 |
6 | # See more config options https://github.com/foundry-rs/foundry/tree/master/config
--------------------------------------------------------------------------------
/remappings.txt:
--------------------------------------------------------------------------------
1 | ds-test/=lib/forge-std/lib/ds-test/src/
2 | forge-std/=lib/forge-std/src/
3 | @openzeppelin/contracts@v5.0.1/=lib/openzeppelin-contracts/contracts/
4 | @openzeppelin-upgradeable/contracts@v5.0.1/=lib/openzeppelin-contracts-upgradeable/contracts/
5 |
--------------------------------------------------------------------------------
/script/DeployFaillapop.s.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {Script} from "forge-std/Script.sol";
5 | import {FP_CoolNFT} from "../src/FP_CoolNFT.sol";
6 | import {FP_DAO} from "../src/FP_DAO.sol";
7 | import {FP_PowersellerNFT} from "../src/FP_PowersellerNFT.sol";
8 | import {FP_Shop} from "../src/FP_Shop.sol";
9 | import {FP_Token} from "../src/FP_Token.sol";
10 | import {FP_Vault} from "../src/FP_Vault.sol";
11 | import {FP_Proxy} from "../src/FP_Proxy.sol";
12 |
13 | contract DeployFaillapop is Script {
14 | address public deployer;
15 | function run() external returns(FP_Shop shop, FP_Token token, FP_CoolNFT coolNFT, FP_PowersellerNFT powersellerNFT, FP_DAO dao, FP_Vault vault, FP_Proxy proxy) {
16 | deployer = vm.addr(vm.envUint("PRIVATE_KEY"));
17 | vm.startBroadcast(deployer);
18 | shop = new FP_Shop();
19 | token = new FP_Token();
20 | coolNFT = new FP_CoolNFT();
21 | powersellerNFT = new FP_PowersellerNFT();
22 | dao = new FP_DAO("password", address(coolNFT), address(token));
23 | vault = new FP_Vault(address(powersellerNFT), address(dao));
24 | proxy = new FP_Proxy(
25 | address(shop),
26 | abi.encodeWithSignature(
27 | "initialize(address,address,address,address)",
28 | address(dao),
29 | address(vault),
30 | address(powersellerNFT),
31 | address(coolNFT)
32 | ),
33 | address(dao)
34 | );
35 |
36 | vault.setShop(address(proxy));
37 | dao.setShop(address(proxy));
38 | powersellerNFT.setShop(address(proxy));
39 | coolNFT.setShop(address(proxy));
40 | coolNFT.setDAO(address(dao));
41 | vm.stopBroadcast();
42 | }
43 | }
--------------------------------------------------------------------------------
/src/FP_CoolNFT.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {IFP_CoolNFT} from "./interfaces/IFP_CoolNFT.sol";
5 | import {AccessControl} from "@openzeppelin/contracts@v5.0.1/access/AccessControl.sol";
6 | import {ERC721} from "@openzeppelin/contracts@v5.0.1/token/ERC721/ERC721.sol";
7 |
8 | /**
9 | @title Interface of the FaillaPop Cool NFT
10 | @author Faillapop team :D
11 | @notice The contract allows the DAO to mint Cool NFTs for users.
12 | @dev Security review is pending... should we deploy this?
13 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
14 | */
15 | contract FP_CoolNFT is IFP_CoolNFT, ERC721, AccessControl {
16 |
17 | /************************************** Constants ****************************************************************/
18 |
19 | ///@notice The Control Role ID for the AccessControl contract. At first it's the msg.sender and then the DAO.
20 | bytes32 public constant CONTROL_ROLE = keccak256("CONTROL_ROLE");
21 | ///@notice The Shop Role ID for the AccessControl contract. At first it's the msg.sender and then the shop.
22 | bytes32 public constant SHOP_ROLE = keccak256("SHOP_ROLE");
23 |
24 | /************************************** State vars ****************************************************************/
25 |
26 | ///@notice Bool to check if the DAO address has been set
27 | bool private _daoSet = false;
28 | ///@notice Bool to check if the shop address has been set
29 | bool private _shopSet = false;
30 | ///@notice The next tokenId to be minted
31 | uint256 public nextTokenId;
32 | ///@notice Mapping from user address to tokenId
33 | mapping (address => uint256[]) public tokenIds;
34 |
35 | /************************************** Modifiers *****************************************************/
36 |
37 | /**
38 | @notice Modifier to check if the DAO address has been set
39 | */
40 | modifier daoNotSet() {
41 | require(!_daoSet, "DAO address already set");
42 | _;
43 | }
44 |
45 | /**
46 | @notice Modifier to check if the Shop address has been set
47 | */
48 | modifier shopNotSet() {
49 | require(!_shopSet, "Shop address already set");
50 | _;
51 | }
52 |
53 | /************************************** External ****************************************************************/
54 |
55 | /**
56 | @notice Constructor, initializes the contract
57 | */
58 | constructor() ERC721("Faillapop Cool NFT", "FCNFT") {
59 | _grantRole(CONTROL_ROLE, msg.sender);
60 | }
61 |
62 | /**
63 | @notice Sets the DAO address as the new Control Role
64 | @param daoAddr The address of the DAO contract
65 | */
66 | function setDAO(address daoAddr) external onlyRole(CONTROL_ROLE) daoNotSet {
67 | _daoSet = true;
68 | _grantRole(CONTROL_ROLE, daoAddr);
69 | }
70 |
71 | /**
72 | @notice Sets the shop address as the SHOP_ROLE
73 | @param shopAddress The address of the shop contract
74 | */
75 | function setShop(address shopAddress) external onlyRole(CONTROL_ROLE) shopNotSet {
76 | _shopSet = true;
77 | _grantRole(SHOP_ROLE, shopAddress);
78 | }
79 |
80 | /**
81 | @notice Mints a Cool NFT for the user
82 | @param to The address of the user that will receive the Cool NFT
83 | */
84 | function mintCoolNFT(address to) external onlyRole(CONTROL_ROLE) {
85 | nextTokenId++;
86 | tokenIds[to].push(nextTokenId);
87 | _safeMint(to, nextTokenId);
88 |
89 | emit CoolNFT_Minted(to, nextTokenId);
90 | }
91 |
92 | /**
93 | @notice Shop can remove all the Cool NFTs from a user
94 | @param owner The address of the user that will lose his Cool NFTs
95 | */
96 | function burnAll(address owner) external onlyRole(SHOP_ROLE) {
97 | if(tokenIds[owner].length > 0){
98 | uint256[] memory userTokens = tokenIds[owner];
99 | for (uint256 i = 0; i < userTokens.length; i++) {
100 | _burn(userTokens[i]);
101 | }
102 | tokenIds[owner] = new uint256[](0);
103 | emit CoolNFTs_Slashed(owner);
104 | }
105 | }
106 |
107 | function getTokenIds(address owner) external view returns(uint256[] memory){
108 | return tokenIds[owner];
109 | }
110 |
111 | /************************************** Public ****************************************************************/
112 |
113 | /**
114 | * @notice Cool NFTs cannot be transferred, so this function is overriden to revert
115 | */
116 | function approve(address /*to*/, uint256 /*tokenId*/) public virtual override{
117 | revert("CoolNFT cannot be approved");
118 | }
119 |
120 | /**
121 | * @notice Cool NFTs cannot be transferred, so this function is overriden to revert
122 | */
123 | function setApprovalForAll(address /*operator*/, bool /*approved*/) public virtual override{
124 | revert("CoolNFT cannot be approved");
125 | }
126 |
127 | /**
128 | * @notice Cool NFTs cannot be transferred, so this function is overriden to revert
129 | */
130 | function transferFrom(address /*from*/, address /*to*/, uint256 /*tokenId*/) public virtual override{
131 | revert("CoolNFT cannot be transferred");
132 | }
133 |
134 | /**
135 | * @notice Cool NFTs cannot be transferred, so this function is overriden to revert
136 | */
137 | function safeTransferFrom(address /*from*/, address /*to*/, uint256 /*tokenId*/, bytes memory /*data*/) public virtual override{
138 | revert("CoolNFT cannot be transferred");
139 | }
140 |
141 | /**
142 | @notice Returns the supported interfaces collection
143 | @param interfaceId The interface identifier
144 | */
145 | function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl) returns (bool) {
146 | return ERC721.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId);
147 | }
148 | }
--------------------------------------------------------------------------------
/src/FP_DAO.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {IFP_DAO} from "./interfaces/IFP_DAO.sol";
5 | import {IFP_CoolNFT} from "./interfaces/IFP_CoolNFT.sol";
6 | import {IFP_Shop} from "./interfaces/IFP_Shop.sol";
7 | import {AccessControl} from "@openzeppelin/contracts@v5.0.1/access/AccessControl.sol";
8 | import {IERC20} from "@openzeppelin/contracts@v5.0.1/token/ERC20/IERC20.sol";
9 |
10 |
11 | /**
12 | @title FaillaPop voting DAO [v.02]
13 | @author Faillapop team :D
14 | @notice The contract allows to vote with FPT tokens on open disputes. If the dispute is resolved in favor of the buyer,
15 | the seller have to refund the buyer. If the dispute is resolved in favor of the seller, the sale is closed.
16 | @dev Security review is pending... should we deploy this?
17 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
18 | */
19 | contract FP_DAO is IFP_DAO, AccessControl {
20 |
21 | /************************************** Constants *******************************************************/
22 |
23 | ///@notice The threshold for the random number generator
24 | uint256 public constant THRESHOLD = 10;
25 | ///@notice The default number of voters for passing a dispute vote
26 | uint256 public constant DEFAULT_DISPUTE_QUORUM = 100;
27 | ///@notice the minimum committing period for votes on a dispute
28 | uint256 constant COMMITTING_TIME = 3 days;
29 | ///@notice The minimum revealing period for votes on a dispute
30 | uint256 constant MIN_REVEALING_TIME = 1 days;
31 | ///@notice The maximum revealing period for votes on a dispute
32 | uint256 constant MAX_REVEALING_TIME = 3 days;
33 | ///@notice The default number of voters for passing an update vote
34 | uint256 public constant DEFAULT_PROPOSAL_QUORUM = 500;
35 | ///@notice The time window in which a proposal can not be voted
36 | uint256 public constant PROPOSAL_REVIEW_TIME = 1 days;
37 | ///@notice The minimum voting period for a proposal
38 | uint256 public constant PROPOSAL_VOTING_TIME = 3 days;
39 | ///@notice The minimum waiting time between approval and execution of a proposal
40 | uint256 public constant PROPOSAL_EXECUTION_DELAY = 1 days;
41 | ///@notice The Control role ID for the AccessControl contract. At first it's the msg.sender and then the shop.
42 | bytes32 public constant CONTROL_ROLE = keccak256("CONTROL_ROLE");
43 |
44 | /************************************** Immutables *******************************************************/
45 |
46 | ///@notice The CoolNFT contract
47 | IFP_CoolNFT public immutable COOL_NFT_CONTRACT;
48 | ///@notice The FPT token contract
49 | IERC20 public immutable FPT_CONTRACT;
50 |
51 | /************************************** State vars *******************************************************/
52 |
53 | ///@notice Bool to check if the shop address has been set
54 | bool private _shopSet = false;
55 |
56 | ///@notice Current disputes, indexed by disputeId
57 | mapping(uint256 => Dispute) public disputes;
58 | ///@notice The ID of the next dispute to be created
59 | uint256 public nextDisputeId;
60 | ///@dev Mapping between disputeId and user address to record the hash of the vote + secret
61 | mapping(uint256 => mapping(address => bytes32)) public commitsOnDisputes;
62 | ///@dev Mapping between user address and disputeId to record the vote.
63 | mapping(address => mapping(uint256 => Vote)) public hasVotedOnDispute;
64 | ///@dev Mapping between disputeId and the result of the dispute.
65 | mapping(uint256 => Vote) public disputeResult;
66 | ///@dev Mapping between user address and disputeId to record the lottery check.
67 | mapping(address => mapping(uint256 => bool)) public hasCheckedLottery;
68 | ///@notice Min number of people to pass a dispute
69 | uint256 public disputeQuorum;
70 |
71 | ///@notice Current upgrade proposals, indexed by upgradeProposalId
72 | mapping(uint256 => UpgradeProposal) public upgradeProposals;
73 | ///@notice The ID of the next upgrade proposal to be created
74 | uint256 public nextUpgradeProposalId;
75 | ///@dev Mapping between user address and upgradeProposalId to record the vote
76 | mapping(address => mapping(uint256 => Vote)) public hasVotedOnUpgradeProposal;
77 | ///@dev Mapping between upgradeProposalId and the result of the proposal.
78 | mapping(uint256 => Vote) public upgradeProposalResult;
79 | ///@notice Min number of people to pass a proposal
80 | uint256 public proposalQuorum = DEFAULT_PROPOSAL_QUORUM;
81 |
82 | ///@notice _password to access key features
83 | string private _password;
84 | ///@notice The address of the Shop contract
85 | address public shopAddress;
86 |
87 |
88 | /*************************************** Errors *******************************************************/
89 |
90 | ///@notice Throwed if a zero address (0x0) is detected in an operation that does not permit it
91 | error ZeroAddress();
92 |
93 |
94 | /************************************** Modifiers *****************************************************/
95 |
96 | /**
97 | @notice Check if the caller is authorized to access key features
98 | @param magicWord The password to access key features
99 | */
100 | modifier isAuthorized(string calldata magicWord) {
101 | require(
102 | keccak256(abi.encodePacked(magicWord)) == keccak256(abi.encodePacked(_password)),
103 | "Unauthorized");
104 | _;
105 | }
106 |
107 |
108 | /**
109 | @notice Modifier to check if the Shop address has been set
110 | */
111 | modifier shopNotSet() {
112 | require(!_shopSet, "Shop address already set");
113 | _;
114 | }
115 |
116 | /**
117 | @notice Check if the address is not zero
118 | @param toCheck The address to be checked
119 | */
120 | modifier notZero(address toCheck) {
121 | assembly {
122 | if iszero(toCheck) {
123 | let ptr := mload(0x40)
124 | mstore(ptr, 0xd92e233d00000000000000000000000000000000000000000000000000000000) // selector for error `ZeroAddress()`
125 | revert(ptr, 0x4)
126 | }
127 | }
128 | _;
129 | }
130 |
131 | /**
132 | @notice Check if the caller has already checked the lottery for a dispute
133 | @param user Caller's address
134 | @param disputeId Id of the dispute
135 | */
136 | modifier notChecked(address user, uint256 disputeId) {
137 | require(
138 | !hasCheckedLottery[user][disputeId],
139 | "User cannot check the lottery more than 1 time per dispute");
140 | _;
141 | }
142 |
143 |
144 | /************************************** External ****************************************************************/
145 |
146 | /**
147 | @notice Constructor to set the password
148 | @param magicWord The password to access key features
149 | @param nftAddress The address of the NFT contract
150 | @param fptAddress The address of the FPT token
151 | */
152 | constructor(string memory magicWord, address nftAddress, address fptAddress) {
153 | _password = magicWord;
154 | _grantRole(CONTROL_ROLE, msg.sender);
155 | COOL_NFT_CONTRACT = IFP_CoolNFT(nftAddress);
156 | FPT_CONTRACT = IERC20(fptAddress);
157 | }
158 |
159 | /**
160 | @notice Sets the shop address as the new Control role
161 | @param shop The address of the shop
162 | */
163 | function setShop(address shop) external onlyRole(CONTROL_ROLE) shopNotSet {
164 | _shopSet = true;
165 | shopAddress = shop;
166 | _grantRole(CONTROL_ROLE, shopAddress);
167 | }
168 |
169 | /**
170 | @notice Open a dispute
171 | @param itemId The ID of the item involved in the dispute
172 | @param buyerReasoning The reasoning of the buyer in favor of the claim
173 | @param sellerReasoning The reasoning of the seller against the claim
174 | */
175 | function newDispute(
176 | uint256 itemId,
177 | string calldata buyerReasoning,
178 | string calldata sellerReasoning
179 | ) external onlyRole(CONTROL_ROLE) returns (uint256) {
180 | uint256 dId = nextDisputeId;
181 | nextDisputeId += 1;
182 |
183 | disputes[dId] = Dispute(
184 | itemId,
185 | buyerReasoning,
186 | sellerReasoning,
187 | 0,
188 | 0,
189 | 0,
190 | block.timestamp,
191 | 0,
192 | DisputeState.COMMITTING_PHASE
193 | );
194 |
195 | emit NewDispute(dId, itemId);
196 | return dId;
197 | }
198 |
199 | /**
200 | @notice Commit the hash of the vote
201 | @param disputeId The ID of the target dispute
202 | @param commit Vote + secret hash
203 | */
204 | function commitVoteOnDispute(uint256 disputeId, bytes32 commit) external {
205 | require(disputes[disputeId].state == DisputeState.COMMITTING_PHASE, "Dispute is not in committing phase");
206 | require(hasVotedOnDispute[msg.sender][disputeId] == Vote.DIDNT_VOTE , "You have already voted");
207 |
208 | hasVotedOnDispute[msg.sender][disputeId] = Vote.COMMITTED;
209 | commitsOnDisputes[disputeId][msg.sender] = commit;
210 |
211 | emit DisputeVoteCommitted(disputeId, msg.sender);
212 | }
213 |
214 | /**
215 | @notice Reveal a vote on a dispute if commiting time has elapsed
216 | @param disputeId The ID of the target dispute
217 | @param vote The vote of the user
218 | @param secret The secret used to commit the vote
219 | */
220 | function revealDisputeVote(uint disputeId, bool vote, string calldata secret) external {
221 | if(disputes[disputeId].state != DisputeState.REVEALING_PHASE) {
222 | if(disputes[disputeId].state == DisputeState.COMMITTING_PHASE && disputes[disputeId].committingStartingTime + COMMITTING_TIME <= block.timestamp) {
223 | disputes[disputeId].state = DisputeState.REVEALING_PHASE;
224 | disputes[disputeId].revealingStartingTime = block.timestamp;
225 | } else {
226 | revert("Conditions for advancing to revealing phase are not met");
227 | }
228 | }
229 | require(hasVotedOnDispute[msg.sender][disputeId] == Vote.COMMITTED, "You currently have no vote to reveal");
230 |
231 | bytes32 voteHash = keccak256(abi.encodePacked(vote, secret));
232 | require(commitsOnDisputes[disputeId][msg.sender] == voteHash, "Invalid vote hash");
233 |
234 | uint votingPower = _calcVotingPower(msg.sender);
235 | disputes[disputeId].totalVoters += 1;
236 |
237 | if (vote) {
238 | disputes[disputeId].votesFor += votingPower;
239 | hasVotedOnDispute[msg.sender][disputeId] = Vote.FOR;
240 | } else {
241 | disputes[disputeId].votesAgainst += votingPower;
242 | }
243 |
244 | emit DisputeVoteCasted(disputeId, msg.sender);
245 | }
246 |
247 | /**
248 | @notice Resolve a dispute if MIN_REVEALING_TIME has elapsed and if enough users have voted or MAX_REVEALING_TIME has elapsed. Then remove it from the storage
249 | @param disputeId The ID of the target dispute
250 | */
251 | function endDispute(uint256 disputeId) external {
252 | require(disputes[disputeId].state == DisputeState.REVEALING_PHASE, "Dispute is not in revealing phase");
253 | require(disputes[disputeId].revealingStartingTime + MIN_REVEALING_TIME <= block.timestamp, "Minimum revealing time hasn't elapsed");
254 | require((disputes[disputeId].totalVoters > disputeQuorum) || (disputes[disputeId].revealingStartingTime + MAX_REVEALING_TIME <= block.timestamp), "Conditions for ending dispute are not met");
255 |
256 | uint256 itemId = disputes[disputeId].itemId;
257 |
258 | if (disputes[disputeId].votesFor > disputes[disputeId].votesAgainst) {
259 | delete disputes[disputeId];
260 | disputeResult[disputeId] = Vote.FOR;
261 | _buyerWins(itemId);
262 | } else {
263 | delete disputes[disputeId];
264 | disputeResult[disputeId] = Vote.AGAINST;
265 | _sellerWins(itemId);
266 | }
267 |
268 | emit EndDispute(disputeId, itemId);
269 | }
270 |
271 |
272 | /**
273 | @notice Cancel an ongoing dispute. Either by the buyer or blacklisting (shop contract)
274 | @param disputeId The ID of the target dispute
275 | */
276 | function cancelDispute(uint256 disputeId) external onlyRole(CONTROL_ROLE) {
277 | uint256 itemId = disputes[disputeId].itemId;
278 |
279 | delete disputes[disputeId];
280 |
281 | emit EndDispute(disputeId, itemId);
282 | }
283 |
284 |
285 | /**
286 | @notice Randomly award an NFT to a user if they voten for the winning side
287 | @param disputeId The ID of the target dispute
288 | */
289 | function checkLottery(uint256 disputeId) external notChecked(msg.sender, disputeId) {
290 | require(hasVotedOnDispute[msg.sender][disputeId] != Vote.DIDNT_VOTE, "User didn't vote");
291 | hasCheckedLottery[msg.sender][disputeId] = true;
292 | if(disputeResult[disputeId] == hasVotedOnDispute[msg.sender][disputeId]) {
293 | _lotteryNFT(msg.sender);
294 | } else {
295 | revert("User voted for the wrong side");
296 | }
297 | }
298 |
299 | /**
300 | @notice Open an upgrade proposal
301 | @param addrNewShop The address of the new Shop contract proposed
302 | */
303 | function newUpgradeProposal(
304 | address addrNewShop
305 | ) external notZero(addrNewShop) returns (uint256) {
306 | require(addrNewShop.code.length > 0, "The new shop address is invalid");
307 | uint256 pId = nextUpgradeProposalId;
308 | nextUpgradeProposalId += 1;
309 |
310 | upgradeProposals[pId] = UpgradeProposal(
311 | msg.sender,
312 | pId,
313 | block.timestamp,
314 | 0,
315 | addrNewShop,
316 | 0,
317 | 0,
318 | 0,
319 | ProposalState.ACTIVE
320 | );
321 |
322 | emit NewUpgradeProposal(pId, block.timestamp, addrNewShop);
323 | return pId;
324 | }
325 |
326 | /**
327 | @notice Cast a vote on an upgrade proposal
328 | @param proposalId The ID of the upgrade proposal
329 | @param vote The vote, true for FOR, false for AGAINST
330 | */
331 | function castVoteOnProposal(uint256 proposalId, bool vote) external {
332 | require(upgradeProposals[proposalId].state == ProposalState.ACTIVE , "Proposal is not active");
333 | require(upgradeProposals[proposalId].creationTimestamp + PROPOSAL_REVIEW_TIME < block.timestamp, "Proposal is not ready to be voted");
334 |
335 | require(hasVotedOnUpgradeProposal[msg.sender][proposalId] == Vote.DIDNT_VOTE , "You have already voted");
336 |
337 | uint256 votingPower = _calcVotingPower(msg.sender);
338 | require(votingPower > 0, "You have no voting power");
339 |
340 | if (vote) {
341 | upgradeProposals[proposalId].votesFor += votingPower;
342 | hasVotedOnUpgradeProposal[msg.sender][proposalId] = Vote.FOR;
343 | } else {
344 | upgradeProposals[proposalId].votesAgainst += votingPower;
345 | hasVotedOnUpgradeProposal[msg.sender][proposalId] = Vote.AGAINST;
346 | }
347 |
348 | upgradeProposals[proposalId].totalVoters += 1;
349 |
350 | emit ProposalVoteCasted(proposalId, msg.sender);
351 | }
352 |
353 | /**
354 | @notice Cancel an ongoing upgrade proposal by the proposal creator
355 | @param proposalId The ID of the upgrade proposal
356 | */
357 | function cancelProposalByCreator(uint256 proposalId) external {
358 | require(upgradeProposals[proposalId].state == ProposalState.ACTIVE, "Proposal is not active");
359 | require(upgradeProposals[proposalId].creator == msg.sender, "You are not the creator of the proposal");
360 | _cancelProposal(proposalId);
361 | }
362 |
363 | /**
364 | @notice Cancel an ongoing upgrade proposal by the admin of the DAO (who knows the password)
365 | @param proposalId The ID of the upgrade proposal
366 | @param magicWord The password to access key features
367 | */
368 | function cancelProposal(uint256 proposalId, string calldata magicWord) external isAuthorized(magicWord) {
369 | require(upgradeProposals[proposalId].state == ProposalState.ACTIVE, "Proposal is not active");
370 | _cancelProposal(proposalId);
371 | }
372 |
373 | /**
374 | @notice Resolve a proposal if enough users have voted and enough time has passed
375 | @param proposalId The ID of the upgrade proposal
376 | */
377 | function resolveUpgradeProposal(uint256 proposalId) external {
378 | require(upgradeProposals[proposalId].state == ProposalState.ACTIVE, "Proposal is not active");
379 | require(upgradeProposals[proposalId].creationTimestamp + PROPOSAL_VOTING_TIME < block.timestamp, "Proposal is not ready to be resolved");
380 | require(upgradeProposals[proposalId].totalVoters > proposalQuorum, "Not enough voters");
381 | address newShop = upgradeProposals[proposalId].newShop;
382 | if (upgradeProposals[proposalId].votesFor > upgradeProposals[proposalId].votesAgainst) {
383 | upgradeProposalResult[proposalId] = Vote.FOR;
384 | upgradeProposals[proposalId].state = ProposalState.PASSED;
385 | upgradeProposals[proposalId].approvalTimestamp = block.timestamp;
386 | emit ProposalPassed(proposalId, newShop, block.timestamp);
387 | } else {
388 | delete upgradeProposals[proposalId];
389 | upgradeProposalResult[proposalId] = Vote.AGAINST;
390 | emit ProposalNotPassed(proposalId, newShop);
391 | }
392 | }
393 |
394 | /**
395 | @notice Execute a passed proposal
396 | @param proposalId The ID of the upgrade proposal
397 | */
398 | function executePassedProposal(uint256 proposalId) external {
399 | require(upgradeProposals[proposalId].state == ProposalState.PASSED, "Proposal is not passed");
400 | require(upgradeProposals[proposalId].approvalTimestamp + PROPOSAL_EXECUTION_DELAY < block.timestamp, "Proposal is not ready to be executed");
401 | address newShop = upgradeProposals[proposalId].newShop;
402 | delete upgradeProposals[proposalId];
403 |
404 | (bool success, ) = shopAddress.call(
405 | abi.encodeWithSignature(
406 | "upgradeToAndCall(address,bytes)",
407 | newShop,
408 | ""
409 | )
410 | );
411 |
412 | require(success, "upgradeToAndCall(address,bytes) call failed");
413 | emit ProposalExecuted(proposalId, newShop);
414 | }
415 |
416 | /************************************** Views *********************************************************************/
417 |
418 | /**
419 | @notice Query the details of a dispute
420 | @param disputeId The ID of the target dispute
421 | */
422 | function queryDispute(uint256 disputeId) public view returns (Dispute memory) {
423 | return disputes[disputeId];
424 | }
425 |
426 | /**
427 | @notice Query the result of a dispute
428 | @param disputeId The ID of the target dispute
429 | */
430 | function queryDisputeResult(uint256 disputeId) public view returns (Vote) {
431 | return disputeResult[disputeId];
432 | }
433 |
434 | /**
435 | @notice Query the details of an upgrade proposal
436 | @param upgradeProposalId The ID of the target proposal
437 | */
438 | function queryUpgradeProposal(uint256 upgradeProposalId) public view returns (UpgradeProposal memory) {
439 | return upgradeProposals[upgradeProposalId];
440 | }
441 |
442 | /**
443 | @notice Query the result of an upgrade proposal
444 | @param upgradeProposalId The ID of the target proposal
445 | */
446 | function queryUpgradeProposalResult(uint256 upgradeProposalId) public view returns (Vote) {
447 | return upgradeProposalResult[upgradeProposalId];
448 | }
449 |
450 | /************************************** Internal *****************************************************************/
451 |
452 | /**
453 | @notice Run a PRNG to award NFT to a user
454 | @param user The address of the elegible user
455 | */
456 | function _lotteryNFT(address user) internal {
457 | uint256 randomNumber = uint8(
458 | uint256(
459 | keccak256(
460 | abi.encodePacked(
461 | blockhash(block.number - 1),
462 | block.timestamp,
463 | user
464 | ))));
465 |
466 | if (randomNumber < THRESHOLD) {
467 | COOL_NFT_CONTRACT.mintCoolNFT(user);
468 | }
469 |
470 | emit AwardNFT(user);
471 | }
472 |
473 | /**
474 | @notice Resolve a dispute in favor of the buyer triggering the Shop's return item and refund logic
475 | @param itemId The ID of the item involved in the dispute
476 | */
477 | function _buyerWins(uint256 itemId) internal {
478 | (bool success, ) = shopAddress.call(
479 | abi.encodeWithSignature(
480 | "returnItem(uint256)",
481 | itemId
482 | )
483 | );
484 | require(success, "returnItem(uint256) call failed");
485 | }
486 |
487 | /**
488 | @notice Resolve a dispute in favor of the seller triggering the Shop's close sale dispute logic
489 | @param itemId The ID of the item involved in the dispute
490 | */
491 | function _sellerWins(uint256 itemId) internal {
492 | (bool success, ) = shopAddress.call(
493 | abi.encodeWithSignature(
494 | "endDispute(uint256)",
495 | itemId
496 | )
497 | );
498 | require(success, "endDispute(uint256) call failed");
499 | }
500 |
501 | /**
502 | @notice Calculate the voting power of a user
503 | @param user The address of the user to calculate the voting power
504 | */
505 | function _calcVotingPower(address user) internal view returns (uint256) {
506 | return FPT_CONTRACT.balanceOf(user);
507 | }
508 |
509 | /**
510 | @notice Cancel an ongoing upgrade proposal. Either by the sender of the proposal or the admin (who knows the password)
511 | @param proposalId The ID of the upgrade proposal
512 | */
513 | function _cancelProposal(uint proposalId) internal {
514 | delete upgradeProposals[proposalId];
515 |
516 | emit ProposalCanceled(proposalId);
517 | }
518 |
519 | }
--------------------------------------------------------------------------------
/src/FP_PowersellerNFT.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {IFP_PowersellerNFT} from "./interfaces/IFP_PowersellerNFT.sol";
5 | import {AccessControl} from "@openzeppelin/contracts@v5.0.1/access/AccessControl.sol";
6 | import {ERC721} from "@openzeppelin/contracts@v5.0.1/token/ERC721/ERC721.sol";
7 |
8 | /**
9 | @title FaillaPop PowerSeller NFT [v0.1]
10 | @author Faillapop team :D
11 | @notice The contract allows the shop to mint a PowerSeller NFT for users and remove it if they are considered malicious. PowerSeller badge is required to claimRewards in the vault.
12 | @dev Security review is pending... should we deploy this?
13 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
14 | */
15 | contract FP_PowersellerNFT is IFP_PowersellerNFT, ERC721, AccessControl {
16 |
17 | /************************************** Constants ****************************************************************/
18 |
19 | ///@notice The Control role ID for the AccessControl contract. At first it's the msg.sender and then the shop.
20 | bytes32 public constant CONTROL_ROLE = keccak256("CONTROL_ROLE");
21 |
22 | /************************************** State vars ****************************************************************/
23 |
24 | ///@notice Bool to check if the shop address has been set
25 | bool private _shopSet = false;
26 | ///@notice The next tokenId to be minted
27 | uint256 public nextTokenId;
28 | ///@notice Total number of users that received a PowerSeller badge
29 | uint256 private _totalPowersellers;
30 | ///@notice Mapping from user address to tokenId
31 | mapping (address => uint256) public tokenIds;
32 |
33 | /************************************** Modifiers *****************************************************/
34 |
35 | /**
36 | @notice Modifier to check if the Shop address has been set
37 | */
38 | modifier shopNotSet() {
39 | require(!_shopSet, "Shop address already set");
40 | _;
41 | }
42 |
43 | /************************************** External ****************************************************************/
44 |
45 | /**
46 | @notice Constructor, initializes the contract
47 | */
48 | constructor() ERC721("Faillapop Powerseller NFT", "FPSNFT") {
49 | _grantRole(CONTROL_ROLE, msg.sender);
50 | }
51 |
52 | /**
53 | @notice Sets the shop address as the new Control role
54 | @param shopAddress The address of the shop contract
55 | */
56 | function setShop(address shopAddress) external onlyRole(CONTROL_ROLE) shopNotSet {
57 | _shopSet = true;
58 | _grantRole(CONTROL_ROLE, shopAddress);
59 | }
60 |
61 | /**
62 | @notice Mints a PowerSeller badge for the user
63 | @param to The address of the user that will receive the badge
64 | */
65 | function safeMint(address to) external onlyRole(CONTROL_ROLE) {
66 | require(tokenIds[to] == 0, "This user is already a Powerseller");
67 | nextTokenId++;
68 | _totalPowersellers++;
69 | tokenIds[to] = nextTokenId;
70 | _safeMint(to, nextTokenId);
71 |
72 | emit PowersellerNFT_Minted(msg.sender, nextTokenId);
73 | }
74 |
75 | /**
76 | @notice Removes the PowerSeller badge from a user
77 | @param user The address of the user that will lose the badge
78 | */
79 | function removePowersellerNFT(address user) external onlyRole(CONTROL_ROLE) {
80 | require(tokenIds[user] != 0, "This user is not a Powerseller");
81 | uint256 tokenId = tokenIds[user];
82 | tokenIds[user] = 0;
83 | _totalPowersellers--;
84 | _burn(tokenId);
85 |
86 | emit PowersellerNFT_Removed(msg.sender, tokenId);
87 | }
88 |
89 | ///@notice Returns the total number of users that received a PowerSeller badge
90 | function totalPowersellers() external view returns (uint256) {
91 | return _totalPowersellers;
92 | }
93 |
94 | /**
95 | @notice Checks if the address holds a Trusted badge
96 | @param user The address of the user to check
97 | */
98 | function checkPrivilege(address user) external view returns (bool) {
99 | return tokenIds[user] != 0;
100 | }
101 |
102 | /************************************** Public ****************************************************************/
103 | /**
104 | * @notice Powerseller NFTs cannot be transferred, so this function is overriden to revert
105 | */
106 | function approve(address /*to*/, uint256 /*tokenId*/) public virtual override{
107 | revert("PowersellerNFT cannot be approved");
108 | }
109 | /**
110 | * @notice Powerseller NFTs cannot be transferred, so this function is overriden to revert
111 | */
112 | function setApprovalForAll(address /*operator*/, bool /*approved*/) public virtual override{
113 | revert("PowersellerNFT cannot be approved");
114 | }
115 | /**
116 | * @notice Powerseller NFTs cannot be transferred, so this function is overriden to revert
117 | */
118 | function transferFrom(address /*from*/, address /*to*/, uint256 /*tokenId*/) public virtual override{
119 | revert("PowersellerNFT cannot be transferred");
120 | }
121 | /**
122 | * @notice Powerseller NFTs cannot be transferred, so this function is overriden to revert
123 | */
124 | function safeTransferFrom(address /*from*/, address /*to*/, uint256 /*tokenId*/, bytes memory /*data*/) public virtual override{
125 | revert("PowersellerNFT cannot be transferred");
126 | }
127 |
128 | /**
129 | @notice Returns the supported interfaces collection
130 | @param interfaceId The interface identifier
131 | */
132 | function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl) returns (bool) {
133 | return ERC721.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId);
134 | }
135 |
136 | }
--------------------------------------------------------------------------------
/src/FP_Proxy.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {ERC1967Proxy} from "@openzeppelin/contracts@v5.0.1/proxy/ERC1967/ERC1967Proxy.sol";
5 | import {ERC1967Utils} from "@openzeppelin/contracts@v5.0.1/proxy/ERC1967/ERC1967Utils.sol";
6 |
7 | /**
8 | * @dev This contract implements an upgradeable proxy.
9 | * The implementation address is stored in storage in the location specified by https://eips.ethereum.org/EIPS/eip-1967[EIP1967],
10 | * so that it doesn't conflict with the storage layout of the implementation behind the proxy.
11 | */
12 | contract FP_Proxy is ERC1967Proxy {
13 |
14 | /************************************** Constants *******************************************************/
15 |
16 | ///@notice The address of the DAO contract
17 | address public immutable DAO_ADDRESS;
18 |
19 |
20 | /************************************** External *******************************************************/
21 |
22 | /**
23 | * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
24 | *
25 | * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
26 | * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
27 | *
28 | * Requirements:
29 | *
30 | * - If `data` is empty, `msg.value` must be zero.
31 | */
32 | constructor(address implementation, bytes memory _data, address _dao) ERC1967Proxy(implementation, _data) {
33 | DAO_ADDRESS = _dao;
34 | }
35 |
36 | /**
37 | * @dev Performs implementation upgrade with additional setup call if data is nonempty.
38 | * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
39 | * to avoid stuck value in the contract.
40 | *
41 | * Emits an {IERC1967-Upgraded} event.
42 | */
43 | function upgradeToAndCall(address _newImplementation, bytes memory _data) external {
44 | require(msg.sender == DAO_ADDRESS, "AccessControlUnauthorizedAccount");
45 | ERC1967Utils.upgradeToAndCall(_newImplementation, _data);
46 | }
47 |
48 | /**
49 | * @dev Returns the current implementation address.
50 | */
51 | function getImplementation() external view returns (address) {
52 | return _implementation();
53 | }
54 | }
--------------------------------------------------------------------------------
/src/FP_Shop.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {IFP_DAO} from "./interfaces/IFP_DAO.sol";
5 | import {IFP_Shop} from "./interfaces/IFP_Shop.sol";
6 | import {IFP_Vault} from "./interfaces/IFP_Vault.sol";
7 | import {IFP_CoolNFT} from "./interfaces/IFP_CoolNFT.sol";
8 | import {IFP_PowersellerNFT} from "./interfaces/IFP_PowersellerNFT.sol";
9 | import {AccessControlUpgradeable} from "@openzeppelin-upgradeable/contracts@v5.0.1/access/AccessControlUpgradeable.sol";
10 | import {Initializable} from "@openzeppelin-upgradeable/contracts@v5.0.1/proxy/utils/Initializable.sol";
11 |
12 | /**
13 | @title The FaillaPop Shop! [v.02]
14 | @author Faillapop team :D
15 | @notice The contract allows anyone to sell and buy goods in a decentralized manner! The seller has to lock funds to avoid malicious behaviour.
16 | In addition, unhappy buyers can open a claim and the DAO will decide if the seller misbehaved or not.
17 | @dev Security review is pending... should we deploy this?
18 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
19 | */
20 | contract FP_Shop is IFP_Shop, AccessControlUpgradeable {
21 |
22 | /************************************** Constants *******************************************************/
23 |
24 | ///@notice The admin role ID for the AccessControl contract
25 | bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
26 | ///@notice The DAO role ID for the AccessControl contract
27 | bytes32 public constant DAO_ROLE = keccak256("DAO_ROLE");
28 | ///@notice The blacklisted role ID for the AccessControl contract
29 | bytes32 public constant BLACKLISTED_ROLE = keccak256("BLACKLISTED_ROLE");
30 | ///@notice The maximum time that a dispute can be kept waiting for a seller's reply
31 | uint256 public constant MAX_DISPUTE_WAITING_FOR_REPLY = 15 days;
32 | ///@notice The maximum time a sale can be pending
33 | uint256 public MAX_PENDING_TIME = 30 days;
34 |
35 | /************************************** State vars *******************************************************/
36 |
37 | ///@notice Mapping between the item ID and its Sale struct
38 | mapping (uint256 => Sale) public offeredItems;
39 | ///@notice The index of the next new Sale
40 | uint256 public offerIndex;
41 | ///@notice Mapping between the seller address and the number of valid sales
42 | mapping (address => uint256) public numValidSales;
43 | ///@notice Mapping between the seller address and the timestamp of the first valid sale
44 | mapping (address => uint256) public firstValidSaleTimestamp;
45 | ///@notice Mapping between the item ID and its Dispute struct
46 | mapping (uint256 => Dispute) public disputedItems;
47 | ///@notice The list of blacklisted seller addresses
48 | address[] public blacklistedSellers;
49 | ///@notice PowersellerNFT contract
50 | IFP_PowersellerNFT public powersellerContract;
51 | ///@notice address of the CoolNFT contract
52 | IFP_CoolNFT public coolNFTContract;
53 | ///@notice Faillapop vault contract
54 | IFP_Vault public vaultContract;
55 | ///@notice Faillapop DAO contract
56 | IFP_DAO public daoContract;
57 |
58 |
59 | /************************************** Modifiers *****************************************************/
60 |
61 | ///@notice Check if the caller is not blacklisted
62 | modifier notBlacklisted() {
63 | require(
64 | !hasRole(BLACKLISTED_ROLE, msg.sender),
65 | "Seller is blacklisted"
66 | );
67 | _;
68 | }
69 |
70 |
71 | /************************************** External ****************************************************************/
72 |
73 | /**
74 | @notice Initializer of the contract
75 | @param daoAddress The address of the DAO contract
76 | @param vaultAddress The address of the Vault contract
77 | @param powersellerNFTAddress The address of the PowersellerNFT contract
78 | @param coolNFTAddress The address of the CoolNFT contract
79 | */
80 | function initialize(address daoAddress, address vaultAddress, address powersellerNFTAddress, address coolNFTAddress) public initializer {
81 | AccessControlUpgradeable.__AccessControl_init();
82 | _grantRole(ADMIN_ROLE, msg.sender);
83 | _grantRole(DAO_ROLE, daoAddress);
84 |
85 | powersellerContract = IFP_PowersellerNFT(powersellerNFTAddress);
86 | coolNFTContract = IFP_CoolNFT(coolNFTAddress);
87 | daoContract = IFP_DAO(daoAddress);
88 | vaultContract = IFP_Vault(vaultAddress);
89 | }
90 |
91 | /**
92 | @notice Endpoint to buy an item
93 | @param itemId The ID of the item being bought
94 | @dev The user must send the exact amount of Ether to buy the item
95 | */
96 | function doBuy(uint256 itemId) external payable {
97 | require(offeredItems[itemId].seller != address(0), "itemId does not exist");
98 | require(offeredItems[itemId].state == State.Selling, "Item cannot be bought");
99 | require(msg.value >= offeredItems[itemId].price, "Incorrect amount of Ether sent");
100 | require(
101 | !hasRole(BLACKLISTED_ROLE, offeredItems[itemId].seller),
102 | "Seller is blacklisted"
103 | );
104 |
105 | offeredItems[itemId].buyer = msg.sender;
106 | offeredItems[itemId].state = State.Pending;
107 | offeredItems[itemId].buyTimestamp = block.timestamp;
108 |
109 | emit Buy(msg.sender, itemId);
110 | }
111 |
112 | /**
113 | @notice Endpoint to dispute a sale. The buyer will supply the supporting info to the DAO
114 | @param itemId The ID of the item being disputed
115 | @param buyerReasoning The reasoning of the buyer for the claim
116 | */
117 | function disputeSale(uint256 itemId, string calldata buyerReasoning) external {
118 | require(offeredItems[itemId].state == State.Pending, "Item not pending");
119 | require(offeredItems[itemId].buyer == msg.sender, "Not the buyer");
120 |
121 | offeredItems[itemId].state = State.Disputed;
122 |
123 | // New dispute with ID = 0 until the correct one is set by the DAO
124 | Dispute memory newDispute = Dispute(0, block.timestamp, buyerReasoning, "");
125 | disputedItems[itemId] = newDispute;
126 | }
127 |
128 | /**
129 | @notice Endpoint to confirm the receipt of an item and trigger the payment to the seller.
130 | @param itemId The ID of the item being confirmed
131 | */
132 | function itemReceived(uint256 itemId) external {
133 | if(offeredItems[itemId].seller == msg.sender) {
134 | require( (block.timestamp - offeredItems[itemId].buyTimestamp) >= MAX_PENDING_TIME, "Insufficient elapsed time" );
135 | }else{
136 | require(offeredItems[itemId].buyer == msg.sender, "Not the buyer");
137 | }
138 | offeredItems[itemId].state = State.Sold;
139 |
140 | // Seller should be paid
141 | closeSale(itemId, false, true, true);
142 | }
143 |
144 | /**
145 | @notice Endpoint to close a dispute. Both the DAO and the buyer could call this function to cancel a dispute.
146 | The buyer can:
147 | - Cancel the dispute if the seller is unresponsive, in which case the money is returned to the buyer and the seller is blacklisted.
148 | - Cancel the dispute, accepting the item, in which case the buyer is paid.
149 | @param itemId The ID of the item being disputed
150 | */
151 | function endDispute(uint256 itemId) external {
152 | require(offeredItems[itemId].state == State.Disputed, "Dispute not found");
153 |
154 | if (msg.sender == offeredItems[itemId].buyer) {
155 | if(bytes(disputedItems[itemId].sellerReasoning).length == 0) {
156 | // Buyer cancels the dispute, the seller is unresponsive
157 | require( (block.timestamp - disputedItems[itemId].disputeTimestamp) >= MAX_DISPUTE_WAITING_FOR_REPLY, "Insufficient elapsed time" );
158 | delete disputedItems[itemId];
159 | offeredItems[itemId].state = State.Sold;
160 | // Seller should not be paid
161 | closeSale(itemId, true, false, true);
162 | } else {
163 | // Self-cancelation of the dispute, the buyer accepts the item
164 | _closeDispute(itemId);
165 | // Seller should be paid
166 | offeredItems[itemId].state = State.Sold;
167 | closeSale(itemId, false, true, true);
168 | }
169 | } else {
170 | // DAO resolving the dispute in favor of the seller, if the buyer wins `returnItem` will be called
171 | _checkRole(DAO_ROLE); // Will revert if msg.sender doesn't have the DAO_ROLE
172 |
173 | delete disputedItems[itemId];
174 | offeredItems[itemId].state = State.Sold;
175 | // Seller should be paid
176 | closeSale(itemId, false, true, true);
177 | }
178 | }
179 |
180 | /**
181 | @notice Endpoint to create a new sale. The seller must have enough funds staked in the Vault so
182 | price amount can be locked to desincentivice malicious behavior
183 | @param title The title of the item being sold
184 | @param description A description of the item being sold
185 | @param price The price in Ether of the item being sold
186 | */
187 | function newSale(string calldata title, string calldata description, uint256 price) external notBlacklisted {
188 | require(price > 0, "Price must be greater than 0");
189 | require(bytes(title).length > 0, "Title cannot be empty");
190 | require(bytes(description).length > 0, "Description cannot be empty");
191 |
192 | uint256 currentId = offerIndex;
193 | Sale memory sale = Sale(msg.sender, address(0), title, description, price, State.Selling, 0);
194 | offeredItems[currentId] = sale;
195 |
196 | // Lock seller staken funds to desincentivize malicious behavior
197 | vaultContract.doLock(msg.sender, price);
198 |
199 | offerIndex += 1;
200 |
201 | emit NewItem(currentId, title);
202 | }
203 |
204 | /**
205 | @notice Endpoint to modify an existing sale. Locked funds will be partially realeased if price decreases.
206 | @param itemId ID of the item being modified
207 | @param newTitle New title of the item being sold
208 | @param newDesc New description of the item being sold
209 | @param newPrice New price in Ether of the item being sold
210 | */
211 | function modifySale(uint256 itemId, string calldata newTitle, string calldata newDesc, uint256 newPrice) external {
212 | require(offeredItems[itemId].state == State.Selling, "Sale can't be modified");
213 | require(newPrice > 0, "Price must be greater than 0");
214 | require(bytes(newTitle).length > 0, "Title cannot be empty");
215 | require(bytes(newDesc).length > 0, "Description cannot be empty");
216 | require(offeredItems[itemId].seller == msg.sender, "Only the seller can modify the sale");
217 |
218 | // Update vault
219 | uint256 priceDifference;
220 | if (offeredItems[itemId].price > newPrice) {
221 | priceDifference = offeredItems[itemId].price - newPrice;
222 | vaultContract.doUnlock(msg.sender, priceDifference);
223 | } else if(offeredItems[itemId].price < newPrice) {
224 | priceDifference = newPrice - offeredItems[itemId].price;
225 | vaultContract.doLock(msg.sender, priceDifference);
226 | }
227 |
228 | // Update details
229 | offeredItems[itemId].title = newTitle;
230 | offeredItems[itemId].description = newDesc;
231 | offeredItems[itemId].price = newPrice;
232 |
233 | emit ModifyItem(itemId, newTitle);
234 | }
235 |
236 | /**
237 | @notice Endpoint to cancel an active sale
238 | @param itemId The ID of the item which sale is being cancelled
239 | */
240 | function cancelActiveSale (uint256 itemId) external {
241 | require(offeredItems[itemId].state == State.Selling, "Sale can't be cancelled");
242 | require(offeredItems[itemId].seller == msg.sender, "Only the seller can cancel the sale");
243 |
244 | //Seller should NOT be paid
245 | closeSale(itemId, false, false, true);
246 | }
247 |
248 | /**
249 | @notice Endpoint to set the vacation mode of a seller. If the seller is in vacation mode nobody can buy his goods
250 | @param vacationMode The new vacation mode of the seller
251 | */
252 | function setVacationMode(bool vacationMode) external {
253 | for (uint256 i = 0; i < offerIndex; i++) {
254 | if (offeredItems[i].seller == msg.sender) {
255 |
256 | if (vacationMode && offeredItems[i].state == State.Selling) {
257 | offeredItems[i].state = State.Vacation;
258 |
259 | } else if (!vacationMode && offeredItems[i].state == State.Vacation) {
260 | offeredItems[i].state = State.Selling;
261 |
262 | }
263 | }
264 | }
265 | }
266 |
267 | /**
268 | @notice Endpoint to reply to a dispute. The seller will supply the supporting info to the DAO. If the seller does not reply in time,
269 | the admin could mark them as malicious and slash their funds, or the buyer could end the dispute and get their money back
270 | @param itemId The ID of the item being disputed
271 | @param sellerReasoning The reasoning of the seller for the claim
272 | */
273 | function disputedSaleReply(uint256 itemId, string calldata sellerReasoning) external {
274 | require(offeredItems[itemId].state == State.Disputed, "Item not disputed");
275 | require(offeredItems[itemId].seller == msg.sender, "Not the seller");
276 | require(bytes(sellerReasoning).length > 0, "Seller's reasoning cannot be empty");
277 |
278 | _openDispute(itemId, sellerReasoning);
279 | }
280 |
281 | /**
282 | @notice Endpoint to return an item, only the DAO can trigger it
283 | @param itemId The ID of the item being returned
284 | */
285 | function returnItem(uint256 itemId) external onlyRole(DAO_ROLE) {
286 | require(offeredItems[itemId].state == State.Disputed, "Item not disputed");
287 |
288 | /*
289 | * A future functionality for dealing with returns will be implemented here!
290 | */
291 |
292 | delete disputedItems[itemId];
293 | closeSale(itemId, true, false, true);
294 | }
295 |
296 | /**
297 | @notice Endpoint to auto-claim the Powerseller badge. The user must have at least 10 valid sales and his first valid sale must be at least 5 weeks old
298 | */
299 | function claimPowersellerBadge() external {
300 | require(numValidSales[msg.sender] >= 10, "Not enough valid sales");
301 | require(block.timestamp - firstValidSaleTimestamp[msg.sender] >= 5 weeks, "Not enough time has elapsed");
302 | powersellerContract.safeMint(msg.sender);
303 | }
304 |
305 | /**
306 | @notice Endpoint to remove a malicious sale and slash the stake. The owner of the contract can remove a malicious sale and blacklist the seller
307 | @param itemId The ID of the item which sale is considered malicious
308 | */
309 | function removeMaliciousSale(uint256 itemId) external onlyRole(ADMIN_ROLE) {
310 | address seller = offeredItems[itemId].seller;
311 | require(seller != address(0), "itemId does not exist");
312 |
313 | _removePowersellerBadge(seller);
314 | _removeCoolNFTs(seller);
315 | _blacklist(seller);
316 |
317 | if (offeredItems[itemId].state == State.Pending) {
318 | closeSale(itemId, true, false, false);
319 | } else if (offeredItems[itemId].state == State.Disputed) {
320 | closeSale(itemId, true, false, false);
321 | _closeDispute(itemId);
322 | } else {
323 | closeSale(itemId, false, false, false);
324 | }
325 | }
326 |
327 | /************************************** Views *******************************************************/
328 |
329 | /**
330 | @notice View function to return a disputed sale by its ID
331 | @param itemId The ID of the item being disputed
332 | @return The dispute details
333 | */
334 | function queryDispute (uint256 itemId) public view returns (Dispute memory) {
335 | return disputedItems[itemId];
336 | }
337 |
338 | /**
339 | @notice View function to return a sale by its ID
340 | @param itemId The ID of the sale
341 | @return The sale details
342 | */
343 | function querySale (uint256 itemId) public view returns (Sale memory) {
344 | return offeredItems[itemId];
345 | }
346 |
347 | /**
348 | @notice View function to return the number of valid sales of a seller
349 | @param seller The address of the seller
350 | @return The number of valid sales
351 | */
352 | function queryNumValidSales(address seller) public view returns (uint256) {
353 | return numValidSales[seller];
354 | }
355 |
356 | /************************************** Internal *****************************************************************/
357 |
358 | /**
359 | @notice Remove a sale from the list
360 | @param itemId The ID of the item which sale is being removed
361 | @param reimburseBuyer Whether the buyer should be reimbursed
362 | @param paySeller Whether the seller should be paid
363 | @param releaseSellerStake Whether the seller stake should be released
364 | */
365 | function closeSale(uint256 itemId, bool reimburseBuyer, bool paySeller, bool releaseSellerStake) public {
366 | address seller = offeredItems[itemId].seller;
367 | address buyer = offeredItems[itemId].buyer;
368 | uint256 price = offeredItems[itemId].price;
369 |
370 | // Buyer reimbursement
371 | if (reimburseBuyer) {
372 | (bool success, ) = payable(buyer).call{value: price}("");
373 | require(success, "Sale payment failed");
374 | emit Reimburse(buyer, price);
375 | }
376 | // Seller payment
377 | if (paySeller) {
378 | numValidSales[seller]++;
379 | if(numValidSales[seller] == 1) {
380 | firstValidSaleTimestamp[seller] = block.timestamp;
381 | }
382 | (bool success, ) = payable(seller).call{value: price}("");
383 | require(success, "Sale payment failed");
384 | }
385 | // Seller stake release
386 | if (releaseSellerStake) {
387 | vaultContract.doUnlock(seller, price);
388 | }
389 |
390 | delete offeredItems[itemId];
391 | }
392 |
393 | /**
394 | @notice Add a user to the seller blacklist and slash their funds in the Vault
395 | @param user The address of the seller
396 | */
397 | function _blacklist(address user) internal {
398 | grantRole(BLACKLISTED_ROLE, user);
399 |
400 | numValidSales[user] = 0;
401 | firstValidSaleTimestamp[user] = 0;
402 |
403 | //Slash the whole user stake
404 | vaultContract.doSlash(user);
405 |
406 | emit BlacklistSeller(user);
407 | }
408 |
409 | /**
410 | @notice Remove the powerseller badge from a malicious seller
411 | @param seller The address of the seller
412 | */
413 | function _removePowersellerBadge(address seller) internal {
414 | if(powersellerContract.checkPrivilege(seller)){
415 | powersellerContract.removePowersellerNFT(seller);
416 | }
417 | }
418 |
419 | /**
420 | @notice Remove CoolNFTs from a malicious seller
421 | @param seller The address of the seller
422 | */
423 | function _removeCoolNFTs(address seller) internal {
424 | coolNFTContract.burnAll(seller);
425 | }
426 |
427 | /**
428 | @notice Open a dispute in the DAO contract
429 | @param itemId The ID of the item being disputed
430 | @param sellerReasoning The reasoning of the seller against the claim
431 | */
432 | function _openDispute(uint256 itemId, string calldata sellerReasoning) internal {
433 | address buyer = offeredItems[itemId].buyer;
434 | Dispute storage dispute = disputedItems[itemId];
435 |
436 | dispute.sellerReasoning = sellerReasoning;
437 | dispute.disputeId = daoContract.newDispute(
438 | itemId,
439 | dispute.buyerReasoning,
440 | dispute.sellerReasoning
441 | );
442 | // No need to "save" the above as dispute has been declared as storage
443 |
444 | emit OpenDispute(buyer, itemId);
445 | }
446 |
447 | /**
448 | @notice Close a dispute in the DAO contract, either due to blacklisting or the buyer deciding not
449 | to pursue the dispute
450 | @param itemId The ID of the item being disputed
451 | */
452 | function _closeDispute(uint256 itemId) internal {
453 | uint256 dId = disputedItems[itemId].disputeId;
454 | // Forcefully cancel an ongoing dispute
455 | daoContract.cancelDispute(dId);
456 |
457 | delete disputedItems[itemId];
458 | }
459 | }
--------------------------------------------------------------------------------
/src/FP_Token.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | /*
5 | * Template ERC20 token for governance
6 | */
7 |
8 | import {AccessControl} from "@openzeppelin/contracts@v5.0.1/access/AccessControl.sol";
9 | import {ERC20} from "@openzeppelin/contracts@v5.0.1/token/ERC20/ERC20.sol";
10 | import {ERC20Burnable} from "@openzeppelin/contracts@v5.0.1/token/ERC20/extensions/ERC20Burnable.sol";
11 | import {Pausable} from "@openzeppelin/contracts@v5.0.1/utils/Pausable.sol";
12 |
13 | contract FP_Token is ERC20, ERC20Burnable, Pausable, AccessControl {
14 | bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
15 | bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
16 |
17 | constructor() ERC20("FaillaPop Token", "FPT") {
18 | _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
19 | _grantRole(PAUSER_ROLE, msg.sender);
20 | _mint(msg.sender, 1000000 * 10 ** decimals());
21 | _grantRole(MINTER_ROLE, msg.sender);
22 | }
23 |
24 | function pause() public onlyRole(PAUSER_ROLE) {
25 | _pause();
26 | }
27 |
28 | function unpause() public onlyRole(PAUSER_ROLE) {
29 | _unpause();
30 | }
31 |
32 | function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
33 | _mint(to, amount);
34 | }
35 |
36 | }
--------------------------------------------------------------------------------
/src/FP_Vault.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {IFP_Shop} from "./interfaces/IFP_Shop.sol";
5 | import {IFP_Vault} from "./interfaces/IFP_Vault.sol";
6 | import {AccessControl} from "@openzeppelin/contracts@v5.0.1/access/AccessControl.sol";
7 |
8 |
9 | /**
10 | @title FaillaPop vault
11 | @author Faillapop team :D
12 | @notice The contract allows anyone to stake and unstake Ether. When a seller publishes a new item
13 | in the shop, the funds are locked during the selling process. Then, If the user is considered malicious,
14 | the funds are slashed.
15 | @dev Security review is pending... should we deploy this?
16 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
17 | */
18 | contract FP_Vault is IFP_Vault, AccessControl {
19 |
20 | /************************************** Constants *******************************************************/
21 |
22 | ///@notice The DAO role ID for the AccessControl contract
23 | bytes32 public constant DAO_ROLE = keccak256("DAO_ROLE");
24 | ///@notice The Shop role ID for the AccessControl contract. At first it's the msg.sender and then the shop.
25 | bytes32 public constant CONTROL_ROLE = keccak256("CONTROL_ROLE");
26 |
27 | /************************************** Immutables *******************************************************/
28 |
29 | ///@notice address of the NFT contract
30 | address public immutable POWERSELLER_NFT_ADDRESS;
31 |
32 | /************************************** State vars *******************************************************/
33 |
34 | ///@notice Bool to check if the shop address has been set
35 | bool private _shopSet = false;
36 | ///@notice The balance of the users in the vault
37 | mapping (address => uint256) public balance;
38 | ///@notice The amount of funds locked for selling purposes
39 | mapping (address => uint256) public lockedFunds;
40 | ///@notice Maximum claimable amount
41 | uint256 public maxClaimableAmount;
42 | ///@notice The amount of rewards claimed by each user
43 | mapping (address => uint256) public rewardsClaimed;
44 | ///@notice The total amount of funds slashed
45 | uint256 public totalSlashed;
46 |
47 |
48 | /************************************** Modifiers *****************************************************/
49 |
50 | /**
51 | @notice Check if the user has enough staked funds to lock or unstake
52 | @param user The address of the user to check
53 | @param amount The amount of funds to check
54 | */
55 | modifier enoughStaked(address user, uint256 amount) {
56 | // Optimized version of the checks!
57 | uint256 userStake = balance[user];
58 | uint256 userLocked = lockedFunds[user];
59 | assembly {
60 | if iszero(userStake) {
61 | mstore(0x00, "No staked funds!")
62 | revert(0x00, 0x20)
63 | }
64 |
65 | let res := sub(sub(userStake, userLocked), amount)
66 |
67 | if lt(res, 1) {
68 | mstore(0x00, "Not enough funds!")
69 | revert(0x00, 0x20)
70 | }
71 | }
72 |
73 | _;
74 | }
75 |
76 | /**
77 | @notice Modifier to check if the Shop address has been set
78 | */
79 | modifier shopNotSet() {
80 | require(!_shopSet, "Shop address already set");
81 | _;
82 | }
83 |
84 |
85 | /************************************** External ****************************************************************/
86 |
87 | /**
88 | @notice Constructor, initializes the contract
89 | @param powersellerNFT The address of the powerseller NFT contract
90 | @param dao The address of the DAO contract
91 | */
92 | constructor(address powersellerNFT, address dao) {
93 | _grantRole(DAO_ROLE, dao);
94 | _grantRole(CONTROL_ROLE, msg.sender);
95 |
96 | POWERSELLER_NFT_ADDRESS = powersellerNFT;
97 | }
98 |
99 | /**
100 | @notice Sets the shop address as the new Control role
101 | @param shopAddress The address of the shop contract
102 | */
103 | function setShop(address shopAddress) external onlyRole(CONTROL_ROLE) shopNotSet {
104 | _shopSet = true;
105 | _grantRole(CONTROL_ROLE, shopAddress);
106 | }
107 |
108 |
109 | ///@notice Stake attached funds in the vault for later locking, the users must do it on their own
110 | function doStake() external payable {
111 | require(msg.value > 0, "Amount cannot be zero");
112 | balance[msg.sender] += msg.value;
113 |
114 | emit Stake(msg.sender, msg.value);
115 | }
116 |
117 |
118 | ///@notice Unstake unlocked funds from the vault, the user must do it on their own
119 | ///@param amount The amount of funds to unstake
120 | function doUnstake(uint256 amount) external enoughStaked(msg.sender, amount) {
121 | require(amount > 0, "Amount cannot be zero");
122 |
123 | balance[msg.sender] -= amount;
124 |
125 | (bool success, ) = payable(msg.sender).call{value: amount}("");
126 | require(success, "Unstake failed");
127 |
128 | emit Unstake(msg.sender, amount);
129 | }
130 |
131 |
132 | /**
133 | @notice Lock funds for selling purposes, the funds are locked until the sale is completed
134 | @param user The address of the user that is selling
135 | @param amount The amount of funds to lock
136 | */
137 | function doLock(address user, uint256 amount) external onlyRole(CONTROL_ROLE) enoughStaked(user, amount) {
138 | require(amount > 0, "Amount cannot be zero");
139 |
140 | lockedFunds[user] += amount;
141 |
142 | emit Locked(user, amount);
143 | }
144 |
145 |
146 | ///@notice Unlock funds after the sale is completed
147 | function doUnlock(address user, uint256 amount) external onlyRole(CONTROL_ROLE) {
148 | require(amount > 0, "Amount cannot be zero");
149 | require(amount <= lockedFunds[user], "Not enough locked funds");
150 |
151 | lockedFunds[user] -= amount;
152 |
153 | emit Unlocked(user, amount);
154 | }
155 |
156 |
157 | ///@notice Slash funds if the user is considered malicious by the DAO
158 | ///@param badUser The address of the malicious user to be slashed
159 | function doSlash(address badUser) external onlyRole(CONTROL_ROLE) {
160 | uint256 amount = balance[badUser];
161 |
162 | balance[badUser] = 0;
163 | lockedFunds[badUser] = 0;
164 |
165 | _distributeSlashing(amount);
166 |
167 | emit Slashed(badUser, amount);
168 | }
169 |
170 |
171 | /**
172 | @notice Claim rewards generated by slashing malicious users.
173 | First checks if the user is elegible through the checkPrivilege function that will revert if not.
174 | */
175 | function claimRewards() external {
176 | // Checks if the user is elegible
177 | POWERSELLER_NFT_ADDRESS.call(
178 | abi.encodeWithSignature(
179 | "checkPrivilege(address)",
180 | msg.sender
181 | )
182 | );
183 | // Checks if the user has already claimed the maximum amount
184 | require(rewardsClaimed[msg.sender] < maxClaimableAmount, "Max claimable amount reached");
185 |
186 | uint256 amount = maxClaimableAmount - rewardsClaimed[msg.sender];
187 |
188 | (bool success, ) = payable(msg.sender).call{value: amount}("");
189 | require(success, "Rewards payment failed");
190 |
191 | rewardsClaimed[msg.sender] = maxClaimableAmount;
192 |
193 | emit RewardsClaimed(msg.sender, amount);
194 | }
195 |
196 | /************************************** Views *******************************************************/
197 |
198 | ///@notice Get the balance of the vault
199 | function vaultBalance () public view returns (uint256) {
200 | return address(this).balance;
201 | }
202 |
203 |
204 | ///@notice Get the staked balance of a user
205 | ///@param user The address of the user to query
206 | function userBalance (address user) public view returns (uint256) {
207 | return balance[user];
208 | }
209 |
210 |
211 | ///@notice Get the locked balance of a user
212 | ///@param user The address of the user to query
213 | function userLockedBalance (address user) public view returns (uint256) {
214 | return lockedFunds[user];
215 | }
216 |
217 | /************************************** Internal *****************************************************************/
218 |
219 | ///@notice Sets a new maximum claimable amount per user based on the total slashed amount
220 | function _distributeSlashing(uint256 amount) internal {
221 | totalSlashed += amount;
222 |
223 | (bool success, bytes memory data) = POWERSELLER_NFT_ADDRESS.call(
224 | abi.encodeWithSignature(
225 | "totalPowersellers()"
226 | )
227 | );
228 | require(success, "totalPowersellers() call failed");
229 | uint256 totalPowersellers = abi.decode(data, (uint256));
230 | if(totalPowersellers > 0) {
231 | _updateMaxClaimableAmount(totalPowersellers);
232 | }
233 | }
234 |
235 | ///@notice Updates the maximum claimable amount based on the total slashed amount and the total powersellers
236 | ///@param totalPowersellers The total amount of powersellers
237 | function _updateMaxClaimableAmount(uint256 totalPowersellers) internal {
238 | uint256 newMax = totalSlashed / totalPowersellers;
239 | maxClaimableAmount = newMax;
240 | }
241 |
242 | }
--------------------------------------------------------------------------------
/src/interfaces/IFP_CoolNFT.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | /**
5 | @title Interface of the FaillaPop Cool NFT
6 | @author Faillapop team :D
7 | @notice The contract allows the DAO to mint a Cool NFT for users.
8 | @dev Security review is pending... should we deploy this?
9 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
10 | */
11 | interface IFP_CoolNFT {
12 |
13 | /************************************** Events *****************************************************/
14 |
15 | ///@notice Emitted when a user's coolNFTs are slashed
16 | event CoolNFTs_Slashed(address indexed owner);
17 | ///@notice Emitted when a user receives a PowerSeller badge
18 | event CoolNFT_Minted(address indexed owner, uint256 tokenId);
19 |
20 | /************************************** Functions *****************************************************/
21 |
22 | /**
23 | @notice Sets the DAO address as the new Control Role
24 | @param daoAddr The address of the DAO contract
25 | */
26 | function setDAO(address daoAddr) external;
27 |
28 | /**
29 | @notice Mints a Cool NFT for the user
30 | @param to The address of the user that will receive the Cool NFT
31 | */
32 | function mintCoolNFT(address to) external;
33 |
34 | /**
35 |
36 | @notice DAO can remove a Cool NFT from a user
37 | @param owner The address of the user that will lose the Cool NFT
38 | */
39 | function burnAll(address owner) external;
40 | }
--------------------------------------------------------------------------------
/src/interfaces/IFP_DAO.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | /**
5 | @title Iterface of the FaillaPop voting DAO for disputes
6 | @author Faillapop team :D
7 | @notice The contract allow to vote with FPT tokens on open disputes. If the dispute is resolved in favor of the buyer,
8 | the seller have to refund the buyer. If the dispute is resolved in favor of the seller, the sale is closed.
9 | @custom:ctf This contract is of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
10 | */
11 | interface IFP_DAO {
12 |
13 | /************************************** Enums and structs *****************************************************/
14 |
15 | /**
16 | @notice The DisputeState enum is used to record the state of a dispute
17 | @dev NOT_ACTIVE is the default value, COMMITTING_PHASE is the state in which users are committing their secret vote, REVEALING_PHASE is the state in which users are revealing their vote
18 | */
19 | enum DisputeState {
20 | NOT_ACTIVE,
21 | COMMITTING_PHASE,
22 | REVEALING_PHASE
23 | }
24 |
25 | /**
26 | @notice The ProposalState enum is used to record the state of a proposal
27 | @dev NOT_ACTIVE is the default value, ACTIVE is the state of an existing proposal, PASSED is the state of a proposal that has been voted and passed but not yet executed
28 | */
29 | enum ProposalState {
30 | NOT_ACTIVE,
31 | ACTIVE,
32 | PASSED
33 | }
34 |
35 | /**
36 | @notice The Vote enum is used to record the vote of a user
37 | @dev DIDNT_VOTE is the default value, COMMITTED is the first phase, FOR and AGAINST are the possible votes
38 | */
39 | enum Vote {
40 | DIDNT_VOTE,
41 | COMMITTED,
42 | FOR,
43 | AGAINST
44 | }
45 |
46 | /**
47 | @notice A Dispute includes the itemId, the reasoning of the buyer and the seller on the claim,
48 | and the number of votes for and against the dispute.
49 | @dev A Dispute is always written from the POV of the buyer
50 | - FOR is in favor of the buyer claim
51 | - AGAINST is in favor of the seller claim
52 | */
53 | struct Dispute {
54 | uint256 itemId;
55 | string buyerReasoning;
56 | string sellerReasoning;
57 | uint256 votesFor;
58 | uint256 votesAgainst;
59 | uint256 totalVoters;
60 | uint256 committingStartingTime;
61 | uint256 revealingStartingTime;
62 | DisputeState state;
63 | }
64 |
65 | /**
66 | @notice An UpgradeProposal includes the address of the creator, the id, the creationTimestamp, the new contract address,
67 | the number of votes for and against the proposal, the total number of voters and the status of the proposal.
68 | @dev newShop is the address of the new contract which can be checked on etherscan
69 | */
70 | struct UpgradeProposal {
71 | address creator;
72 | uint256 id;
73 | uint256 creationTimestamp;
74 | uint256 approvalTimestamp;
75 | address newShop;
76 | uint256 votesFor;
77 | uint256 votesAgainst;
78 | uint256 totalVoters;
79 | ProposalState state;
80 | }
81 |
82 | /************************************** Events *****************************************************/
83 |
84 | ///@notice Emitted when the contract configuration is changed, contains the address of the Shop
85 | event NewConfig(address shop, address nft);
86 | ///@notice Emitted when a user commits the hash of his vote, contains the disputeId and the user address
87 | event DisputeVoteCommitted(uint disputeId, address user);
88 | ///@notice Emitted when a user votes, contains the disputeId and the user address
89 | event DisputeVoteCasted(uint256 disputeId, address user);
90 | ///@notice Emitted when a new dispute is created, contains the disputeId and the itemId
91 | event NewDispute(uint256 disputeId, uint256 itemId);
92 | ///@notice Emitted when a dispute is closed, contains the disputeId and the itemId
93 | event EndDispute(uint256 disputeId, uint256 itemId);
94 | ///@notice Emitted when a user is awarder a cool NFT, contains the user address
95 | event AwardNFT(address user);
96 |
97 | ///@notice Emitted when a new upgrade proposal is created, contains the proposalId, the creationTimestamp and the new contract address
98 | event NewUpgradeProposal(uint256 id, uint256 creationTimestamp, address newShop);
99 | ///@notice Emitted when a user votes on an upgrade proposal, contains the proposalId and the user address
100 | event ProposalVoteCasted(uint256 proposalId, address user);
101 | ///@notice Emitted when an upgrade proposal is passed, contains the proposalId, the new contract address and the timestamp
102 | event ProposalPassed(uint256 proposalId, address newShop, uint256 approvalTimestamp);
103 | ///@notice Emitted when an upgrade proposal is not passed because not enough users voted in favor, contains the proposalId and the new contract address
104 | event ProposalNotPassed(uint256 proposalId, address newShop);
105 | ///@notice Emitted when an upgrade proposal is executed, contains the proposalId and the new contract address
106 | event ProposalExecuted(uint256 proposalId, address newShop);
107 | ///@notice Emitted when an upgrade proposal is canceled, contains the proposalId
108 | event ProposalCanceled(uint256 proposalId);
109 |
110 |
111 | /************************************** Functions *****************************************************/
112 |
113 | /**
114 | @notice Sets the shop address as the new Control role
115 | @param shop The address of the shop
116 | */
117 | function setShop(address shop) external;
118 |
119 | /**
120 | @notice Commit the hash of the vote
121 | @param disputeId The ID of the target dispute
122 | @param commit Vote + secret hash
123 | */
124 | function commitVoteOnDispute(uint256 disputeId, bytes32 commit) external;
125 |
126 | /**
127 | @notice Open a dispute
128 | @param itemId The ID of the item involved in the dispute
129 | @param buyerReasoning The reasoning of the buyer in favor of the claim
130 | @param sellerReasoning The reasoning of the seller against the claim
131 | */
132 | function newDispute(
133 | uint256 itemId,
134 | string calldata buyerReasoning,
135 | string calldata sellerReasoning
136 | ) external returns (uint256);
137 |
138 | /**
139 | @notice Reveal a vote on a dispute if enough users have voted
140 | @param disputeId The ID of the target dispute
141 | @param vote The vote of the user
142 | @param secret The secret used to commit the vote
143 | */
144 | function revealDisputeVote(uint disputeId, bool vote, string calldata secret) external;
145 |
146 | /**
147 | @notice Resolve a dispute if revealing time has elapsed and remove it from the storage
148 | @param disputeId The ID of the target dispute
149 | */
150 | function endDispute(uint256 disputeId) external;
151 |
152 |
153 | /**
154 | @notice Cancel an ongoing dispute. Either by the buyer or blacklisting (shop contract)
155 | @param disputeId The ID of the target dispute
156 | */
157 | function cancelDispute(uint256 disputeId) external;
158 |
159 |
160 | /**
161 | @notice Award NFT to a user if they voten for the winning side
162 | @param disputeID The ID of the target dispute
163 | */
164 | function checkLottery(uint256 disputeID) external;
165 |
166 | /**
167 | @notice Open an upgrade proposal
168 | @param addrNewShop The address of the new Shop contract proposed
169 | */
170 | function newUpgradeProposal(address addrNewShop) external returns (uint);
171 |
172 | /**
173 | @notice Cast a vote on an upgrade proposal
174 | @param proposalId The ID of the upgrade proposal
175 | @param vote The vote, true for FOR, false for AGAINST
176 | */
177 | function castVoteOnProposal(uint proposalId, bool vote) external;
178 |
179 | /**
180 | @notice Cancel an ongoing upgrade proposal by the proposal creator
181 | @param proposalId The ID of the upgrade proposal
182 | */
183 | function cancelProposalByCreator(uint proposalId) external;
184 |
185 | /**
186 | @notice Cancel an ongoing upgrade proposal by the admin of the DAO (who knows the password)
187 | @param proposalId The ID of the upgrade proposal
188 | @param magicWord The password to access key features
189 | */
190 | function cancelProposal(uint proposalId, string calldata magicWord) external;
191 |
192 | /**
193 | @notice Resolve a proposal if enough users have voted and enough time has passed
194 | @param proposalId The ID of the upgrade proposal
195 | */
196 | function resolveUpgradeProposal(uint256 proposalId) external;
197 |
198 | /**
199 | @notice Execute a passed proposal
200 | @param proposalId The ID of the upgrade proposal
201 | */
202 | function executePassedProposal(uint256 proposalId) external;
203 |
204 | }
--------------------------------------------------------------------------------
/src/interfaces/IFP_PowersellerNFT.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | /**
5 | @title Interface of the FaillaPop PowerSeller NFT
6 | @author Faillapop team :D
7 | @notice The contract allows the shop to mint a PowerSeller NFT for users and remove it if they are considered malicious. PowerSeller badge is required to claimRewards in the vault.
8 | @dev Security review is pending... should we deploy this?
9 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
10 | */
11 | interface IFP_PowersellerNFT {
12 |
13 | /************************************** Events *****************************************************/
14 |
15 | ///@notice Emitted when a user loses a PowerSeller badge
16 | event PowersellerNFT_Removed(address indexed owner, uint256 tokenId);
17 | ///@notice Emitted when a user receives a PowerSeller badge
18 | event PowersellerNFT_Minted(address indexed owner, uint256 tokenId);
19 |
20 |
21 | /************************************** Functions *****************************************************/
22 |
23 | /**
24 | @notice Sets the shop address as the new Control role
25 | @param shopAddress The address of the shop contract
26 | */
27 | function setShop(address shopAddress) external;
28 |
29 | /**
30 | @notice Mints a PowerSeller badge for the user
31 | @param to The address of the user that will receive the badge
32 | */
33 | function safeMint(address to) external;
34 |
35 | /**
36 | @notice Removes the PowerSeller badge from bad a user
37 | @param maliciousPowerseller The address of the user that will lose the badge
38 | */
39 | function removePowersellerNFT(address maliciousPowerseller) external;
40 |
41 | ///@notice Returns the total number of users that received a PowerSeller badge
42 | function totalPowersellers() external view returns (uint256);
43 |
44 | /**
45 | @notice Checks if the address holds a Trusted badge
46 | @param user The address of the user to check
47 | */
48 | function checkPrivilege(address user) external view returns (bool);
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/src/interfaces/IFP_Proxy.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | interface IFP_Proxy {
5 | /**
6 | * @dev Performs implementation upgrade with additional setup call if data is nonempty.
7 | * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
8 | * to avoid stuck value in the contract.
9 | *
10 | * Emits an {IERC1967-Upgraded} event.
11 | */
12 | function upgradeToAndCall(address _newImplementation, bytes memory _data) external;
13 |
14 | /**
15 | * @dev Returns the current implementation address.
16 | */
17 | function getImplementation() external view returns (address);
18 | }
--------------------------------------------------------------------------------
/src/interfaces/IFP_Shop.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 |
5 | /**
6 | @title Interface of the FaillaPop Shop!
7 | @author Faillapop team :D
8 | @notice The contract allows anyone to stake and unstake Ether. When a seller publish a new item
9 | in the shop, the funds are locked during the sale. If the user is considered malicious
10 | by the DAO, the funds are slashed.
11 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
12 | */
13 | interface IFP_Shop {
14 | /************************************** Enum and structs *******************************************************/
15 |
16 | /**
17 | @dev A Sale can be in one of three states:
18 | `Selling` deal still active
19 | `Disputed` the buyer submitted a claim
20 | `Pending` waiting buyer confirmation
21 | `Sold` deal is over, no claim was submitted
22 | `Vacation` the seller is on vacation, sale halted
23 | */
24 | enum State {
25 | Undefined,
26 | Selling,
27 | Pending,
28 | Disputed,
29 | Sold,
30 | Vacation
31 | }
32 |
33 | /**
34 | @dev A Sale struct represent each of the active sales in the shop.
35 | @param seller The address of the seller
36 | @param buyer The address of the buyer, if any
37 | @param title The title of the item being sold
38 | @param description A description of the item being sold
39 | @param price The price in Ether of the item being sold
40 | @param state The current state of the sale
41 | */
42 | struct Sale {
43 | address seller;
44 | address buyer;
45 | string title;
46 | string description;
47 | uint256 price;
48 | State state;
49 | uint256 buyTimestamp;
50 | }
51 |
52 | /**
53 | @dev A Dispute struct represent each of the active disputes in the shop.
54 | @param itemId The ID of the item being disputed
55 | @param disputeTimestamp The timestamp of the dispute
56 | @param buyerReasoning The reasoning of the buyer for the claim
57 | @param sellerReasoning The reasoning of the seller against the claim
58 | */
59 | struct Dispute {
60 | uint256 disputeId;
61 | uint256 disputeTimestamp;
62 | string buyerReasoning;
63 | string sellerReasoning;
64 | }
65 |
66 |
67 | /************************************** Events *****************************************************/
68 |
69 | ///@notice Emitted when a user buys an item, contains the user address and the item ID
70 | event Buy(address user, uint256 item);
71 | ///@notice Emitted when a user creates a new sale, contains the item ID and the title of the item
72 | event NewItem(uint256 id, string title);
73 | ///@notice Emitted when a user modifies a sale, contains the item ID and the title of the item
74 | event ModifyItem(uint256 id, string title);
75 | ///@notice Emitted when a user disputes a sale, contains the user address and the item ID
76 | event OpenDispute(address user, uint256 item);
77 | ///@notice Emitted when a user received a refund, contains the user address and the amount
78 | event Reimburse(address user, uint256 amount);
79 | ///@notice Emitted when a user receives an reward NFT, contains the user address
80 | event AwardNFT(address user);
81 | ///@notice Emitted when a user is blacklisted, contains the user address
82 | event BlacklistSeller(address seller);
83 |
84 |
85 | /************************************** Functions *****************************************************/
86 |
87 | /**
88 | @notice Initializer of the contract
89 | @param daoAddress The address of the DAO contract
90 | @param vaultAddress The address of the Vault contract
91 | @param powersellerNFTAddress The address of the PowersellerNFT contract
92 | @param coolNFTAddress The address of the CoolNFT contract
93 | */
94 | function initialize(address daoAddress, address vaultAddress, address powersellerNFTAddress, address coolNFTAddress) external;
95 |
96 | /**
97 | @notice Endpoint to buy an item
98 | @param itemId The ID of the item being bought
99 | @dev The user must send the exact amount of Ether to buy the item
100 | */
101 | function doBuy(uint256 itemId) external payable;
102 |
103 | /**
104 | @notice Endpoint to dispute a sale. The buyer will supply the supporting info to the DAO
105 | @param itemId The ID of the item being disputed
106 | @param buyerReasoning The reasoning of the buyer for the claim
107 | */
108 | function disputeSale(uint256 itemId, string calldata buyerReasoning) external;
109 |
110 | /**
111 | @notice Endpoint to confirm the receipt of an item and trigger the payment to the seller.
112 | @param itemId The ID of the item being confirmed
113 | */
114 | function itemReceived(uint256 itemId) external;
115 |
116 |
117 | /**
118 | @notice Endpoint to close a dispute. Both the DAO and the buyer could call this function to cancel a dispute
119 | @param itemId The ID of the item being disputed
120 | */
121 | function endDispute(uint256 itemId) external;
122 |
123 | /**
124 | @notice Endpoint to create a new sale. The seller must have enough funds staked in the Vault so
125 | price amount can be locked to desincentivice malicious behavior
126 | @param title The title of the item being sold
127 | @param description A description of the item being sold
128 | @param price The price in Ether of the item being sold
129 | */
130 | function newSale(string calldata title, string calldata description, uint256 price) external;
131 |
132 | /**
133 | @notice Endpoint to modify an existing sale. Locked funds will be partially realeased if price decreases.
134 | @param itemId ID of the item being modified
135 | @param newTitle New title of the item being sold
136 | @param newDesc New description of the item being sold
137 | @param newPrice New price in Ether of the item being sold
138 | */
139 | function modifySale(uint256 itemId, string calldata newTitle, string calldata newDesc, uint256 newPrice) external;
140 |
141 | /**
142 | @notice Endpoint to cancel an active sale
143 | @param itemId The ID of the item which sale is being cancelled
144 | */
145 | function cancelActiveSale (uint256 itemId) external;
146 |
147 | /**
148 | @notice Endpoint to set the vacation mode of a seller. If the seller is in vacation mode nobody can buy his goods
149 | @param vacationMode The new vacation mode of the seller
150 | */
151 | function setVacationMode(bool vacationMode) external;
152 |
153 |
154 | /**
155 | @notice Endpoint to reply to a dispute. The seller will supply the supporting info to the DAO. If the seller does not reply,
156 | the admin could mark them as malicious and slash their funds
157 | @param itemId The ID of the item being disputed
158 | @param sellerReasoning The reasoning of the seller for the claim
159 | */
160 | function disputedSaleReply(uint256 itemId, string calldata sellerReasoning) external;
161 |
162 |
163 | /**
164 | @notice Endpoint to return an item, only the DAO can trigger it
165 | @param itemId The ID of the item being returned
166 | */
167 | function returnItem(uint256 itemId) external;
168 |
169 | /**
170 | @notice Endpoint to auto-claim the Powerseller badge. The user must have at least 10 valid sales
171 | */
172 | function claimPowersellerBadge() external;
173 |
174 | /**
175 | @notice Endpoint to remove a malicious sale and slash the stake. The owner of the contract can remove a malicious sale and blacklist the seller
176 | @param itemId The ID of the item which sale is considered malicious
177 | */
178 | function removeMaliciousSale(uint256 itemId) external;
179 |
180 | }
--------------------------------------------------------------------------------
/src/interfaces/IFP_Vault.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 |
5 | /**
6 | @title Interface of FaillaPop vault
7 | @author Faillapop team :D
8 | @notice The contract allows anyone to stake and unstake Ether. When a seller publish a new item
9 | in the shop, the funds are locked during the sale. If the user is considered malicious
10 | by the DAO, the funds are slashed.
11 | @custom:ctf This contract is part of JC's mock-audit exercise at https://github.com/jcr-security/faillapop
12 | */
13 | interface IFP_Vault {
14 |
15 | /************************************** Events *****************************************************/
16 |
17 | ///@notice Emitted when a user stakes funds, contains the user address and the amount staked
18 | event Stake(address user, uint256 amount);
19 | ///@notice Emitted when a user unstakes funds, contains the user address and the amount unstaked
20 | event Unstake(address user, uint256 amount);
21 | ///@notice Emitted when a user funds get locked, contains the user address and the amount locked
22 | event Locked(address user, uint256 amount);
23 | ///@notice Emitted when a user funds get unlocked, contains the user address and the amount unlocked
24 | event Unlocked(address user, uint256 amount);
25 | ///@notice Emitted when a user funds get slashed, contains the user address and the amount slashed
26 | event Slashed(address user, uint256 amount);
27 | ///@notice Emitted when a user claims rewards, contains the user address and the amount claimed
28 | event RewardsClaimed(address user, uint256 amount);
29 |
30 |
31 | /************************************** Functions *****************************************************/
32 |
33 | /**
34 | @notice Sets the shop address as the new Control role
35 | @param shopAddress The address of the shop contract
36 | */
37 | function setShop(address shopAddress) external;
38 |
39 | ///@notice Stake attached funds in the vault for later locking, the users must do it on their own
40 | function doStake() external payable;
41 |
42 |
43 | ///@notice Unstake unlocked funds from the vault, the user must do it on their own
44 | ///@param amount The amount of funds to unstake
45 | function doUnstake(uint256 amount) external;
46 |
47 |
48 | /**
49 | @notice Lock funds for selling purposes, the funds are locked until the sale is completed
50 | @param user The address of the user that is selling
51 | @param amount The amount of funds to lock
52 | */
53 | function doLock(address user, uint256 amount) external;
54 |
55 |
56 | ///@notice Unlock funds after the sale is completed
57 | function doUnlock(address user, uint256 amount) external;
58 |
59 |
60 | ///@notice Slash funds if the user is considered malicious by the DAO
61 | ///@param badUser The address of the malicious user to be slashed
62 | function doSlash(address badUser) external;
63 |
64 |
65 | /**
66 | @notice Claim rewards generated by slashing malicious users.
67 | First checks if the user is elegible through the checkPrivilege function that will revert if not.
68 | */
69 | function claimRewards() external;
70 | }
--------------------------------------------------------------------------------
/test/unit/FP_CoolNFT.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {Test, console} from "forge-std/Test.sol";
5 | import {FP_CoolNFT} from "../../src/FP_CoolNFT.sol";
6 | import {FP_DAO} from "../../src/FP_DAO.sol";
7 | import {FP_PowersellerNFT} from "../../src/FP_PowersellerNFT.sol";
8 | import {FP_Shop} from "../../src/FP_Shop.sol";
9 | import {FP_Token} from "../../src/FP_Token.sol";
10 | import {FP_Vault} from "../../src/FP_Vault.sol";
11 | import {FP_Proxy} from "../../src/FP_Proxy.sol";
12 | import {DeployFaillapop} from "../../script/DeployFaillapop.s.sol";
13 |
14 | contract FP_CoolNFT_Test is Test {
15 | address public constant USER1 = address(bytes20("USER1"));
16 | address public constant USER2 = address(bytes20("USER2"));
17 |
18 | FP_CoolNFT public coolNFT;
19 | FP_DAO public dao;
20 | FP_Token public token;
21 | FP_Vault public vault;
22 | FP_Shop public shop;
23 | FP_PowersellerNFT public powersellerNFT;
24 | FP_Proxy public proxy;
25 |
26 | /************************************** Modifiers **************************************/
27 |
28 | modifier mint(uint256 times) {
29 | for(uint256 i = 0; i < times; i++) {
30 | vm.prank(address(dao));
31 | coolNFT.mintCoolNFT(USER1);
32 | }
33 | _;
34 | }
35 |
36 | /************************************** Set Up **************************************/
37 |
38 | function setUp() external {
39 | vm.deal(USER1, 10);
40 |
41 | DeployFaillapop deploy = new DeployFaillapop();
42 | (shop, token, coolNFT, powersellerNFT, dao, vault, proxy) = deploy.run();
43 | }
44 |
45 | /************************************** Tests **************************************/
46 |
47 | function test_SetUp() public view {
48 | assertEq(coolNFT.name(), "Faillapop Cool NFT", "Incorrect token name");
49 | assertEq(coolNFT.symbol(), "FCNFT", "Incorrect token symbol");
50 | }
51 |
52 | function test_setDao() public view {
53 | assertTrue(coolNFT.hasRole(bytes32(coolNFT.CONTROL_ROLE()), address(dao)));
54 | }
55 |
56 | function test_setDao_x2() public {
57 | vm.prank(address(dao));
58 | vm.expectRevert(bytes("DAO address already set"));
59 | coolNFT.setDAO(address(dao));
60 | }
61 |
62 | function test_setShop() public view {
63 | assertTrue(coolNFT.hasRole(bytes32(coolNFT.SHOP_ROLE()), address(proxy)));
64 | }
65 |
66 | function test_setShop_x2() public {
67 | vm.prank(address(dao));
68 | vm.expectRevert(bytes("Shop address already set"));
69 | coolNFT.setShop(address(proxy));
70 | }
71 |
72 | function test_mintCoolNFT() public mint(1) {
73 | uint256[] memory userTokenIds = coolNFT.getTokenIds(USER1);
74 | assertEq(coolNFT.balanceOf(USER1), 1, "Incorrect balance");
75 | assertEq(userTokenIds[userTokenIds.length-1], 1, "Incorrect tokenId");
76 | assertEq(coolNFT.ownerOf(1), USER1, "Incorrect owner");
77 | }
78 |
79 | function test_mintCoolNFT_multipleTimes() public mint(15) {
80 | uint256[] memory userTokenIds = coolNFT.getTokenIds(USER1);
81 | assertEq(coolNFT.balanceOf(USER1), 15, "Incorrect balance");
82 | for(uint256 i = 0; i < userTokenIds.length; i++) {
83 | assertEq(userTokenIds[i], i+1, "Incorrect tokenId");
84 | assertEq(coolNFT.ownerOf(i+1), USER1, "Incorrect owner");
85 | }
86 | }
87 |
88 | function test_mintCoolNFT_RevertIf_CallerIsNotDao() public {
89 | vm.prank(USER1);
90 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER1), keccak256("CONTROL_ROLE")));
91 | coolNFT.mintCoolNFT(USER1);
92 | }
93 |
94 | function test_burnAll() public mint(1) {
95 | vm.prank(address(proxy));
96 | coolNFT.burnAll(USER1);
97 | uint256[] memory userTokenIds = coolNFT.getTokenIds(USER1);
98 |
99 | assertEq(coolNFT.balanceOf(USER1), 0, "Incorrect balance");
100 | assertEq(userTokenIds.length, 0, "Incorrect tokenId");
101 | }
102 |
103 | function test_burnAll_multipleCoolNFTs() public mint(15) {
104 | vm.prank(address(proxy));
105 | coolNFT.burnAll(USER1);
106 | uint256[] memory userTokenIds = coolNFT.getTokenIds(USER1);
107 |
108 | assertEq(coolNFT.balanceOf(USER1), 0, "Incorrect balance");
109 | assertEq(userTokenIds.length, 0, "Incorrect tokenId");
110 | }
111 |
112 | function test_burnAll_RevertIf_CallerIsNotShop() public {
113 | vm.prank(USER1);
114 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER1), keccak256("SHOP_ROLE")));
115 | coolNFT.burnAll(USER1);
116 | }
117 |
118 | function test_approve() public mint(1) {
119 | vm.prank(USER1);
120 | vm.expectRevert(bytes("CoolNFT cannot be approved"));
121 | coolNFT.approve(USER2, 1);
122 | }
123 |
124 | function test_setApprovalForAll() public mint(1) {
125 | vm.prank(USER1);
126 | vm.expectRevert(bytes("CoolNFT cannot be approved"));
127 | coolNFT.setApprovalForAll(USER2, true);
128 | }
129 |
130 | function test_transferFrom() public mint(1) {
131 | vm.prank(USER1);
132 | vm.expectRevert(bytes("CoolNFT cannot be transferred"));
133 | coolNFT.transferFrom(USER1, USER2, 1);
134 | }
135 |
136 | function test_safeTransferFrom() public mint(1) {
137 | vm.prank(USER1);
138 | vm.expectRevert(bytes("CoolNFT cannot be transferred"));
139 | coolNFT.safeTransferFrom(USER1, USER2, 1);
140 | }
141 |
142 | function test_safeTransferFrom_withData() public mint(1) {
143 | vm.prank(USER1);
144 | vm.expectRevert(bytes("CoolNFT cannot be transferred"));
145 | coolNFT.safeTransferFrom(USER1, USER2, 1, "data");
146 | }
147 | }
--------------------------------------------------------------------------------
/test/unit/FP_DAO.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {Test, console} from "forge-std/Test.sol";
5 | import {FP_CoolNFT} from "../../src/FP_CoolNFT.sol";
6 | import {FP_DAO} from "../../src/FP_DAO.sol";
7 | import {IFP_DAO} from "../../src/interfaces/IFP_DAO.sol";
8 | import {FP_PowersellerNFT} from "../../src/FP_PowersellerNFT.sol";
9 | import {FP_Shop} from "../../src/FP_Shop.sol";
10 | import {FP_Token} from "../../src/FP_Token.sol";
11 | import {FP_Vault} from "../../src/FP_Vault.sol";
12 | import {FP_Proxy} from "../../src/FP_Proxy.sol";
13 | import {DeployFaillapop} from "../../script/DeployFaillapop.s.sol";
14 |
15 | contract FP_DAO_Test is Test {
16 | ///@notice The time window in which a proposal can not be voted
17 | uint256 public constant PROPOSAL_REVIEW_TIME = 1 days;
18 | ///@notice The minimum voting period for a proposal
19 | uint256 public constant PROPOSAL_VOTING_TIME = 3 days;
20 | ///@notice The minimum waiting time between approval and execution of a proposal
21 | uint256 public constant PROPOSAL_EXECUTION_DELAY = 1 days;
22 | ///@notice the minimum committing period for votes on a dispute
23 | uint256 constant COMMITTING_TIME = 3 days;
24 | ///@notice The minimum revealing period for votes on a dispute
25 | uint256 constant MIN_REVEALING_TIME = 1 days;
26 | ///@notice The maximum revealing period for votes on a dispute
27 | uint256 constant MAX_REVEALING_TIME = 3 days;
28 | address public constant USER1 = address(bytes20("USER1"));
29 | address public constant USER2 = address(bytes20("USER2"));
30 | address public constant SELLER1 = address(bytes20("SELLER1"));
31 | address public constant BUYER1 = address(bytes20("BUYER1"));
32 |
33 | FP_Shop public shop;
34 | FP_Vault public vault;
35 | FP_DAO public dao;
36 | FP_Token public token;
37 | FP_CoolNFT public coolNFT;
38 | FP_PowersellerNFT public powersellerNFT;
39 | FP_Proxy public proxy;
40 |
41 | /************************************* Modifiers *************************************/
42 |
43 | modifier createLegitSale() {
44 | // Simulate an user's stake in the Vault
45 | vm.prank(SELLER1);
46 | vault.doStake{value: 2 ether}();
47 |
48 | // New sale
49 | string memory title = "Test Item";
50 | string memory description = "This is a test item";
51 | uint256 price = 1 ether;
52 |
53 | vm.prank(SELLER1);
54 | (bool success, ) = address(proxy).call(
55 | abi.encodeWithSignature(
56 | "newSale(string,string,uint256)",
57 | title,
58 | description,
59 | price
60 | )
61 | );
62 | require(success, "Sale not created");
63 | _;
64 | }
65 |
66 | modifier buyLastItem() {
67 | (bool success, bytes memory data) = address(proxy).call(
68 | abi.encodeWithSignature(
69 | "offerIndex()"
70 | )
71 | );
72 | require(success, "Offer index not retrieved");
73 | uint256 saleId = abi.decode(data, (uint256)) - 1;
74 |
75 | vm.prank(BUYER1);
76 | (bool success2, ) = address(proxy).call{value: 1 ether}(
77 | abi.encodeWithSignature(
78 | "doBuy(uint256)",
79 | saleId
80 | )
81 | );
82 | require(success2, "Sale not bought");
83 | _;
84 | }
85 |
86 | modifier disputeSale() {
87 | vm.prank(BUYER1);
88 | (bool success,) = address(proxy).call(
89 | abi.encodeWithSignature(
90 | "disputeSale(uint256,string)",
91 | 0,
92 | "Buyer's reasoning"
93 | )
94 | );
95 | require(success, "Sale not disputed");
96 | _;
97 | }
98 |
99 | modifier replyDisputedSale() {
100 | vm.prank(SELLER1);
101 | (bool success,) = address(proxy).call(
102 | abi.encodeWithSignature(
103 | "disputedSaleReply(uint256,string)",
104 | 0,
105 | "Seller's reasoning"
106 | )
107 | );
108 | require(success, "Disputed sale not replied");
109 | _;
110 | }
111 |
112 | modifier mintAndCommitVote(bool vote, string memory secret) {
113 | // Mint FP_tokens
114 | uint amount = 1000;
115 | vm.prank(vm.envAddress("DEPLOYER"));
116 | token.mint(address(USER1), amount);
117 | assertEq(token.balanceOf(address(USER1)), amount, "Wrong balance");
118 |
119 | // Commit vote
120 | bytes32 commit = keccak256(abi.encodePacked(vote, secret));
121 | vm.prank(USER1);
122 | dao.commitVoteOnDispute(0, commit);
123 | _;
124 | }
125 |
126 | modifier revealVote(bool vote, string memory secret) {
127 | // Manipulate time to pass the committing time
128 | vm.warp(block.timestamp + COMMITTING_TIME);
129 |
130 | // Reveal vote
131 | vm.prank(USER1);
132 | dao.revealDisputeVote(0, vote, secret);
133 | _;
134 | }
135 |
136 | modifier createUpgradeProposal() {
137 | // Deploy new shop
138 | FP_Shop newShop = new FP_Shop();
139 |
140 | vm.prank(USER1);
141 | dao.newUpgradeProposal(address(newShop));
142 | _;
143 | }
144 |
145 | modifier spendReviewTime() {
146 | // Manipulate time to pass the review time
147 | FP_DAO.UpgradeProposal memory proposal = dao.queryUpgradeProposal(0);
148 | vm.warp(proposal.creationTimestamp + PROPOSAL_REVIEW_TIME + 1);
149 | _;
150 | }
151 |
152 | modifier spendVotingTime() {
153 | // Manipulate time to pass the review time
154 | FP_DAO.UpgradeProposal memory proposal = dao.queryUpgradeProposal(0);
155 | vm.warp(proposal.creationTimestamp + PROPOSAL_VOTING_TIME + 1);
156 | _;
157 | }
158 |
159 | modifier mintAndVoteOnProposal(address user, uint256 amount, bool vote) {
160 | // Mint FP_tokens
161 | vm.prank(vm.envAddress("DEPLOYER"));
162 | token.mint(user, amount);
163 | assertEq(token.balanceOf(user), amount, "Wrong balance");
164 |
165 | // Cast vote
166 | vm.prank(user);
167 | dao.castVoteOnProposal(0, vote);
168 | _;
169 | }
170 |
171 | modifier cast501Votes(bool vote) {
172 | // Mint FP_tokens and cast enough votes to pass the proposal (proposalQuorum = 500)
173 | for (uint160 i = 1; i <= 501; i++){
174 | // Mint FP_tokens
175 | vm.prank(vm.envAddress("DEPLOYER"));
176 | token.mint(address(i), 1000);
177 | assertEq(token.balanceOf(address(i)), 1000, "Wrong balance");
178 |
179 | // Cast vote
180 | vm.prank(address(i));
181 | dao.castVoteOnProposal(0, vote);
182 | }
183 | _;
184 | }
185 |
186 | /************************************** Set Up **************************************/
187 |
188 | function setUp() external {
189 | vm.deal(SELLER1, 10 ether);
190 | vm.deal(BUYER1, 10 ether);
191 | vm.deal(USER1, 10 ether);
192 | vm.deal(USER2, 10 ether);
193 |
194 | DeployFaillapop deploy = new DeployFaillapop();
195 | (shop, token, coolNFT, powersellerNFT, dao, vault, proxy) = deploy.run();
196 | }
197 |
198 | /************************************** Tests **************************************/
199 |
200 | function test_setShop() public view {
201 | assertTrue(dao.hasRole(bytes32(dao.CONTROL_ROLE()), address(proxy)));
202 | assertEq(address(dao.shopAddress()), address(proxy));
203 | }
204 |
205 | function test_setShop_x2() public {
206 | vm.prank(address(proxy));
207 | vm.expectRevert(bytes("Shop address already set"));
208 | dao.setShop(address(proxy));
209 | }
210 |
211 | function test_newDispute() public createLegitSale() buyLastItem() disputeSale() {
212 | // Save dispute before creation
213 | FP_DAO.Dispute memory disputeBefore = dao.queryDispute(0);
214 | assertEq(disputeBefore.itemId, 0, "Wrong itemId");
215 | assertEq(disputeBefore.buyerReasoning, "", "Wrong buyerReasoning");
216 | assertEq(disputeBefore.sellerReasoning, "", "Wrong sellerReasoning");
217 | assertEq(disputeBefore.votesFor, 0, "Wrong votesFor");
218 | assertEq(disputeBefore.votesAgainst, 0, "Wrong votesAgainst");
219 | assertEq(disputeBefore.totalVoters, 0, "Wrong totalVoters");
220 | assertEq(disputeBefore.committingStartingTime, 0, "Wrong committingStartingTime");
221 | assertEq(disputeBefore.revealingStartingTime, 0, "Wrong revealingStartingTime");
222 | assertEq(uint256(disputeBefore.state), uint256(IFP_DAO.DisputeState.NOT_ACTIVE), "Wrong totalVoters");
223 |
224 | // Create dispute
225 | vm.prank(SELLER1);
226 | (bool success,) = address(proxy).call(
227 | abi.encodeWithSignature(
228 | "disputedSaleReply(uint256,string)",
229 | 0,
230 | "Seller's reasoning"
231 | )
232 | );
233 | require(success, "Disputed sale not replied");
234 |
235 | // Check the dispute creation
236 | FP_DAO.Dispute memory disputeAfter = dao.queryDispute(0);
237 | assertEq(disputeAfter.itemId, 0, "Wrong itemId, dispute creation failed");
238 | assertEq(disputeAfter.buyerReasoning, "Buyer's reasoning", "Wrong buyerReasoning, dispute creation failed");
239 | assertEq(disputeAfter.sellerReasoning, "Seller's reasoning", "Wrong sellerReasoning, dispute creation failed");
240 | assertEq(disputeAfter.votesFor, 0, "Wrong votesFor, dispute creation failed");
241 | assertEq(disputeAfter.votesAgainst, 0, "Wrong votesAgainst, dispute creation failed");
242 | assertEq(disputeAfter.totalVoters, 0, "Wrong totalVoters, dispute creation failed");
243 | assertEq(disputeAfter.committingStartingTime, block.timestamp, "Wrong committingStartingTime");
244 | assertEq(disputeAfter.revealingStartingTime, 0, "Wrong revealingStartingTime");
245 | assertEq(uint256(disputeAfter.state), uint256(IFP_DAO.DisputeState.COMMITTING_PHASE), "Wrong totalVoters");
246 | }
247 |
248 | function test_newDispute_RevertIf_CallerIsNotTheShop() public createLegitSale() buyLastItem() disputeSale() {
249 | // Create dispute with unauthorized account
250 | vm.prank(SELLER1);
251 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(SELLER1), keccak256("CONTROL_ROLE")));
252 | dao.newDispute(0, "Buyer's reasoning", "Seller's reasoning");
253 | }
254 |
255 |
256 | function test_commitVoteOnDispute() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") {
257 | // Check
258 | FP_DAO.Dispute memory dispute = dao.queryDispute(0);
259 | assertEq(uint(dao.hasVotedOnDispute(USER1, 0)), uint(IFP_DAO.Vote.COMMITTED), "Wrong hasVoted");
260 | assertEq(uint(dao.commitsOnDisputes(0, USER1)), uint(keccak256(abi.encodePacked(true, "secret"))),"Wrong commit");
261 | assertEq(dispute.itemId, 0, "Wrong itemId");
262 | assertEq(dispute.votesFor, 0, "Wrong votesFor");
263 | assertEq(dispute.votesAgainst, 0, "Wrong votesAgainst");
264 | assertEq(dispute.totalVoters, 0, "Wrong totalVoters");
265 | assertEq(dispute.revealingStartingTime, 0, "Wrong revealingStartingTime");
266 | assertEq(uint256(dispute.state), uint256(IFP_DAO.DisputeState.COMMITTING_PHASE), "Wrong state");
267 | }
268 |
269 | function test_commitVoteOnDispute_RevertIf_NotInCommitingPhase() public createLegitSale() buyLastItem() {
270 | // Commit vote
271 | bytes32 commit = keccak256(abi.encodePacked(true, "secret"));
272 | vm.prank(USER1);
273 | vm.expectRevert(bytes("Dispute is not in committing phase"));
274 | dao.commitVoteOnDispute(0, commit);
275 | }
276 |
277 | function test_commitVoteOnDispute_RevertIf_UserHasAlreadyVoted() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") {
278 | // Commit vote again
279 | vm.expectRevert(bytes("You have already voted"));
280 | vm.prank(USER1);
281 | dao.commitVoteOnDispute(0, keccak256(abi.encodePacked(true, "secret")));
282 | }
283 |
284 | function test_revealDisputeVote() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") revealVote(true, "secret") {
285 | // Check vote
286 | FP_DAO.Dispute memory dispute = dao.queryDispute(0);
287 | assertEq(uint(dao.hasVotedOnDispute(USER1, 0)), uint(IFP_DAO.Vote.FOR), "Wrong hasVoted");
288 | assertEq(dispute.itemId, 0, "Wrong itemId");
289 | assertEq(dispute.buyerReasoning, "Buyer's reasoning", "Wrong buyerReasoning");
290 | assertEq(dispute.sellerReasoning, "Seller's reasoning", "Wrong sellerReasoning");
291 | assertEq(dispute.votesFor, 1000, "Wrong votesFor");
292 | assertEq(dispute.votesAgainst, 0, "Wrong votesAgainst");
293 | assertEq(dispute.totalVoters, 1, "Wrong totalVoters");
294 | assertEq(dispute.revealingStartingTime, block.timestamp, "Wrong revealingStartingTime");
295 | assertEq(uint256(dispute.state), uint256(IFP_DAO.DisputeState.REVEALING_PHASE), "Wrong state");
296 | }
297 |
298 | function test_revealDisputeVote_RevertIf_ItsNeitherInReveilingPhaseNorInCommittingPhase() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() {
299 | // Reveal vote
300 | vm.prank(USER1);
301 | vm.expectRevert(bytes("Conditions for advancing to revealing phase are not met"));
302 | dao.revealDisputeVote(0, true, "secret");
303 | }
304 |
305 | function test_revealDisputeVote_RevertIf_CommitingTimeHasNotElapsed() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") {
306 | // Reveal vote
307 | vm.prank(USER1);
308 | vm.expectRevert(bytes("Conditions for advancing to revealing phase are not met"));
309 | dao.revealDisputeVote(0, true, "secret");
310 | }
311 |
312 | function test_revealDisputeVote_RevertIf_UserHasNotCommitted() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") {
313 | // Manipulate time to pass the committing time
314 | vm.warp(block.timestamp + COMMITTING_TIME);
315 |
316 | // Reveal vote
317 | vm.prank(USER2);
318 | vm.expectRevert(bytes("You currently have no vote to reveal"));
319 | dao.revealDisputeVote(0, true, "secret");
320 | }
321 |
322 | function test_revealDisputeVote_RevertIf_UserHasAlreadyRevealed() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") revealVote(true, "secret") {
323 | // Reveal vote again
324 | vm.prank(USER1);
325 | vm.expectRevert(bytes("You currently have no vote to reveal"));
326 | dao.revealDisputeVote(0, true, "secret");
327 | }
328 |
329 | function test_revealDisputeVote_RevertIf_SecretIsWrong() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") {
330 | // Manipulate time to pass the committing time
331 | vm.warp(block.timestamp + COMMITTING_TIME);
332 |
333 | // Reveal vote
334 | vm.prank(USER1);
335 | vm.expectRevert(bytes("Invalid vote hash"));
336 | dao.revealDisputeVote(0, true, "wrong secret");
337 | }
338 |
339 | function test_endDispute_VotesFor() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") revealVote(true, "secret") {
340 | vm.warp(block.timestamp + MIN_REVEALING_TIME);
341 | dao.endDispute(0);
342 | FP_DAO.Dispute memory dispute = dao.queryDispute(0);
343 | IFP_DAO.Vote result = dao.queryDisputeResult(0);
344 | assertEq(dispute.itemId, 0, "Wrong itemId");
345 | assertEq(dispute.buyerReasoning, "", "Wrong buyerReasoning");
346 | assertEq(dispute.sellerReasoning, "", "Wrong sellerReasoning");
347 | assertEq(dispute.votesFor, 0, "Wrong votesFor");
348 | assertEq(dispute.votesAgainst, 0, "Wrong votesAgainst");
349 | assertEq(dispute.totalVoters, 0, "Wrong totalVoters");
350 | assertEq(dispute.committingStartingTime, 0, "Wrong committingStartingTime");
351 | assertEq(dispute.revealingStartingTime, 0, "Wrong revealingStartingTime");
352 | assertEq(uint(result), uint(IFP_DAO.Vote.FOR), "Wrong result");
353 | }
354 |
355 | function test_endDispute_VotesAgainst() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(false, "secret") revealVote(false, "secret") {
356 | vm.warp(block.timestamp + MIN_REVEALING_TIME);
357 | dao.endDispute(0);
358 | FP_DAO.Dispute memory dispute = dao.queryDispute(0);
359 | IFP_DAO.Vote result = dao.queryDisputeResult(0);
360 | assertEq(dispute.itemId, 0, "Wrong itemId");
361 | assertEq(dispute.buyerReasoning, "", "Wrong buyerReasoning");
362 | assertEq(dispute.sellerReasoning, "", "Wrong sellerReasoning");
363 | assertEq(dispute.votesFor, 0, "Wrong votesFor");
364 | assertEq(dispute.votesAgainst, 0, "Wrong votesAgainst");
365 | assertEq(dispute.totalVoters, 0, "Wrong totalVoters");
366 | assertEq(dispute.committingStartingTime, 0, "Wrong committingStartingTime");
367 | assertEq(dispute.revealingStartingTime, 0, "Wrong revealingStartingTime");
368 | assertEq(uint(result), uint(IFP_DAO.Vote.AGAINST), "Wrong result");
369 | }
370 |
371 | function test_endDispute_RevertIf_NotInRevealingPhase() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") {
372 | vm.expectRevert(bytes("Dispute is not in revealing phase"));
373 | dao.endDispute(0);
374 | }
375 |
376 | function test_endDispute_RevertIf_RevealingTimeHasNotElapsed() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") revealVote(true, "secret") {
377 | vm.expectRevert(bytes("Minimum revealing time hasn't elapsed"));
378 | dao.endDispute(0);
379 | }
380 |
381 | function test_cancelDispute() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() {
382 | vm.prank(address(proxy));
383 | dao.cancelDispute(0);
384 |
385 | FP_DAO.Dispute memory dispute = dao.queryDispute(0);
386 | assertEq(dispute.itemId, 0, "Wrong itemId");
387 | assertEq(dispute.buyerReasoning, "", "Wrong buyerReasoning");
388 | assertEq(dispute.sellerReasoning, "", "Wrong sellerReasoning");
389 | assertEq(dispute.votesFor, 0, "Wrong votesFor");
390 | assertEq(dispute.votesAgainst, 0, "Wrong votesAgainst");
391 | assertEq(dispute.totalVoters, 0, "Wrong totalVoters");
392 | }
393 |
394 | function test_cancelDispute_RevertIf_CallerIsNotTheShop() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() {
395 | vm.prank(SELLER1);
396 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(SELLER1), keccak256("CONTROL_ROLE")));
397 | dao.cancelDispute(0);
398 | }
399 |
400 | function test_checkLottery() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") revealVote(true, "secret") {
401 | vm.warp(block.timestamp + MIN_REVEALING_TIME);
402 | dao.endDispute(0);
403 |
404 | vm.prank(USER1);
405 | dao.checkLottery(0);
406 | assertTrue(dao.hasCheckedLottery(USER1, 0));
407 | }
408 |
409 | function test_checkLottery_RevertIf_UserHasVotedToTheWrongSide() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") {
410 | uint amount2 = 130;
411 | vm.prank(vm.envAddress("DEPLOYER"));
412 | token.mint(address(USER2), amount2);
413 |
414 | bytes32 commit = keccak256(abi.encodePacked(false, "secret"));
415 | vm.prank(USER2);
416 | dao.commitVoteOnDispute(0, commit);
417 |
418 | vm.warp(block.timestamp + COMMITTING_TIME);
419 | vm.prank(USER1);
420 | dao.revealDisputeVote(0, true, "secret");
421 | vm.prank(USER2);
422 | dao.revealDisputeVote(0, false, "secret");
423 |
424 | vm.warp(block.timestamp + MIN_REVEALING_TIME);
425 | dao.endDispute(0);
426 |
427 | vm.expectRevert(bytes("User voted for the wrong side"));
428 | vm.prank(USER2);
429 | dao.checkLottery(0);
430 | }
431 |
432 | function test_checkLottery_RevertIf_UserHasAlreadyCheckedIt() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() mintAndCommitVote(true, "secret") revealVote(true, "secret") {
433 | vm.warp(block.timestamp + MIN_REVEALING_TIME);
434 | dao.endDispute(0);
435 |
436 | vm.prank(USER1);
437 | dao.checkLottery(0);
438 |
439 | vm.expectRevert(bytes("User cannot check the lottery more than 1 time per dispute"));
440 | vm.prank(USER1);
441 | dao.checkLottery(0);
442 | }
443 |
444 | function test_checkLottery_RevertIf_UserHasNotVoted() public createLegitSale() buyLastItem() disputeSale() replyDisputedSale() {
445 | // Check lottery without voting
446 | vm.expectRevert(bytes("User didn't vote"));
447 | vm.prank(USER1);
448 | dao.checkLottery(0);
449 | }
450 |
451 | function test_newUpgradeProposal() public {
452 | // Save proposal before creation
453 | FP_DAO.UpgradeProposal memory proposalBefore = dao.queryUpgradeProposal(0);
454 | assertEq(proposalBefore.creator, address(0), "Wrong creator");
455 | assertEq(proposalBefore.id, 0, "Wrong proposalId");
456 | assertEq(proposalBefore.creationTimestamp, 0, "Wrong creation timestamp");
457 | assertEq(proposalBefore.approvalTimestamp, 0, "Wrong approval timestamp");
458 | assertEq(proposalBefore.newShop, address(0), "Wrong shop address");
459 | assertEq(proposalBefore.votesFor, 0, "Wrong votesFor");
460 | assertEq(proposalBefore.votesAgainst, 0, "Wrong votesAgainst");
461 | assertEq(proposalBefore.totalVoters, 0, "Wrong totalVoters");
462 | assertEq(uint256(proposalBefore.state), uint256(IFP_DAO.ProposalState.NOT_ACTIVE), "Wrong state");
463 |
464 | // Create proposal
465 | FP_Shop newShop = new FP_Shop();
466 | vm.prank(USER1);
467 | dao.newUpgradeProposal(address(newShop));
468 |
469 | // Check the dispute creation
470 | FP_DAO.UpgradeProposal memory newProposal = dao.queryUpgradeProposal(0);
471 | assertEq(newProposal.creator, USER1, "Wrong creator");
472 | assertEq(newProposal.id, 0, "Wrong proposalId");
473 | assertEq(newProposal.creationTimestamp, block.timestamp, "Wrong creation timestamp");
474 | assertEq(newProposal.approvalTimestamp, 0, "Wrong approval timestamp");
475 | assertEq(newProposal.newShop, address(newShop), "Wrong shop address");
476 | assertEq(newProposal.votesFor, 0, "Wrong votesFor");
477 | assertEq(newProposal.votesAgainst, 0, "Wrong votesAgainst");
478 | assertEq(newProposal.totalVoters, 0, "Wrong totalVoters");
479 | assertEq(uint256(newProposal.state), uint256(IFP_DAO.ProposalState.ACTIVE), "Wrong state");
480 | }
481 |
482 | function test_newUpgradeProposal_RevertIf_AddressHasNoCode() public {
483 | vm.prank(USER1);
484 | vm.expectRevert(bytes("The new shop address is invalid"));
485 | dao.newUpgradeProposal(address(3333));
486 | }
487 |
488 | function test_castVoteOnProposal_VoteFor() public createUpgradeProposal() spendReviewTime() mintAndVoteOnProposal(USER1, 1000, true) {
489 | // Check vote
490 | FP_DAO.UpgradeProposal memory updatedProposal = dao.queryUpgradeProposal(0);
491 | assertEq(uint(dao.hasVotedOnUpgradeProposal(address(USER1), 0)), uint(IFP_DAO.Vote.FOR),"Wrong hasVoted");
492 | assertEq(updatedProposal.id, 0, "Wrong proposalId");
493 | assertEq(updatedProposal.votesFor, 1000, "Wrong votesFor");
494 | assertEq(updatedProposal.votesAgainst, 0, "Wrong votesAgainst");
495 | assertEq(updatedProposal.totalVoters, 1, "Wrong totalVoters");
496 | assertEq(uint256(updatedProposal.state), uint256(IFP_DAO.ProposalState.ACTIVE), "Wrong state");
497 | }
498 |
499 | function test_castVoteOnProposal_VoteAgainst() public createUpgradeProposal() spendReviewTime() mintAndVoteOnProposal(USER1, 1000, false) {
500 | // Check vote
501 | FP_DAO.UpgradeProposal memory updatedProposal = dao.queryUpgradeProposal(0);
502 | assertEq(uint(dao.hasVotedOnUpgradeProposal(address(USER1), 0)), uint(IFP_DAO.Vote.AGAINST),"Wrong hasVoted");
503 | assertEq(updatedProposal.id, 0, "Wrong proposalId");
504 | assertEq(updatedProposal.votesFor, 0, "Wrong votesFor");
505 | assertEq(updatedProposal.votesAgainst, 1000, "Wrong votesAgainst");
506 | assertEq(updatedProposal.totalVoters, 1, "Wrong totalVoters");
507 | assertEq(uint256(updatedProposal.state), uint256(IFP_DAO.ProposalState.ACTIVE), "Wrong state");
508 | }
509 |
510 | function test_castVoteOnProposal_2Votes() public createUpgradeProposal() spendReviewTime() mintAndVoteOnProposal(USER1, 1000, false) mintAndVoteOnProposal(USER2, 3500, true){
511 | // Check vote
512 | FP_DAO.UpgradeProposal memory updatedProposal = dao.queryUpgradeProposal(0);
513 | assertEq(uint(dao.hasVotedOnUpgradeProposal(address(USER1), 0)), uint(IFP_DAO.Vote.AGAINST),"Wrong hasVoted");
514 | assertEq(uint(dao.hasVotedOnUpgradeProposal(address(USER2), 0)), uint(IFP_DAO.Vote.FOR),"Wrong hasVoted");
515 | assertEq(updatedProposal.id, 0, "Wrong proposalId");
516 | assertEq(updatedProposal.votesAgainst, 1000, "Wrong votesAgainst");
517 | assertEq(updatedProposal.votesFor, 3500, "Wrong votesFor");
518 | assertEq(updatedProposal.totalVoters, 2, "Wrong totalVoters");
519 | assertEq(uint256(updatedProposal.state), uint256(IFP_DAO.ProposalState.ACTIVE), "Wrong state");
520 | }
521 |
522 | function test_castVoteOnProposal_RevertIf_ReviewTimeHasNotElapsed() public createUpgradeProposal() {
523 | // Mint FP_tokens
524 | uint amount = 1000;
525 | vm.prank(vm.envAddress("DEPLOYER"));
526 | token.mint(address(USER1), amount);
527 | assertEq(token.balanceOf(address(USER1)), amount, "Wrong balance");
528 |
529 | // Cast vote
530 | vm.prank(USER1);
531 | vm.expectRevert(bytes("Proposal is not ready to be voted"));
532 | dao.castVoteOnProposal(0, true);
533 |
534 | // Check vote
535 | FP_DAO.UpgradeProposal memory proposal = dao.queryUpgradeProposal(0);
536 |
537 | assertEq(uint(dao.hasVotedOnUpgradeProposal(address(USER1), 0)), uint(IFP_DAO.Vote.DIDNT_VOTE),"Wrong hasVoted");
538 | assertEq(proposal.votesFor, 0, "Wrong votesFor");
539 | assertEq(proposal.votesAgainst, 0, "Wrong votesAgainst");
540 | assertEq(proposal.totalVoters, 0, "Wrong totalVoters");
541 | }
542 |
543 | function test_castVoteOnProposal_RevertIf_ProposalIsNotActive() public {
544 | // Mint FP_tokens
545 | uint amount = 1000;
546 | vm.prank(vm.envAddress("DEPLOYER"));
547 | token.mint(address(USER1), amount);
548 | assertEq(token.balanceOf(address(USER1)), amount, "Wrong balance");
549 |
550 | // Cast vote
551 | vm.prank(USER1);
552 | vm.expectRevert(bytes("Proposal is not active"));
553 | dao.castVoteOnProposal(0, true);
554 | }
555 |
556 | function test_castVoteOnProposal_RevertIf_UserHasAlreadyVoted() public createUpgradeProposal() spendReviewTime() mintAndVoteOnProposal(USER1, 1000, true){
557 | // Cast another vote
558 | vm.prank(USER1);
559 | vm.expectRevert(bytes("You have already voted"));
560 | dao.castVoteOnProposal(0, true);
561 |
562 | // Check vote
563 | FP_DAO.UpgradeProposal memory updatedProposal = dao.queryUpgradeProposal(0);
564 |
565 | assertEq(uint(dao.hasVotedOnUpgradeProposal(address(USER1), 0)), uint(IFP_DAO.Vote.FOR),"Wrong hasVoted");
566 | assertEq(updatedProposal.id, 0, "Wrong proposalId");
567 | assertEq(updatedProposal.votesFor, 1000, "Wrong votesFor");
568 | assertEq(updatedProposal.votesAgainst, 0, "Wrong votesAgainst");
569 | assertEq(updatedProposal.totalVoters, 1, "Wrong totalVoters");
570 | assertEq(uint256(updatedProposal.state), uint256(IFP_DAO.ProposalState.ACTIVE), "Wrong state");
571 | }
572 |
573 | function test_castVoteOnProposal_RevertIf_HasNoTokens() public createUpgradeProposal() spendReviewTime() {
574 | // Cast vote
575 | vm.prank(USER1);
576 | vm.expectRevert(bytes("You have no voting power"));
577 | dao.castVoteOnProposal(0, true);
578 |
579 | // Check vote
580 | FP_DAO.UpgradeProposal memory updatedProposal = dao.queryUpgradeProposal(0);
581 |
582 | assertEq(uint(dao.hasVotedOnUpgradeProposal(address(USER1), 0)), uint(IFP_DAO.Vote.DIDNT_VOTE),"Wrong hasVoted");
583 | assertEq(updatedProposal.votesFor, 0, "Wrong votesFor");
584 | assertEq(updatedProposal.votesAgainst, 0, "Wrong votesAgainst");
585 | assertEq(updatedProposal.totalVoters, 0, "Wrong totalVoters");
586 | }
587 |
588 | function test_cancelProposalByCreator() public createUpgradeProposal() {
589 | // Cancel proposal
590 | vm.prank(USER1);
591 | dao.cancelProposalByCreator(0);
592 |
593 | // Check proposal
594 | FP_DAO.UpgradeProposal memory canceledProposal = dao.queryUpgradeProposal(0);
595 | assertEq(canceledProposal.creator, address(0), "Wrong creator");
596 | assertEq(canceledProposal.id, 0, "Wrong proposalId");
597 | assertEq(canceledProposal.creationTimestamp, 0, "Wrong timestamp");
598 | assertEq(canceledProposal.approvalTimestamp, 0, "Wrong timestamp");
599 | assertEq(canceledProposal.newShop, address(0), "Wrong shop address");
600 | assertEq(canceledProposal.votesFor, 0, "Wrong votesFor");
601 | assertEq(canceledProposal.votesAgainst, 0, "Wrong votesAgainst");
602 | assertEq(canceledProposal.totalVoters, 0, "Wrong totalVoters");
603 | assertEq(uint256(canceledProposal.state), uint256(IFP_DAO.ProposalState.NOT_ACTIVE), "Wrong state");
604 | }
605 |
606 | function test_cancelProposalByCreator_RevertIf_CallerIsNotCreator() public createUpgradeProposal() {
607 | // Cancel proposal
608 | vm.prank(USER2);
609 | vm.expectRevert(bytes("You are not the creator of the proposal"));
610 | dao.cancelProposalByCreator(0);
611 |
612 | // Check proposal
613 | FP_DAO.UpgradeProposal memory proposal = dao.queryUpgradeProposal(0);
614 | assertEq(proposal.creator, USER1, "Wrong creator");
615 | assertEq(proposal.id, 0, "Wrong proposalId");
616 | assertEq(proposal.creationTimestamp, block.timestamp, "Wrong timestamp");
617 | assertEq(uint256(proposal.state), uint256(IFP_DAO.ProposalState.ACTIVE), "Wrong state");
618 | }
619 |
620 | function test_cancelProposalByCreator_RevertIf_ProposalIsNotActive() public {
621 | // Cancel proposal
622 | vm.prank(USER1);
623 | vm.expectRevert(bytes("Proposal is not active"));
624 | dao.cancelProposalByCreator(0);
625 | }
626 |
627 | function test_cancelProposal() public createUpgradeProposal() {
628 | // Cancel proposal
629 | vm.prank(USER2);
630 | dao.cancelProposal(0, "password");
631 |
632 | FP_DAO.UpgradeProposal memory canceledProposal = dao.queryUpgradeProposal(0);
633 | assertEq(canceledProposal.creator, address(0), "Wrong creator");
634 | assertEq(canceledProposal.id, 0, "Wrong proposalId");
635 | assertEq(canceledProposal.creationTimestamp, 0, "Wrong timestamp");
636 | assertEq(canceledProposal.newShop, address(0), "Wrong shop address");
637 | assertEq(canceledProposal.votesFor, 0, "Wrong votesFor");
638 | assertEq(canceledProposal.votesAgainst, 0, "Wrong votesAgainst");
639 | assertEq(canceledProposal.totalVoters, 0, "Wrong totalVoters");
640 | assertEq(uint256(canceledProposal.state), uint256(IFP_DAO.ProposalState.NOT_ACTIVE), "Wrong state");
641 | }
642 |
643 | function test_cancelProposal_RevertIf_PasswordIsWrong() public createUpgradeProposal() {
644 | // Cancel proposal
645 | vm.prank(USER2);
646 | vm.expectRevert(bytes("Unauthorized"));
647 | dao.cancelProposal(0, "qwerty");
648 |
649 | // Check proposal
650 | FP_DAO.UpgradeProposal memory proposal = dao.queryUpgradeProposal(0);
651 | assertEq(proposal.creator, USER1, "Wrong creator");
652 | assertEq(proposal.id, 0, "Wrong proposalId");
653 | assertEq(proposal.creationTimestamp, block.timestamp, "Wrong timestamp");
654 | assertEq(uint256(proposal.state), uint256(IFP_DAO.ProposalState.ACTIVE), "Wrong state");
655 | }
656 |
657 | function test_cancelProposal_RevertIf_ProposalIsNotActive() public {
658 | // Cancel proposal
659 | vm.prank(USER1);
660 | vm.expectRevert(bytes("Proposal is not active"));
661 | dao.cancelProposal(0, "password");
662 | }
663 |
664 | function test_resolveUpgradeProposal_Approved() public createUpgradeProposal() spendReviewTime() cast501Votes(true) spendVotingTime() {
665 | // Check current shop implementation and obtain new shop address
666 | assertEq(proxy.getImplementation(), address(shop), "Actual implementation is wrong");
667 | FP_DAO.UpgradeProposal memory proposalBefore = dao.queryUpgradeProposal(0);
668 |
669 | // Resolve proposal
670 | dao.resolveUpgradeProposal(0);
671 |
672 | // Check proposal
673 | FP_DAO.UpgradeProposal memory resolvedProposal = dao.queryUpgradeProposal(0);
674 | assertEq(resolvedProposal.creator, proposalBefore.creator, "Wrong creator");
675 | assertEq(resolvedProposal.id, 0, "Wrong proposalId");
676 | assertEq(resolvedProposal.creationTimestamp, proposalBefore.creationTimestamp, "Wrong timestamp");
677 | assertEq(resolvedProposal.approvalTimestamp, block.timestamp, "Wrong timestamp");
678 | assertEq(resolvedProposal.newShop, proposalBefore.newShop, "Wrong shop address");
679 | assertEq(resolvedProposal.votesFor, proposalBefore.votesFor, "Wrong votesFor");
680 | assertEq(resolvedProposal.votesAgainst, proposalBefore.votesAgainst, "Wrong votesAgainst");
681 | assertEq(resolvedProposal.totalVoters, proposalBefore.totalVoters, "Wrong totalVoters");
682 | assertEq(uint256(resolvedProposal.state), uint256(IFP_DAO.ProposalState.PASSED), "Wrong state");
683 |
684 | // Check proposal result
685 | assertEq(uint(dao.queryUpgradeProposalResult(0)), uint(IFP_DAO.Vote.FOR), "Wrong proposal result");
686 |
687 | // Check current implementation again
688 | assertEq(proxy.getImplementation(), address(shop), "Actual implementation is wrong");
689 | }
690 |
691 | function test_resolveUpgradeProposal_NotApproved() public createUpgradeProposal() spendReviewTime() cast501Votes(false) spendVotingTime() {
692 | // Check current shop implementation and obtain new shop address
693 | assertEq(proxy.getImplementation(), address(shop), "Actual implementation is wrong");
694 |
695 | // Resolve proposal
696 | dao.resolveUpgradeProposal(0);
697 |
698 | // Check proposal
699 | FP_DAO.UpgradeProposal memory resolvedProposal = dao.queryUpgradeProposal(0);
700 | assertEq(resolvedProposal.creator, address(0), "Wrong creator");
701 | assertEq(resolvedProposal.id, 0, "Wrong proposalId");
702 | assertEq(resolvedProposal.creationTimestamp, 0, "Wrong timestamp");
703 | assertEq(resolvedProposal.approvalTimestamp, 0, "Wrong timestamp");
704 | assertEq(resolvedProposal.newShop, address(0), "Wrong shop address");
705 | assertEq(resolvedProposal.votesFor, 0, "Wrong votesFor");
706 | assertEq(resolvedProposal.votesAgainst, 0, "Wrong votesAgainst");
707 | assertEq(resolvedProposal.totalVoters, 0, "Wrong totalVoters");
708 | assertEq(uint256(resolvedProposal.state), uint256(IFP_DAO.ProposalState.NOT_ACTIVE), "Wrong state");
709 |
710 | // Check proposal result
711 | assertEq(uint(dao.queryUpgradeProposalResult(0)), uint(IFP_DAO.Vote.AGAINST), "Wrong proposal result");
712 |
713 | // Check current implementation
714 | assertEq(proxy.getImplementation(), address(shop), "Actual implementation is wrong");
715 | }
716 |
717 | function test_resolveUpgradeProposal_RevertIf_ProposalIsNotActive() public {
718 | // Resolve proposal
719 | vm.expectRevert(bytes("Proposal is not active"));
720 | dao.resolveUpgradeProposal(0);
721 | }
722 |
723 | function test_resolveUpgradeProposal_RevertIf_VotingTimeHasNotElapsed() public createUpgradeProposal() spendReviewTime() mintAndVoteOnProposal(USER1, 1000, false) {
724 | // Resolve proposal
725 | vm.expectRevert(bytes("Proposal is not ready to be resolved"));
726 | dao.resolveUpgradeProposal(0);
727 | }
728 |
729 | function test_resolveUpgradeProposal_RevertIf__NotEnoughUsersVoted() public createUpgradeProposal() spendReviewTime() mintAndVoteOnProposal(USER1, 1000, false) spendVotingTime() {
730 | // Resolve proposal
731 | vm.expectRevert(bytes("Not enough voters"));
732 | dao.resolveUpgradeProposal(0);
733 | }
734 |
735 | function test_executePassedProposal() public createUpgradeProposal() spendReviewTime() cast501Votes(true) spendVotingTime() {
736 | // Resolve proposal
737 | dao.resolveUpgradeProposal(0);
738 |
739 | // Check current shop implementation and obtain new shop address
740 | assertEq(proxy.getImplementation(), address(shop), "Actual implementation is wrong");
741 | FP_DAO.UpgradeProposal memory proposalBefore = dao.queryUpgradeProposal(0);
742 | address newShop = proposalBefore.newShop;
743 |
744 | // Execute proposal
745 | vm.warp(block.timestamp + PROPOSAL_EXECUTION_DELAY + 1);
746 | dao.executePassedProposal(0);
747 |
748 | // Check proposal
749 | FP_DAO.UpgradeProposal memory executedProposal = dao.queryUpgradeProposal(0);
750 | assertEq(executedProposal.creator, address(0), "Wrong creator");
751 | assertEq(executedProposal.id, 0, "Wrong proposalId");
752 | assertEq(executedProposal.creationTimestamp, 0, "Wrong timestamp");
753 | assertEq(executedProposal.approvalTimestamp, 0, "Wrong timestamp");
754 | assertEq(executedProposal.newShop, address(0), "Wrong shop address");
755 | assertEq(executedProposal.votesFor, 0, "Wrong votesFor");
756 | assertEq(executedProposal.votesAgainst, 0, "Wrong votesAgainst");
757 | assertEq(executedProposal.totalVoters, 0, "Wrong totalVoters");
758 | assertEq(uint256(executedProposal.state), uint256(IFP_DAO.ProposalState.NOT_ACTIVE), "Wrong state");
759 |
760 | // Check new implementation again
761 | assertEq(proxy.getImplementation(), newShop, "Actual implementation is wrong");
762 | }
763 |
764 | function test_executePassedProposal_RevertIf_ProposalIsNotPassed() public createUpgradeProposal() spendReviewTime() cast501Votes(true) spendVotingTime() {
765 | // Execute proposal
766 | vm.expectRevert(bytes("Proposal is not passed"));
767 | dao.executePassedProposal(0);
768 | }
769 |
770 | function test_executePassedProposal_RevertIf_DelayHasNotElapsed() public createUpgradeProposal() spendReviewTime() cast501Votes(true) spendVotingTime() {
771 | // Resolve proposal
772 | dao.resolveUpgradeProposal(0);
773 |
774 | // Execute proposal
775 | vm.expectRevert(bytes("Proposal is not ready to be executed"));
776 | dao.executePassedProposal(0);
777 | }
778 | }
--------------------------------------------------------------------------------
/test/unit/FP_PowersellerNFT.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {Test, console} from "forge-std/Test.sol";
5 | import {FP_CoolNFT} from "../../src/FP_CoolNFT.sol";
6 | import {FP_DAO} from "../../src/FP_DAO.sol";
7 | import {FP_PowersellerNFT} from "../../src/FP_PowersellerNFT.sol";
8 | import {FP_Shop} from "../../src/FP_Shop.sol";
9 | import {FP_Token} from "../../src/FP_Token.sol";
10 | import {FP_Vault} from "../../src/FP_Vault.sol";
11 | import {FP_Proxy} from "../../src/FP_Proxy.sol";
12 | import {DeployFaillapop} from "../../script/DeployFaillapop.s.sol";
13 |
14 | contract FP_PowersellerNFT_Test is Test {
15 | address public constant USER1 = address(bytes20("USER1"));
16 | address public constant USER2 = address(bytes20("USER2"));
17 |
18 | FP_CoolNFT public coolNFT;
19 | FP_PowersellerNFT public powersellerNFT;
20 | FP_DAO public dao;
21 | FP_Vault public vault;
22 | FP_Shop public shop;
23 | FP_Token public token;
24 | FP_Proxy public proxy;
25 |
26 | /************************************** Modifiers **************************************/
27 |
28 | modifier mint() {
29 | vm.prank(address(proxy));
30 | powersellerNFT.safeMint(USER1);
31 | _;
32 | }
33 |
34 | /************************************** Set Up **************************************/
35 |
36 | function setUp() external {
37 | vm.deal(USER1, 10);
38 |
39 | DeployFaillapop deploy = new DeployFaillapop();
40 | (shop, token, coolNFT, powersellerNFT, dao, vault, proxy) = deploy.run();
41 | }
42 |
43 | /************************************** Tests **************************************/
44 |
45 | function test_SetUp() public view {
46 | assertEq(powersellerNFT.name(), "Faillapop Powerseller NFT", "Incorrect token name");
47 | assertEq(powersellerNFT.symbol(), "FPSNFT", "Incorrect token symbol");
48 | }
49 |
50 | function test_setShop() public view {
51 | assertTrue(powersellerNFT.hasRole(bytes32(powersellerNFT.CONTROL_ROLE()), address(proxy)));
52 | }
53 |
54 | function test_setShop_x2() public {
55 | vm.prank(address(proxy));
56 | vm.expectRevert(bytes("Shop address already set"));
57 | powersellerNFT.setShop(address(proxy));
58 | }
59 |
60 | function test_safeMint() public mint() {
61 | assertEq(powersellerNFT.balanceOf(USER1), 1, "Incorrect balance");
62 | assertEq(powersellerNFT.ownerOf(1), USER1, "Incorrect owner");
63 | assertEq(powersellerNFT.tokenIds(USER1), 1, "Incorrect tokenId");
64 | assertEq(powersellerNFT.totalPowersellers(), 1, "Incorrect totalPowersellers");
65 | assertTrue(powersellerNFT.checkPrivilege(USER1));
66 | }
67 |
68 | function test_safeMint_RevertIf_CallerIsNotShop() public {
69 | vm.prank(USER1);
70 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER1), keccak256("CONTROL_ROLE")));
71 | powersellerNFT.safeMint(USER1);
72 | }
73 |
74 | function test_safeMint_RevertIf_UserIsAlreadyPowerseller() public mint() {
75 | vm.prank(address(proxy));
76 | vm.expectRevert(bytes("This user is already a Powerseller"));
77 | powersellerNFT.safeMint(USER1);
78 | }
79 |
80 | function test_removePowersellerNFT() public mint() {
81 | uint256 previousTotalPowersellers = powersellerNFT.totalPowersellers();
82 | vm.prank(address(proxy));
83 | powersellerNFT.removePowersellerNFT(USER1);
84 |
85 | assertEq(powersellerNFT.balanceOf(USER1), 0, "Incorrect balance");
86 | assertEq(powersellerNFT.tokenIds(USER1), 0, "Incorrect tokenId");
87 | assertEq(powersellerNFT.totalPowersellers(), previousTotalPowersellers - 1, "Incorrect totalPowersellers");
88 | assertFalse(powersellerNFT.checkPrivilege(USER1));
89 | }
90 |
91 | function test_removePowersellerNFT_RevertIf_UserIsNotPowerseller() public {
92 | vm.prank(address(proxy));
93 | vm.expectRevert(bytes("This user is not a Powerseller"));
94 | powersellerNFT.removePowersellerNFT(USER1);
95 | }
96 |
97 | function test_approve() public mint() {
98 | vm.prank(USER1);
99 | vm.expectRevert(bytes("PowersellerNFT cannot be approved"));
100 | powersellerNFT.approve(USER2, 1);
101 | }
102 |
103 | function test_setApprovalForAll() public mint() {
104 | vm.prank(USER1);
105 | vm.expectRevert(bytes("PowersellerNFT cannot be approved"));
106 | powersellerNFT.setApprovalForAll(USER2, true);
107 | }
108 |
109 | function test_transferFrom() public mint() {
110 | vm.prank(USER1);
111 | vm.expectRevert(bytes("PowersellerNFT cannot be transferred"));
112 | powersellerNFT.transferFrom(USER1, USER2, 1);
113 | }
114 |
115 | function test_safeTransferFrom() public mint() {
116 | vm.prank(USER1);
117 | vm.expectRevert(bytes("PowersellerNFT cannot be transferred"));
118 | powersellerNFT.safeTransferFrom(USER1, USER2, 1);
119 | }
120 |
121 | function test_safeTransferFrom_withData() public mint() {
122 | vm.prank(USER1);
123 | vm.expectRevert(bytes("PowersellerNFT cannot be transferred"));
124 | powersellerNFT.safeTransferFrom(USER1, USER2, 1, "data");
125 | }
126 | }
--------------------------------------------------------------------------------
/test/unit/FP_Proxy.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {Test, console} from "forge-std/Test.sol";
5 | import {FP_CoolNFT} from "../../src/FP_CoolNFT.sol";
6 | import {FP_DAO} from "../../src/FP_DAO.sol";
7 | import {FP_PowersellerNFT} from "../../src/FP_PowersellerNFT.sol";
8 | import {FP_Shop} from "../../src/FP_Shop.sol";
9 | import {FP_Token} from "../../src/FP_Token.sol";
10 | import {FP_Vault} from "../../src/FP_Vault.sol";
11 | import {FP_Proxy} from "../../src/FP_Proxy.sol";
12 | import {DeployFaillapop} from "../../script/DeployFaillapop.s.sol";
13 |
14 | contract FP_Proxy_Test is Test {
15 | FP_Shop public shop;
16 | FP_Vault public vault;
17 | FP_DAO public dao;
18 | FP_Token public token;
19 | FP_CoolNFT public coolNFT;
20 | FP_PowersellerNFT public powersellerNFT;
21 | FP_Proxy public proxy;
22 |
23 | /************************************** Set Up **************************************/
24 |
25 | function setUp() external {
26 | DeployFaillapop deploy = new DeployFaillapop();
27 | (shop, token, coolNFT, powersellerNFT, dao, vault, proxy) = deploy.run();
28 | }
29 |
30 | /************************************** Tests **************************************/
31 |
32 | function test_setUp() external view {
33 | assertEq(proxy.DAO_ADDRESS(), address(dao));
34 | assertEq(proxy.getImplementation(), address(shop));
35 | }
36 |
37 | function test_upgradeToAndCall() external {
38 | FP_Shop newShop = new FP_Shop();
39 | vm.prank(address(dao));
40 | proxy.upgradeToAndCall(
41 | address(newShop),
42 | ""
43 | );
44 | assertEq(proxy.getImplementation(), address(newShop));
45 | }
46 |
47 | function test_upgradeToAndCall_RevertIf_CallerIsNotTheDao() external {
48 | FP_Shop newShop = new FP_Shop();
49 | vm.expectRevert("AccessControlUnauthorizedAccount");
50 | proxy.upgradeToAndCall(
51 | address(newShop),
52 | ""
53 | );
54 | }
55 | }
--------------------------------------------------------------------------------
/test/unit/FP_Token.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {Test, console} from "forge-std/Test.sol";
5 | import {FP_Token} from "../../src/FP_Token.sol";
6 |
7 | contract FP_Token_Test is Test {
8 | address public constant ADMIN = address(bytes20("ADMIN"));
9 | address public constant USER = address(bytes20("USER"));
10 |
11 | FP_Token public token;
12 |
13 | /************************************** Set Up **************************************/
14 |
15 | function setUp() external {
16 | vm.deal(ADMIN, 10);
17 | vm.deal(USER, 10);
18 | vm.prank(ADMIN);
19 | token = new FP_Token();
20 | }
21 |
22 | /************************************** Tests **************************************/
23 |
24 | function test_setUp() public {
25 | assertTrue(token.hasRole(0x00, address(ADMIN)), "Owner should have DEFAULT_ADMIN_ROLE");
26 | assertTrue(token.hasRole(bytes32(token.PAUSER_ROLE()), address(ADMIN)), "Owner should have PAUSER_ROLE");
27 | assertTrue(token.hasRole(bytes32(token.MINTER_ROLE()), address(ADMIN)), "Owner should have MINTER_ROLE");
28 | assertEq(token.balanceOf(address(ADMIN)), 1000000 * 10 ** token.decimals(), "Incorrect token balance after minting");
29 | }
30 |
31 | function testTokenNameAndSymbol() public {
32 | assertEq(token.name(), "FaillaPop Token", "Incorrect token name");
33 | assertEq(token.symbol(), "FPT", "Incorrect token symbol");
34 | }
35 |
36 | function test_pause() public {
37 | vm.prank(ADMIN);
38 | token.pause();
39 |
40 | assertTrue(token.paused(), "Contract should be paused");
41 | }
42 |
43 | function test_pause_RevertIf_CallerIsNotPauser() public {
44 | vm.prank(USER);
45 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER), keccak256("PAUSER_ROLE")));
46 | token.pause();
47 | }
48 |
49 | function test_unpause() public {
50 | vm.startPrank(ADMIN);
51 | token.pause();
52 | token.unpause();
53 | vm.stopPrank();
54 | assertFalse(token.paused(), "Contract should be unpaused");
55 | }
56 |
57 | function test_unpause_RevertIf_CallerIsNotPauser() public {
58 | vm.prank(USER);
59 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER), keccak256("PAUSER_ROLE")));
60 | token.unpause();
61 | }
62 |
63 | function test_mint() public {
64 | address to = USER;
65 | uint256 amount = 1000;
66 |
67 | vm.prank(ADMIN);
68 | token.mint(to, amount);
69 |
70 | assertEq(token.balanceOf(to), amount, "Incorrect token balance after minting");
71 | }
72 |
73 | function test_mint_RevertIf_CallerIsNotMinter() public {
74 | address to = USER;
75 | uint256 amount = 1000;
76 |
77 | vm.prank(USER);
78 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER), keccak256("MINTER_ROLE")));
79 | token.mint(to, amount);
80 |
81 | assertEq(token.balanceOf(to), 0, "Incorrect token balance after minting");
82 | }
83 |
84 | }
--------------------------------------------------------------------------------
/test/unit/FP_Vault.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0
2 | pragma solidity ^0.8.13;
3 |
4 | import {Test, console} from "forge-std/Test.sol";
5 | import {FP_CoolNFT} from "../../src/FP_CoolNFT.sol";
6 | import {FP_DAO} from "../../src/FP_DAO.sol";
7 | import {FP_PowersellerNFT} from "../../src/FP_PowersellerNFT.sol";
8 | import {FP_Shop} from "../../src/FP_Shop.sol";
9 | import {FP_Token} from "../../src/FP_Token.sol";
10 | import {FP_Vault} from "../../src/FP_Vault.sol";
11 | import {FP_Proxy} from "../../src/FP_Proxy.sol";
12 | import {DeployFaillapop} from "../../script/DeployFaillapop.s.sol";
13 |
14 | contract FP_Vault_Test is Test {
15 | address public constant SELLER1 = address(bytes20("SELLER1"));
16 | address public constant SELLER2 = address(bytes20("SELLER2"));
17 | address public constant USER1 = address(bytes20("USER1"));
18 | address public constant BUYER1 = address(bytes20("BUYER1"));
19 |
20 | address public deployer;
21 | FP_Shop public shop;
22 | FP_Vault public vault;
23 | FP_DAO public dao;
24 | FP_Token public token;
25 | FP_CoolNFT public coolNFT;
26 | FP_PowersellerNFT public powersellerNFT;
27 | FP_Proxy public proxy;
28 |
29 | /************************************* Modifiers *************************************/
30 |
31 | modifier doStake(address user, uint256 amount) {
32 | vm.prank(user);
33 | vault.doStake{value: amount}();
34 | _;
35 | }
36 |
37 | modifier doLock(address user, uint256 amount) {
38 | vm.prank(address(proxy));
39 | vault.doLock(user, amount);
40 | _;
41 | }
42 |
43 | /************************************** Set Up **************************************/
44 |
45 | function setUp() external {
46 | vm.deal(USER1, 15 ether);
47 | vm.deal(SELLER1, 15 ether);
48 | vm.deal(SELLER2, 15 ether);
49 | vm.deal(BUYER1, 15 ether);
50 |
51 | DeployFaillapop deploy = new DeployFaillapop();
52 | (shop, token, coolNFT, powersellerNFT, dao, vault, proxy) = deploy.run();
53 | deployer = deploy.deployer();
54 | }
55 |
56 | /************************************** Tests **************************************/
57 |
58 | function test_setShop() public view {
59 | assertTrue(vault.hasRole(keccak256("CONTROL_ROLE"), address(proxy)));
60 | }
61 |
62 | function test_setShop_x2() public {
63 | vm.prank(address(proxy));
64 | vm.expectRevert("Shop address already set");
65 | vault.setShop(address(proxy));
66 | }
67 |
68 | function test_doStake() public {
69 | uint256 userStakeBefore = vault.userBalance(USER1);
70 | uint256 vaultBalanceBefore = vault.vaultBalance();
71 |
72 | vm.prank(USER1);
73 | vault.doStake{value: 2 ether}();
74 |
75 | assertEq(vault.userBalance(USER1), userStakeBefore + 2 ether);
76 | assertEq(vault.vaultBalance(), vaultBalanceBefore + 2 ether);
77 | assertEq(vault.userLockedBalance(USER1), 0);
78 | }
79 |
80 | function test_doStake_RevertIf_ValueIsZero() public {
81 | vm.prank(USER1);
82 | vm.expectRevert("Amount cannot be zero");
83 | vault.doStake{value: 0}();
84 | }
85 |
86 | function test_doUnstake() public doStake(USER1, 2 ether) {
87 | uint256 userStakeBefore = vault.userBalance(USER1);
88 | uint256 userBalanceBefore = address(USER1).balance;
89 | uint256 vaultBalanceBefore = vault.vaultBalance();
90 |
91 | vm.prank(USER1);
92 | vault.doUnstake(1 ether);
93 |
94 | assertEq(vault.userBalance(USER1), userStakeBefore - 1 ether);
95 | assertEq(address(USER1).balance, userBalanceBefore + 1 ether);
96 | assertEq(vault.vaultBalance(), vaultBalanceBefore - 1 ether);
97 | assertEq(vault.userLockedBalance(USER1), 0);
98 | }
99 |
100 | function test_doUnstake_RevertIf_AmountIsZero() public doStake(USER1, 2 ether) {
101 | vm.prank(USER1);
102 | vm.expectRevert("Amount cannot be zero");
103 | vault.doUnstake(0);
104 | }
105 |
106 | function test_doUnstake_RevertIf_AmountIsGreaterThanStake() public doStake(USER1, 2 ether) {
107 | vm.prank(USER1);
108 | vm.expectRevert();
109 | vault.doUnstake(3 ether);
110 | }
111 |
112 | function test_doLock() public doStake(USER1, 2 ether) {
113 | uint256 userStakeBefore = vault.userBalance(USER1);
114 | uint256 userLockedBefore = vault.userLockedBalance(USER1);
115 | uint256 vaultBalanceBefore = vault.vaultBalance();
116 |
117 | vm.prank(address(proxy));
118 | vault.doLock(USER1, 1 ether);
119 |
120 | assertEq(vault.userBalance(USER1), userStakeBefore);
121 | assertEq(vault.userLockedBalance(USER1), userLockedBefore + 1 ether);
122 | assertEq(vault.vaultBalance(), vaultBalanceBefore);
123 | }
124 |
125 | function test_doLock_RevertIf_CallerIsNotTheShop() public doStake(USER1, 2 ether) {
126 | vm.prank(USER1);
127 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER1), keccak256("CONTROL_ROLE")));
128 | vault.doLock(USER1, 1 ether);
129 | }
130 |
131 | function test_doLock_RevertIf_AmountIsZero() public doStake(USER1, 2 ether) {
132 | vm.prank(address(proxy));
133 | vm.expectRevert("Amount cannot be zero");
134 | vault.doLock(USER1, 0 ether);
135 | }
136 |
137 | function test_doLock_RevertIf_AmountIsGreaterThanStake() public doStake(USER1, 2 ether) {
138 | vm.prank(address(proxy));
139 | vm.expectRevert();
140 | vault.doLock(USER1, 3 ether);
141 | }
142 |
143 | function test_doUnlock() public doStake(USER1, 2 ether) doLock(USER1, 1 ether) {
144 | uint256 userStakeBefore = vault.userBalance(USER1);
145 | uint256 userLockedBefore = vault.userLockedBalance(USER1);
146 | uint256 vaultBalanceBefore = vault.vaultBalance();
147 |
148 | vm.prank(address(proxy));
149 | vault.doUnlock(USER1, 1 ether);
150 |
151 | assertEq(vault.userBalance(USER1), userStakeBefore);
152 | assertEq(vault.userLockedBalance(USER1), userLockedBefore - 1 ether);
153 | assertEq(vault.vaultBalance(), vaultBalanceBefore);
154 | }
155 |
156 | function test_doUnlock_RevertIf_CallerIsNotTheShop() public doStake(USER1, 2 ether) doLock(USER1, 1 ether) {
157 | vm.prank(USER1);
158 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER1), keccak256("CONTROL_ROLE")));
159 | vault.doUnlock(USER1, 1 ether);
160 | }
161 |
162 | function test_doUnlock_RevertIf_AmountIsZero() public doStake(USER1, 2 ether) doLock(USER1, 1 ether) {
163 | vm.prank(address(proxy));
164 | vm.expectRevert("Amount cannot be zero");
165 | vault.doUnlock(USER1, 0 ether);
166 | }
167 |
168 | function test_doUnlock_RevertIf_AmountIsGreaterThanLocked() public doStake(USER1, 2 ether) doLock(USER1, 1 ether) {
169 | vm.prank(address(proxy));
170 | vm.expectRevert("Not enough locked funds");
171 | vault.doUnlock(USER1, 3 ether);
172 | }
173 |
174 | function test_doSlash() public doStake(USER1, 2 ether) doLock(USER1, 1 ether) {
175 | uint256 totalSlashedBefore = vault.totalSlashed();
176 | uint256 userStakeBefore = vault.userBalance(USER1);
177 | uint256 vaultBalanceBefore = vault.vaultBalance();
178 |
179 | vm.prank(address(proxy));
180 | vault.doSlash(USER1);
181 |
182 | assertEq(vault.userBalance(USER1), 0);
183 | assertEq(vault.userLockedBalance(USER1), 0);
184 | assertEq(vault.totalSlashed(), totalSlashedBefore + userStakeBefore);
185 | assertEq(vault.vaultBalance(), vaultBalanceBefore);
186 | }
187 |
188 | function test_doSlash_RevertIf_CallerIsNotTheShop() public doStake(USER1, 2 ether) doLock(USER1, 1 ether) {
189 | vm.prank(USER1);
190 | vm.expectRevert(abi.encodeWithSignature("AccessControlUnauthorizedAccount(address,bytes32)", address(USER1), keccak256("CONTROL_ROLE")));
191 | vault.doSlash(USER1);
192 | }
193 |
194 |
195 | function test_claimRewards() public {
196 | // Create a powerseller
197 | //Lets recreate 10 valid sales
198 | vm.prank(SELLER1);
199 | vault.doStake{value: 10 ether}();
200 | for(uint i = 0; i < 10; i++) {
201 | // New sale
202 | string memory title = "Test Item";
203 | string memory description = "This is a test item";
204 | uint256 price = 0.5 ether;
205 |
206 | vm.prank(SELLER1);
207 | (bool success, ) = address(proxy).call(
208 | abi.encodeWithSignature(
209 | "newSale(string,string,uint256)",
210 | title,
211 | description,
212 | price
213 | )
214 | );
215 | require(success, "Sale not created");
216 |
217 | (bool success2, bytes memory data) = address(proxy).call(
218 | abi.encodeWithSignature(
219 | "offerIndex()"
220 | )
221 | );
222 | require(success2, "Offer index not retrieved");
223 | uint256 saleId = abi.decode(data, (uint256)) - 1;
224 |
225 | vm.startPrank(BUYER1);
226 | (bool success3, ) = address(proxy).call{value: 0.5 ether}(
227 | abi.encodeWithSignature(
228 | "doBuy(uint256)",
229 | saleId
230 | )
231 | );
232 | require(success3, "Sale not bought");
233 | (bool success4, ) = address(proxy).call(
234 | abi.encodeWithSignature(
235 | "itemReceived(uint256)",
236 | saleId
237 | )
238 | );
239 | require(success4, "Item not received");
240 | vm.stopPrank();
241 | }
242 |
243 | vm.prank(SELLER1);
244 | vm.warp(block.timestamp + 6 weeks);
245 | (bool success5, ) = address(proxy).call(
246 | abi.encodeWithSignature(
247 | "claimPowersellerBadge()"
248 | )
249 | );
250 | require(success5, "Powerseller badge not claimed");
251 |
252 | assertEq(powersellerNFT.balanceOf(SELLER1), 1, "Seller should not have the badge yet");
253 | assertTrue(powersellerNFT.checkPrivilege(SELLER1), "Powerseller badge not minted correctly");
254 |
255 | //Create malicious sale
256 | vm.prank(SELLER2);
257 | vault.doStake{value: 10 ether}();
258 | vm.prank(SELLER2);
259 | (bool success6, ) = address(proxy).call(
260 | abi.encodeWithSignature(
261 | "newSale(string,string,uint256)",
262 | "Sale",
263 | "This is a malicious sale",
264 | 0.5 ether
265 | )
266 | );
267 | require(success6, "Malicious sale not created");
268 |
269 | // Remove malicious sale
270 | (bool success7, bytes memory data2) = address(proxy).call(
271 | abi.encodeWithSignature(
272 | "offerIndex()"
273 | )
274 | );
275 | require(success7, "Offer index not retrieved");
276 | uint256 maliciousSaleId = abi.decode(data2, (uint256)) - 1;
277 | vm.prank(deployer);
278 | (bool success8, ) = address(proxy).call(
279 | abi.encodeWithSignature(
280 | "removeMaliciousSale(uint256)",
281 | maliciousSaleId
282 | )
283 | );
284 | require(success8, "Malicious sale not removed");
285 |
286 | vm.prank(SELLER1);
287 | vault.claimRewards();
288 |
289 | assertEq(vault.rewardsClaimed(SELLER1), vault.maxClaimableAmount(), "Seller should have claimed the max amount");
290 | }
291 | }
--------------------------------------------------------------------------------