diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..67c16cc
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,32 @@
+# NETWORK AND ACCOUNT(s)
+DEPLOYMENT_PRIVATE_KEY="0x..."
+REFUND_ADDRESS="0x..."
+
+# The name of the networks to use for test/production
+TESTNET_NETWORK="holesky"
+PRODNET_NETWORK="mainnet"
+
+# The RPC of the networks to use for test/production
+TESTNET_RPC_URL="https://holesky.drpc.org"
+PRODNET_RPC_URL="https://eth.drpc.org"
+
+# API Keys (optional)
+# Note that having these active will slow down unit tests even when not needed
+# So recommended to only activate when needed
+ALCHEMY_API_KEY="..."
+ETHERSCAN_API_KEY="..."
+
+# Plugin ENS Subdomain to deploy under (per-network)
+ENS_DOMAIN="lock-to-vote-dev-1"
+
+# OSx BASE CONTRACT ADDRESSES (network dependent, see active_contracts.json on lib/osx)
+
+# HOLESKY
+PLUGIN_REPO_FACTORY="0x95D563382BeD5AcB458759EE05b27DF2CB019Cc7"
+GOVERNANCE_ERC20_BASE="0xC24188a73dc09aA7C721f96Ad8857B469C01dC9f"
+GOVERNANCE_WRAPPED_ERC20_BASE="0x7a62da7B56fB3bfCdF70E900787010Bc4c9Ca42e"
+
+# # SEPOLIA
+# PLUGIN_REPO_FACTORY="0x07f49c49Ce2A99CF7C28F66673d406386BDD8Ff4"
+# GOVERNANCE_ERC20_BASE="0xA03C2182af8eC460D498108C92E8638a580b94d4"
+# GOVERNANCE_WRAPPED_ERC20_BASE="0x6E924eA5864044D8642385683fFA5AD42FB687f2"
diff --git a/.gitignore b/.gitignore
index 85198aa..86e0b4f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,3 +12,15 @@ docs/
# Dotenv file
.env
+
+# Development
+.DS_Store
+lcov.info
+report
+*.tree
+
+# Deployment
+logs/*
+
+# Draw.io backup files
+*.drawio.bkp
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000..da30228
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,660 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ Copyright (C) 2024 Aragon X
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..46f6319
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,201 @@
+.DEFAULT_TARGET: help
+
+# Import the .env files and export their values (ignore any error if missing)
+-include .env
+
+# RULE SPECIFIC ENV VARS [optional]
+
+# Override the verifier and block explorer parameters (network dependent)
+deploy-testnet: export ETHERSCAN_API_KEY_PARAM = --etherscan-api-key $(ETHERSCAN_API_KEY)
+deploy-prodnet: export ETHERSCAN_API_KEY_PARAM = --etherscan-api-key $(ETHERSCAN_API_KEY)
+# deploy-testnet: export VERIFIER_TYPE_PARAM = --verifier blockscout
+# deploy-testnet: export VERIFIER_URL_PARAM = --verifier-url "https://server/api\?"
+
+# CONSTANTS
+
+TEST_COVERAGE_SRC_FILES:=$(wildcard test/*.sol test/**/*.sol script/*.sol script/**/*.sol src/escrow/increasing/delegation/*.sol src/libs/ProxyLib.sol)
+DEPLOY_SCRIPT:=script/Deploy.s.sol:Deploy
+VERBOSITY:=-vvv
+SHELL:=/bin/bash
+
+SOLIDITY_VERSION=0.8.17
+TEST_TREE_MARKDOWN=TEST_TREE.md
+SOURCE_FILES=$(wildcard test/*.t.yaml test/integration/*.t.yaml)
+TREE_FILES = $(SOURCE_FILES:.t.yaml=.tree)
+TARGET_TEST_FILES = $(SOURCE_FILES:.tree=.t.sol)
+MAKE_TEST_TREE=deno run ./test/script/make-test-tree.ts
+MAKEFILE=Makefile
+
+# TARGETS
+
+.PHONY: help
+help:
+ @echo "Available targets:"
+ @grep -E '^[a-zA-Z0-9_-]*:.*?## .*$$' Makefile \
+ | sed -n 's/^\(.*\): \(.*\)##\(.*\)/- make \1 \3/p' \
+ | sed 's/^- make $$//g'
+
+: ##
+
+.PHONY: init
+init: .env ## Check the dependencies and prompt to install if needed
+ @which deno > /dev/null && echo "Deno is available" || echo "Install Deno: curl -fsSL https://deno.land/install.sh | sh"
+ @which bulloak > /dev/null && echo "bulloak is available" || echo "Install bulloak: cargo install bulloak"
+
+ @which forge > /dev/null || curl -L https://foundry.paradigm.xyz | bash
+ @forge build
+ @which lcov > /dev/null || echo "Note: lcov can be installed by running 'sudo apt install lcov'"
+
+.PHONY: clean
+clean: ## Clean the build artifacts
+ rm -f $(TREE_FILES)
+ rm -f $(TEST_TREE_MARKDOWN)
+ rm -Rf ./out/* lcov.info* ./report/*
+
+: ##
+
+.PHONY: test
+test: ## Run unit tests, locally
+ forge test $(VERBOSITY)
+# forge test --no-match-path $(FORK_TEST_WILDCARD) $(VERBOSITY)
+
+test-coverage: report/index.html ## Generate an HTML coverage report under ./report
+ @which open > /dev/null && open report/index.html || echo -n
+ @which xdg-open > /dev/null && xdg-open report/index.html || echo -n
+
+report/index.html: lcov.info.pruned
+ genhtml $^ -o report --branch-coverage
+
+lcov.info.pruned: lcov.info
+ lcov --remove $< -o ./$@ $^
+
+lcov.info: $(TEST_COVERAGE_SRC_FILES)
+ forge coverage --report lcov
+# forge coverage --no-match-path $(FORK_TEST_WILDCARD) --report lcov
+
+: ##
+
+sync-tests: $(TREE_FILES) ## Scaffold or sync tree files into solidity tests
+ @for file in $^; do \
+ if [ ! -f $${file%.tree}.t.sol ]; then \
+ echo "[Scaffold] $${file%.tree}.t.sol" ; \
+ bulloak scaffold -s $(SOLIDITY_VERSION) --vm-skip -w $$file ; \
+ else \
+ echo "[Sync file] $${file%.tree}.t.sol" ; \
+ bulloak check --fix $$file ; \
+ fi \
+ done
+
+check-tests: $(TREE_FILES) ## Checks if solidity files are out of sync
+ bulloak check $^
+
+markdown-tests: $(TEST_TREE_MARKDOWN) ## Generates a markdown file with the test definitions rendered as a tree
+
+# Internal targets
+
+# Generate a markdown file with the test trees
+$(TEST_TREE_MARKDOWN): $(TREE_FILES)
+ @echo "[Markdown] TEST_TREE.md"
+ @echo "# Test tree definitions" > $@
+ @echo "" >> $@
+ @echo "Below is the graphical definition of the contract tests implemented on [the test folder](./test)" >> $@
+ @echo "" >> $@
+
+ @for file in $^; do \
+ echo "\`\`\`" >> $@ ; \
+ cat $$file >> $@ ; \
+ echo "\`\`\`" >> $@ ; \
+ echo "" >> $@ ; \
+ done
+
+# Internal dependencies and transformations
+
+$(TREE_FILES): $(SOURCE_FILES)
+
+%.tree: %.t.yaml
+ @for file in $^; do \
+ echo "[Convert] $$file -> $${file%.t.yaml}.tree" ; \
+ cat $$file | $(MAKE_TEST_TREE) > $${file%.t.yaml}.tree ; \
+ done
+
+# Copy the .env files if not present
+.env:
+ cp .env.example .env
+ @echo "NOTE: Edit the correct values of .env before you continue"
+
+: ##
+
+#### Deployment targets ####
+
+pre-deploy-testnet: export RPC_URL = $(TESTNET_RPC_URL)
+pre-deploy-testnet: export NETWORK = $(TESTNET_NETWORK)
+pre-deploy-prodnet: export RPC_URL = $(PRODNET_RPC_URL)
+pre-deploy-prodnet: export NETWORK = $(PRODNET_NETWORK)
+
+pre-deploy-testnet: pre-deploy ## Simulate a deployment to the testnet
+pre-deploy-prodnet: pre-deploy ## Simulate a deployment to the production network
+
+: ##
+
+deploy-testnet: export RPC_URL = $(TESTNET_RPC_URL)
+deploy-testnet: export NETWORK = $(TESTNET_NETWORK)
+deploy-prodnet: export RPC_URL = $(PRODNET_RPC_URL)
+deploy-prodnet: export NETWORK = $(PRODNET_NETWORK)
+
+deploy-testnet: export DEPLOYMENT_LOG_FILE=./deployment-$(TESTNET_NETWORK)-$(shell date +"%y-%m-%d-%H-%M").log
+deploy-prodnet: export DEPLOYMENT_LOG_FILE=./deployment-$(PRODNET_NETWORK)-$(shell date +"%y-%m-%d-%H-%M").log
+
+deploy-testnet: deploy ## Deploy to the testnet and verify
+deploy-prodnet: deploy ## Deploy to the production network and verify
+
+.PHONY: pre-deploy
+pre-deploy:
+ @echo "Simulating the deployment"
+ forge script $(DEPLOY_SCRIPT) \
+ --chain $(NETWORK) \
+ --rpc-url $(RPC_URL) \
+ $(VERBOSITY)
+
+.PHONY: deploy
+deploy: test
+ @echo "Starting the deployment"
+ @mkdir -p logs/
+ forge script $(DEPLOY_SCRIPT) \
+ --chain $(NETWORK) \
+ --rpc-url $(RPC_URL) \
+ --broadcast \
+ --verify \
+ $(VERIFIER_TYPE_PARAM) \
+ $(VERIFIER_URL_PARAM) \
+ $(ETHERSCAN_API_KEY_PARAM) \
+ $(VERBOSITY) | tee logs/$(DEPLOYMENT_LOG_FILE)
+
+: ##
+
+refund: export DEPLOYMENT_ADDRESS = $(shell cast wallet address --private-key $(DEPLOYMENT_PRIVATE_KEY))
+
+.PHONY: refund
+refund: ## Refund the balance left on the deployment account
+ @echo "Refunding the remaining balance on $(DEPLOYMENT_ADDRESS)"
+ @if [ -z $(REFUND_ADDRESS) -o $(REFUND_ADDRESS) = "0x0000000000000000000000000000000000000000" ]; then \
+ echo "- The refund address is empty" ; \
+ exit 1; \
+ fi
+ @BALANCE=$(shell cast balance $(DEPLOYMENT_ADDRESS) --rpc-url $(PRODNET_RPC_URL)) && \
+ GAS_PRICE=$(shell cast gas-price --rpc-url $(PRODNET_RPC_URL)) && \
+ REMAINING=$$(echo "$$BALANCE - $$GAS_PRICE * 21000" | bc) && \
+ \
+ ENOUGH_BALANCE=$$(echo "$$REMAINING > 0" | bc) && \
+ if [ "$$ENOUGH_BALANCE" = "0" ]; then \
+ echo -e "- No balance can be refunded: $$BALANCE wei\n- Minimum balance: $${REMAINING:1} wei" ; \
+ exit 1; \
+ fi ; \
+ echo -n -e "Summary:\n- Refunding: $$REMAINING (wei)\n- Recipient: $(REFUND_ADDRESS)\n\nContinue? (y/N) " && \
+ \
+ read CONFIRM && \
+ if [ "$$CONFIRM" != "y" ]; then echo "Aborting" ; exit 1; fi ; \
+ \
+ cast send --private-key $(DEPLOYMENT_PRIVATE_KEY) \
+ --rpc-url $(PRODNET_RPC_URL) \
+ --value $$REMAINING \
+ $(REFUND_ADDRESS)
diff --git a/README.md b/README.md
index 9265b45..d99ade8 100644
--- a/README.md
+++ b/README.md
@@ -1,66 +1,217 @@
-## Foundry
+# Lock to Vote Plugin - OSx
-**Foundry is a blazing fast, portable and modular toolkit for Ethereum application development written in Rust.**
+This reposity contains the codebase of the Lock to Vote plugin, along with its helper contract.
-Foundry consists of:
+## Overview
-- **Forge**: Ethereum testing framework (like Truffle, Hardhat and DappTools).
-- **Cast**: Swiss army knife for interacting with EVM smart contracts, sending transactions and getting chain data.
-- **Anvil**: Local Ethereum node, akin to Ganache, Hardhat Network.
-- **Chisel**: Fast, utilitarian, and verbose solidity REPL.
+This is a work in progress
-## Documentation
+## Get Started
-https://book.getfoundry.sh/
+To get started, ensure that [Foundry](https://getfoundry.sh/) and [Make](https://www.gnu.org/software/make/) are installed on your computer.
-## Usage
+### Using the Makefile
-### Build
+The `Makefile` is the target launcher of the project. It's the recommended way to work with it. It manages the env variables of common tasks and executes only the steps that need to be run.
-```shell
-$ forge build
```
+$ make
+Available targets:
-### Test
+- make init Check the dependencies and prompt to install if needed
+- make clean Clean the build artifacts
-```shell
-$ forge test
+- make test Run unit tests, locally
+- make test-coverage Generate an HTML coverage report under ./report
+
+- make sync-tests Scaffold or sync tree files into solidity tests
+- make check-tests Checks if solidity files are out of sync
+- make markdown-tests Generates a markdown file with the test definitions rendered as a tree
+
+- make pre-deploy-testnet Simulate a deployment to the testnet
+- make pre-deploy-prodnet Simulate a deployment to the production network
+
+- make deploy-testnet Deploy to the testnet and verify
+- make deploy-prodnet Deploy to the production network and verify
+
+- make refund Refund the remaining balance left on the deployment account
+```
+
+Run `make init`:
+- It ensures that Foundry is installed
+- It runs a first compilation of the project
+- It copies `.env.example` into `.env`
+
+Next, customize the values of `.env`.
+
+### Understanding `.env.example`
+
+The env.example file contains descriptions for all the initial settings. You don't need all of these right away but should review prior to fork tests and deployments
+
+### Deployment Checklist
+
+- [ ] I have cloned the official repository on my computer and I have checked out the corresponding branch
+- [ ] I am using the latest official docker engine, running a Debian Linux (stable) image
+ - [ ] I have run `docker run --rm -it -v .:/deployment debian:bookworm-slim`
+ - [ ] I have run `apt update && apt install -y make curl git vim neovim bc`
+ - [ ] I have run `curl -L https://foundry.paradigm.xyz | bash`
+ - [ ] I have run `source /root/.bashrc && foundryup`
+ - [ ] I have run `cd /deployment`
+ - [ ] I have run `make init`
+ - [ ] I have printed the contents of `.env` on the screen
+- [ ] I am opening an editor on the `/deployment` folder, within the Docker container
+- [ ] The `.env` file contains the correct parameters for the deployment
+ - [ ] I have created a brand new burner wallet with `cast wallet new` and copied the private key to `DEPLOYMENT_PRIVATE_KEY` within `.env`
+ - [ ] I have reviewed the target network and RPC URL
+ - The plugin ENS subdomain
+ - [ ] Contains a meaningful and unique value
+ - The given OSx addresses:
+ - [ ] Exist on the target network
+ - [ ] Contain the latest stable official version of the OSx DAO implementation, the Plugin Setup Processor and the Plugin Repo Factory
+ - [ ] I have verified the values on https://www.npmjs.com/package/@aragon/osx-commons-configs?activeTab=code > `/@aragon/osx-commons-configs/dist/deployments/json/`
+- [ ] All the unit tests pass (`make test`)
+- **Target test network**
+ - [ ] I have run a preview deployment on the testnet
+ - `make pre-deploy-testnet`
+ - [ ] I have deployed my contracts successfully to the target testnet
+ - `make deploy-testnet`
+ - [ ] I have tested that these contracts work successfully
+- [ ] My deployment wallet is a newly created account, ready for safe production deploys.
+- My computer:
+ - [ ] Is running in a safe physical location and a trusted network
+ - [ ] It exposes no services or ports
+ - [ ] The wifi or wired network used does does not have open ports to a WAN
+- [ ] I have previewed my deploy without any errors
+ - `make pre-deploy-prodnet`
+- [ ] The deployment wallet has sufficient native token for gas
+ - At least, 15% more than the estimated simulation
+- [ ] Unit tests still run clean
+- [ ] I have run `git status` and it reports no local changes
+- [ ] The current local git branch (`main`) corresponds to its counterpart on `origin`
+ - [ ] I confirm that the rest of members of the ceremony pulled the last commit of my branch and reported the same commit hash as my output for `git log -n 1`
+- [ ] I have initiated the production deployment with `make deploy-prodnet`
+
+### Post deployment checklist
+
+- [ ] The deployment process completed with no errors
+- [ ] The deployed factory was deployed by the deployment address
+- [ ] The reported contracts have been created created by the newly deployed factory
+- [ ] The smart contracts are correctly verified on Etherscan or the corresponding block explorer
+- [ ] The output of the latest `deployment-*.log` file corresponds to the console output
+- [ ] I have transferred the remaining funds of the deployment wallet to the address that originally funded it
+ - `make refund`
+
+## Manual deployment (CLI)
+
+You can of course run all commands from the command line:
+
+```sh
+# Load the env vars
+source .env
```
-### Format
+```sh
+# run unit tests
+forge test --no-match-path "test/fork/**/*.sol"
+```
+
+```sh
+# Set the right RPC URL
+RPC_URL="https://eth-sepolia.g.alchemy.com/v2/${ALCHEMY_API_KEY}"
+```
+
+```sh
+# Run the deployment script
+
+# If using Etherscan
+forge script --chain "$NETWORK" script/Deploy.s.sol:Deploy --rpc-url "$RPC_URL" --broadcast --verify
-```shell
-$ forge fmt
+# If using BlockScout
+forge script --chain "$NETWORK" script/Deploy.s.sol:Deploy --rpc-url "$RPC_URL" --broadcast --verify --verifier blockscout --verifier-url "https://sepolia.explorer.mode.network/api\?"
```
-### Gas Snapshots
+If you get the error Failed to get EIP-1559 fees, add `--legacy` to the command:
-```shell
-$ forge snapshot
+```sh
+forge script --chain "$NETWORK" script/Deploy.s.sol:Deploy --rpc-url "$RPC_URL" --broadcast --verify --legacy
```
-### Anvil
+If some contracts fail to verify on Etherscan, retry with this command:
-```shell
-$ anvil
+```sh
+forge script --chain "$NETWORK" script/Deploy.s.sol:Deploy --rpc-url "$RPC_URL" --verify --legacy --private-key "$DEPLOYMENT_PRIVATE_KEY" --resume
```
-### Deploy
+## Testing
-```shell
-$ forge script script/Counter.s.sol:CounterScript --rpc-url --private-key
+See the [test tree](./TEST_TREE.md) file for a visual representation of the implemented tests.
+
+Tests can be described using yaml files. They will be automatically transformed into solidity test files with [bulloak](https://github.com/alexfertel/bulloak).
+
+Create a file with `.t.yaml` extension within the `test` folder and describe a hierarchy of test cases:
+
+```yaml
+# MyPluginTest.t.yaml
+
+MyPluginTest:
+- given: proposal exists
+ comment: Comment here
+ and:
+ - given: proposal is in the last stage
+ and:
+
+ - when: proposal can advance
+ then:
+ - it: Should return true
+
+ - when: proposal cannot advance
+ then:
+ - it: Should return false
+
+ - when: proposal is not in the last stage
+ then:
+ - it: should do A
+ comment: This is an important remark
+ - it: should do B
+ - it: should do C
+
+- when: proposal doesn't exist
+ comment: Testing edge cases here
+ then:
+ - it: should revert
```
-### Cast
+Then use `make` to automatically sync the described branches into solidity test files.
+
+```sh
+$ make
+Available targets:
+# ...
+- make sync-tests Scaffold or sync tree files into solidity tests
+- make check-tests Checks if solidity files are out of sync
+- make markdown-tests Generates a markdown file with the test definitions rendered as a tree
-```shell
-$ cast
+$ make sync-tests
```
-### Help
+The final output will look like a human readable tree:
-```shell
-$ forge --help
-$ anvil --help
-$ cast --help
```
+# MyPluginTest.tree
+
+MyPluginTest
+├── Given proposal exists // Comment here
+│ ├── Given proposal is in the last stage
+│ │ ├── When proposal can advance
+│ │ │ └── It Should return true
+│ │ └── When proposal cannot advance
+│ │ └── It Should return false
+│ └── When proposal is not in the last stage
+│ ├── It should do A // Careful here
+│ ├── It should do B
+│ └── It should do C
+└── When proposal doesn't exist // Testing edge cases here
+ └── It should revert
+```
+
+And the given tree file will be used by bulloak to produce test file templates where tests can be addeed to.
diff --git a/foundry.toml b/foundry.toml
index 25b918f..e61bc34 100644
--- a/foundry.toml
+++ b/foundry.toml
@@ -2,5 +2,9 @@
src = "src"
out = "out"
libs = ["lib"]
-
-# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options
+fs_permissions = [{ access = "read", path = "./script" }]
+# evm_version = "cancun"
+optimizer = true
+optimizer-runs = 200
+solc = "0.8.17"
+via_ir = false
diff --git a/remappings.txt b/remappings.txt
new file mode 100644
index 0000000..926df45
--- /dev/null
+++ b/remappings.txt
@@ -0,0 +1,5 @@
+@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/
+@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/
+@aragon/osx/=lib/osx/packages/contracts/src/
+@ensdomains/ens-contracts/=lib/ens-contracts/
+forge-std/=lib/forge-std/src/
diff --git a/script/Counter.s.sol b/script/Counter.s.sol
deleted file mode 100644
index cdc1fe9..0000000
--- a/script/Counter.s.sol
+++ /dev/null
@@ -1,19 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-pragma solidity ^0.8.13;
-
-import {Script, console} from "forge-std/Script.sol";
-import {Counter} from "../src/Counter.sol";
-
-contract CounterScript is Script {
- Counter public counter;
-
- function setUp() public {}
-
- function run() public {
- vm.startBroadcast();
-
- counter = new Counter();
-
- vm.stopBroadcast();
- }
-}
diff --git a/script/Deploy.s.sol b/script/Deploy.s.sol
new file mode 100644
index 0000000..5b3028c
--- /dev/null
+++ b/script/Deploy.s.sol
@@ -0,0 +1,204 @@
+// SPDX-License-Identifier: UNLICENSED
+pragma solidity ^0.8.17;
+
+import {Script, console} from "forge-std/Script.sol";
+import {DAO} from "@aragon/osx/core/dao/DAO.sol";
+import {IVotesUpgradeable} from "@openzeppelin/contracts-upgradeable/governance/utils/IVotesUpgradeable.sol";
+import {GovernanceERC20} from "@aragon/osx/token/ERC20/governance/GovernanceERC20.sol";
+import {GovernanceWrappedERC20} from "@aragon/osx/token/ERC20/governance/GovernanceWrappedERC20.sol";
+import {LockToVotePluginSetup} from "../src/setup/LockToVotePluginSetup.sol";
+import {PluginRepoFactory} from "@aragon/osx/framework/plugin/repo/PluginRepoFactory.sol";
+import {PluginSetupProcessor} from "@aragon/osx/framework/plugin/setup/PluginSetupProcessor.sol";
+import {GovernanceERC20Mock} from "../test/mocks/GovernanceERC20Mock.sol";
+
+contract Deploy is Script {
+ LockToVotePluginSetup lockToVotePluginSetup;
+
+ modifier broadcast() {
+ uint256 privKey = vm.envUint("DEPLOYMENT_PRIVATE_KEY");
+ vm.startBroadcast(privKey);
+ console.log("Deploying from:", vm.addr(privKey));
+
+ _;
+
+ vm.stopBroadcast();
+ }
+
+ // function run() public broadcast {
+ // // Deploy the plugin setup's
+ // lockToVotePluginSetup = new LockToVotePluginSetup(
+ // GovernanceERC20(vm.envAddress("GOVERNANCE_ERC20_BASE")),
+ // GovernanceWrappedERC20(
+ // vm.envAddress("GOVERNANCE_WRAPPED_ERC20_BASE")
+ // )
+ // );
+
+ // console.log("Chain ID:", block.chainid);
+
+ // DeploymentSettings memory settings;
+ // if (vm.envOr("MINT_TEST_TOKENS", false)) {
+ // settings = getTestTokenSettings();
+ // } else {
+ // settings = getProductionSettings();
+ // }
+
+ // console.log("");
+
+ // // TODO: DEPLOY
+
+ // // Done
+ // printDeploymentSummary(factory, delegationWall);
+ // }
+
+ // function getProductionSettings()
+ // internal
+ // view
+ // returns (DeploymentSettings memory settings)
+ // {
+ // console.log("Using production settings");
+
+ // settings = DeploymentSettings({
+ // tokenAddress: IVotesUpgradeable(vm.envAddress("TOKEN_ADDRESS")),
+ // timelockPeriod: uint32(vm.envUint("TIME_LOCK_PERIOD")),
+ // l2InactivityPeriod: uint32(vm.envUint("L2_INACTIVITY_PERIOD")),
+ // l2AggregationGracePeriod: uint32(
+ // vm.envUint("L2_AGGREGATION_GRACE_PERIOD")
+ // ),
+ // skipL2: bool(vm.envBool("SKIP_L2")),
+ // // Voting settings
+ // minVetoRatio: uint32(vm.envUint("MIN_VETO_RATIO")),
+ // minStdProposalDuration: uint32(
+ // vm.envUint("MIN_STD_PROPOSAL_DURATION")
+ // ),
+ // minStdApprovals: uint16(vm.envUint("MIN_STD_APPROVALS")),
+ // minEmergencyApprovals: uint16(
+ // vm.envUint("MIN_EMERGENCY_APPROVALS")
+ // ),
+ // // OSx contracts
+ // osxDaoFactory: vm.envAddress("DAO_FACTORY"),
+ // pluginSetupProcessor: PluginSetupProcessor(
+ // vm.envAddress("PLUGIN_SETUP_PROCESSOR")
+ // ),
+ // pluginRepoFactory: PluginRepoFactory(
+ // vm.envAddress("PLUGIN_REPO_FACTORY")
+ // ),
+ // // Plugin setup's
+ // multisigPluginSetup: MultisigPluginSetup(multisigPluginSetup),
+ // emergencyMultisigPluginSetup: EmergencyMultisigPluginSetup(
+ // emergencyMultisigPluginSetup
+ // ),
+ // lockToVotePluginSetup: LockToVotePluginSetup(lockToVotePluginSetup),
+ // // Multisig members
+ // multisigMembers: readMultisigMembers(),
+ // multisigExpirationPeriod: uint32(
+ // vm.envUint("MULTISIG_PROPOSAL_EXPIRATION_PERIOD")
+ // ),
+ // // ENS
+ // stdMultisigEnsDomain: vm.envString("STD_MULTISIG_ENS_DOMAIN"),
+ // emergencyMultisigEnsDomain: vm.envString(
+ // "EMERGENCY_MULTISIG_ENS_DOMAIN"
+ // ),
+ // optimisticTokenVotingEnsDomain: vm.envString(
+ // "OPTIMISTIC_TOKEN_VOTING_ENS_DOMAIN"
+ // )
+ // });
+ // }
+
+ // function getTestTokenSettings()
+ // internal
+ // returns (DeploymentSettings memory settings)
+ // {
+ // console.log("Using test token settings");
+
+ // address[] memory multisigMembers = readMultisigMembers();
+ // address votingToken = createTestToken(
+ // multisigMembers
+ // );
+
+ // settings = DeploymentSettings({
+ // tokenAddress: IVotesUpgradeable(votingToken),
+ // timelockPeriod: uint32(vm.envUint("TIME_LOCK_PERIOD")),
+ // l2InactivityPeriod: uint32(vm.envUint("L2_INACTIVITY_PERIOD")),
+ // l2AggregationGracePeriod: uint32(
+ // vm.envUint("L2_AGGREGATION_GRACE_PERIOD")
+ // ),
+ // skipL2: bool(vm.envBool("SKIP_L2")),
+ // // Voting settings
+ // minVetoRatio: uint32(vm.envUint("MIN_VETO_RATIO")),
+ // minStdProposalDuration: uint32(
+ // vm.envUint("MIN_STD_PROPOSAL_DURATION")
+ // ),
+ // minStdApprovals: uint16(vm.envUint("MIN_STD_APPROVALS")),
+ // minEmergencyApprovals: uint16(
+ // vm.envUint("MIN_EMERGENCY_APPROVALS")
+ // ),
+ // // OSx contracts
+ // osxDaoFactory: vm.envAddress("DAO_FACTORY"),
+ // pluginSetupProcessor: PluginSetupProcessor(
+ // vm.envAddress("PLUGIN_SETUP_PROCESSOR")
+ // ),
+ // pluginRepoFactory: PluginRepoFactory(
+ // vm.envAddress("PLUGIN_REPO_FACTORY")
+ // ),
+ // // Plugin setup's
+ // multisigPluginSetup: MultisigPluginSetup(multisigPluginSetup),
+ // emergencyMultisigPluginSetup: EmergencyMultisigPluginSetup(
+ // emergencyMultisigPluginSetup
+ // ),
+ // lockToVotePluginSetup: LockToVotePluginSetup(lockToVotePluginSetup),
+ // // Multisig members
+ // multisigMembers: multisigMembers,
+ // multisigExpirationPeriod: uint32(
+ // vm.envUint("MULTISIG_PROPOSAL_EXPIRATION_PERIOD")
+ // ),
+ // // ENS
+ // stdMultisigEnsDomain: vm.envString("STD_MULTISIG_ENS_DOMAIN"),
+ // emergencyMultisigEnsDomain: vm.envString(
+ // "EMERGENCY_MULTISIG_ENS_DOMAIN"
+ // ),
+ // optimisticTokenVotingEnsDomain: vm.envString(
+ // "OPTIMISTIC_TOKEN_VOTING_ENS_DOMAIN"
+ // )
+ // });
+ // }
+
+ // function printDeploymentSummary(
+ // ) internal view {
+ // DeploymentSettings memory settings = factory.getSettings();
+ // Deployment memory daoDeployment = factory.getDeployment();
+
+ // console.log("Factory:", address(factory));
+ // console.log("");
+ // console.log("DAO:", address(daoDeployment.dao));
+ // console.log("Voting token:", address(settings.tokenAddress));
+ // console.log("");
+
+ // console.log("Plugins");
+ // console.log(
+ // "- Lock to vote plugin:",
+ // address(daoDeployment.multisigPlugin)
+ // );
+ // console.log("");
+
+ // console.log("Helpers");
+ // console.log("- Lock Manager", address(daoDeployment.signerList));
+
+ // console.log("");
+
+ // console.log("Plugin repositories");
+ // console.log(
+ // "- Lock to vote plugin repository:",
+ // address(daoDeployment.optimisticTokenVotingPluginRepo)
+ // );
+ // }
+
+ // function createTestToken(
+ // address[] memory members,
+ // ) internal returns (address) {
+ // GovernanceERC20Mock testToken = new GovernanceERC20Mock(address(0));
+ // console.log("Minting test tokens for the members");
+ // testToken.mintAndDelegate(members, 10 ether);
+
+ // return address(testToken);
+ // }
+}
diff --git a/src/Counter.sol b/src/Counter.sol
deleted file mode 100644
index aded799..0000000
--- a/src/Counter.sol
+++ /dev/null
@@ -1,14 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-pragma solidity ^0.8.13;
-
-contract Counter {
- uint256 public number;
-
- function setNumber(uint256 newNumber) public {
- number = newNumber;
- }
-
- function increment() public {
- number++;
- }
-}
diff --git a/src/LockManager.sol b/src/LockManager.sol
new file mode 100644
index 0000000..0447779
--- /dev/null
+++ b/src/LockManager.sol
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: UNLICENSED
+pragma solidity ^0.8.13;
+
+import {ILockManager} from "./interfaces/ILockManager.sol";
+
+contract LockManager is ILockManager {
+ struct PluginSettings {
+ uint64 proposlDuration;
+ }
+}
diff --git a/src/LockToVotePlugin.sol b/src/LockToVotePlugin.sol
new file mode 100644
index 0000000..5ad080c
--- /dev/null
+++ b/src/LockToVotePlugin.sol
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: UNLICENSED
+pragma solidity ^0.8.13;
+
+import {ILockToVotePlugin} from "./interfaces/ILockToVotePlugin.sol";
+
+contract LockToVotePlugin is ILockToVotePlugin {
+ struct PluginSettings {
+ uint64 proposlDuration;
+ }
+}
diff --git a/src/interfaces/ILockManager.sol b/src/interfaces/ILockManager.sol
new file mode 100644
index 0000000..60fb2ab
--- /dev/null
+++ b/src/interfaces/ILockManager.sol
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.17;
+
+/// @title ILockManager
+/// @author Aragon Association - 2024
+/// @notice
+interface ILockManager {
+
+}
diff --git a/src/interfaces/ILockToVotePlugin.sol b/src/interfaces/ILockToVotePlugin.sol
new file mode 100644
index 0000000..ff3df9a
--- /dev/null
+++ b/src/interfaces/ILockToVotePlugin.sol
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.17;
+
+import {IDAO} from "@aragon/osx/core/dao/IDAO.sol";
+
+/// @title ILockToVotePlugin
+/// @author Aragon Association - 2024
+/// @notice
+interface ILockToVotePlugin {
+
+}
diff --git a/src/setup/LockToVotePluginSetup.sol b/src/setup/LockToVotePluginSetup.sol
new file mode 100644
index 0000000..2d9670e
--- /dev/null
+++ b/src/setup/LockToVotePluginSetup.sol
@@ -0,0 +1,334 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.17;
+
+import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
+import {Address} from "@openzeppelin/contracts/utils/Address.sol";
+import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
+import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
+import {IVotesUpgradeable} from "@openzeppelin/contracts-upgradeable/governance/utils/IVotesUpgradeable.sol";
+
+import {IDAO} from "@aragon/osx/core/dao/IDAO.sol";
+import {DAO} from "@aragon/osx/core/dao/DAO.sol";
+import {PermissionLib} from "@aragon/osx/core/permission/PermissionLib.sol";
+import {PluginSetup, IPluginSetup} from "@aragon/osx/framework/plugin/setup/PluginSetup.sol";
+import {GovernanceERC20} from "@aragon/osx/token/ERC20/governance/GovernanceERC20.sol";
+import {GovernanceWrappedERC20} from "@aragon/osx/token/ERC20/governance/GovernanceWrappedERC20.sol";
+import {IGovernanceWrappedERC20} from "@aragon/osx/token/ERC20/governance/IGovernanceWrappedERC20.sol";
+import {LockToVotePlugin} from "../LockToVotePlugin.sol";
+import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
+
+/// @title LockToVotePluginSetup
+/// @author Aragon Association - 2022-2024
+/// @notice The setup contract of the `LockToVotePlugin` contract.
+/// @custom:security-contact sirt@aragon.org
+contract LockToVotePluginSetup { // is PluginSetup {
+ // using Address for address;
+ // using Clones for address;
+ // using ERC165Checker for address;
+ // /// @notice The address of the `LockToVotePlugin` base contract.
+ // LockToVotePlugin private immutable lockToVotePluginBase;
+ // /// @notice The address of the `GovernanceERC20` base contract.
+ // address public immutable governanceERC20Base;
+ // /// @notice The address of the `GovernanceWrappedERC20` base contract.
+ // address public immutable governanceWrappedERC20Base;
+ // /// @notice The token settings struct.
+ // /// @param addr The token address. If this is `address(0)`, a new `GovernanceERC20` token is deployed. If not, the existing token is wrapped as an `GovernanceWrappedERC20`.
+ // /// @param name The token name. This parameter is only relevant if the token address is `address(0)`.
+ // /// @param symbol The token symbol. This parameter is only relevant if the token address is `address(0)`.
+ // struct TokenSettings {
+ // address addr;
+ // string name;
+ // string symbol;
+ // }
+ // struct InstallationParameters {
+ // LockToVotePlugin.PluginSettings settings;
+ // TokenSettings tokenSettings;
+ // // only used for GovernanceERC20 (when token is not passed)
+ // GovernanceERC20.MintSettings mintSettings;
+ // uint64 stdProposalMinDuration;
+ // address stdProposer;
+ // address emergencyProposer;
+ // }
+ // /// @notice Thrown if token address is passed which is not a token.
+ // /// @param token The token address
+ // error TokenNotContract(address token);
+ // /// @notice Thrown if token address is not ERC20.
+ // /// @param token The token address
+ // error TokenNotERC20(address token);
+ // /// @notice Thrown if passed helpers array is of wrong length.
+ // /// @param length The array length of passed helpers.
+ // error WrongHelpersArrayLength(uint256 length);
+ // /// @notice The contract constructor deploying the plugin implementation contract and receiving the governance token base contracts to clone from.
+ // /// @param _governanceERC20Base The base `GovernanceERC20` contract to create clones from.
+ // /// @param _governanceWrappedERC20Base The base `GovernanceWrappedERC20` contract to create clones from.
+ // constructor(
+ // GovernanceERC20 _governanceERC20Base,
+ // GovernanceWrappedERC20 _governanceWrappedERC20Base
+ // ) {
+ // lockToVotePluginBase = new LockToVotePlugin();
+ // governanceERC20Base = address(_governanceERC20Base);
+ // governanceWrappedERC20Base = address(_governanceWrappedERC20Base);
+ // }
+ // /// @inheritdoc IPluginSetup
+ // function prepareInstallation(
+ // address _dao,
+ // bytes calldata _installParameters
+ // )
+ // external
+ // returns (address plugin, PreparedSetupData memory preparedSetupData)
+ // {
+ // // Decode `_installParameters` to extract the params needed for deploying and initializing `LockToVotePlugin` contract,
+ // // and the required helpers
+ // InstallationParameters
+ // memory installationParams = decodeInstallationParams(
+ // _installParameters
+ // );
+ // address token = installationParams.tokenSettings.addr;
+ // // Prepare helpers.
+ // address[] memory helpers = new address[](1);
+ // if (token != address(0x0)) {
+ // if (!token.isContract()) {
+ // revert TokenNotContract(token);
+ // } else if (!_supportsErc20(token)) {
+ // revert TokenNotERC20(token);
+ // }
+ // if (
+ // !_supportsIVotes(token) &&
+ // !_supportsIGovernanceWrappedERC20(token)
+ // ) {
+ // // Wrap the token
+ // token = governanceWrappedERC20Base.clone();
+ // // User already has a token. We need to wrap it in
+ // // GovernanceWrappedERC20 in order to make the token
+ // // include governance functionality.
+ // GovernanceWrappedERC20(token).initialize(
+ // IERC20Upgradeable(installationParams.tokenSettings.addr),
+ // installationParams.tokenSettings.name,
+ // installationParams.tokenSettings.symbol
+ // );
+ // }
+ // } else {
+ // // Create a brand new token
+ // token = governanceERC20Base.clone();
+ // GovernanceERC20(token).initialize(
+ // IDAO(_dao),
+ // installationParams.tokenSettings.name,
+ // installationParams.tokenSettings.symbol,
+ // installationParams.mintSettings
+ // );
+ // }
+ // helpers[0] = token;
+ // // Prepare and deploy plugin proxy.
+ // plugin = createERC1967Proxy(
+ // address(lockToVotePluginBase),
+ // abi.encodeCall(
+ // LockToVotePlugin.initialize,
+ // (
+ // IDAO(_dao),
+ // installationParams.settings,
+ // IVotesUpgradeable(token)
+ // )
+ // )
+ // );
+ // // Prepare permissions
+ // PermissionLib.MultiTargetPermission[]
+ // memory permissions = new PermissionLib.MultiTargetPermission[](
+ // installationParams.tokenSettings.addr != address(0) ? 5 : 6
+ // );
+ // // Request the permissions to be granted
+ // // The DAO can update the plugin settings
+ // permissions[0] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Grant,
+ // where: plugin,
+ // who: _dao,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: lockToVotePluginBase
+ // .UPDATE_OPTIMISTIC_GOVERNANCE_SETTINGS_PERMISSION_ID()
+ // });
+ // // The DAO can upgrade the plugin implementation
+ // permissions[1] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Grant,
+ // where: plugin,
+ // who: _dao,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: lockToVotePluginBase.UPGRADE_PLUGIN_PERMISSION_ID()
+ // });
+ // // The plugin can make the DAO execute actions
+ // permissions[2] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Grant,
+ // where: _dao,
+ // who: plugin,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: DAO(payable(_dao)).EXECUTE_PERMISSION_ID()
+ // });
+ // {
+ // // Deploy the Std proposal condition
+ // StandardProposalCondition stdProposalCondition = new StandardProposalCondition(
+ // address(_dao),
+ // installationParams.stdProposalMinDuration
+ // );
+ // // Proposer plugins can create proposals
+ // permissions[3] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Grant,
+ // where: plugin,
+ // who: installationParams.stdProposer,
+ // condition: address(stdProposalCondition),
+ // permissionId: lockToVotePluginBase.PROPOSER_PERMISSION_ID()
+ // });
+ // }
+ // permissions[4] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Grant,
+ // where: plugin,
+ // who: installationParams.emergencyProposer,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: lockToVotePluginBase.PROPOSER_PERMISSION_ID()
+ // });
+ // if (installationParams.tokenSettings.addr == address(0x0)) {
+ // // The DAO can mint ERC20 tokens
+ // permissions[5] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Grant,
+ // where: token,
+ // who: _dao,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: GovernanceERC20(token).MINT_PERMISSION_ID()
+ // });
+ // }
+ // preparedSetupData.helpers = helpers;
+ // preparedSetupData.permissions = permissions;
+ // }
+ // /// @inheritdoc IPluginSetup
+ // function prepareUninstallation(
+ // address _dao,
+ // SetupPayload calldata _payload
+ // )
+ // external
+ // view
+ // returns (PermissionLib.MultiTargetPermission[] memory permissions)
+ // {
+ // // Prepare permissions.
+ // uint256 helperLength = _payload.currentHelpers.length;
+ // if (helperLength != 1) {
+ // revert WrongHelpersArrayLength({length: helperLength});
+ // }
+ // // token can be either GovernanceERC20, GovernanceWrappedERC20, or IVotesUpgradeable, which
+ // // does not follow the GovernanceERC20 and GovernanceWrappedERC20 standard.
+ // address token = _payload.currentHelpers[0];
+ // bool isGovernanceERC20 = _supportsErc20(token) &&
+ // _supportsIVotes(token) &&
+ // !_supportsIGovernanceWrappedERC20(token);
+ // permissions = new PermissionLib.MultiTargetPermission[](
+ // isGovernanceERC20 ? 4 : 3
+ // );
+ // // Set permissions to be Revoked.
+ // permissions[0] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Revoke,
+ // where: _payload.plugin,
+ // who: _dao,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: lockToVotePluginBase
+ // .UPDATE_OPTIMISTIC_GOVERNANCE_SETTINGS_PERMISSION_ID()
+ // });
+ // permissions[1] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Revoke,
+ // where: _payload.plugin,
+ // who: _dao,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: lockToVotePluginBase.UPGRADE_PLUGIN_PERMISSION_ID()
+ // });
+ // permissions[2] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Revoke,
+ // where: _dao,
+ // who: _payload.plugin,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: DAO(payable(_dao)).EXECUTE_PERMISSION_ID()
+ // });
+ // // Note: It no longer matters if proposers can still create proposals
+ // // Revocation of permission is necessary only if the deployed token is GovernanceERC20,
+ // // as GovernanceWrapped does not possess this permission. Only return the following
+ // // if it's type of GovernanceERC20, otherwise revoking this permission wouldn't have any effect.
+ // if (isGovernanceERC20) {
+ // permissions[3] = PermissionLib.MultiTargetPermission({
+ // operation: PermissionLib.Operation.Revoke,
+ // where: token,
+ // who: _dao,
+ // condition: PermissionLib.NO_CONDITION,
+ // permissionId: GovernanceERC20(token).MINT_PERMISSION_ID()
+ // });
+ // }
+ // }
+ // /// @inheritdoc IPluginSetup
+ // function implementation() external view virtual override returns (address) {
+ // return address(lockToVotePluginBase);
+ // }
+ // /// @notice Encodes the given installation parameters into a byte array
+ // function encodeInstallationParams(
+ // InstallationParameters memory installationParams
+ // ) external pure returns (bytes memory) {
+ // return abi.encode(installationParams);
+ // }
+ // /// @notice Decodes the given byte array into the original installation parameters
+ // function decodeInstallationParams(
+ // bytes memory _data
+ // ) public pure returns (InstallationParameters memory installationParams) {
+ // installationParams = abi.decode(_data, (InstallationParameters));
+ // }
+ // /// @notice Unsatisfiably determines if the contract is an ERC20 token.
+ // /// @dev It's important to first check whether token is a contract prior to this call.
+ // /// @param token The token address
+ // function _supportsErc20(address token) private view returns (bool) {
+ // (bool success, bytes memory data) = token.staticcall(
+ // abi.encodeCall(IERC20Upgradeable.balanceOf, (address(this)))
+ // );
+ // if (!success || data.length != 0x20) return false;
+ // (success, data) = token.staticcall(
+ // abi.encodeCall(IERC20Upgradeable.totalSupply, ())
+ // );
+ // if (!success || data.length != 0x20) return false;
+ // (success, data) = token.staticcall(
+ // abi.encodeCall(
+ // IERC20Upgradeable.allowance,
+ // (address(this), address(this))
+ // )
+ // );
+ // if (!success || data.length != 0x20) return false;
+ // return true;
+ // }
+ // /// @notice Unsatisfiably determines if the contract is an ERC20 token.
+ // /// @dev It's important to first check whether token is a contract prior to this call.
+ // /// @param token The token address
+ // function _supportsIVotes(address token) private view returns (bool) {
+ // (bool success, bytes memory data) = token.staticcall(
+ // abi.encodeCall(IVotesUpgradeable.getVotes, (address(this)))
+ // );
+ // if (!success || data.length != 0x20) return false;
+ // (success, data) = token.staticcall(
+ // abi.encodeCall(IVotesUpgradeable.getPastVotes, (address(this), 0))
+ // );
+ // if (!success || data.length != 0x20) return false;
+ // (success, data) = token.staticcall(
+ // abi.encodeCall(IVotesUpgradeable.getPastTotalSupply, (0))
+ // );
+ // if (!success || data.length != 0x20) return false;
+ // (success, data) = token.staticcall(
+ // abi.encodeCall(IVotesUpgradeable.delegates, (address(this)))
+ // );
+ // if (!success || data.length != 0x20) return false;
+ // return true;
+ // }
+ // /// @notice Unsatisfiably determines if the contract is an ERC20 token.
+ // /// @dev It's important to first check whether token is a contract prior to this call.
+ // /// @param token The token address
+ // function _supportsIGovernanceWrappedERC20(
+ // address token
+ // ) private view returns (bool) {
+ // (bool success, bytes memory data) = token.staticcall(
+ // abi.encodeCall(IERC165.supportsInterface, (bytes4(0)))
+ // );
+ // if (!success || data.length != 0x20) return false;
+ // return
+ // IERC165(token).supportsInterface(
+ // type(IGovernanceWrappedERC20).interfaceId
+ // );
+ // }
+}
diff --git a/test/Counter.t.sol b/test/Counter.t.sol
deleted file mode 100644
index 54b724f..0000000
--- a/test/Counter.t.sol
+++ /dev/null
@@ -1,24 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-pragma solidity ^0.8.13;
-
-import {Test, console} from "forge-std/Test.sol";
-import {Counter} from "../src/Counter.sol";
-
-contract CounterTest is Test {
- Counter public counter;
-
- function setUp() public {
- counter = new Counter();
- counter.setNumber(0);
- }
-
- function test_Increment() public {
- counter.increment();
- assertEq(counter.number(), 1);
- }
-
- function testFuzz_SetNumber(uint256 x) public {
- counter.setNumber(x);
- assertEq(counter.number(), x);
- }
-}
diff --git a/test/LockToVote.t.sol b/test/LockToVote.t.sol
new file mode 100644
index 0000000..7a833af
--- /dev/null
+++ b/test/LockToVote.t.sol
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: UNLICENSED
+pragma solidity 0.8.17;
+
+import {Test} from "forge-std/Test.sol";
+import {AragonTest} from "./util/AragonTest.sol";
+
+contract LockToVoteTest is AragonTest {
+ function test_WhenDeployingTheContract() external {
+ // It should initialize normally
+ vm.skip(true);
+ }
+
+ function test_GivenADeployedContract() external {
+ // It should refuse to initialize again
+ vm.skip(true);
+ }
+
+ modifier givenANewInstance() {
+ _;
+ }
+
+ function test_GivenCallingInitialize() external givenANewInstance {
+ // It should set the DAO address
+ vm.skip(true);
+ }
+
+ modifier whenCallingUpdateSettings() {
+ _;
+ }
+
+ function test_RevertWhen_UpdateSettingsWithoutThePermission()
+ external
+ whenCallingUpdateSettings
+ {
+ // It should revert
+ vm.skip(true);
+ }
+
+ function test_WhenCallingSupportsInterface() external {
+ // It does not support the empty interface
+ // It supports IERC165Upgradeable
+ vm.skip(true);
+ }
+}
diff --git a/test/LockToVote.t.yaml b/test/LockToVote.t.yaml
new file mode 100644
index 0000000..5a1a332
--- /dev/null
+++ b/test/LockToVote.t.yaml
@@ -0,0 +1,24 @@
+LockToVoteTest:
+ # contract lifecycle
+ - when: deploying the contract
+ then:
+ - it: should initialize normally
+ - given: a deployed contract
+ then:
+ - it: should refuse to initialize again
+ - given: a new instance
+ and:
+ - given: calling initialize
+ and:
+ - it: should set the DAO address
+
+ - when: calling updateSettings
+ and:
+ - when: updateSettings without the permission
+ then:
+ - it: should revert
+
+ - when: calling supportsInterface
+ then:
+ - it: does not support the empty interface
+ - it: supports IERC165Upgradeable
diff --git a/test/constants.sol b/test/constants.sol
new file mode 100644
index 0000000..eb493f5
--- /dev/null
+++ b/test/constants.sol
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: UNLICENSED
+pragma solidity ^0.8.17;
+
+bytes32 constant PROPOSER_PERMISSION_ID = keccak256("PROPOSER_PERMISSION");
+bytes32 constant EXECUTE_PERMISSION_ID = keccak256("EXECUTE_PERMISSION");
+bytes32 constant UPDATE_SETTINGS_PERMISSION_ID = keccak256(
+ "UPDATE_SETTINGS_PERMISSION"
+);
+bytes32 constant UPGRADE_PLUGIN_PERMISSION_ID = keccak256(
+ "UPGRADE_PLUGIN_PERMISSION"
+);
+bytes32 constant ROOT_PERMISSION_ID = keccak256("ROOT_PERMISSION");
+
+uint64 constant MAX_UINT64 = uint64(2 ** 64 - 1);
+address constant ADDRESS_ZERO = address(0x0);
+address constant NO_CONDITION = ADDRESS_ZERO;
+
+// Actors
+address constant ALICE_ADDRESS = address(
+ 0xa11ce00000000a11ce00000000a11ce0000000
+);
+address constant BOB_ADDRESS = address(
+ 0xB0B00000000B0B00000000B0B00000000B0B00
+);
+address constant CAROL_ADDRESS = address(
+ 0xc460100000000c460100000000c46010000000
+);
+address constant DAVID_ADDRESS = address(
+ 0xd471d00000000d471d00000000d471d0000000
+);
diff --git a/test/mocks/GovernanceERC20Mock.sol b/test/mocks/GovernanceERC20Mock.sol
new file mode 100644
index 0000000..db3f0eb
--- /dev/null
+++ b/test/mocks/GovernanceERC20Mock.sol
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: UNLICENSED
+pragma solidity >=0.8.17 <0.9.0;
+
+import {GovernanceERC20} from "@aragon/osx/token/ERC20/governance/GovernanceERC20.sol";
+import {IDAO} from "@aragon/osx/core/dao/IDAO.sol";
+import {ERC20VotesUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol";
+import {SafeCastUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
+
+contract GovernanceERC20Mock is GovernanceERC20 {
+ constructor(
+ address _dao
+ )
+ GovernanceERC20(
+ IDAO(_dao),
+ "Mock Votes token",
+ "MTK",
+ MintSettings({
+ amounts: new uint256[](0),
+ receivers: new address[](0)
+ })
+ )
+ {
+ // MintSettings memory _mintSettings = MintSettings({amounts: new uint256[](0), receivers: new address[](0)});
+ }
+
+ function clock() public view override returns (uint48) {
+ return SafeCastUpgradeable.toUint48(block.timestamp);
+ }
+
+ // solhint-disable-next-line func-name-mixedcase
+ function CLOCK_MODE() public pure override returns (string memory) {
+ // See https://eips.ethereum.org/EIPS/eip-6372
+ return "mode=timestamp";
+ }
+
+ function _mint(address to, uint256 amount) internal override {
+ super._mint(to, amount);
+ }
+
+ function _delegate(
+ address delegator,
+ address delegatee
+ ) internal override(ERC20VotesUpgradeable) {
+ super._delegate(delegator, delegatee);
+ }
+
+ function _burn(address account, uint256 amount) internal override {
+ super._burn(account, amount);
+ }
+
+ function mint() external {
+ _mint(msg.sender, 10 ether);
+ }
+
+ function mintTo(address receiver, uint256 amount) external {
+ _mint(receiver, amount);
+ }
+
+ function mintAndDelegate(address receiver, uint256 amount) external {
+ _mint(receiver, amount);
+ _delegate(receiver, receiver);
+ }
+
+ function mintAndDelegate(
+ address[] memory receivers,
+ uint256 amount
+ ) external {
+ for (uint256 i = 0; i < receivers.length; i++) {
+ _mint(receivers[i], amount);
+ _delegate(receivers[i], receivers[i]);
+ }
+ }
+}
diff --git a/test/mocks/TestToken.sol b/test/mocks/TestToken.sol
new file mode 100644
index 0000000..3fb648d
--- /dev/null
+++ b/test/mocks/TestToken.sol
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.9;
+
+import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
+import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
+import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
+
+contract TestToken is ERC20, ERC20Permit, ERC20Votes {
+ constructor() ERC20("TestToken", "VETO") ERC20Permit("TestToken") {
+ mint(msg.sender, 10 ether);
+ }
+
+ // The following functions are overrides required by Solidity.
+
+ function _afterTokenTransfer(
+ address from,
+ address to,
+ uint256 amount
+ ) internal override(ERC20, ERC20Votes) {
+ super._afterTokenTransfer(from, to, amount);
+ }
+
+ function mint(address to, uint256 amount) public {
+ _mint(to, amount);
+ }
+
+ function burn(address account, uint256 amount) public {
+ _burn(account, amount);
+ }
+
+ function _mint(
+ address to,
+ uint256 amount
+ ) internal override(ERC20, ERC20Votes) {
+ super._mint(to, amount);
+ }
+
+ function _burn(
+ address account,
+ uint256 amount
+ ) internal override(ERC20, ERC20Votes) {
+ super._burn(account, amount);
+ }
+}
diff --git a/test/mocks/osx/MockPSP.sol b/test/mocks/osx/MockPSP.sol
new file mode 100644
index 0000000..973e9a3
--- /dev/null
+++ b/test/mocks/osx/MockPSP.sol
@@ -0,0 +1,828 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.17;
+
+import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
+
+import {DAO, IDAO} from "@aragon/osx/core/dao/DAO.sol";
+import {PermissionLib} from "@aragon/osx/core/permission/PermissionLib.sol";
+import {PluginUUPSUpgradeable} from "@aragon/osx/core/plugin/PluginUUPSUpgradeable.sol";
+import {IPlugin} from "@aragon/osx/core/plugin/IPlugin.sol";
+
+import {PluginRepo} from "@aragon/osx/framework/plugin/repo/PluginRepo.sol";
+
+import {IPluginSetup} from "@aragon/osx/framework/plugin/setup/IPluginSetup.sol";
+import {PluginSetup} from "@aragon/osx/framework/plugin/setup/PluginSetup.sol";
+import {PluginSetupRef, hashHelpers, hashPermissions, _getPreparedSetupId, _getAppliedSetupId, _getPluginInstallationId, PreparationType} from "@aragon/osx/framework/plugin/setup/PluginSetupProcessorHelpers.sol";
+
+/// @title PluginSetupProcessor
+/// @author Aragon Association - 2022-2023
+/// @notice This contract processes the preparation and application of plugin setups (installation, update, uninstallation) on behalf of a requesting DAO.
+/// @dev This contract is temporarily granted the `ROOT_PERMISSION_ID` permission on the applying DAO and therefore is highly security critical.
+contract MockPluginSetupProcessor {
+ using ERC165Checker for address;
+
+ /// @notice The ID of the permission required to call the `applyInstallation` function.
+ bytes32 public constant APPLY_INSTALLATION_PERMISSION_ID =
+ keccak256("APPLY_INSTALLATION_PERMISSION");
+
+ /// @notice The ID of the permission required to call the `applyUpdate` function.
+ bytes32 public constant APPLY_UPDATE_PERMISSION_ID =
+ keccak256("APPLY_UPDATE_PERMISSION");
+
+ /// @notice The ID of the permission required to call the `applyUninstallation` function.
+ bytes32 public constant APPLY_UNINSTALLATION_PERMISSION_ID =
+ keccak256("APPLY_UNINSTALLATION_PERMISSION");
+
+ /// @notice The hash obtained from the bytes-encoded empty array to be used for UI updates being required to submit an empty permission array.
+ /// @dev The hash is computed via `keccak256(abi.encode([]))`.
+ bytes32 private constant EMPTY_ARRAY_HASH =
+ 0x569e75fc77c1a856f6daaf9e69d8a9566ca34aa47f9133711ce065a571af0cfd;
+
+ /// @notice The hash obtained from the bytes-encoded zero value.
+ /// @dev The hash is computed via `keccak256(abi.encode(0))`.
+ bytes32 private constant ZERO_BYTES_HASH =
+ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
+
+ /// @notice A struct containing information related to plugin setups that have been applied.
+ /// @param blockNumber The block number at which the `applyInstallation`, `applyUpdate` or `applyUninstallation` was executed.
+ /// @param currentAppliedSetupId The current setup id that plugin holds. Needed to confirm that `prepareUpdate` or `prepareUninstallation` happens for the plugin's current/valid dependencies.
+ /// @param preparedSetupIdToBlockNumber The mapping between prepared setup IDs and block numbers at which `prepareInstallation`, `prepareUpdate` or `prepareUninstallation` was executed.
+ struct PluginState {
+ uint256 blockNumber;
+ bytes32 currentAppliedSetupId;
+ mapping(bytes32 => uint256) preparedSetupIdToBlockNumber;
+ }
+
+ /// @notice A mapping between the plugin installation ID (obtained from the DAO and plugin address) and the plugin state information.
+ /// @dev This variable is public on purpose to allow future versions to access and migrate the storage.
+ mapping(bytes32 => PluginState) public states;
+
+ /// @notice The struct containing the parameters for the `prepareInstallation` function.
+ /// @param pluginSetupRef The reference to the plugin setup to be used for the installation.
+ /// @param data The bytes-encoded data containing the input parameters for the installation preparation as specified in the corresponding ABI on the version's metadata.
+ struct PrepareInstallationParams {
+ PluginSetupRef pluginSetupRef;
+ bytes data;
+ }
+
+ /// @notice The struct containing the parameters for the `applyInstallation` function.
+ /// @param pluginSetupRef The reference to the plugin setup used for the installation.
+ /// @param plugin The address of the plugin contract to be installed.
+ /// @param permissions The array of multi-targeted permission operations to be applied by the `PluginSetupProcessor` to the DAO.
+ /// @param helpersHash The hash of helpers that were deployed in `prepareInstallation`. This helps to derive the setup ID.
+ struct ApplyInstallationParams {
+ PluginSetupRef pluginSetupRef;
+ address plugin;
+ PermissionLib.MultiTargetPermission[] permissions;
+ bytes32 helpersHash;
+ }
+
+ /// @notice The struct containing the parameters for the `prepareUpdate` function.
+ /// @param currentVersionTag The tag of the current plugin version to update from.
+ /// @param newVersionTag The tag of the new plugin version to update to.
+ /// @param pluginSetupRepo The plugin setup repository address on which the plugin exists.
+ /// @param setupPayload The payload containing the plugin and helper contract addresses deployed in a preparation step as well as optional data to be consumed by the plugin setup.
+ /// This includes the bytes-encoded data containing the input parameters for the update preparation as specified in the corresponding ABI on the version's metadata.
+ struct PrepareUpdateParams {
+ PluginRepo.Tag currentVersionTag;
+ PluginRepo.Tag newVersionTag;
+ PluginRepo pluginSetupRepo;
+ IPluginSetup.SetupPayload setupPayload;
+ }
+
+ /// @notice The struct containing the parameters for the `applyUpdate` function.
+ /// @param plugin The address of the plugin contract to be updated.
+ /// @param pluginSetupRef The reference to the plugin setup used for the update.
+ /// @param initData The encoded data (function selector and arguments) to be provided to `upgradeToAndCall`.
+ /// @param permissions The array of multi-targeted permission operations to be applied by the `PluginSetupProcessor` to the DAO.
+ /// @param helpersHash The hash of helpers that were deployed in `prepareUpdate`. This helps to derive the setup ID.
+ struct ApplyUpdateParams {
+ address plugin;
+ PluginSetupRef pluginSetupRef;
+ bytes initData;
+ PermissionLib.MultiTargetPermission[] permissions;
+ bytes32 helpersHash;
+ }
+
+ /// @notice The struct containing the parameters for the `prepareUninstallation` function.
+ /// @param pluginSetupRef The reference to the plugin setup to be used for the uninstallation.
+ /// @param setupPayload The payload containing the plugin and helper contract addresses deployed in a preparation step as well as optional data to be consumed by the plugin setup.
+ /// This includes the bytes-encoded data containing the input parameters for the uninstallation preparation as specified in the corresponding ABI on the version's metadata.
+ struct PrepareUninstallationParams {
+ PluginSetupRef pluginSetupRef;
+ IPluginSetup.SetupPayload setupPayload;
+ }
+
+ /// @notice The struct containing the parameters for the `applyInstallation` function.
+ /// @param plugin The address of the plugin contract to be uninstalled.
+ /// @param pluginSetupRef The reference to the plugin setup used for the uninstallation.
+ /// @param permissions The array of multi-targeted permission operations to be applied by the `PluginSetupProcess.
+ struct ApplyUninstallationParams {
+ address plugin;
+ PluginSetupRef pluginSetupRef;
+ PermissionLib.MultiTargetPermission[] permissions;
+ }
+
+ /// @notice The plugin repo registry listing the `PluginRepo` contracts versioning the `PluginSetup` contracts.
+ // PluginRepoRegistry public repoRegistry;
+
+ /// @notice Thrown if a setup is unauthorized and cannot be applied because of a missing permission of the associated DAO.
+ /// @param dao The address of the DAO to which the plugin belongs.
+ /// @param caller The address (EOA or contract) that requested the application of a setup on the associated DAO.
+ /// @param permissionId The permission identifier.
+ /// @dev This is thrown if the `APPLY_INSTALLATION_PERMISSION_ID`, `APPLY_UPDATE_PERMISSION_ID`, or APPLY_UNINSTALLATION_PERMISSION_ID is missing.
+ error SetupApplicationUnauthorized(
+ address dao,
+ address caller,
+ bytes32 permissionId
+ );
+
+ /// @notice Thrown if a plugin is not upgradeable.
+ /// @param plugin The address of the plugin contract.
+ error PluginNonupgradeable(address plugin);
+
+ /// @notice Thrown if the upgrade of an `UUPSUpgradeable` proxy contract (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)) failed.
+ /// @param proxy The address of the proxy.
+ /// @param implementation The address of the implementation contract.
+ /// @param initData The initialization data to be passed to the upgradeable plugin contract via `upgradeToAndCall`.
+ error PluginProxyUpgradeFailed(
+ address proxy,
+ address implementation,
+ bytes initData
+ );
+
+ /// @notice Thrown if a contract does not support the `IPlugin` interface.
+ /// @param plugin The address of the contract.
+ error IPluginNotSupported(address plugin);
+
+ /// @notice Thrown if a plugin repository does not exist on the plugin repo registry.
+ error PluginRepoNonexistent();
+
+ /// @notice Thrown if a plugin setup was already prepared indicated by the prepared setup ID.
+ /// @param preparedSetupId The prepared setup ID.
+ error SetupAlreadyPrepared(bytes32 preparedSetupId);
+
+ /// @notice Thrown if a prepared setup ID is not eligible to be applied. This can happen if another setup has been already applied or if the setup wasn't prepared in the first place.
+ /// @param preparedSetupId The prepared setup ID.
+ error SetupNotApplicable(bytes32 preparedSetupId);
+
+ /// @notice Thrown if the update version is invalid.
+ /// @param currentVersionTag The tag of the current version to update from.
+ /// @param newVersionTag The tag of the new version to update to.
+ error InvalidUpdateVersion(
+ PluginRepo.Tag currentVersionTag,
+ PluginRepo.Tag newVersionTag
+ );
+
+ /// @notice Thrown if plugin is already installed and one tries to prepare or apply install on it.
+ error PluginAlreadyInstalled();
+
+ /// @notice Thrown if the applied setup ID resulting from the supplied setup payload does not match with the current applied setup ID.
+ /// @param currentAppliedSetupId The current applied setup ID with which the data in the supplied payload must match.
+ /// @param appliedSetupId The applied setup ID obtained from the data in the supplied setup payload.
+ error InvalidAppliedSetupId(
+ bytes32 currentAppliedSetupId,
+ bytes32 appliedSetupId
+ );
+
+ /// @notice Emitted with a prepared plugin installation to store data relevant for the application step.
+ /// @param sender The sender that prepared the plugin installation.
+ /// @param dao The address of the DAO to which the plugin belongs.
+ /// @param preparedSetupId The prepared setup ID obtained from the supplied data.
+ /// @param pluginSetupRepo The repository storing the `PluginSetup` contracts of all versions of a plugin.
+ /// @param versionTag The version tag of the plugin setup of the prepared installation.
+ /// @param data The bytes-encoded data containing the input parameters for the preparation as specified in the corresponding ABI on the version's metadata.
+ /// @param plugin The address of the plugin contract.
+ /// @param preparedSetupData The deployed plugin's relevant data which consists of helpers and permissions.
+ event InstallationPrepared(
+ address indexed sender,
+ address indexed dao,
+ bytes32 preparedSetupId,
+ PluginRepo indexed pluginSetupRepo,
+ PluginRepo.Tag versionTag,
+ bytes data,
+ address plugin,
+ IPluginSetup.PreparedSetupData preparedSetupData
+ );
+
+ /// @notice Emitted after a plugin installation was applied.
+ /// @param dao The address of the DAO to which the plugin belongs.
+ /// @param plugin The address of the plugin contract.
+ /// @param preparedSetupId The prepared setup ID.
+ /// @param appliedSetupId The applied setup ID.
+ event InstallationApplied(
+ address indexed dao,
+ address indexed plugin,
+ bytes32 preparedSetupId,
+ bytes32 appliedSetupId
+ );
+
+ /// @notice Emitted with a prepared plugin update to store data relevant for the application step.
+ /// @param sender The sender that prepared the plugin update.
+ /// @param dao The address of the DAO to which the plugin belongs.
+ /// @param preparedSetupId The prepared setup ID.
+ /// @param pluginSetupRepo The repository storing the `PluginSetup` contracts of all versions of a plugin.
+ /// @param versionTag The version tag of the plugin setup of the prepared update.
+ /// @param setupPayload The payload containing the plugin and helper contract addresses deployed in a preparation step as well as optional data to be consumed by the plugin setup.
+ /// @param preparedSetupData The deployed plugin's relevant data which consists of helpers and permissions.
+ /// @param initData The initialization data to be passed to the upgradeable plugin contract.
+ event UpdatePrepared(
+ address indexed sender,
+ address indexed dao,
+ bytes32 preparedSetupId,
+ PluginRepo indexed pluginSetupRepo,
+ PluginRepo.Tag versionTag,
+ IPluginSetup.SetupPayload setupPayload,
+ IPluginSetup.PreparedSetupData preparedSetupData,
+ bytes initData
+ );
+
+ /// @notice Emitted after a plugin update was applied.
+ /// @param dao The address of the DAO to which the plugin belongs.
+ /// @param plugin The address of the plugin contract.
+ /// @param preparedSetupId The prepared setup ID.
+ /// @param appliedSetupId The applied setup ID.
+ event UpdateApplied(
+ address indexed dao,
+ address indexed plugin,
+ bytes32 preparedSetupId,
+ bytes32 appliedSetupId
+ );
+
+ /// @notice Emitted with a prepared plugin uninstallation to store data relevant for the application step.
+ /// @param sender The sender that prepared the plugin uninstallation.
+ /// @param dao The address of the DAO to which the plugin belongs.
+ /// @param preparedSetupId The prepared setup ID.
+ /// @param pluginSetupRepo The repository storing the `PluginSetup` contracts of all versions of a plugin.
+ /// @param versionTag The version tag of the plugin to used for install preparation.
+ /// @param setupPayload The payload containing the plugin and helper contract addresses deployed in a preparation step as well as optional data to be consumed by the plugin setup.
+ /// @param permissions The list of multi-targeted permission operations to be applied to the installing DAO.
+ event UninstallationPrepared(
+ address indexed sender,
+ address indexed dao,
+ bytes32 preparedSetupId,
+ PluginRepo indexed pluginSetupRepo,
+ PluginRepo.Tag versionTag,
+ IPluginSetup.SetupPayload setupPayload,
+ PermissionLib.MultiTargetPermission[] permissions
+ );
+
+ /// @notice Emitted after a plugin installation was applied.
+ /// @param dao The address of the DAO to which the plugin belongs.
+ /// @param plugin The address of the plugin contract.
+ /// @param preparedSetupId The prepared setup ID.
+ event UninstallationApplied(
+ address indexed dao,
+ address indexed plugin,
+ bytes32 preparedSetupId
+ );
+
+ /// @notice A modifier to check if a caller has the permission to apply a prepared setup.
+ /// @param _dao The address of the DAO.
+ /// @param _permissionId The permission identifier.
+ modifier canApply(address _dao, bytes32 _permissionId) {
+ _canApply(_dao, _permissionId);
+ _;
+ }
+
+ /// @notice Constructs the plugin setup processor by setting the associated plugin repo registry.
+ // / @param _repoRegistry The plugin repo registry contract.
+ constructor(address[] memory _setups) {
+ for (uint256 i = 0; i < _setups.length; i++) {
+ queueSetup(_setups[i]);
+ }
+ // repoRegistry = _repoRegistry;
+ }
+
+ address[] setups;
+
+ function queueSetup(address _setup) public {
+ setups.push(_setup);
+ }
+
+ function popSetup() internal returns (address) {
+ require(setups.length > 0, "No setups queued");
+ address _setup = setups[setups.length - 1];
+ setups.pop();
+ return _setup;
+ }
+
+ /// @notice Prepares the installation of a plugin.
+ /// @param _dao The address of the installing DAO.
+ /// @param _params The struct containing the parameters for the `prepareInstallation` function.
+ /// @return plugin The prepared plugin contract address.
+ /// @return preparedSetupData The data struct containing the array of helper contracts and permissions that the setup has prepared.
+ function prepareInstallation(
+ address _dao,
+ PrepareInstallationParams calldata _params
+ )
+ external
+ returns (
+ address plugin,
+ IPluginSetup.PreparedSetupData memory preparedSetupData
+ )
+ {
+ // PluginRepo pluginSetupRepo = _params.pluginSetupRef.pluginSetupRepo;
+
+ // // Check that the plugin repository exists on the plugin repo registry.
+ // if (!repoRegistry.entries(address(pluginSetupRepo))) {
+ // revert PluginRepoNonexistent();
+ // }
+
+ // // reverts if not found
+ // PluginRepo.Version memory version = pluginSetupRepo.getVersion(
+ // _params.pluginSetupRef.versionTag
+ // );
+
+ // Prepare the installation
+ address setup = popSetup();
+ (plugin, preparedSetupData) = PluginSetup(setup).prepareInstallation(
+ _dao,
+ _params.data
+ );
+
+ // bytes32 pluginInstallationId = _getPluginInstallationId(_dao, plugin);
+
+ // bytes32 preparedSetupId = _getPreparedSetupId(
+ // _params.pluginSetupRef,
+ // hashPermissions(preparedSetupData.permissions),
+ // hashHelpers(preparedSetupData.helpers),
+ // bytes(""),
+ // PreparationType.Installation
+ // );
+
+ // PluginState storage pluginState = states[pluginInstallationId];
+
+ // // Check if this plugin is already installed.
+ // if (pluginState.currentAppliedSetupId != bytes32(0)) {
+ // revert PluginAlreadyInstalled();
+ // }
+
+ // // Check if this setup has already been prepared before and is pending.
+ // if (pluginState.blockNumber < pluginState.preparedSetupIdToBlockNumber[preparedSetupId]) {
+ // revert SetupAlreadyPrepared({preparedSetupId: preparedSetupId});
+ // }
+
+ // pluginState.preparedSetupIdToBlockNumber[preparedSetupId] = block.number;
+
+ // emit InstallationPrepared({
+ // sender: msg.sender,
+ // dao: _dao,
+ // preparedSetupId: preparedSetupId,
+ // pluginSetupRepo: pluginSetupRepo,
+ // versionTag: _params.pluginSetupRef.versionTag,
+ // data: _params.data,
+ // plugin: plugin,
+ // preparedSetupData: preparedSetupData
+ // });
+
+ return (plugin, preparedSetupData);
+ }
+
+ /// @notice Applies the permissions of a prepared installation to a DAO.
+ /// @param _dao The address of the installing DAO.
+ /// @param _params The struct containing the parameters for the `applyInstallation` function.
+ function applyInstallation(
+ address _dao,
+ ApplyInstallationParams calldata _params
+ ) external canApply(_dao, APPLY_INSTALLATION_PERMISSION_ID) {
+ // bytes32 pluginInstallationId = _getPluginInstallationId(_dao, _params.plugin);
+
+ // PluginState storage pluginState = states[pluginInstallationId];
+
+ // bytes32 preparedSetupId = _getPreparedSetupId(
+ // _params.pluginSetupRef,
+ // hashPermissions(_params.permissions),
+ // _params.helpersHash,
+ // bytes(""),
+ // PreparationType.Installation
+ // );
+
+ // // Check if this plugin is already installed.
+ // if (pluginState.currentAppliedSetupId != bytes32(0)) {
+ // revert PluginAlreadyInstalled();
+ // }
+
+ // validatePreparedSetupId(pluginInstallationId, preparedSetupId);
+
+ // bytes32 appliedSetupId = _getAppliedSetupId(_params.pluginSetupRef, _params.helpersHash);
+
+ // pluginState.currentAppliedSetupId = appliedSetupId;
+ // pluginState.blockNumber = block.number;
+
+ // Process the permissions, which requires the `ROOT_PERMISSION_ID` from the installing DAO.
+ if (_params.permissions.length > 0) {
+ DAO(payable(_dao)).applyMultiTargetPermissions(_params.permissions);
+ }
+
+ // emit InstallationApplied({
+ // dao: _dao,
+ // plugin: _params.plugin,
+ // preparedSetupId: preparedSetupId,
+ // appliedSetupId: appliedSetupId
+ // });
+ }
+
+ /// @notice Prepares the update of an UUPS upgradeable plugin.
+ /// @param _dao The address of the DAO For which preparation of update happens.
+ /// @param _params The struct containing the parameters for the `prepareUpdate` function.
+ /// @return initData The initialization data to be passed to upgradeable contracts when the update is applied
+ /// @return preparedSetupData The data struct containing the array of helper contracts and permissions that the setup has prepared.
+ /// @dev The list of `_params.setupPayload.currentHelpers` has to be specified in the same order as they were returned from previous setups preparation steps (the latest `prepareInstallation` or `prepareUpdate` step that has happend) on which the update is prepared for.
+ function prepareUpdate(
+ address _dao,
+ PrepareUpdateParams calldata _params
+ )
+ external
+ returns (
+ bytes memory initData,
+ IPluginSetup.PreparedSetupData memory preparedSetupData
+ )
+ {
+ if (
+ _params.currentVersionTag.release !=
+ _params.newVersionTag.release ||
+ _params.currentVersionTag.build >= _params.newVersionTag.build
+ ) {
+ revert InvalidUpdateVersion({
+ currentVersionTag: _params.currentVersionTag,
+ newVersionTag: _params.newVersionTag
+ });
+ }
+
+ bytes32 pluginInstallationId = _getPluginInstallationId(
+ _dao,
+ _params.setupPayload.plugin
+ );
+
+ PluginState storage pluginState = states[pluginInstallationId];
+
+ bytes32 currentHelpersHash = hashHelpers(
+ _params.setupPayload.currentHelpers
+ );
+
+ bytes32 appliedSetupId = _getAppliedSetupId(
+ PluginSetupRef(_params.currentVersionTag, _params.pluginSetupRepo),
+ currentHelpersHash
+ );
+
+ // The following check implicitly confirms that plugin is currently installed.
+ // Otherwise, `currentAppliedSetupId` would not be set.
+ if (pluginState.currentAppliedSetupId != appliedSetupId) {
+ revert InvalidAppliedSetupId({
+ currentAppliedSetupId: pluginState.currentAppliedSetupId,
+ appliedSetupId: appliedSetupId
+ });
+ }
+
+ PluginRepo.Version memory currentVersion = _params
+ .pluginSetupRepo
+ .getVersion(_params.currentVersionTag);
+
+ PluginRepo.Version memory newVersion = _params
+ .pluginSetupRepo
+ .getVersion(_params.newVersionTag);
+
+ bytes32 preparedSetupId;
+
+ // If the current and new plugin setup are identical, this is an UI update.
+ // In this case, the permission hash is set to the empty array hash and the `prepareUpdate` call is skipped to avoid side effects.
+ if (currentVersion.pluginSetup == newVersion.pluginSetup) {
+ preparedSetupId = _getPreparedSetupId(
+ PluginSetupRef(_params.newVersionTag, _params.pluginSetupRepo),
+ EMPTY_ARRAY_HASH,
+ currentHelpersHash,
+ bytes(""),
+ PreparationType.Update
+ );
+
+ // Because UI updates do not change the plugin functionality, the array of helpers
+ // associated with this plugin version `preparedSetupData.helpers` and being returned must
+ // equal `_params.setupPayload.currentHelpers` returned by the previous setup step (installation or update )
+ // that this update is transitioning from.
+ preparedSetupData.helpers = _params.setupPayload.currentHelpers;
+ } else {
+ // Check that plugin is `PluginUUPSUpgradable`.
+ if (
+ !_params.setupPayload.plugin.supportsInterface(
+ type(IPlugin).interfaceId
+ )
+ ) {
+ revert IPluginNotSupported({
+ plugin: _params.setupPayload.plugin
+ });
+ }
+ if (
+ IPlugin(_params.setupPayload.plugin).pluginType() !=
+ IPlugin.PluginType.UUPS
+ ) {
+ revert PluginNonupgradeable({
+ plugin: _params.setupPayload.plugin
+ });
+ }
+
+ // Prepare the update.
+ (initData, preparedSetupData) = PluginSetup(newVersion.pluginSetup)
+ .prepareUpdate(
+ _dao,
+ _params.currentVersionTag.build,
+ _params.setupPayload
+ );
+
+ preparedSetupId = _getPreparedSetupId(
+ PluginSetupRef(_params.newVersionTag, _params.pluginSetupRepo),
+ hashPermissions(preparedSetupData.permissions),
+ hashHelpers(preparedSetupData.helpers),
+ initData,
+ PreparationType.Update
+ );
+ }
+
+ // Check if this setup has already been prepared before and is pending.
+ if (
+ pluginState.blockNumber <
+ pluginState.preparedSetupIdToBlockNumber[preparedSetupId]
+ ) {
+ revert SetupAlreadyPrepared({preparedSetupId: preparedSetupId});
+ }
+
+ pluginState.preparedSetupIdToBlockNumber[preparedSetupId] = block
+ .number;
+
+ // Avoid stack too deep.
+ emitPrepareUpdateEvent(
+ _dao,
+ preparedSetupId,
+ _params,
+ preparedSetupData,
+ initData
+ );
+
+ return (initData, preparedSetupData);
+ }
+
+ /// @notice Applies the permissions of a prepared update of an UUPS upgradeable proxy contract to a DAO.
+ /// @param _dao The address of the updating DAO.
+ /// @param _params The struct containing the parameters for the `applyInstallation` function.
+ function applyUpdate(
+ address _dao,
+ ApplyUpdateParams calldata _params
+ ) external canApply(_dao, APPLY_UPDATE_PERMISSION_ID) {
+ bytes32 pluginInstallationId = _getPluginInstallationId(
+ _dao,
+ _params.plugin
+ );
+
+ PluginState storage pluginState = states[pluginInstallationId];
+
+ bytes32 preparedSetupId = _getPreparedSetupId(
+ _params.pluginSetupRef,
+ hashPermissions(_params.permissions),
+ _params.helpersHash,
+ _params.initData,
+ PreparationType.Update
+ );
+
+ validatePreparedSetupId(pluginInstallationId, preparedSetupId);
+
+ bytes32 appliedSetupId = _getAppliedSetupId(
+ _params.pluginSetupRef,
+ _params.helpersHash
+ );
+
+ pluginState.blockNumber = block.number;
+ pluginState.currentAppliedSetupId = appliedSetupId;
+
+ PluginRepo.Version memory version = _params
+ .pluginSetupRef
+ .pluginSetupRepo
+ .getVersion(_params.pluginSetupRef.versionTag);
+
+ address currentImplementation = PluginUUPSUpgradeable(_params.plugin)
+ .implementation();
+ address newImplementation = PluginSetup(version.pluginSetup)
+ .implementation();
+
+ if (currentImplementation != newImplementation) {
+ _upgradeProxy(_params.plugin, newImplementation, _params.initData);
+ }
+
+ // Process the permissions, which requires the `ROOT_PERMISSION_ID` from the updating DAO.
+ if (_params.permissions.length > 0) {
+ DAO(payable(_dao)).applyMultiTargetPermissions(_params.permissions);
+ }
+
+ emit UpdateApplied({
+ dao: _dao,
+ plugin: _params.plugin,
+ preparedSetupId: preparedSetupId,
+ appliedSetupId: appliedSetupId
+ });
+ }
+
+ /// @notice Prepares the uninstallation of a plugin.
+ /// @param _dao The address of the uninstalling DAO.
+ /// @param _params The struct containing the parameters for the `prepareUninstallation` function.
+ /// @return permissions The list of multi-targeted permission operations to be applied to the uninstalling DAO.
+ /// @dev The list of `_params.setupPayload.currentHelpers` has to be specified in the same order as they were returned from previous setups preparation steps (the latest `prepareInstallation` or `prepareUpdate` step that has happend) on which the uninstallation was prepared for.
+ function prepareUninstallation(
+ address _dao,
+ PrepareUninstallationParams calldata _params
+ )
+ external
+ returns (PermissionLib.MultiTargetPermission[] memory permissions)
+ {
+ // bytes32 pluginInstallationId = _getPluginInstallationId(_dao, _params.setupPayload.plugin);
+
+ // PluginState storage pluginState = states[pluginInstallationId];
+
+ // bytes32 appliedSetupId = _getAppliedSetupId(
+ // _params.pluginSetupRef,
+ // hashHelpers(_params.setupPayload.currentHelpers)
+ // );
+
+ // if (pluginState.currentAppliedSetupId != appliedSetupId) {
+ // revert InvalidAppliedSetupId({
+ // currentAppliedSetupId: pluginState.currentAppliedSetupId,
+ // appliedSetupId: appliedSetupId
+ // });
+ // }
+
+ // PluginRepo.Version memory version = _params.pluginSetupRef.pluginSetupRepo.getVersion(
+ // _params.pluginSetupRef.versionTag
+ // );
+
+ permissions = PluginSetup(popSetup()).prepareUninstallation(
+ _dao,
+ _params.setupPayload
+ );
+
+ // bytes32 preparedSetupId = _getPreparedSetupId(
+ // _params.pluginSetupRef,
+ // hashPermissions(permissions),
+ // ZERO_BYTES_HASH,
+ // bytes(""),
+ // PreparationType.Uninstallation
+ // );
+
+ // // Check if this setup has already been prepared before and is pending.
+ // if (pluginState.blockNumber < pluginState.preparedSetupIdToBlockNumber[preparedSetupId]) {
+ // revert SetupAlreadyPrepared({preparedSetupId: preparedSetupId});
+ // }
+
+ // pluginState.preparedSetupIdToBlockNumber[preparedSetupId] = block.number;
+
+ // emit UninstallationPrepared({
+ // sender: msg.sender,
+ // dao: _dao,
+ // preparedSetupId: preparedSetupId,
+ // pluginSetupRepo: _params.pluginSetupRef.pluginSetupRepo,
+ // versionTag: _params.pluginSetupRef.versionTag,
+ // setupPayload: _params.setupPayload,
+ // permissions: permissions
+ // });
+ }
+
+ /// @notice Applies the permissions of a prepared uninstallation to a DAO.
+ /// @param _dao The address of the DAO.
+ /// @param _dao The address of the uninstalling DAO.
+ /// @param _params The struct containing the parameters for the `applyUninstallation` function.
+ /// @dev The list of `_params.setupPayload.currentHelpers` has to be specified in the same order as they were returned from previous setups preparation steps (the latest `prepareInstallation` or `prepareUpdate` step that has happend) on which the uninstallation was prepared for.
+ function applyUninstallation(
+ address _dao,
+ ApplyUninstallationParams calldata _params
+ ) external canApply(_dao, APPLY_UNINSTALLATION_PERMISSION_ID) {
+ // bytes32 pluginInstallationId = _getPluginInstallationId(_dao, _params.plugin);
+
+ // PluginState storage pluginState = states[pluginInstallationId];
+
+ // bytes32 preparedSetupId = _getPreparedSetupId(
+ // _params.pluginSetupRef,
+ // hashPermissions(_params.permissions),
+ // ZERO_BYTES_HASH,
+ // bytes(""),
+ // PreparationType.Uninstallation
+ // );
+
+ // validatePreparedSetupId(pluginInstallationId, preparedSetupId);
+
+ // // Since the plugin is uninstalled, only the current block number must be updated.
+ // pluginState.blockNumber = block.number;
+ // pluginState.currentAppliedSetupId = bytes32(0);
+
+ // Process the permissions, which requires the `ROOT_PERMISSION_ID` from the uninstalling DAO.
+ if (_params.permissions.length > 0) {
+ DAO(payable(_dao)).applyMultiTargetPermissions(_params.permissions);
+ }
+
+ // emit UninstallationApplied({
+ // dao: _dao,
+ // plugin: _params.plugin,
+ // preparedSetupId: preparedSetupId
+ // });
+ }
+
+ /// @notice Validates that a setup ID can be applied for `applyInstallation`, `applyUpdate`, or `applyUninstallation`.
+ /// @param pluginInstallationId The plugin installation ID obtained from the hash of `abi.encode(daoAddress, pluginAddress)`.
+ /// @param preparedSetupId The prepared setup ID to be validated.
+ /// @dev If the block number stored in `states[pluginInstallationId].blockNumber` exceeds the one stored in `pluginState.preparedSetupIdToBlockNumber[preparedSetupId]`, the prepared setup with `preparedSetupId` is outdated and not applicable anymore.
+ function validatePreparedSetupId(
+ bytes32 pluginInstallationId,
+ bytes32 preparedSetupId
+ ) public view {
+ PluginState storage pluginState = states[pluginInstallationId];
+ if (
+ pluginState.blockNumber >=
+ pluginState.preparedSetupIdToBlockNumber[preparedSetupId]
+ ) {
+ revert SetupNotApplicable({preparedSetupId: preparedSetupId});
+ }
+ }
+
+ /// @notice Upgrades a UUPS upgradeable proxy contract (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
+ /// @param _proxy The address of the proxy.
+ /// @param _implementation The address of the implementation contract.
+ /// @param _initData The initialization data to be passed to the upgradeable plugin contract via `upgradeToAndCall`.
+ function _upgradeProxy(
+ address _proxy,
+ address _implementation,
+ bytes memory _initData
+ ) private {
+ if (_initData.length > 0) {
+ try
+ PluginUUPSUpgradeable(_proxy).upgradeToAndCall(
+ _implementation,
+ _initData
+ )
+ {} catch Error(string memory reason) {
+ revert(reason);
+ } catch (bytes memory) /*lowLevelData*/ {
+ revert PluginProxyUpgradeFailed({
+ proxy: _proxy,
+ implementation: _implementation,
+ initData: _initData
+ });
+ }
+ } else {
+ try
+ PluginUUPSUpgradeable(_proxy).upgradeTo(_implementation)
+ {} catch Error(string memory reason) {
+ revert(reason);
+ } catch (bytes memory) /*lowLevelData*/ {
+ revert PluginProxyUpgradeFailed({
+ proxy: _proxy,
+ implementation: _implementation,
+ initData: _initData
+ });
+ }
+ }
+ }
+
+ /// @notice Checks if a caller can apply a setup. The caller can be either the DAO to which the plugin setup is applied to or another account to which the DAO has granted the respective permission.
+ /// @param _dao The address of the applying DAO.
+ /// @param _permissionId The permission ID.
+ function _canApply(address _dao, bytes32 _permissionId) private view {
+ if (
+ msg.sender != _dao &&
+ !DAO(payable(_dao)).hasPermission(
+ address(this),
+ msg.sender,
+ _permissionId,
+ bytes("")
+ )
+ ) {
+ revert SetupApplicationUnauthorized({
+ dao: _dao,
+ caller: msg.sender,
+ permissionId: _permissionId
+ });
+ }
+ }
+
+ /// @notice A helper to emit the `UpdatePrepared` event from the supplied, structured data.
+ /// @param _dao The address of the updating DAO.
+ /// @param _preparedSetupId The prepared setup ID.
+ /// @param _params The struct containing the parameters for the `prepareUpdate` function.
+ /// @param _preparedSetupData The deployed plugin's relevant data which consists of helpers and permissions.
+ /// @param _initData The initialization data to be passed to upgradeable contracts when the update is applied
+ /// @dev This functions exists to avoid stack-too-deep errors.
+ function emitPrepareUpdateEvent(
+ address _dao,
+ bytes32 _preparedSetupId,
+ PrepareUpdateParams calldata _params,
+ IPluginSetup.PreparedSetupData memory _preparedSetupData,
+ bytes memory _initData
+ ) private {
+ emit UpdatePrepared({
+ sender: msg.sender,
+ dao: _dao,
+ preparedSetupId: _preparedSetupId,
+ pluginSetupRepo: _params.pluginSetupRepo,
+ versionTag: _params.newVersionTag,
+ setupPayload: _params.setupPayload,
+ preparedSetupData: _preparedSetupData,
+ initData: _initData
+ });
+ }
+}
diff --git a/test/mocks/osx/MockPluginRepoRegistry.sol b/test/mocks/osx/MockPluginRepoRegistry.sol
new file mode 100644
index 0000000..30917af
--- /dev/null
+++ b/test/mocks/osx/MockPluginRepoRegistry.sol
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity 0.8.17;
+
+import {IDAO} from "@aragon/osx/core/dao/IDAO.sol";
+import {InterfaceBasedRegistry} from "@aragon/osx/test/utils/InterfaceBasedRegistryMock.sol";
+import {IPluginRepo} from "@aragon/osx/framework/plugin/repo/IPluginRepo.sol";
+
+/// @title MockPluginRepoRegistry
+/// @author Aragon Association - 2022-2023
+/// @notice This contract maintains an address-based registry of plugin repositories in the Aragon App DAO framework.
+contract MockPluginRepoRegistry is InterfaceBasedRegistry {
+ /// @notice The ID of the permission required to call the `register` function.
+ // bytes32 public constant REGISTER_PLUGIN_REPO_PERMISSION_ID = keccak256("REGISTER_PLUGIN_REPO_PERMISSION");
+
+ /// @notice Emitted if a new plugin repository is registered.
+ /// @param subdomain The subdomain of the plugin repository.
+ /// @param pluginRepo The address of the plugin repository.
+ event PluginRepoRegistered(string subdomain, address pluginRepo);
+
+ // /// @notice Thrown if the plugin subdomain doesn't match the regex `[0-9a-z\-]`
+ // error InvalidPluginSubdomain(string subdomain);
+
+ // /// @notice Thrown if the plugin repository subdomain is empty.
+ // error EmptyPluginRepoSubdomain();
+
+ /// @dev Used to disallow initializing the implementation contract by an attacker for extra safety.
+ constructor() {
+ _disableInitializers();
+ }
+
+ /// @notice Initializes the contract by setting calling the `InterfaceBasedRegistry` base class initialize method.
+ /// @param _dao The address of the managing DAO.
+ function initialize(IDAO _dao) external initializer {
+ bytes4 pluginRepoInterfaceId = type(IPluginRepo).interfaceId;
+ __InterfaceBasedRegistry_init(_dao, pluginRepoInterfaceId);
+
+ // subdomainRegistrar = _subdomainRegistrar;
+ }
+
+ /// @notice Registers a plugin repository with a subdomain and address.
+ /// @param subdomain The subdomain of the PluginRepo.
+ /// @param pluginRepo The address of the PluginRepo contract.
+ function registerPluginRepo(string calldata subdomain, address pluginRepo) external
+ // auth(REGISTER_PLUGIN_REPO_PERMISSION_ID)
+ {
+ // if (!(bytes(subdomain).length > 0)) {
+ // revert EmptyPluginRepoSubdomain();
+ // }
+
+ // if (!isSubdomainValid(subdomain)) {
+ // revert InvalidPluginSubdomain({subdomain: subdomain});
+ // }
+
+ // bytes32 labelhash = keccak256(bytes(subdomain));
+ // subdomainRegistrar.registerSubnode(labelhash, pluginRepo);
+
+ // _register(pluginRepo);
+
+ // emit PluginRepoRegistered(subdomain, pluginRepo);
+ }
+
+ /// @notice This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain (see [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)).
+ uint256[50] private __gap;
+}
diff --git a/test/script/make-test-tree.ts b/test/script/make-test-tree.ts
new file mode 100644
index 0000000..9ffbfa7
--- /dev/null
+++ b/test/script/make-test-tree.ts
@@ -0,0 +1,155 @@
+// Run this program with:
+// $ cat file.t.yaml | deno run test/script/make-test-tree.ts
+
+import { parse } from "jsr:@std/yaml";
+
+type Rule = {
+ comment?: string;
+ given?: string;
+ when?: string;
+ and?: Array;
+ then?: Array;
+ it?: string;
+};
+
+type TreeItem = {
+ content: string;
+ children: Array;
+ comment?: string;
+};
+
+async function main() {
+ const content = await readStdinText();
+ const tree = processTree(content);
+ Deno.stdout.write(new TextEncoder().encode(tree));
+}
+
+function processTree(content: string) {
+ const data: { [k: string]: Array } = parse(content);
+ if (!data || typeof data !== "object") {
+ throw new Error("The file format is not a valid yaml object");
+ }
+
+ const rootKeys = Object.keys(data);
+ if (rootKeys.length > 1) {
+ throw new Error("The test definition must have only one root node");
+ }
+ const [rootKey] = rootKeys;
+ if (!rootKey || !data[rootKey]) {
+ throw new Error("A root node needs to be defined");
+ } else if (!data[rootKey].length) {
+ throw new Error("The root node needs to include at least one element");
+ }
+
+ const root: TreeItem = {
+ content: rootKey,
+ children: parseRuleChildren(data[rootKey]),
+ };
+ return renderTree(root);
+}
+
+function parseRuleChildren(lines: Array): Array {
+ if (!lines.length) return [];
+
+ const result: Array = lines.map((rule) => {
+ if (!rule.when && !rule.given && !rule.it)
+ throw new Error("All rules should have a 'given', 'when' or 'it' rule");
+
+ let content = "";
+ if (rule.given) {
+ content = "Given " + cleanText(rule.given);
+ } else if (rule.when) {
+ content = "When " + cleanText(rule.when);
+ } else if (rule.it) {
+ content = "It " + rule.it;
+ }
+
+ let children: TreeItem[] = [];
+ if (rule.and?.length) {
+ children = parseRuleChildren(rule.and);
+ } else if (rule.then?.length) {
+ children = parseRuleChildren(rule.then);
+ }
+
+ const result: TreeItem = {
+ content,
+ children,
+ };
+
+ if (rule.comment) result.comment = rule.comment;
+ return result;
+ });
+
+ return result;
+}
+
+function renderTree(root: TreeItem): string {
+ let result = root.content + "\n";
+
+ for (let i = 0; i < root.children.length; i++) {
+ const item = root.children[i];
+ const newLines = renderTreeItem(item, i === root.children.length - 1);
+ result += newLines.join("\n") + "\n";
+ }
+
+ return result;
+}
+
+function renderTreeItem(
+ root: TreeItem,
+ lastChildren: boolean,
+ prefix = "",
+): Array {
+ const result: string[] = [];
+
+ // Add ourselves
+ const content = root.comment
+ ? `${root.content} // ${root.comment}`
+ : root.content;
+
+ if (lastChildren) {
+ result.push(prefix + "└── " + content);
+ } else {
+ result.push(prefix + "├── " + content);
+ }
+
+ // Add any children
+ for (let i = 0; i < root.children.length; i++) {
+ const item = root.children[i];
+
+ // Last child
+ if (i === root.children.length - 1) {
+ const newPrefix = lastChildren ? prefix + " " : prefix + "│ ";
+ const lines = renderTreeItem(item, true, newPrefix);
+ lines.forEach((line) => result.push(line));
+ continue;
+ }
+
+ // The rest of children
+ const newPrefix = lastChildren ? prefix + " " : prefix + "│ ";
+ const lines = renderTreeItem(item, false, newPrefix);
+ lines.forEach((line) => result.push(line));
+ }
+
+ return result;
+}
+
+function cleanText(input: string): string {
+ return input.replace(/[^a-zA-Z0-9 ]/g, "").trim();
+}
+
+async function readStdinText() {
+ let result = "";
+ const decoder = new TextDecoder();
+ for await (const chunk of Deno.stdin.readable) {
+ const text = decoder.decode(chunk);
+ result += text;
+ }
+ return result;
+}
+
+if (import.meta.main) {
+ main().catch((err) => {
+ console.error("Error: " + err.message);
+ });
+}
diff --git a/test/util/AragonTest.sol b/test/util/AragonTest.sol
new file mode 100644
index 0000000..9cb7566
--- /dev/null
+++ b/test/util/AragonTest.sol
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+pragma solidity ^0.8.17;
+
+import {IPluginSetup, PluginSetup} from "@aragon/osx/framework/plugin/setup/PluginSetup.sol";
+import {DAO} from "@aragon/osx/core/dao/DAO.sol";
+import {ALICE_ADDRESS, BOB_ADDRESS, CAROL_ADDRESS, DAVID_ADDRESS} from "../constants.sol";
+import {Test} from "forge-std/Test.sol";
+
+contract AragonTest is Test {
+ address immutable alice = ALICE_ADDRESS;
+ address immutable bob = BOB_ADDRESS;
+ address immutable carol = CAROL_ADDRESS;
+ address immutable david = DAVID_ADDRESS;
+ address immutable randomWallet = vm.addr(1234567890);
+
+ address immutable DAO_BASE = address(new DAO());
+
+ bytes internal constant EMPTY_BYTES = "";
+
+ constructor() {
+ vm.label(alice, "Alice");
+ vm.label(bob, "Bob");
+ vm.label(carol, "Carol");
+ vm.label(david, "David");
+ vm.label(randomWallet, "Random wallet");
+ }
+
+ /// @notice Returns the address and private key associated to the given name.
+ /// @param name The name to get the address and private key for.
+ /// @return addr The address associated with the name.
+ /// @return pk The private key associated with the name.
+ function getWallet(
+ string memory name
+ ) internal returns (address addr, uint256 pk) {
+ pk = uint256(keccak256(abi.encodePacked(name)));
+ addr = vm.addr(pk);
+ vm.label(addr, name);
+ }
+}
diff --git a/test/util/DaoBuilder.sol b/test/util/DaoBuilder.sol
new file mode 100644
index 0000000..ac48d87
--- /dev/null
+++ b/test/util/DaoBuilder.sol
@@ -0,0 +1,194 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+pragma solidity ^0.8.17;
+
+import {Test} from "forge-std/Test.sol";
+import {DAO} from "@aragon/osx/core/dao/DAO.sol";
+import {createProxyAndCall} from "./proxy.sol";
+import {ALICE_ADDRESS} from "../constants.sol";
+import {LockToVotePlugin} from "../../src/LockToVotePlugin.sol";
+import {LockManager} from "../../src/LockManager.sol";
+import {GovernanceERC20Mock} from "../mocks/GovernanceERC20Mock.sol";
+
+contract DaoBuilder is Test {
+ // address immutable DAO_BASE = address(new DAO());
+
+ // struct MintEntry {
+ // address tokenHolder;
+ // uint256 amount;
+ // }
+
+ // address public owner = ALICE_ADDRESS;
+
+ // address[] public proposers;
+ // MintEntry[] public tokenHolders;
+
+ // bool public onlyListed = true;
+ // uint16 public minApprovals = 1;
+ // uint32 public proposalDuration = 10 days;
+
+ // function withDaoOwner(address newOwner) public returns (DaoBuilder) {
+ // owner = newOwner;
+ // return this;
+ // }
+
+ // function withTokenHolder(
+ // address newTokenHolder,
+ // uint256 amount
+ // ) public returns (DaoBuilder) {
+ // tokenHolders.push(
+ // MintEntry({tokenHolder: newTokenHolder, amount: amount})
+ // );
+ // return this;
+ // }
+
+ // function withMinVetoRatio(
+ // uint32 newMinVetoRatio
+ // ) public returns (DaoBuilder) {
+ // if (newMinVetoRatio > RATIO_BASE) revert("Veto rate above 100%");
+ // minVetoRatio = newMinVetoRatio;
+ // return this;
+ // }
+
+ // function withMinDuration(
+ // uint32 newMinDuration
+ // ) public returns (DaoBuilder) {
+ // minDuration = newMinDuration;
+ // return this;
+ // }
+
+ // function withDuration(uint32 newDuration) public returns (DaoBuilder) {
+ // proposalDuration = newDuration;
+ // return this;
+ // }
+
+ // function withTimelock(uint32 newTimeLock) public returns (DaoBuilder) {
+ // timelockPeriod = newTimeLock;
+ // return this;
+ // }
+
+ // function withExpiration(
+ // uint32 newExpirationPeriod
+ // ) public returns (DaoBuilder) {
+ // multisigProposalExpirationPeriod = newExpirationPeriod;
+ // return this;
+ // }
+
+ // function withOnlyListed() public returns (DaoBuilder) {
+ // onlyListed = true;
+ // return this;
+ // }
+
+ // function withoutOnlyListed() public returns (DaoBuilder) {
+ // onlyListed = false;
+ // return this;
+ // }
+
+ // function withMultisigMember(address newMember) public returns (DaoBuilder) {
+ // multisigMembers.push(newMember);
+ // return this;
+ // }
+
+ // function withProposer(address newProposer) public returns (DaoBuilder) {
+ // proposers.push(newProposer);
+ // return this;
+ // }
+
+ // function withMinApprovals(
+ // uint16 newMinApprovals
+ // ) public returns (DaoBuilder) {
+ // if (newMinApprovals > multisigMembers.length) {
+ // revert("You should add enough multisig members first");
+ // }
+ // minApprovals = newMinApprovals;
+ // return this;
+ // }
+
+ // /// @dev Creates a DAO with the given orchestration settings.
+ // /// @dev The setup is done on block/timestamp 0 and tests should be made on block/timestamp 1 or later.
+ // function build()
+ // public
+ // returns (DAO dao, LockToVotePlugin plugin, LockManager helper)
+ // {
+ // // Deploy the DAO with `this` as root
+ // dao = DAO(
+ // payable(
+ // createProxyAndCall(
+ // address(DAO_BASE),
+ // abi.encodeCall(
+ // DAO.initialize,
+ // ("", address(this), address(0x0), "")
+ // )
+ // )
+ // )
+ // );
+
+ // // Deploy ERC20 token
+ // votingToken = new GovernanceERC20Mock(address(dao));
+
+ // if (tokenHolders.length > 0) {
+ // for (uint256 i = 0; i < tokenHolders.length; i++) {
+ // votingToken.mintAndDelegate(
+ // tokenHolders[i].tokenHolder,
+ // tokenHolders[i].amount
+ // );
+ // }
+ // } else {
+ // votingToken.mintAndDelegate(owner, 10 ether);
+ // }
+
+ // {
+ // LockToVote.PluginSettings memory targetContractSettings = LockToVote
+ // .PluginSettings({
+ // minVetoRatio: minVetoRatio,
+ // minDuration: minDuration,
+ // timelockPeriod: timelockPeriod,
+ // l2InactivityPeriod: l2InactivityPeriod,
+ // l2AggregationGracePeriod: l2AggregationGracePeriod,
+ // skipL2: skipL2
+ // });
+
+ // plugin = LockToVote(
+ // createProxyAndCall(
+ // address(OPTIMISTIC_BASE),
+ // abi.encodeCall(
+ // LockToVote.initialize,
+ // (
+ // dao,
+ // targetContractSettings,
+ // votingToken,
+ // )
+ // )
+ // )
+ // );
+ // }
+
+ // // The plugin can execute on the DAO
+ // dao.grant(address(dao), address(plugin), dao.EXECUTE_PERMISSION_ID());
+
+ // if (proposers.length > 0) {
+ // for (uint256 i = 0; i < proposers.length; i++) {
+ // dao.grant(
+ // address(plugin),
+ // proposers[i],
+ // plugin.PROPOSER_PERMISSION_ID()
+ // );
+ // }
+ // } else {
+ // // Ensure that at least the owner can propose
+ // dao.grant(address(plugin), owner, plugin.PROPOSER_PERMISSION_ID());
+ // }
+
+ // // Revoke transfer ownership to the owner
+ // dao.grant(address(dao), owner, dao.ROOT_PERMISSION_ID());
+ // dao.revoke(address(dao), address(this), dao.ROOT_PERMISSION_ID());
+
+ // // Labels
+ // vm.label(address(dao), "DAO");
+ // vm.label(address(plugin), "LockToVote plugin");
+ // vm.label(address(votingToken), "VotingToken");
+
+ // // Moving forward to avoid proposal creations failing or getVotes() giving inconsistent values
+ // vm.roll(block.number + 1);
+ // vm.warp(block.timestamp + 1);
+ // }
+}
diff --git a/test/util/proxy.sol b/test/util/proxy.sol
new file mode 100644
index 0000000..4eec965
--- /dev/null
+++ b/test/util/proxy.sol
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: UNLICENSED
+pragma solidity ^0.8.17;
+
+import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
+
+function createProxyAndCall(
+ address _logic,
+ bytes memory _data
+) returns (address) {
+ return address(new ERC1967Proxy(_logic, _data));
+}