diff --git a/.github/workflows/certora.yml b/.github/workflows/certora.yml
new file mode 100644
index 00000000..b106dd88
--- /dev/null
+++ b/.github/workflows/certora.yml
@@ -0,0 +1,51 @@
+name: Certora
+
+on: [push, pull_request]
+
+jobs:
+ certora:
+ name: Certora
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ allocator:
+ - buffer
+ - vault
+ - roles
+ - oracle
+ - registry
+ - swapper
+ - depositoruniv3
+ - stable-swapper
+ - stable-depositoruniv3
+ - conduit-mover
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v3
+
+ - uses: actions/setup-java@v3
+ with:
+ distribution: 'zulu'
+ java-version: '11'
+ java-package: jre
+
+ - name: Set up Python 3.8
+ uses: actions/setup-python@v4
+ with:
+ python-version: 3.8
+
+ - name: Install solc-select
+ run: pip3 install solc-select
+
+ - name: Solc Select 0.8.16
+ run: solc-select install 0.8.16
+
+ - name: Install Certora
+ run: pip3 install certora-cli-beta
+
+ - name: Certora verify ${{ matrix.allocator }}
+ run: make certora-${{ matrix.allocator }}
+ env:
+ CERTORAKEY: ${{ secrets.CERTORAKEY }}
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 09880b1d..b5f0b324 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -1,34 +1,22 @@
-name: test
+name: Tests
-on: workflow_dispatch
-
-env:
- FOUNDRY_PROFILE: ci
+on: [push, pull_request]
jobs:
- check:
- strategy:
- fail-fast: true
-
- name: Foundry project
+ tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- with:
- submodules: recursive
- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1
with:
version: nightly
- - name: Run Forge build
- run: |
- forge --version
- forge build --sizes
- id: build
+ - name: Install Dependencies
+ run: forge install
- - name: Run Forge tests
- run: |
- forge test -vvv
- id: test
+ - name: Run tests
+ run: forge test
+ env:
+ ETH_RPC_URL: ${{ secrets.ETH_RPC_URL }}
diff --git a/.gitignore b/.gitignore
index 85198aaa..a7e4a060 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,3 +12,12 @@ docs/
# Dotenv file
.env
+tmp
+
+# Certora
+.*certora*
+.last_confs/
+*.zip
+resource_errors.json
+.zip-output-url.txt
+certora_debug_log.txt
diff --git a/.gitmodules b/.gitmodules
index 888d42dc..a2df3f1f 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,3 +1,3 @@
-[submodule "lib/forge-std"]
- path = lib/forge-std
- url = https://github.com/foundry-rs/forge-std
+[submodule "lib/dss-test"]
+ path = lib/dss-test
+ url = https://github.com/makerdao/dss-test
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..0ad25db4
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,661 @@
+ 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)
+
+ 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 00000000..42b768f9
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,12 @@
+PATH := ~/.solc-select/artifacts/solc-0.8.16:~/.solc-select/artifacts:$(PATH)
+certora-buffer :; PATH=${PATH} certoraRun certora/AllocatorBuffer.conf$(if $(rule), --rule $(rule),)
+certora-vault :; PATH=${PATH} certoraRun certora/AllocatorVault.conf$(if $(rule), --rule $(rule),)
+certora-roles :; PATH=${PATH} certoraRun certora/AllocatorRoles.conf$(if $(rule), --rule $(rule),)
+certora-oracle :; PATH=${PATH} certoraRun certora/AllocatorOracle.conf$(if $(rule), --rule $(rule),)
+certora-registry :; PATH=${PATH} certoraRun certora/AllocatorRegistry.conf$(if $(rule), --rule $(rule),)
+certora-swapper :; PATH=${PATH} certoraRun certora/funnels/Swapper.conf$(if $(rule), --rule $(rule),)
+certora-depositoruniv3 :; PATH=${PATH} certoraRun certora/funnels/DepositorUniV3.conf$(if $(rule), --rule $(rule),)
+certora-vault-minter :; PATH=${PATH} certoraRun certora/funnels/automation/VaultMinter.conf$(if $(rule), --rule $(rule),)
+certora-stable-swapper :; PATH=${PATH} certoraRun certora/funnels/automation/StableSwapper.conf$(if $(rule), --rule $(rule),)
+certora-stable-depositoruniv3 :; PATH=${PATH} certoraRun certora/funnels/automation/StableDepositorUniV3.conf$(if $(rule), --rule $(rule),)
+certora-conduit-mover :; PATH=${PATH} certoraRun certora/funnels/automation/ConduitMover.conf$(if $(rule), --rule $(rule),)
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..82032bfa
--- /dev/null
+++ b/README.md
@@ -0,0 +1,160 @@
+# `dss-allocator`
+
+Part of this code was inspired by https://github.com/makerdao/rwa-toolkit/blob/master/src/urns/RwaUrn.sol mainly authored by livnev and https://github.com/dapphub/ds-roles/blob/master/src/roles.sol authored by DappHub.
+Since it should belong to the MakerDAO community the Copyright from our additions has been transferred to Dai Foundation.
+
+## Important Update:
+
+**The funnels in this repository and their automation contracts should now be regarded as included for illustrative purposes only. In practice, other use-case specialized funnels are expected to be built.**
+
+**The deployment libraries, tests and the documentation below still use the specific included funnels (e.g DepositorUniV3, Swapper). Those parts should be considered as obsolete.**
+
+## Overview
+Implementation of the allocation system, based on the [technical specification forum post](https://forum.makerdao.com/t/preliminary-technical-specification-of-the-allocation-system/20921).
+The conduits are implemented separately. See for example [dss-conduits](https://github.com/makerdao/dss-conduits).
+
+
+
+## Layers
+The system is comprised of several layers:
+
+- Core Allocation System (*green above*):
+ - Smart contracts that can be considered a part of the Maker Core Protocol, and are immutable and present in all Allocators.
+ - Their main role is to mint USDS (New Stable Token) and hold it (possibly with other tokens) in the `AllocatorBuffer`.
+- Deployment Funnels (*blue above*):
+ - Contracts that pull funds from the `AllocatorBuffer`.
+ - The funds can be swapped and/or deployed into AMM pools or specific conduits.
+ - A typical setting for a funnel includes a base rate-limited contract (such as Swapper) and an automation contract on top of it (such as StableSwapper).
+- Conduits (*orange above*):
+ - Yield investment singletons that support deposits and withdrawals.
+
+## Actors
+The allocation system includes several actor types:
+
+- Pause Proxy:
+ - Performs actions through spells with governance delay.
+ - In charge of setting up the core components and the USDS minting instant access modules (DC-IAMs).
+ - Ward of the singleton contracts (e.g RWA conduits, Coinbase Custody, `AllocatorRoles`).
+- AllocatorDAO Proxy:
+ - Performs actions through a sub-spell with governance delay.
+ - Ward of its `AllocatorVault`, `AllocatorBuffer` and funnel contracts.
+ - In charge of adding new contracts to the funnel network (e.g Swapper, DepositorUniV3).
+ - Can add operators to its funnel network through the `AllocatorRoles` contract.
+ - In charge of setting rate-limiting safety parameters for operators.
+- Operator:
+ - Performs actions without a spell and without governance delay.
+ - An optional actor which is whitelisted through the `AllocatorRoles` contract to perform specified actions on the `AllocatorVault`, funnels and conduits.
+ - Will typically be a facilitator multisig or an automation contract controlled by one (e.g `StableSwapper`, `StableDepositorUniV3`).
+- Keeper:
+ - An optional actor which can be set up to trigger the automation contracts in case repetitive actions are needed (such as swapping USDS to USDC every time interval).
+
+
+
+## Contracts and Configuration
+### VAT Configuration
+
+Each AllocatorDAO has a unique `ilk` (collateral type) with one VAT vault set up for it.
+
+- All the `ilk`s have a shared simple [oracle](https://github.com/makerdao/dss-allocator/blob/dev/src/AllocatorOracle.sol) that just returns a fixed price of 1:1 (which multiplied by a huge amount of collateral makes sure the max debt ceiling can indeed be reached). In case it is necessary a governance spell could also increase it further.
+
+### AllocatorVault
+
+Single contract per `ilk`, which operators can use to:
+
+- Mint (`draw`) USDS from the vault to the AllocatorBuffer.
+- Repay (`wipe`) USDS from the AllocatorBuffer.
+
+### AllocatorBuffer
+
+A simple contract for the AllocatorDAO to hold funds in.
+
+- Supports approving contracts to `transferFrom` it.
+- Note that although the `AllocatorVault` pushes and pulls USDS to/from the `AllocatorBuffer`, it can manage other tokens as well.
+
+### AllocatorRoles
+
+A global permissions registry, inspired by [ds-roles](https://github.com/dapphub/ds-roles).
+
+- Allows AllocatorDAOs to list operators to manage `AllocatorVault`s, funnels and conduits in a per-action resolution.
+- Warded by the Pause Proxy, which needs to add a new AllocatorDAO once one is onboarded.
+
+### AllocatorRegistry
+
+A registry where each AllocatorDAO’s `AllocatorBuffer` address is listed.
+
+### Swapper
+
+A module that pulls tokens from the `AllocatorBuffer` and sends them to be swapped at a callee contract. The resulting funds are sent back to the `AllocatorBuffer`.
+
+It enforces that:
+
+- The swap rate is not faster than a pre-configured rate.
+- The amount to swap each time is not larger than a pre-configured amount.
+- The received funds are not less than a minimal amount specified on the swap call.
+
+### Swapper Callees
+
+Contracts that perform the actual swap and send the resulting funds to the Swapper (to be forwarded to the AllocatorBuffer).
+
+- They can be implemented on top of any DEX / swap vehicle.
+- An example is `SwapperCalleeUniV3`, where swaps in Uniswap V3 can be triggered.
+
+### DepositorUniV3
+
+A primitive for depositing liquidity to Uniswap V3 in a fixed range.
+
+As the Swapper, it includes rate limit protection and is designed so facilitators and automation contracts can use it.
+
+### VaultMinter
+
+An automation contract sample, which can be used by the AllocatorDAOs to `draw` or `wipe` from/to the `AllocatorVault`.
+- It can be useful for automating generation of funds from the vault to the buffer or repayment from the buffer to the vault.
+
+### StableSwapper
+
+An automation contract, which can be used by the AllocatorDAOs to set up recurring swaps of stable tokens (e.g USDS to USDC).
+
+- In order to use it, the AllocatorDAO should list it as an operator of its `Swapper` primitive in the `AllocatorRoles` contract.
+- The `Swapper` primitive will rate-limit the automation contract.
+
+### StableDepositorUniV3
+
+An automation contract sample, which can be used by the AllocatorDAOs to set up recurring deposits or withdraws.
+
+- In order to use it, the AllocatorDAO should list it as an operator of its `DepositorUniV3` primitive in the `AllocatorRoles` contract.
+- The `Depositor` primitive will rate-limit the automation contract.
+
+### ConduitMover
+
+An automation contract sample, which can be used by the AllocatorDAOs to move funds between their `AllocatorBuffer` and the conduits in an automated manner.
+- Although there is no built-in rate limit in the transfer of funds from/to the `AllocatorBuffer` to/form the conduits,
+this can be useful for optimizing yield by moving funds to the destination conduit just in time for them to get processed
+(in case the destination conduit has an agreed upon rate limiting).
+- It can also be useful for automating movement of funds from the buffer in the same rate as they are swapped or withdrawn into it.
+
+### IAllocatorConduit
+
+An interface which each Conduit should implement.
+
+## Security Model:
+- AllocatorDAOs can not incur a loss of more than the debt ceiling (`line`) of their respective `ilk`.
+- A funnel operator (whether a facilitator or an automated contract) can not incur a loss of more than `cap` amount of funds per `era` interval for a specific configuration. This includes not being able to move funds directly to any unknown address that the AllocatorDAO Proxy did not approve.
+- A keeper's maximum loss must be bounded by `cap` amount of funds per `era` (as for a funnel operator) but is additionally constrainted by `lot` (or `amt0` and `amt1`) amount of funds per `hop` for a specific configuration. Moreover, a keeper's execution must guarantee a minimum amount of output tokens, defined by `req` (or `req0` and `req1`) for a specific configuration.
+- If a rate limit is needed for depositing or withdrawing in a specific Conduit (in order to limit the harm a rogue facilitator can cause), it is the responsibility of the Conduit itself to implement it.
+
+## Technical Assumptions:
+- A `uint32` is suitable for storing timestamps or time intervals in the funnels, as the current version of the Allocation System is expected to be deprecated long before 2106.
+- A `uint96` is suitable for storing token amounts in the funnels, as amounts in the scale of 70B are not expected to be used. This implies that the Allocation System does not support tokens with extremely low prices.
+- As with most MakerDAO contracts, non standard token implementations are assumed to not be supported. As examples, this includes tokens that:
+ * Do not have a decimals field or have more than 18 decimals.
+ * Do not revert and instead rely on a return value.
+ * Implement fee on transfer.
+ * Include rebasing logic.
+ * Implement callbacks/hooks.
+- In the Swapper, in case `limit.era` is zero the full cap amount can be swapped for multiple times in the same transaction because `limit.due` will be reset upon re-entry. However, this is consistent with the intended behavior, as in that case zero cooldown is explicitly defined.
+- In StableSwapper the keeper's minimal out value is assumed to be updated whenever `configs[src][dst]` is changed. Failing to do so may result in the swap call reverting or in taking on more slippage than intended (up to a limit controlled by `configs[src][dst].min`).
+- In StableDepositorUniV3 the keeper's minimal amt values are assumed to be updated whenever `configs[gem0][gem1][fee][tickLower][tickUpper]` is changed. Failing to do so may result in the deposit/withdraw call reverting or in taking on more slippage than intended (up to a limit controlled by `configs[gem0][gem1][fee][tickLower][tickUpper].req0/1`).
+- Deployment sanity checks are done as part of the init functions (see the `deploy` directory).
+- DepositorUniV3 has limits for the maximum amount of a pair of tokens that can be added or removed from the pool per era. The rate is purposefully shared between the deposit and withdraw operations (so both actions share the same capacity).
+- The AllocatorDAO Proxy configuring the different rate limits is assumed to know what it is doing and is allowed to set any configuration, even if one configuration collides or duplicates others.
+- The Allocation System assumes that the ESM threshold is set large enough prior to its deployment, so Emergency Shutdown can never be called.
diff --git a/audit/20240909-ChainSecurity_MakerDAO_Allocator_Deployment_Scripts_audit.pdf b/audit/20240909-ChainSecurity_MakerDAO_Allocator_Deployment_Scripts_audit.pdf
new file mode 100644
index 00000000..ccbaa117
Binary files /dev/null and b/audit/20240909-ChainSecurity_MakerDAO_Allocator_Deployment_Scripts_audit.pdf differ
diff --git a/audit/20240909-ChainSecurity_MakerDAO_Allocator_audit.pdf b/audit/20240909-ChainSecurity_MakerDAO_Allocator_audit.pdf
new file mode 100644
index 00000000..a7f5ab48
Binary files /dev/null and b/audit/20240909-ChainSecurity_MakerDAO_Allocator_audit.pdf differ
diff --git a/audit/FPS_dss-allocator_Assessment_FINAL.pdf b/audit/FPS_dss-allocator_Assessment_FINAL.pdf
new file mode 100644
index 00000000..4c6c9822
Binary files /dev/null and b/audit/FPS_dss-allocator_Assessment_FINAL.pdf differ
diff --git a/audit/cantina-report-review-makerdao-dssallocator.pdf b/audit/cantina-report-review-makerdao-dssallocator.pdf
new file mode 100644
index 00000000..eeddbdad
Binary files /dev/null and b/audit/cantina-report-review-makerdao-dssallocator.pdf differ
diff --git a/certora/AllocatorBuffer.conf b/certora/AllocatorBuffer.conf
new file mode 100644
index 00000000..b81471da
--- /dev/null
+++ b/certora/AllocatorBuffer.conf
@@ -0,0 +1,17 @@
+{
+ "files": [
+ "src/AllocatorBuffer.sol",
+ "test/mocks/GemMock.sol"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize_map": {
+ "AllocatorBuffer": "200",
+ "GemMock": "0"
+ },
+ "verify": "AllocatorBuffer:certora/AllocatorBuffer.spec",
+ "parametric_contracts": [
+ "AllocatorBuffer"
+ ],
+ "wait_for_results": "all"
+}
diff --git a/certora/AllocatorBuffer.spec b/certora/AllocatorBuffer.spec
new file mode 100644
index 00000000..fe099a4d
--- /dev/null
+++ b/certora/AllocatorBuffer.spec
@@ -0,0 +1,118 @@
+// AllocatorBuffer.spec
+
+using GemMock as gem;
+
+methods {
+ function wards(address) external returns (uint256) envfree;
+ function gem.allowance(address, address) external returns (uint256) envfree;
+ function _.approve(address, uint256) external => DISPATCHER(true) UNRESOLVED;
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+
+ mathint wardsBefore = wards(anyAddr);
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting approve
+rule approve(address asset, address spender, uint256 amount) {
+ env e;
+
+ require asset == gem;
+
+ approve(e, asset, spender, amount);
+
+ mathint allowance = gem.allowance(currentContract, spender);
+
+ assert allowance == to_mathint(amount), "approve did not set allowance to amount value";
+}
+
+// Verify revert rules on approve
+rule approve_revert(address asset, address spender, uint256 amount) {
+ env e;
+
+ require asset == gem;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ approve@withrevert(e, asset, spender, amount);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
diff --git a/certora/AllocatorOracle.conf b/certora/AllocatorOracle.conf
new file mode 100644
index 00000000..127e1c57
--- /dev/null
+++ b/certora/AllocatorOracle.conf
@@ -0,0 +1,10 @@
+{
+ "files": [
+ "src/AllocatorOracle.sol"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize": "200",
+ "verify": "AllocatorOracle:certora/AllocatorOracle.spec",
+ "wait_for_results": "all"
+}
diff --git a/certora/AllocatorOracle.spec b/certora/AllocatorOracle.spec
new file mode 100644
index 00000000..072f4dbb
--- /dev/null
+++ b/certora/AllocatorOracle.spec
@@ -0,0 +1,23 @@
+// AllocatorOracle.spec
+
+methods {
+ function peek() external returns (bytes32, bool) envfree;
+ function read() external returns (bytes32) envfree;
+}
+
+// Verify correct response from peek
+rule peek() {
+ bytes32 val;
+ bool ok;
+ val, ok = peek();
+
+ assert val == to_bytes32(10^18), "peek did not return the expected val result";
+ assert ok, "peek did not return the expected ok result";
+}
+
+// Verify correct response from read
+rule read() {
+ bytes32 val = read();
+
+ assert val == to_bytes32(10^18), "read did not return the expected result";
+}
diff --git a/certora/AllocatorRegistry.conf b/certora/AllocatorRegistry.conf
new file mode 100644
index 00000000..7bb23ed5
--- /dev/null
+++ b/certora/AllocatorRegistry.conf
@@ -0,0 +1,10 @@
+{
+ "files": [
+ "src/AllocatorRegistry.sol"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize": "200",
+ "verify": "AllocatorRegistry:certora/AllocatorRegistry.spec",
+ "wait_for_results": "all"
+}
diff --git a/certora/AllocatorRegistry.spec b/certora/AllocatorRegistry.spec
new file mode 100644
index 00000000..0fd524d6
--- /dev/null
+++ b/certora/AllocatorRegistry.spec
@@ -0,0 +1,123 @@
+// AllocatorRegistry.spec
+
+methods {
+ function wards(address) external returns (uint256) envfree;
+ function buffers(bytes32) external returns (address) envfree;
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+ bytes32 anyBytes32;
+
+ mathint wardsBefore = wards(anyAddr);
+ address buffersBefore = buffers(anyBytes32);
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ address buffersAfter = buffers(anyBytes32);
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert buffersAfter != buffersBefore => f.selector == sig:file(bytes32,bytes32,address).selector, "buffers[x] changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting file
+rule file(bytes32 ilk, bytes32 what, address data) {
+ env e;
+
+ bytes32 otherBytes32;
+ require otherBytes32 != ilk;
+
+ address buffersOtherBefore = buffers(otherBytes32);
+
+ file(e, ilk, what, data);
+
+ address buffersIlkAfter = buffers(ilk);
+ address buffersOtherAfter = buffers(otherBytes32);
+
+ assert buffersIlkAfter == data, "file did not set buffers[ilk] to data";
+ assert buffersOtherAfter == buffersOtherBefore, "file did not keep unchanged the rest of buffers[x]";
+}
+
+// Verify revert rules on file
+rule file_revert(bytes32 ilk, bytes32 what, address data) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ file@withrevert(e, ilk, what, data);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+ bool revert3 = what != to_bytes32(0x6275666665720000000000000000000000000000000000000000000000000000);
+
+ assert lastReverted <=> revert1 || revert2 || revert3, "Revert rules failed";
+}
diff --git a/certora/AllocatorRoles.conf b/certora/AllocatorRoles.conf
new file mode 100644
index 00000000..10376ef8
--- /dev/null
+++ b/certora/AllocatorRoles.conf
@@ -0,0 +1,10 @@
+{
+ "files": [
+ "src/AllocatorRoles.sol"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize": "200",
+ "verify": "AllocatorRoles:certora/AllocatorRoles.spec",
+ "wait_for_results": "all"
+}
diff --git a/certora/AllocatorRoles.spec b/certora/AllocatorRoles.spec
new file mode 100644
index 00000000..00f52ccc
--- /dev/null
+++ b/certora/AllocatorRoles.spec
@@ -0,0 +1,236 @@
+// AllocatorRoles.spec
+
+methods {
+ function wards(address) external returns (uint256) envfree;
+ function ilkAdmins(bytes32) external returns (address) envfree;
+ function userRoles(bytes32, address) external returns (bytes32) envfree;
+ function actionsRoles(bytes32, address, bytes4) external returns (bytes32) envfree;
+ function hasUserRole(bytes32, address, uint8) external returns (bool) envfree;
+ function hasActionRole(bytes32, address, bytes4, uint8) external returns (bool) envfree;
+ function canCall(bytes32, address, address, bytes4) external returns (bool) envfree;
+}
+
+definition bitNot(uint256 input) returns uint256 = input xor max_uint256;
+
+// Verify correct response from hasUserRole
+rule hasUserRole(bytes32 ilk, address who, uint8 role) {
+ bool ok = userRoles(ilk, who) & to_bytes32(assert_uint256(2^role)) != to_bytes32(0);
+
+ bool ok2 = hasUserRole(ilk, who, role);
+
+ assert ok2 == ok, "hasUserRole did not return the expected result";
+}
+
+// Verify correct response from hasActionRole
+rule hasActionRole(bytes32 ilk, address target, bytes4 sign, uint8 role) {
+ bool ok = actionsRoles(ilk, target, sign) & to_bytes32(assert_uint256(2^role)) != to_bytes32(0);
+
+ bool ok2 = hasActionRole(ilk, target, sign, role);
+
+ assert ok2 == ok, "hasActionRole did not return the expected result";
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+ bytes32 anyBytes32;
+ bytes4 anyBytes4;
+
+ mathint wardsBefore = wards(anyAddr);
+ address ilkAdminsBefore = ilkAdmins(anyBytes32);
+ bytes32 userRolesBefore = userRoles(anyBytes32, anyAddr);
+ bytes32 actionsRolesBefore = actionsRoles(anyBytes32, anyAddr, anyBytes4);
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ address ilkAdminsAfter = ilkAdmins(anyBytes32);
+ bytes32 userRolesAfter = userRoles(anyBytes32, anyAddr);
+ bytes32 actionsRolesAfter = actionsRoles(anyBytes32, anyAddr, anyBytes4);
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert ilkAdminsAfter != ilkAdminsBefore => f.selector == sig:setIlkAdmin(bytes32,address).selector, "ilkAdmins[x] changed in an unexpected function";
+ assert userRolesAfter != userRolesBefore => f.selector == sig:setUserRole(bytes32,address,uint8,bool).selector, "userRoles[x][y] changed in an unexpected function";
+ assert actionsRolesAfter != actionsRolesBefore => f.selector == sig:setRoleAction(bytes32,uint8,address,bytes4,bool).selector, "actionsRoles[x][y][z] changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setIlkAdmin
+rule setIlkAdmin(bytes32 ilk, address usr) {
+ env e;
+
+ bytes32 otherBytes32;
+ require otherBytes32 != ilk;
+
+ address ilkAdminsOtherBefore = ilkAdmins(otherBytes32);
+
+ setIlkAdmin(e, ilk, usr);
+
+ address ilkAdminsIlkAfter = ilkAdmins(ilk);
+ address ilkAdminsOtherAfter = ilkAdmins(otherBytes32);
+
+ assert ilkAdminsIlkAfter == usr, "setIlkAdmin did not set ilkAdmins[ilk] to usr";
+ assert ilkAdminsOtherAfter == ilkAdminsOtherBefore, "setIlkAdmin did not keep unchanged the rest of ilkAdmins[x]";
+}
+
+// Verify revert rules on setIlkAdmin
+rule setIlkAdmin_revert(bytes32 ilk, address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ setIlkAdmin@withrevert(e, ilk, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setUserRole
+rule setUserRole(bytes32 ilk, address who, uint8 role, bool enabled) {
+ env e;
+
+ bytes32 otherBytes32;
+ address otherAddr;
+ require otherBytes32 != ilk || otherAddr != who;
+
+ bytes32 userRolesIlkWhoBefore = userRoles(ilk, who);
+ bytes32 userRolesOtherBefore = userRoles(otherBytes32, otherAddr);
+ uint256 mask = assert_uint256(2^role);
+ bytes32 value = enabled ? userRolesIlkWhoBefore | to_bytes32(mask) : userRolesIlkWhoBefore & to_bytes32(bitNot(mask));
+
+ setUserRole(e, ilk, who, role, enabled);
+
+ bytes32 userRolesIlkWhoAfter = userRoles(ilk, who);
+ bytes32 userRolesOtherAfter = userRoles(otherBytes32, otherAddr);
+
+ assert userRolesIlkWhoAfter == value, "setUserRole did not set userRoles[ilk][who] by the corresponding value";
+ assert userRolesOtherAfter == userRolesOtherBefore, "setUserRole did not keep unchanged the rest of userRoles[x][y]";
+}
+
+// Verify revert rules on setUserRole
+rule setUserRole_revert(bytes32 ilk, address who, uint8 role, bool enabled) {
+ env e;
+
+ address ilkAuthIlk = ilkAdmins(ilk);
+
+ setUserRole@withrevert(e, ilk, who, role, enabled);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = ilkAuthIlk != e.msg.sender;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setRoleAction
+rule setRoleAction(bytes32 ilk, uint8 role, address target, bytes4 sign, bool enabled) {
+ env e;
+
+ bytes32 otherBytes32;
+ address otherAddr;
+ bytes4 otherBytes4;
+ require otherBytes32 != ilk || otherAddr != target || otherBytes4 != sign;
+
+ bytes32 actionsRolesIlkTargetSigBefore = actionsRoles(ilk, target, sign);
+ bytes32 actionsRolesOtherBefore = actionsRoles(otherBytes32, otherAddr, otherBytes4);
+ uint256 mask = assert_uint256(2^role);
+ bytes32 value = enabled ? actionsRolesIlkTargetSigBefore | to_bytes32(mask) : actionsRolesIlkTargetSigBefore & to_bytes32(bitNot(mask));
+
+ setRoleAction(e, ilk, role, target, sign, enabled);
+
+ bytes32 actionsRolesIlkTargetSigAfter = actionsRoles(ilk, target, sign);
+ bytes32 actionsRolesOtherAfter = actionsRoles(otherBytes32, otherAddr, otherBytes4);
+
+ assert actionsRolesIlkTargetSigAfter == value, "setRoleAction did not set actionsRoles[ilk][target][sig] by the corresponding value";
+ assert actionsRolesOtherAfter == actionsRolesOtherBefore, "setRoleAction did not keep unchanged the rest of actionsRoles[x][y][z]";
+}
+
+// Verify revert rules on setRoleAction
+rule setRoleAction_revert(bytes32 ilk, uint8 role, address target, bytes4 sign, bool enabled) {
+ env e;
+
+ address ilkAuthIlk = ilkAdmins(ilk);
+
+ setRoleAction@withrevert(e, ilk, role, target, sign, enabled);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = ilkAuthIlk != e.msg.sender;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct response from canCall
+rule canCall(bytes32 ilk, address caller, address target, bytes4 sign) {
+ bool ok = userRoles(ilk, caller) & actionsRoles(ilk, target, sign) != to_bytes32(0);
+
+ bool ok2 = canCall(ilk, caller, target, sign);
+
+ assert ok2 == ok, "canCall did not return the expected result";
+}
diff --git a/certora/AllocatorVault.conf b/certora/AllocatorVault.conf
new file mode 100644
index 00000000..9a5356c7
--- /dev/null
+++ b/certora/AllocatorVault.conf
@@ -0,0 +1,36 @@
+{
+ "files": [
+ "src/AllocatorVault.sol",
+ "src/AllocatorRoles.sol",
+ "test/mocks/VatMock.sol",
+ "test/mocks/JugMock.sol",
+ "test/mocks/UsdsJoinMock.sol",
+ "test/mocks/UsdsMock.sol"
+ ],
+ "link": [
+ "AllocatorVault:roles=AllocatorRoles",
+ "AllocatorVault:vat=VatMock",
+ "AllocatorVault:jug=JugMock",
+ "AllocatorVault:usdsJoin=UsdsJoinMock",
+ "AllocatorVault:usds=UsdsMock",
+ "JugMock:vat=VatMock",
+ "UsdsJoinMock:vat=VatMock",
+ "UsdsJoinMock:usds=UsdsMock"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize_map": {
+ "AllocatorVault": "200",
+ "AllocatorRoles": "200",
+ "VatMock": "0",
+ "JugMock": "0",
+ "UsdsJoinMock": "0",
+ "UsdsMock": "0"
+ },
+ "verify": "AllocatorVault:certora/AllocatorVault.spec",
+ "parametric_contracts": [
+ "AllocatorVault"
+ ],
+ "multi_assert_check": true,
+ "wait_for_results": "all"
+}
diff --git a/certora/AllocatorVault.spec b/certora/AllocatorVault.spec
new file mode 100644
index 00000000..cb2baad8
--- /dev/null
+++ b/certora/AllocatorVault.spec
@@ -0,0 +1,280 @@
+// AllocatorVault.spec
+
+using AllocatorRoles as roles;
+using VatMock as vat;
+using JugMock as jug;
+using UsdsJoinMock as usdsJoin;
+using UsdsMock as usds;
+
+methods {
+ function ilk() external returns (bytes32) envfree;
+ function wards(address) external returns (uint256) envfree;
+ function jug() external returns (address) envfree;
+ function buffer() external returns (address) envfree;
+ function roles.canCall(bytes32, address, address, bytes4) external returns (bool) envfree;
+ function vat.can(address, address) external returns (uint256) envfree;
+ function vat.dai(address) external returns (uint256) envfree;
+ function vat.gem(bytes32, address) external returns (uint256) envfree;
+ function vat.urns(bytes32, address) external returns (uint256, uint256) envfree;
+ function vat.rate() external returns (uint256) envfree;
+ function jug.duty() external returns (uint256) envfree;
+ function jug.rho() external returns (uint256) envfree;
+ function usds.allowance(address, address) external returns (uint256) envfree;
+ function usds.balanceOf(address) external returns (uint256) envfree;
+ function usds.totalSupply() external returns (uint256) envfree;
+}
+
+definition WAD() returns mathint = 10^18;
+definition RAY() returns mathint = 10^27;
+definition max_int256() returns mathint = 2^255 - 1;
+definition divUp(mathint x, mathint y) returns mathint = x != 0 ? ((x - 1) / y) + 1 : 0;
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+
+ mathint wardsBefore = wards(anyAddr);
+ address jugBefore = jug();
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ address jugAfter = jug();
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert jugAfter != jugBefore => f.selector == sig:file(bytes32,address).selector, "jug changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x65fae35e));
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x9c52a7f1));
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting file
+rule file(bytes32 what, address data) {
+ env e;
+
+ file(e, what, data);
+
+ address jugAfter = jug();
+
+ assert jugAfter == data, "file did not set jug";
+}
+
+// Verify revert rules on file
+rule file_revert(bytes32 what, address data) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0xd4e8be83));
+ mathint wardsSender = wards(e.msg.sender);
+
+ file@withrevert(e, what, data);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+ bool revert3 = what != to_bytes32(0x6a75670000000000000000000000000000000000000000000000000000000000);
+
+ assert lastReverted <=> revert1 || revert2 || revert3, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting draw
+rule draw(uint256 wad) {
+ env e;
+
+ mathint usdsTotalSupplyBefore = usds.totalSupply();
+ mathint usdsBalanceOfBufferBefore = usds.balanceOf(buffer());
+ require usdsBalanceOfBufferBefore <= usdsTotalSupplyBefore;
+ mathint vatInkVaultBefore; mathint vatArtVaultBefore;
+ vatInkVaultBefore, vatArtVaultBefore = vat.urns(ilk(), currentContract);
+ mathint rate = vat.rate() + (jug.duty() - RAY()) * (e.block.timestamp - jug.rho());
+ require rate > 0;
+ mathint dart = divUp(wad * RAY(), rate);
+
+ draw(e, wad);
+
+ mathint usdsTotalSupplyAfter = usds.totalSupply();
+ mathint usdsBalanceOfBufferAfter = usds.balanceOf(buffer());
+ mathint vatInkVaultAfter; mathint vatArtVaultAfter;
+ vatInkVaultAfter, vatArtVaultAfter = vat.urns(ilk(), currentContract);
+
+ assert vatInkVaultAfter == vatInkVaultBefore, "draw did not keep vat.urns(ilk,vault).ink unchanged";
+ assert vatArtVaultAfter == vatArtVaultBefore + dart, "draw did not increase vat.urns(ilk,vault).art by dart";
+ assert usdsBalanceOfBufferAfter == usdsBalanceOfBufferBefore + wad, "draw did not increase usds.balanceOf(buffer) by wad";
+ assert usdsTotalSupplyAfter == usdsTotalSupplyBefore + wad, "draw did not increase usds.totalSupply() by wad";
+}
+
+// Verify revert rules on draw
+rule draw_revert(uint256 wad) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x3b304147));
+ mathint wardsSender = wards(e.msg.sender);
+ mathint usdsTotalSupply = usds.totalSupply();
+ mathint usdsBalanceOfBuffer = usds.balanceOf(buffer());
+ require usdsBalanceOfBuffer <= usdsTotalSupply;
+ mathint vatInkVault; mathint vatArtVault;
+ vatInkVault, vatArtVault = vat.urns(ilk(), currentContract);
+ mathint duty = jug.duty();
+ require duty >= RAY();
+ mathint rho = jug.rho();
+ require to_mathint(e.block.timestamp) >= rho;
+ mathint rate = vat.rate() + (duty - RAY()) * (e.block.timestamp - jug.rho());
+ require rate > 0 && rate <= max_int256();
+ mathint dart = divUp(wad * RAY(), rate);
+ mathint vatDaiVault = vat.dai(currentContract);
+ mathint vatCanVaultUsdsJoin = vat.can(currentContract, usdsJoin);
+ mathint vatDaiUsdsJoin = vat.dai(usdsJoin);
+
+ draw@withrevert(e, wad);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+ bool revert3 = wad * RAY() > max_uint256;
+ bool revert4 = dart > max_int256();
+ bool revert5 = vatArtVault + dart > max_uint256;
+ bool revert6 = rate * dart > max_int256();
+ bool revert7 = vatDaiVault + rate * dart > max_uint256;
+ bool revert8 = vatCanVaultUsdsJoin != 1;
+ bool revert9 = vatDaiUsdsJoin + wad * RAY() > max_uint256;
+ bool revert10 = usdsTotalSupply + wad > max_uint256;
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6 ||
+ revert7 || revert8 || revert9 ||
+ revert10, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting wipe
+rule wipe(uint256 wad) {
+ env e;
+
+ mathint usdsTotalSupplyBefore = usds.totalSupply();
+ mathint usdsBalanceOfBufferBefore = usds.balanceOf(buffer());
+ require usdsBalanceOfBufferBefore <= usdsTotalSupplyBefore;
+ mathint vatInkVaultBefore; mathint vatArtVaultBefore;
+ vatInkVaultBefore, vatArtVaultBefore = vat.urns(ilk(), currentContract);
+ mathint rate = vat.rate() + (jug.duty() - RAY()) * (e.block.timestamp - jug.rho());
+ require rate > 0;
+ mathint dart = wad * RAY() / rate;
+
+ wipe(e, wad);
+
+ mathint usdsTotalSupplyAfter = usds.totalSupply();
+ mathint usdsBalanceOfBufferAfter = usds.balanceOf(buffer());
+ mathint vatInkVaultAfter; mathint vatArtVaultAfter;
+ vatInkVaultAfter, vatArtVaultAfter = vat.urns(ilk(), currentContract);
+
+ assert vatInkVaultAfter == vatInkVaultBefore, "wipe did not keep vat.urns(ilk,vault).ink unchanged";
+ assert vatArtVaultAfter == vatArtVaultBefore - dart, "wipe did not decrease vat.urns(ilk,vault).art by dart";
+ assert usdsBalanceOfBufferAfter == usdsBalanceOfBufferBefore - wad, "wipe did not decrease usds.balanceOf(buffer) by wad";
+ assert usdsTotalSupplyAfter == usdsTotalSupplyBefore - wad, "wipe did not decrease usds.totalSupply() by wad";
+}
+
+// Verify revert rules on wipe
+rule wipe_revert(uint256 wad) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0xb38a1620));
+ mathint wardsSender = wards(e.msg.sender);
+ mathint usdsTotalSupply = usds.totalSupply();
+ address buffer = buffer();
+ require buffer != currentContract;
+ mathint usdsBalanceOfBuffer = usds.balanceOf(buffer);
+ mathint usdsBalanceOfVault = usds.balanceOf(currentContract);
+ require usdsBalanceOfBuffer + usdsBalanceOfVault <= usdsTotalSupply;
+ mathint usdsAllowanceBufferVault = usds.allowance(buffer, currentContract);
+ mathint usdsAllowanceVaultUsdsJoin = usds.allowance(currentContract, usdsJoin);
+ mathint vatInkVault; mathint vatArtVault;
+ vatInkVault, vatArtVault = vat.urns(ilk(), currentContract);
+ mathint duty = jug.duty();
+ require duty >= RAY();
+ mathint rho = jug.rho();
+ require to_mathint(e.block.timestamp) >= rho;
+ mathint rate = vat.rate() + (duty - RAY()) * (e.block.timestamp - jug.rho());
+ require rate > 0 && rate <= max_int256();
+ mathint dart = wad * RAY() / rate;
+ mathint vatDaiVault = vat.dai(currentContract);
+ mathint vatDaiUsdsJoin = vat.dai(usdsJoin);
+
+ wipe@withrevert(e, wad);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+ bool revert3 = usdsBalanceOfBuffer < to_mathint(wad);
+ bool revert4 = usdsAllowanceBufferVault < to_mathint(wad);
+ bool revert5 = wad * RAY() > max_uint256;
+ bool revert6 = usdsAllowanceVaultUsdsJoin < to_mathint(wad);
+ bool revert7 = vatArtVault < dart;
+ bool revert8 = vatDaiUsdsJoin < wad * RAY();
+ bool revert9 = vatDaiVault + wad * RAY() > max_uint256;
+ bool revert10 = rate * dart > max_int256();
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6 ||
+ revert7 || revert8 || revert9 ||
+ revert10, "Revert rules failed";
+}
diff --git a/certora/funnels/Auxiliar.sol b/certora/funnels/Auxiliar.sol
new file mode 100644
index 00000000..007ceb11
--- /dev/null
+++ b/certora/funnels/Auxiliar.sol
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+contract Auxiliar {
+ function getHash(address addr, int24 tickLower, int24 tickUpper) external pure returns (bytes32 hashC) {
+ hashC = keccak256(abi.encodePacked(addr, tickLower, tickUpper));
+ }
+
+ function decode(bytes calldata data) external pure returns (address gem0, address gem1, uint24 fee) {
+ (gem0, gem1, fee) = abi.decode(data, (address, address, uint24));
+ }
+}
diff --git a/certora/funnels/DepositorUniV3.conf b/certora/funnels/DepositorUniV3.conf
new file mode 100644
index 00000000..ae5dbe0e
--- /dev/null
+++ b/certora/funnels/DepositorUniV3.conf
@@ -0,0 +1,28 @@
+{
+ "files": [
+ "src/funnels/DepositorUniV3.sol",
+ "src/AllocatorRoles.sol",
+ "test/mocks/PoolUniV3Mock.sol",
+ "test/mocks/Gem0Mock.sol",
+ "test/mocks/Gem1Mock.sol",
+ "certora/funnels/Auxiliar.sol"
+ ],
+ "link": [
+ "DepositorUniV3:roles=AllocatorRoles"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize_map": {
+ "DepositorUniV3": "200",
+ "AllocatorRoles": "200",
+ "PoolUniV3Mock": "0",
+ "Gem0Mock": "0",
+ "Gem1Mock": "0",
+ "Auxiliar": "0"
+ },
+ "verify": "DepositorUniV3:certora/funnels/DepositorUniV3.spec",
+ "parametric_contracts": [
+ "DepositorUniV3"
+ ],
+ "wait_for_results": "all"
+}
diff --git a/certora/funnels/DepositorUniV3.spec b/certora/funnels/DepositorUniV3.spec
new file mode 100644
index 00000000..27221a6b
--- /dev/null
+++ b/certora/funnels/DepositorUniV3.spec
@@ -0,0 +1,606 @@
+// DepositorUniV3.spec
+
+using AllocatorRoles as roles;
+using PoolUniV3Mock as poolCon;
+using Gem0Mock as gem0Con;
+using Gem1Mock as gem1Con;
+using Auxiliar as aux;
+
+methods {
+ function ilk() external returns (bytes32) envfree;
+ function buffer() external returns (address) envfree;
+ function wards(address) external returns (uint256) envfree;
+ function limits(address, address, uint24) external returns (uint96, uint96, uint32, uint96, uint96, uint32) envfree;
+ function _getPool(address gem0, address gem1, uint24 fee) internal returns (address) => getPoolSummary(gem0, gem1, fee);
+ function _getLiquidityForAmts(address pool, int24 tickLower, int24 tickUpper, uint256 amt0Desired, uint256 amt1Desired) internal returns (uint128) => getLiquidityForAmtsSummary(pool, tickLower, tickUpper, amt0Desired, amt1Desired);
+ function getPosition(address, address, uint24, int24, int24) external returns (uint128, uint256, uint256, uint128, uint128) envfree;
+ function roles.canCall(bytes32, address, address, bytes4) external returns (bool) envfree;
+ function _.mint(address, int24, int24, uint128, bytes) external => DISPATCHER(true);
+ function _.burn(int24, int24, uint128) external => DISPATCHER(true);
+ function _.collect(address, int24, int24, uint128, uint128) external => DISPATCHER(true);
+ function _.uniswapV3MintCallback(uint256, uint256, bytes) external => DISPATCHER(true);
+ function poolCon.gem0() external returns (address) envfree;
+ function poolCon.gem1() external returns (address) envfree;
+ function poolCon.fee() external returns (uint24) envfree;
+ function poolCon.random0() external returns (uint128) envfree;
+ function poolCon.random1() external returns (uint128) envfree;
+ function poolCon.random2() external returns (uint128) envfree;
+ function poolCon.random3() external returns (uint128) envfree;
+ function _.positions(bytes32) external => DISPATCHER(true);
+ function gem0Con.balanceOf(address) external returns (uint256) envfree;
+ function gem1Con.balanceOf(address) external returns (uint256) envfree;
+ function gem0Con.allowance(address, address) external returns (uint256) envfree;
+ function gem1Con.allowance(address, address) external returns (uint256) envfree;
+ function aux.getHash(address, int24, int24) external returns (bytes32) envfree;
+ function aux.decode(bytes) external returns (address, address, uint24) envfree;
+ function _.transfer(address, uint256) external => DISPATCHER(true) UNRESOLVED;
+ function _.transferFrom(address, address, uint256) external => DISPATCHER(true) UNRESOLVED;
+}
+
+ghost mapping(address => mapping(int24 => mapping(int24 => mapping(uint256 => mapping(uint256 => uint128))))) _liquidityMap;
+
+function getLiquidityForAmtsSummary(address pool, int24 tickLower, int24 tickUpper, uint256 amt0Desired, uint256 amt1Desired) returns uint128 {
+ return _liquidityMap[pool][tickLower][tickUpper][amt0Desired][amt1Desired];
+}
+
+ghost mapping(address => mapping(address => mapping(uint24 => address))) _poolMap;
+
+function getPoolSummary(address gem0, address gem1, uint24 fee) returns address {
+ return _poolMap[gem0][gem1][fee];
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+ address anyAddr_2;
+ uint24 anyUint24;
+
+ mathint wardsBefore = wards(anyAddr);
+ mathint cap0Before; mathint cap1Before; mathint eraBefore; mathint due0Before; mathint due1Before; mathint endBefore;
+ cap0Before, cap1Before, eraBefore, due0Before, due1Before, endBefore = limits(anyAddr, anyAddr_2, anyUint24);
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ mathint cap0After; mathint cap1After; mathint eraAfter; mathint due0After; mathint due1After; mathint endAfter;
+ cap0After, cap1After, eraAfter, due0After, due1After, endAfter = limits(anyAddr, anyAddr_2, anyUint24);
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert cap0After != cap0Before => f.selector == sig:setLimits(address,address,uint24,uint96,uint96,uint32).selector, "limits[x][y][z].cap0 changed in an unexpected function";
+ assert cap1After != cap1Before => f.selector == sig:setLimits(address,address,uint24,uint96,uint96,uint32).selector, "limits[x][y][z].cap1 changed in an unexpected function";
+ assert eraAfter != eraBefore => f.selector == sig:setLimits(address,address,uint24,uint96,uint96,uint32).selector, "limits[x][y][z].era changed in an unexpected function";
+ assert due0After != due0Before => f.selector == sig:setLimits(address,address,uint24,uint96,uint96,uint32).selector || f.selector == sig:deposit(DepositorUniV3.LiquidityParams).selector || f.selector == sig:withdraw(DepositorUniV3.LiquidityParams,bool).selector, "limits[x][y][z].due0 changed in an unexpected function";
+ assert due1After != due1Before => f.selector == sig:setLimits(address,address,uint24,uint96,uint96,uint32).selector || f.selector == sig:deposit(DepositorUniV3.LiquidityParams).selector || f.selector == sig:withdraw(DepositorUniV3.LiquidityParams,bool).selector, "limits[x][y][z].due1 changed in an unexpected function";
+ assert endAfter != endBefore => f.selector == sig:setLimits(address,address,uint24,uint96,uint96,uint32).selector || f.selector == sig:deposit(DepositorUniV3.LiquidityParams).selector || f.selector == sig:withdraw(DepositorUniV3.LiquidityParams,bool).selector, "limits[x][y][z].end changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x65fae35e));
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x9c52a7f1));
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setLimits
+rule setLimits(address gem0, address gem1, uint24 fee, uint96 cap0, uint96 cap1, uint32 era) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ uint24 otherUint24;
+ require otherAddr != gem0 || otherAddr_2 != gem1 || otherUint24 != fee;
+
+ mathint cap0OtherBefore; mathint cap1OtherBefore; mathint eraOtherBefore; mathint due0OtherBefore; mathint due1OtherBefore; mathint endOtherBefore;
+ cap0OtherBefore, cap1OtherBefore, eraOtherBefore, due0OtherBefore, due1OtherBefore, endOtherBefore = limits(otherAddr, otherAddr_2, otherUint24);
+
+ setLimits(e, gem0, gem1, fee, cap0, cap1, era);
+
+ mathint cap0Gem0Gem1FeeAfter; mathint cap1Gem0Gem1FeeAfter; mathint eraGem0Gem1FeeAfter; mathint due0Gem0Gem1FeeAfter; mathint due1Gem0Gem1FeeAfter; mathint endGem0Gem1FeeAfter;
+ cap0Gem0Gem1FeeAfter, cap1Gem0Gem1FeeAfter, eraGem0Gem1FeeAfter, due0Gem0Gem1FeeAfter, due1Gem0Gem1FeeAfter, endGem0Gem1FeeAfter = limits(gem0, gem1, fee);
+ mathint cap0OtherAfter; mathint cap1OtherAfter; mathint eraOtherAfter; mathint due0OtherAfter; mathint due1OtherAfter; mathint endOtherAfter;
+ cap0OtherAfter, cap1OtherAfter, eraOtherAfter, due0OtherAfter, due1OtherAfter, endOtherAfter = limits(otherAddr, otherAddr_2, otherUint24);
+
+ assert cap0Gem0Gem1FeeAfter == to_mathint(cap0), "setLimits did not set limits[gem0][gem1][fee].cap0 to cap0";
+ assert cap1Gem0Gem1FeeAfter == to_mathint(cap1), "setLimits did not set limits[gem0][gem1][fee].cap1 to cap1";
+ assert eraGem0Gem1FeeAfter == to_mathint(era), "setLimits did not set limits[gem0][gem1][fee].era to era";
+ assert due0Gem0Gem1FeeAfter == 0, "setLimits did not set limits[gem0][gem1][fee].due0 to 0";
+ assert due1Gem0Gem1FeeAfter == 0, "setLimits did not set limits[gem0][gem1][fee].due1 to 0";
+ assert endGem0Gem1FeeAfter == 0, "setLimits did not set limits[gem0][gem1][fee].end to 0";
+ assert cap0OtherAfter == cap0OtherBefore, "setLimits did not keep unchanged the rest of limits[x][y][z].cap0";
+ assert cap1OtherAfter == cap1OtherBefore, "setLimits did not keep unchanged the rest of limits[x][y][z].cap1";
+ assert eraOtherAfter == eraOtherBefore, "setLimits did not keep unchanged the rest of limits[x][y][z].era";
+ assert due0OtherAfter == due0OtherBefore, "setLimits did not keep unchanged the rest of limits[x][y][z].due0";
+ assert due1OtherAfter == due1OtherBefore, "setLimits did not keep unchanged the rest of limits[x][y][z].due1";
+ assert endOtherAfter == endOtherBefore, "setLimits did not keep unchanged the rest of limits[x][y][z].end";
+}
+
+// Verify revert rules on setLimits
+rule setLimits_revert(address gem0, address gem1, uint24 fee, uint96 cap0, uint96 cap1, uint32 era) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x222df168));
+ mathint wardsSender = wards(e.msg.sender);
+
+ setLimits@withrevert(e, gem0, gem1, fee, cap0, cap1, era);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+ bool revert3 = gem0 >= gem1;
+
+ assert lastReverted <=> revert1 || revert2 || revert3, "Revert rules failed";
+}
+
+// Verify correct response from getPosition
+rule getPosition(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper) {
+ env e;
+
+ bytes32 hashC = aux.getHash(currentContract, tickLower, tickUpper);
+ mathint expLiquidity; mathint expFeeGrowthInside0LastX128; mathint expFeeGrowthInside1LastX128; mathint expTokensOwed0; mathint expTokensOwed1;
+ expLiquidity, expFeeGrowthInside0LastX128, expFeeGrowthInside1LastX128, expTokensOwed0, expTokensOwed1 = poolCon.positions(e, hashC);
+
+ mathint liquidity; mathint feeGrowthInside0LastX128; mathint feeGrowthInside1LastX128; mathint tokensOwed0; mathint tokensOwed1;
+ liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1 = getPosition(gem0, gem1, fee, tickLower, tickUpper);
+
+ assert liquidity == expLiquidity, "getPosition did not return the expected liquidity value";
+ assert feeGrowthInside0LastX128 == expFeeGrowthInside0LastX128, "getPosition did not return the expected feeGrowthInside0LastX128 value";
+ assert feeGrowthInside1LastX128 == expFeeGrowthInside1LastX128, "getPosition did not return the expected feeGrowthInside1LastX128 value";
+ assert tokensOwed0 == expTokensOwed0, "getPosition did not return the expected tokensOwed0 value";
+ assert tokensOwed1 == expTokensOwed1, "getPosition did not return the expected tokensOwed1 value";
+}
+
+// Verify correct storage changes for non reverting uniswapV3MintCallback
+rule uniswapV3MintCallback(uint256 amt0Owed, uint256 amt1Owed, bytes data) {
+ env e;
+
+ address gem0; address gem1; uint24 fee;
+ gem0, gem1, fee = aux.decode(data);
+
+ require gem0 == gem0Con;
+ require gem1 == gem1Con;
+
+ address buffer = buffer();
+ require buffer != e.msg.sender;
+
+ mathint gem0BalanceOfBufferBefore = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBufferBefore = gem1Con.balanceOf(buffer);
+ mathint gem0BalanceOfSenderBefore = gem0Con.balanceOf(e.msg.sender);
+ mathint gem1BalanceOfSenderBefore = gem1Con.balanceOf(e.msg.sender);
+
+ require gem0BalanceOfBufferBefore + gem0BalanceOfSenderBefore <= max_uint256;
+ require gem1BalanceOfBufferBefore + gem1BalanceOfSenderBefore <= max_uint256;
+
+ uniswapV3MintCallback(e, amt0Owed, amt1Owed, data);
+
+ mathint gem0BalanceOfBufferAfter = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBufferAfter = gem1Con.balanceOf(buffer);
+ mathint gem0BalanceOfSenderAfter = gem0Con.balanceOf(e.msg.sender);
+ mathint gem1BalanceOfSenderAfter = gem1Con.balanceOf(e.msg.sender);
+
+ assert gem0BalanceOfBufferAfter == gem0BalanceOfBufferBefore - amt0Owed, "uniswapV3MintCallback did not decrease gem0.balanceOf(buffer) by amt0Owed";
+ assert gem1BalanceOfBufferAfter == gem1BalanceOfBufferBefore - amt1Owed, "uniswapV3MintCallback did not decrease gem1.balanceOf(buffer) by amt1Owed";
+ assert gem0BalanceOfSenderAfter == gem0BalanceOfSenderBefore + amt0Owed, "uniswapV3MintCallback did not increase gem0.balanceOf(pool) by amt0Owed";
+ assert gem1BalanceOfSenderAfter == gem1BalanceOfSenderBefore + amt1Owed, "uniswapV3MintCallback did not increase gem1.balanceOf(pool) by amt1Owed";
+}
+
+// Verify revert rules on uniswapV3MintCallback
+rule uniswapV3MintCallback_revert(uint256 amt0Owed, uint256 amt1Owed, bytes data) {
+ env e;
+
+ address gem0; address gem1; uint24 fee;
+ gem0, gem1, fee = aux.decode(data);
+
+ require gem0 == gem0Con;
+ require gem1 == gem1Con;
+
+ address buffer = buffer();
+ require buffer != currentContract;
+ require buffer != e.msg.sender;
+
+ address pool = getPoolSummary(gem0, gem1, fee);
+
+ mathint gem0BalanceOfBuffer = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBuffer = gem1Con.balanceOf(buffer);
+ mathint gem0AllowanceBufferDepositor = gem0Con.allowance(buffer, currentContract);
+ mathint gem1AllowanceBufferDepositor = gem1Con.allowance(buffer, currentContract);
+
+ require gem0BalanceOfBuffer + gem0Con.balanceOf(e.msg.sender) <= max_uint256;
+ require gem1BalanceOfBuffer + gem1Con.balanceOf(e.msg.sender) <= max_uint256;
+
+ uniswapV3MintCallback@withrevert(e, amt0Owed, amt1Owed, data);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = e.msg.sender != pool;
+ bool revert3 = gem0BalanceOfBuffer < to_mathint(amt0Owed);
+ bool revert4 = gem0AllowanceBufferDepositor < to_mathint(amt0Owed);
+ bool revert5 = gem1BalanceOfBuffer < to_mathint(amt1Owed);
+ bool revert6 = gem1AllowanceBufferDepositor < to_mathint(amt1Owed);
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deposit
+rule deposit(DepositorUniV3.LiquidityParams p) {
+ env e;
+
+ require p.gem0 == gem0Con;
+ require p.gem1 == gem1Con;
+ require p.gem0 == poolCon.gem0();
+ require p.gem1 == poolCon.gem1();
+ require p.fee == poolCon.fee();
+
+ address otherAddr;
+ address otherAddr_2;
+ uint24 otherUint24;
+ require otherAddr != p.gem0 || otherAddr_2 != p.gem1 || otherUint24 != p.fee;
+
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+ require buffer != poolCon;
+
+ mathint a; mathint b; mathint c;
+
+ mathint cap0Gem0Gem1Fee; mathint cap1Gem0Gem1Fee; mathint eraGem0Gem1Fee; mathint due0Gem0Gem1FeeBefore; mathint due1Gem0Gem1FeeBefore; mathint endGem0Gem1FeeBefore;
+ cap0Gem0Gem1Fee, cap1Gem0Gem1Fee, eraGem0Gem1Fee, due0Gem0Gem1FeeBefore, due1Gem0Gem1FeeBefore, endGem0Gem1FeeBefore = limits(p.gem0, p.gem1, p.fee);
+ mathint due0OtherBefore; mathint due1OtherBefore; mathint endOtherBefore;
+ a, b, c, due0OtherBefore, due1OtherBefore, endOtherBefore = limits(otherAddr, otherAddr_2, otherUint24);
+ mathint gem0BalanceOfBufferBefore = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBufferBefore = gem1Con.balanceOf(buffer);
+ mathint gem0BalanceOfPoolBefore = gem0Con.balanceOf(poolCon);
+ mathint gem1BalanceOfPoolBefore = gem1Con.balanceOf(poolCon);
+
+ require gem0BalanceOfBufferBefore + gem0BalanceOfPoolBefore <= max_uint256;
+ require gem1BalanceOfBufferBefore + gem1BalanceOfPoolBefore <= max_uint256;
+
+ mathint amt0 = poolCon.random0();
+ mathint amt1 = poolCon.random1();
+
+ mathint liquidity = p.liquidity > 0 ? p.liquidity : getLiquidityForAmtsSummary(poolCon, p.tickLower, p.tickUpper, p.amt0Desired, p.amt1Desired);
+
+ mathint retLiq; mathint retAmt0; mathint retAmt1;
+ retLiq, retAmt0, retAmt1 = deposit(e, p);
+
+ mathint due0Gem0Gem1FeeAfter; mathint due1Gem0Gem1FeeAfter; mathint endGem0Gem1FeeAfter;
+ a, b, c, due0Gem0Gem1FeeAfter, due1Gem0Gem1FeeAfter, endGem0Gem1FeeAfter = limits(p.gem0, p.gem1, p.fee);
+ mathint due0OtherAfter; mathint due1OtherAfter; mathint endOtherAfter;
+ a, b, c, due0OtherAfter, due1OtherAfter, endOtherAfter = limits(otherAddr, otherAddr_2, otherUint24);
+ mathint gem0BalanceOfBufferAfter = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBufferAfter = gem1Con.balanceOf(buffer);
+ mathint gem0BalanceOfPoolAfter = gem0Con.balanceOf(poolCon);
+ mathint gem1BalanceOfPoolAfter = gem1Con.balanceOf(poolCon);
+
+ mathint expectedDue0 = (to_mathint(e.block.timestamp) >= endGem0Gem1FeeBefore ? cap0Gem0Gem1Fee : due0Gem0Gem1FeeBefore) - amt0;
+ mathint expectedDue1 = (to_mathint(e.block.timestamp) >= endGem0Gem1FeeBefore ? cap1Gem0Gem1Fee : due1Gem0Gem1FeeBefore) - amt1;
+ mathint expectedEnd = to_mathint(e.block.timestamp) >= endGem0Gem1FeeBefore ? e.block.timestamp + eraGem0Gem1Fee : endGem0Gem1FeeBefore;
+
+ assert due0Gem0Gem1FeeAfter == expectedDue0, "deposit did not set limits[gem0][gem1][fee].due0 to the expected value";
+ assert due1Gem0Gem1FeeAfter == expectedDue1, "deposit did not set limits[gem0][gem1][fee].due1 to the expected value";
+ assert endGem0Gem1FeeAfter == expectedEnd, "deposit did not set limits[gem0][gem1][fee].end to the expected value";
+ assert due0OtherAfter == due0OtherBefore, "deposit did not keep unchanged the rest of limits[x][y][z].due0";
+ assert due1OtherAfter == due1OtherBefore, "deposit did not keep unchanged the rest of limits[x][y][z].due1";
+ assert endOtherAfter == endOtherBefore, "deposit did not keep unchanged the rest of limits[x][y][z].end";
+ assert gem0BalanceOfBufferAfter == gem0BalanceOfBufferBefore - amt0, "deposit did not decrease gem0.balanceOf(buffer) by amt0";
+ assert gem1BalanceOfBufferAfter == gem1BalanceOfBufferBefore - amt1, "deposit did not decrease gem1.balanceOf(buffer) by amt1";
+ assert gem0BalanceOfPoolAfter == gem0BalanceOfPoolBefore + amt0, "deposit did not increase gem0.balanceOf(pool) by amt0";
+ assert gem1BalanceOfPoolAfter == gem1BalanceOfPoolBefore + amt1, "deposit did not increase gem1.balanceOf(pool) by amt1";
+ assert retLiq == liquidity, "deposit did not return the expected liquidity";
+ assert retAmt0 == amt0, "deposit did not return the expected amt0";
+ assert retAmt1 == amt1, "deposit did not return the expected amt1";
+}
+
+// Verify revert rules on deposit
+rule deposit_revert(DepositorUniV3.LiquidityParams p) {
+ env e;
+
+ require p.gem0 == gem0Con;
+ require p.gem1 == gem1Con;
+ require p.gem0 == poolCon.gem0();
+ require p.gem1 == poolCon.gem1();
+ require p.fee == poolCon.fee();
+
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+ require buffer != currentContract;
+ require buffer != poolCon;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0xc82cb114));
+ mathint wardsSender = wards(e.msg.sender);
+ mathint cap0Gem0Gem1Fee; mathint cap1Gem0Gem1Fee; mathint eraGem0Gem1Fee; mathint due0Gem0Gem1Fee; mathint due1Gem0Gem1Fee; mathint endGem0Gem1Fee;
+ cap0Gem0Gem1Fee, cap1Gem0Gem1Fee, eraGem0Gem1Fee, due0Gem0Gem1Fee, due1Gem0Gem1Fee, endGem0Gem1Fee = limits(p.gem0, p.gem1, p.fee);
+ mathint amt0 = poolCon.random0();
+ mathint amt1 = poolCon.random1();
+ mathint gem0AllowanceBufferDepositor = gem0Con.allowance(buffer, currentContract);
+ mathint gem0BalanceOfBuffer = gem0Con.balanceOf(buffer);
+ mathint gem1AllowanceBufferDepositor = gem1Con.allowance(buffer, currentContract);
+ mathint gem1BalanceOfBuffer = gem1Con.balanceOf(buffer);
+ mathint due0Updated = to_mathint(e.block.timestamp) >= endGem0Gem1Fee ? cap0Gem0Gem1Fee : due0Gem0Gem1Fee;
+ mathint due1Updated = to_mathint(e.block.timestamp) >= endGem0Gem1Fee ? cap1Gem0Gem1Fee : due1Gem0Gem1Fee;
+
+ deposit@withrevert(e, p);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+ bool revert3 = p.gem0 >= p.gem1;
+ bool revert4 = to_mathint(e.block.timestamp) >= endGem0Gem1Fee && e.block.timestamp + eraGem0Gem1Fee > max_uint32;
+ bool revert5 = gem0AllowanceBufferDepositor < amt0;
+ bool revert6 = gem0BalanceOfBuffer < amt0;
+ bool revert7 = gem1AllowanceBufferDepositor < amt1;
+ bool revert8 = gem1BalanceOfBuffer < amt1;
+ bool revert9 = amt0 < to_mathint(p.amt0Min) || amt1 < to_mathint(p.amt1Min);
+ bool revert10 = amt0 > due0Updated || amt1 > due1Updated;
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6 ||
+ revert7 || revert8 || revert9 ||
+ revert10, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting withdraw
+rule withdraw(DepositorUniV3.LiquidityParams p, bool takeFees) {
+ env e;
+
+ require p.gem0 == gem0Con;
+ require p.gem1 == gem1Con;
+ require p.gem0 == poolCon.gem0();
+ require p.gem1 == poolCon.gem1();
+ require p.fee == poolCon.fee();
+
+ require poolCon.random2() >= poolCon.random0();
+ require poolCon.random3() >= poolCon.random1();
+
+ address otherAddr;
+ address otherAddr_2;
+ uint24 otherUint24;
+ require otherAddr != p.gem0 || otherAddr_2 != p.gem1 || otherUint24 != p.fee;
+
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+ require buffer != poolCon;
+
+ mathint a; mathint b; mathint c;
+
+ mathint cap0Gem0Gem1Fee; mathint cap1Gem0Gem1Fee; mathint eraGem0Gem1Fee; mathint due0Gem0Gem1FeeBefore; mathint due1Gem0Gem1FeeBefore; mathint endGem0Gem1FeeBefore;
+ cap0Gem0Gem1Fee, cap1Gem0Gem1Fee, eraGem0Gem1Fee, due0Gem0Gem1FeeBefore, due1Gem0Gem1FeeBefore, endGem0Gem1FeeBefore = limits(p.gem0, p.gem1, p.fee);
+ mathint cap0OtherBefore; mathint cap1OtherBefore; mathint eraOtherBefore; mathint due0OtherBefore; mathint due1OtherBefore; mathint endOtherBefore;
+ a, b, c, due0OtherBefore, due1OtherBefore, endOtherBefore = limits(otherAddr, otherAddr_2, otherUint24);
+ mathint gem0BalanceOfBufferBefore = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBufferBefore = gem1Con.balanceOf(buffer);
+ mathint gem0BalanceOfPoolBefore = gem0Con.balanceOf(poolCon);
+ mathint gem1BalanceOfPoolBefore = gem1Con.balanceOf(poolCon);
+
+ require gem0BalanceOfBufferBefore + gem0BalanceOfPoolBefore <= max_uint256;
+ require gem1BalanceOfBufferBefore + gem1BalanceOfPoolBefore <= max_uint256;
+
+ mathint amt0 = poolCon.random0();
+ mathint amt1 = poolCon.random1();
+ mathint col0 = takeFees ? poolCon.random2() : amt0;
+ mathint col1 = takeFees ? poolCon.random3() : amt1;
+
+ mathint liquidity = p.liquidity > 0 ? p.liquidity : getLiquidityForAmtsSummary(poolCon, p.tickLower, p.tickUpper, p.amt0Desired, p.amt1Desired);
+
+ mathint retLiq; mathint retAmt0; mathint retAmt1; mathint retFees0; mathint retFees1;
+ retLiq, retAmt0, retAmt1, retFees0, retFees1 = withdraw(e, p, takeFees);
+
+ mathint due0Gem0Gem1FeeAfter; mathint due1Gem0Gem1FeeAfter; mathint endGem0Gem1FeeAfter;
+ a, b, c, due0Gem0Gem1FeeAfter, due1Gem0Gem1FeeAfter, endGem0Gem1FeeAfter = limits(p.gem0, p.gem1, p.fee);
+ mathint due0OtherAfter; mathint due1OtherAfter; mathint endOtherAfter;
+ a, b, c, due0OtherAfter, due1OtherAfter, endOtherAfter = limits(otherAddr, otherAddr_2, otherUint24);
+ mathint gem0BalanceOfBufferAfter = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBufferAfter = gem1Con.balanceOf(buffer);
+ mathint gem0BalanceOfPoolAfter = gem0Con.balanceOf(poolCon);
+ mathint gem1BalanceOfPoolAfter = gem1Con.balanceOf(poolCon);
+
+ mathint expectedDue0 = (to_mathint(e.block.timestamp) >= endGem0Gem1FeeBefore ? cap0Gem0Gem1Fee : due0Gem0Gem1FeeBefore) - amt0;
+ mathint expectedDue1 = (to_mathint(e.block.timestamp) >= endGem0Gem1FeeBefore ? cap1Gem0Gem1Fee : due1Gem0Gem1FeeBefore) - amt1;
+ mathint expectedEnd = to_mathint(e.block.timestamp) >= endGem0Gem1FeeBefore ? e.block.timestamp + eraGem0Gem1Fee : endGem0Gem1FeeBefore;
+
+ assert due0Gem0Gem1FeeAfter == expectedDue0, "withdraw did not set limits[gem0][gem1][fee].due0 to the expected value";
+ assert due1Gem0Gem1FeeAfter == expectedDue1, "withdraw did not set limits[gem0][gem1][fee].due1 to the expected value";
+ assert endGem0Gem1FeeAfter == expectedEnd, "withdraw did not set limits[gem0][gem1][fee].end to the expected value";
+ assert due0OtherAfter == due0OtherBefore, "withdraw did not keep unchanged the rest of limits[x][y][z].due0";
+ assert due1OtherAfter == due1OtherBefore, "withdraw did not keep unchanged the rest of limits[x][y][z].due1";
+ assert endOtherAfter == endOtherBefore, "withdraw did not keep unchanged the rest of limits[x][y][z].end";
+ assert gem0BalanceOfBufferAfter == gem0BalanceOfBufferBefore + col0, "withdraw did not increase gem0.balanceOf(buffer) by col0";
+ assert gem1BalanceOfBufferAfter == gem1BalanceOfBufferBefore + col1, "withdraw did not increase gem1.balanceOf(buffer) by col1";
+ assert gem0BalanceOfPoolAfter == gem0BalanceOfPoolBefore - col0, "withdraw did not decrease gem0.balanceOf(pool) by col0";
+ assert gem1BalanceOfPoolAfter == gem1BalanceOfPoolBefore - col1, "withdraw did not decrease gem1.balanceOf(pool) by col1";
+ assert retLiq == liquidity, "withdraw did not return the expected liquidity";
+ assert retAmt0 == amt0, "withdraw did not return the expected amt0";
+ assert retAmt1 == amt1, "withdraw did not return the expected amt1";
+ assert retFees0 == col0 - amt0, "withdraw did not return the expected col0 - amt0";
+ assert retFees1 == col1 - amt1, "withdraw did not return the expected col1 - amt1";
+}
+
+// Verify revert rules on withdraw
+rule withdraw_revert(DepositorUniV3.LiquidityParams p, bool takeFees) {
+ env e;
+
+ require p.gem0 == gem0Con;
+ require p.gem1 == gem1Con;
+ require p.gem0 == poolCon.gem0();
+ require p.gem1 == poolCon.gem1();
+ require p.fee == poolCon.fee();
+
+ require poolCon.random2() >= poolCon.random0();
+ require poolCon.random3() >= poolCon.random1();
+
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+ require buffer != currentContract;
+ require buffer != poolCon;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0xcd8e305c));
+ mathint wardsSender = wards(e.msg.sender);
+ mathint cap0Gem0Gem1Fee; mathint cap1Gem0Gem1Fee; mathint eraGem0Gem1Fee; mathint due0Gem0Gem1Fee; mathint due1Gem0Gem1Fee; mathint endGem0Gem1Fee;
+ cap0Gem0Gem1Fee, cap1Gem0Gem1Fee, eraGem0Gem1Fee, due0Gem0Gem1Fee, due1Gem0Gem1Fee, endGem0Gem1Fee = limits(p.gem0, p.gem1, p.fee);
+ mathint amt0 = poolCon.random0();
+ mathint amt1 = poolCon.random1();
+ mathint col0 = takeFees ? poolCon.random2() : amt0;
+ mathint col1 = takeFees ? poolCon.random3() : amt1;
+ mathint gem0BalanceOfPool = gem0Con.balanceOf(poolCon);
+ mathint gem1BalanceOfPool = gem1Con.balanceOf(poolCon);
+ require gem0BalanceOfPool >= col0;
+ require gem1BalanceOfPool >= col1;
+ mathint due0Updated = to_mathint(e.block.timestamp) >= endGem0Gem1Fee ? cap0Gem0Gem1Fee : due0Gem0Gem1Fee;
+ mathint due1Updated = to_mathint(e.block.timestamp) >= endGem0Gem1Fee ? cap1Gem0Gem1Fee : due1Gem0Gem1Fee;
+
+ withdraw@withrevert(e, p, takeFees);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+ bool revert3 = p.gem0 >= p.gem1;
+ bool revert4 = to_mathint(e.block.timestamp) >= endGem0Gem1Fee && e.block.timestamp + eraGem0Gem1Fee > max_uint32;
+ bool revert5 = amt0 < to_mathint(p.amt0Min) || amt1 < to_mathint(p.amt1Min);
+ bool revert6 = amt0 > due0Updated || amt1 > due1Updated;
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting collect
+rule collect(DepositorUniV3.CollectParams p) {
+ env e;
+
+ require p.gem0 == gem0Con;
+ require p.gem1 == gem1Con;
+ require p.gem0 == poolCon.gem0();
+ require p.gem1 == poolCon.gem1();
+ require p.fee == poolCon.fee();
+
+ require poolCon.random2() >= poolCon.random0();
+ require poolCon.random3() >= poolCon.random1();
+
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+ require buffer != poolCon;
+
+ mathint gem0BalanceOfBufferBefore = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBufferBefore = gem1Con.balanceOf(buffer);
+ mathint gem0BalanceOfPoolBefore = gem0Con.balanceOf(poolCon);
+ mathint gem1BalanceOfPoolBefore = gem1Con.balanceOf(poolCon);
+
+ require gem0BalanceOfBufferBefore + gem0BalanceOfPoolBefore <= max_uint256;
+ require gem1BalanceOfBufferBefore + gem1BalanceOfPoolBefore <= max_uint256;
+
+ mathint fees0 = poolCon.random2();
+ mathint fees1 = poolCon.random3();
+
+ mathint retFees0; mathint retFees1;
+ retFees0, retFees1 = collect(e, p);
+
+ mathint gem0BalanceOfBufferAfter = gem0Con.balanceOf(buffer);
+ mathint gem1BalanceOfBufferAfter = gem1Con.balanceOf(buffer);
+ mathint gem0BalanceOfPoolAfter = gem0Con.balanceOf(poolCon);
+ mathint gem1BalanceOfPoolAfter = gem1Con.balanceOf(poolCon);
+
+ assert gem0BalanceOfBufferAfter == gem0BalanceOfBufferBefore + fees0, "collect did not increase gem0.balanceOf(buffer) by fees0";
+ assert gem1BalanceOfBufferAfter == gem1BalanceOfBufferBefore + fees1, "collect did not increase gem1.balanceOf(buffer) by fees1";
+ assert gem0BalanceOfPoolAfter == gem0BalanceOfPoolBefore - fees0, "collect did not decrease gem0.balanceOf(pool) by fees0";
+ assert gem1BalanceOfPoolAfter == gem1BalanceOfPoolBefore - fees1, "collect did not decrease gem1.balanceOf(pool) by fees1";
+ assert retFees0 == fees0, "collect did not return the expected fees0";
+ assert retFees1 == fees1, "collect did not return the expected fees1";
+}
+
+// Verify revert rules on collect
+rule collect_revert(DepositorUniV3.CollectParams p) {
+ env e;
+
+ require p.gem0 == gem0Con;
+ require p.gem1 == gem1Con;
+ require p.gem0 == poolCon.gem0();
+ require p.gem1 == poolCon.gem1();
+ require p.fee == poolCon.fee();
+
+ require poolCon.random2() >= poolCon.random0();
+ require poolCon.random3() >= poolCon.random1();
+
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+ require buffer != currentContract;
+ require buffer != poolCon;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x4ead5ba3));
+ mathint wardsSender = wards(e.msg.sender);
+ mathint fees0 = poolCon.random2();
+ mathint fees1 = poolCon.random3();
+ mathint gem0BalanceOfPool = gem0Con.balanceOf(poolCon);
+ mathint gem1BalanceOfPool = gem1Con.balanceOf(poolCon);
+ require gem0BalanceOfPool >= fees0;
+ require gem1BalanceOfPool >= fees1;
+
+ collect@withrevert(e, p);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+ bool revert3 = p.gem0 >= p.gem1;
+
+ assert lastReverted <=> revert1 || revert2 || revert3, "Revert rules failed";
+}
diff --git a/certora/funnels/Swapper.conf b/certora/funnels/Swapper.conf
new file mode 100644
index 00000000..5af6980f
--- /dev/null
+++ b/certora/funnels/Swapper.conf
@@ -0,0 +1,26 @@
+{
+ "files": [
+ "src/funnels/Swapper.sol",
+ "src/AllocatorRoles.sol",
+ "test/mocks/Gem0Mock.sol",
+ "test/mocks/Gem1Mock.sol",
+ "test/mocks/CalleeMock.sol"
+ ],
+ "link": [
+ "Swapper:roles=AllocatorRoles"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize_map": {
+ "Swapper": "200",
+ "AllocatorRoles": "200",
+ "Gem0Mock": "0",
+ "Gem1Mock": "0",
+ "CalleeMock": "0"
+ },
+ "verify": "Swapper:certora/funnels/Swapper.spec",
+ "parametric_contracts": [
+ "Swapper"
+ ],
+ "wait_for_results": "all"
+}
diff --git a/certora/funnels/Swapper.spec b/certora/funnels/Swapper.spec
new file mode 100644
index 00000000..8eeda42c
--- /dev/null
+++ b/certora/funnels/Swapper.spec
@@ -0,0 +1,243 @@
+// Swapper.spec
+
+using AllocatorRoles as roles;
+using Gem0Mock as srcCon;
+using Gem1Mock as dstCon;
+using CalleeMock as calleeCon;
+
+methods {
+ function ilk() external returns (bytes32) envfree;
+ function buffer() external returns (address) envfree;
+ function wards(address) external returns (uint256) envfree;
+ function limits(address, address) external returns (uint96, uint32, uint96, uint32) envfree;
+ function roles.canCall(bytes32, address, address, bytes4) external returns (bool) envfree;
+ function _.swapCallback(address, address, uint256, uint256, address, bytes) external => DISPATCHER(true) UNRESOLVED;
+ function _.allowance(address, address) external => DISPATCHER(true) UNRESOLVED;
+ function _.balanceOf(address) external => DISPATCHER(true) UNRESOLVED;
+ function _.transfer(address, uint256) external => DISPATCHER(true) UNRESOLVED;
+ function _.transferFrom(address, address, uint256) external => DISPATCHER(true) UNRESOLVED;
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+ address anyAddr_2;
+
+ mathint wardsBefore = wards(anyAddr);
+ mathint capBefore; mathint eraBefore; mathint dueBefore; mathint endBefore;
+ capBefore, eraBefore, dueBefore, endBefore = limits(anyAddr, anyAddr_2);
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ mathint capAfter; mathint eraAfter; mathint dueAfter; mathint endAfter;
+ capAfter, eraAfter, dueAfter, endAfter = limits(anyAddr, anyAddr_2);
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert capAfter != capBefore => f.selector == sig:setLimits(address,address,uint96,uint32).selector, "limits[x][y].cap changed in an unexpected function";
+ assert eraAfter != eraBefore => f.selector == sig:setLimits(address,address,uint96,uint32).selector, "limits[x][y].era changed in an unexpected function";
+ assert dueAfter != dueBefore => f.selector == sig:setLimits(address,address,uint96,uint32).selector || f.selector == sig:swap(address,address,uint256,uint256,address,bytes).selector, "limits[x][y].due changed in an unexpected function";
+ assert endAfter != endBefore => f.selector == sig:setLimits(address,address,uint96,uint32).selector || f.selector == sig:swap(address,address,uint256,uint256,address,bytes).selector, "limits[x][y].end changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x65fae35e));
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0x9c52a7f1));
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setLimits
+rule setLimits(address src, address dst, uint96 cap, uint32 era) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ require otherAddr != src || otherAddr_2 != dst;
+
+ mathint capOtherBefore; mathint eraOtherBefore; mathint dueOtherBefore; mathint endOtherBefore;
+ capOtherBefore, eraOtherBefore, dueOtherBefore, endOtherBefore = limits(otherAddr, otherAddr_2);
+
+ setLimits(e, src, dst, cap, era);
+
+ mathint capSrcDstAfter; mathint eraSrcDstAfter; mathint dueSrcDstAfter; mathint endSrcDstAfter;
+ capSrcDstAfter, eraSrcDstAfter, dueSrcDstAfter, endSrcDstAfter = limits(src, dst);
+ mathint capOtherAfter; mathint eraOtherAfter; mathint dueOtherAfter; mathint endOtherAfter;
+ capOtherAfter, eraOtherAfter, dueOtherAfter, endOtherAfter = limits(otherAddr, otherAddr_2);
+
+ assert capSrcDstAfter == to_mathint(cap), "setLimits did not set limits[src][dst].cap to cap";
+ assert eraSrcDstAfter == to_mathint(era), "setLimits did not set limits[src][dst].era to era";
+ assert dueSrcDstAfter == 0, "setLimits did not set limits[src][dst].due to 0";
+ assert endSrcDstAfter == 0, "setLimits did not set limits[src][dst].end to 0";
+ assert capOtherAfter == capOtherBefore, "setLimits did not keep unchanged the rest of limits[x][y].cap";
+ assert eraOtherAfter == eraOtherBefore, "setLimits did not keep unchanged the rest of limits[x][y].era";
+ assert dueOtherAfter == dueOtherBefore, "setLimits did not keep unchanged the rest of limits[x][y].due";
+ assert endOtherAfter == endOtherBefore, "setLimits did not keep unchanged the rest of limits[x][y].end";
+}
+
+// Verify revert rules on setLimits
+rule setLimits_revert(address src, address dst, uint96 cap, uint32 era) {
+ env e;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0xf1b8ac2e));
+ mathint wardsSender = wards(e.msg.sender);
+
+ setLimits@withrevert(e, src, dst, cap, era);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting swap
+rule swap(address src, address dst, uint256 amt, uint256 minOut, address callee, bytes data) {
+ env e;
+
+ require src == srcCon;
+ require dst == dstCon;
+ require callee == calleeCon;
+
+ address otherAddr;
+ address otherAddr_2;
+ require otherAddr != src || otherAddr_2 != dst;
+
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+ require buffer != currentContract;
+ require buffer != callee;
+
+ mathint a; mathint b;
+
+ mathint cap; mathint era; mathint dueBefore; mathint endBefore;
+ cap, era, dueBefore, endBefore = limits(src, dst);
+ mathint dueOtherBefore; mathint endOtherBefore;
+ a, b, dueOtherBefore, endOtherBefore = limits(otherAddr, otherAddr_2);
+ mathint srcBalanceOfBufferBefore = srcCon.balanceOf(e, buffer);
+ mathint dstBalanceOfBufferBefore = dstCon.balanceOf(e, buffer);
+
+ require dstBalanceOfBufferBefore + dstCon.balanceOf(e, currentContract) + dstCon.balanceOf(e, callee) <= max_uint256;
+
+ swap(e, src, dst, amt, minOut, callee, data);
+
+ mathint dueAfter; mathint endAfter;
+ a, b, dueAfter, endAfter = limits(src, dst);
+ mathint dueOtherAfter; mathint endOtherAfter;
+ a, b, dueOtherAfter, endOtherAfter = limits(otherAddr, otherAddr_2);
+
+ mathint expectedDue = (to_mathint(e.block.timestamp) >= endBefore ? cap : dueBefore) - amt;
+ mathint expectedEnd = to_mathint(e.block.timestamp) >= endBefore ? e.block.timestamp + era : endBefore;
+ mathint srcBalanceOfBufferAfter = srcCon.balanceOf(e, buffer);
+ mathint dstBalanceOfBufferAfter = dstCon.balanceOf(e, buffer);
+
+ assert dueAfter == expectedDue, "swap did not set limits[src][dst].due to expected value";
+ assert endAfter == expectedEnd, "swap did not set limits[src][dst].end to expected value";
+ assert dueOtherAfter == dueOtherBefore, "swap did not keep unchanged the rest of limits[x][y].due";
+ assert endOtherAfter == endOtherBefore, "swap did not keep unchanged the rest of limits[x][y].end";
+ assert srcBalanceOfBufferAfter == srcBalanceOfBufferBefore - amt, "swap did not decrease src.balanceOf(buffer) by amt";
+ assert dstBalanceOfBufferAfter >= dstBalanceOfBufferBefore + minOut, "swap did not increase dst.balanceOf(buffer) by at least minOut";
+}
+
+// Verify revert rules on swap
+rule swap_revert(address src, address dst, uint256 amt, uint256 minOut, address callee, bytes data) {
+ env e;
+
+ require src == srcCon;
+ require dst == dstCon;
+ require callee == calleeCon;
+
+ require data.length < max_uint32;
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+ require buffer != currentContract;
+
+ bool canCall = roles.canCall(ilk(), e.msg.sender, currentContract, to_bytes4(0xb69cbf9f));
+ mathint wardsSender = wards(e.msg.sender);
+ mathint cap; mathint era; mathint due; mathint end;
+ cap, era, due, end = limits(src, dst);
+ mathint dueUpdated = to_mathint(e.block.timestamp) >= end ? cap : due;
+ mathint srcBalanceOfBuffer = srcCon.balanceOf(e, buffer);
+ mathint srcAllowanceBufferSwapper = srcCon.allowance(e, buffer, currentContract);
+ mathint dstBalanceOfBuffer = dstCon.balanceOf(e, buffer);
+ mathint dstBalanceOfSwapper = dstCon.balanceOf(e, currentContract);
+ mathint dstBalanceOfCallee = dstCon.balanceOf(e, callee);
+ require dstBalanceOfBuffer + dstBalanceOfSwapper + dstBalanceOfCallee <= max_uint256;
+
+ swap@withrevert(e, src, dst, amt, minOut, callee, data);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = !canCall && wardsSender != 1;
+ bool revert3 = to_mathint(e.block.timestamp) >= end && e.block.timestamp + era > max_uint32;
+ bool revert4 = to_mathint(amt) > dueUpdated;
+ bool revert5 = srcBalanceOfBuffer < to_mathint(amt);
+ bool revert6 = srcAllowanceBufferSwapper < to_mathint(amt);
+ bool revert7 = dstBalanceOfSwapper + dstBalanceOfCallee < to_mathint(minOut);
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6 ||
+ revert7, "Revert rules failed";
+}
diff --git a/certora/funnels/automation/ConduitMover.conf b/certora/funnels/automation/ConduitMover.conf
new file mode 100644
index 00000000..7456aece
--- /dev/null
+++ b/certora/funnels/automation/ConduitMover.conf
@@ -0,0 +1,10 @@
+{
+ "files": [
+ "src/funnels/automation/ConduitMover.sol"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize": "200",
+ "verify": "ConduitMover:certora/funnels/automation/ConduitMover.spec",
+ "wait_for_results": "all"
+}
diff --git a/certora/funnels/automation/ConduitMover.spec b/certora/funnels/automation/ConduitMover.spec
new file mode 100644
index 00000000..a9315a27
--- /dev/null
+++ b/certora/funnels/automation/ConduitMover.spec
@@ -0,0 +1,334 @@
+// ConduitMover.spec
+
+methods {
+ function wards(address) external returns (uint256) envfree;
+ function buds(address) external returns (uint256) envfree;
+ function configs(address, address, address) external returns (uint64, uint32, uint32, uint128) envfree;
+ function ilk() external returns (bytes32) envfree;
+ function buffer() external returns (address) envfree;
+ function _.withdraw(bytes32 ilk, address gem, uint256 amount) external => withdrawSummary(calledContract, ilk, gem, amount) expect uint256;
+ function _.deposit(bytes32 ilk, address gem, uint256 amount) external => depositSummary(calledContract, ilk, gem, amount) expect bool; // Forcing to have a return value as otherwise Certora will throw a compiler error
+}
+
+ghost mapping(address => bool) nonZeroExtcodesize;
+hook EXTCODESIZE(address addr) uint v {
+ nonZeroExtcodesize[addr] = (v != 0);
+}
+
+ghost mathint withdrawCounter;
+ghost address withdrawAddr;
+ghost bytes32 withdrawIlk;
+ghost address withdrawGem;
+ghost uint256 withdrawAmount;
+ghost uint256 withdrawReturn;
+function withdrawSummary(address addr, bytes32 ilk, address gem, uint256 amount) returns uint256 {
+ withdrawCounter = withdrawCounter + 1;
+ withdrawAddr = addr;
+ withdrawIlk = ilk;
+ withdrawGem = gem;
+ withdrawAmount = amount;
+ return withdrawReturn;
+}
+
+ghost mathint depositCounter;
+ghost address depositAddr;
+ghost bytes32 depositIlk;
+ghost address depositGem;
+ghost uint256 depositAmount;
+function depositSummary(address addr, bytes32 ilk, address gem, uint256 amount) returns bool {
+ depositCounter = depositCounter + 1;
+ depositAddr = addr;
+ depositIlk = ilk;
+ depositGem = gem;
+ depositAmount = amount;
+ return true;
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+ address anyAddr_2;
+ address anyAddr_3;
+
+ mathint wardsBefore = wards(anyAddr);
+ mathint budsBefore = buds(anyAddr);
+ mathint numBefore; mathint hopBefore; mathint zzzBefore; mathint lotBefore;
+ numBefore, hopBefore, zzzBefore, lotBefore = configs(anyAddr, anyAddr_2, anyAddr_3);
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ mathint budsAfter = buds(anyAddr);
+ mathint numAfter; mathint hopAfter; mathint zzzAfter; mathint lotAfter;
+ numAfter, hopAfter, zzzAfter, lotAfter = configs(anyAddr, anyAddr_2, anyAddr_3);
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert budsAfter != budsBefore => f.selector == sig:kiss(address).selector || f.selector == sig:diss(address).selector, "buds[x] changed in an unexpected function";
+ assert numAfter != numBefore => f.selector == sig:setConfig(address,address,address,uint64,uint32,uint128).selector || f.selector == sig:move(address,address,address).selector, "configs[x][y][z].num changed in an unexpected function";
+ assert hopAfter != hopBefore => f.selector == sig:setConfig(address,address,address,uint64,uint32,uint128).selector, "configs[x][y][z].hop changed in an unexpected function";
+ assert zzzAfter != zzzBefore => f.selector == sig:setConfig(address,address,address,uint64,uint32,uint128).selector || f.selector == sig:move(address,address,address).selector, "configs[x][y][z].zzz changed in an unexpected function";
+ assert lotAfter != lotBefore => f.selector == sig:setConfig(address,address,address,uint64,uint32,uint128).selector, "configs[x][y][z].lot changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting kiss
+rule kiss(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint budsOtherBefore = buds(other);
+
+ kiss(e, usr);
+
+ mathint budsUsrAfter = buds(usr);
+ mathint budsOtherAfter = buds(other);
+
+ assert budsUsrAfter == 1, "kiss did not set the buds";
+ assert budsOtherAfter == budsOtherBefore, "kiss did not keep unchanged the rest of buds[x]";
+}
+
+// Verify revert rules on kiss
+rule kiss_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ kiss@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting diss
+rule diss(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint budsOtherBefore = buds(other);
+
+ diss(e, usr);
+
+ mathint budsUsrAfter = buds(usr);
+ mathint budsOtherAfter = buds(other);
+
+ assert budsUsrAfter == 0, "diss did not set the buds";
+ assert budsOtherAfter == budsOtherBefore, "diss did not keep unchanged the rest of buds[x]";
+}
+
+// Verify revert rules on diss
+rule diss_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ diss@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setConfig
+rule setConfig(address from, address to, address gem, uint64 num, uint32 hop, uint128 lot) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ address otherAddr_3;
+ require otherAddr != from || otherAddr_2 != to || otherAddr_3 != gem;
+
+ mathint numOtherBefore; mathint hopOtherBefore; mathint zzzOtherBefore; mathint lotOtherBefore;
+ numOtherBefore, hopOtherBefore, zzzOtherBefore, lotOtherBefore = configs(otherAddr, otherAddr_2, otherAddr_3);
+
+ setConfig(e, from, to, gem, num, hop, lot);
+
+ mathint numFromToGemAfter; mathint hopFromToGemAfter; mathint zzzFromToGemAfter; mathint lotFromToGemAfter;
+ numFromToGemAfter, hopFromToGemAfter, zzzFromToGemAfter, lotFromToGemAfter = configs(from, to, gem);
+ mathint numOtherAfter; mathint hopOtherAfter; mathint zzzOtherAfter; mathint lotOtherAfter;
+ numOtherAfter, hopOtherAfter, zzzOtherAfter, lotOtherAfter = configs(otherAddr, otherAddr_2, otherAddr_3);
+
+ assert numFromToGemAfter == to_mathint(num), "setConfig did not set configs[from][to][gem].num to num";
+ assert hopFromToGemAfter == to_mathint(hop), "setConfig did not set configs[from][to][gem].hop to hop";
+ assert zzzFromToGemAfter == 0, "setConfig did not set configs[from][to][gem].zzz to 0";
+ assert lotFromToGemAfter == to_mathint(lot), "setConfig did not set configs[from][to][gem].lot to lot";
+ assert numOtherAfter == numOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y][z].num";
+ assert hopOtherAfter == hopOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y][z].hop";
+ assert zzzOtherAfter == zzzOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y][z].zzz";
+ assert lotOtherAfter == lotOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y][z].lot";
+}
+
+// Verify revert rules on setConfig
+rule setConfig_revert(address from, address to, address gem, uint64 num, uint32 hop, uint128 lot) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ setConfig@withrevert(e, from, to, gem, num, hop, lot);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting move
+rule move(address from, address to, address gem) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ address otherAddr_3;
+ require otherAddr != from || otherAddr_2 != to || otherAddr_3 != gem;
+
+ require e.block.timestamp <= max_uint32;
+
+ address buffer = buffer();
+
+ mathint a; mathint b;
+
+ mathint numFromToGemBefore; mathint lotFromToGem;
+ numFromToGemBefore, a, b, lotFromToGem = configs(from, to, gem);
+ mathint numOtherBefore; mathint zzzOtherBefore;
+ numOtherBefore, a, zzzOtherBefore, b = configs(otherAddr, otherAddr_2, otherAddr_3);
+
+ bytes32 withdrawIlkBefore = withdrawIlk;
+ address withdrawGemBefore = withdrawGem;
+ mathint withdrawAmountBefore = withdrawAmount;
+ bytes32 depositIlkBefore = depositIlk;
+ address depositGemBefore = depositGem;
+ mathint depositAmountBefore = depositAmount;
+
+ mathint withdrawCounterBefore = withdrawCounter;
+ mathint depositCounterBefore = depositCounter;
+
+ move(e, from, to, gem);
+
+ mathint numFromToGemAfter; mathint zzzFromToGemAfter;
+ numFromToGemAfter, a, zzzFromToGemAfter, b = configs(from, to, gem);
+ mathint numOtherAfter; mathint zzzOtherAfter;
+ numOtherAfter, a, zzzOtherAfter, b = configs(otherAddr, otherAddr_2, otherAddr_3);
+
+ assert numFromToGemAfter == numFromToGemBefore - 1, "move did not decrease configs[from][to][gem].num by 1";
+ assert zzzFromToGemAfter == to_mathint(e.block.timestamp), "move did not set configs[from][to][gem].zzz to block.timestamp";
+ assert numOtherAfter == numOtherBefore, "move did not keep unchanged the rest of configs[x][y][z].num";
+ assert zzzOtherAfter == zzzOtherBefore, "move did not keep unchanged the rest of configs[x][y][z].zzz";
+ assert from != buffer => withdrawCounter == withdrawCounterBefore + 1, "move did not execute exactly one withdraw external call";
+ assert from != buffer => withdrawAddr == from, "move did not execute the withdraw external call to the correct 'from' contract";
+ assert from != buffer => withdrawIlk == ilk(), "move did not pass the correct ilk to the withdraw external call";
+ assert from != buffer => withdrawGem == gem, "move did not pass the correct gen to the withdraw external call";
+ assert from != buffer => to_mathint(withdrawAmount) == lotFromToGem, "move did not pass the correct amount to the withdraw external call";
+ assert from == buffer => withdrawCounter == withdrawCounterBefore, "move did execute one or more withdraw external call when it did not correspond";
+ assert from == buffer => withdrawIlk == withdrawIlkBefore, "move did execute the withdraw external call when it did not correspond";
+ assert from == buffer => withdrawGem == withdrawGemBefore, "move did execute the withdraw external call when it did not correspond 2";
+ assert from == buffer => to_mathint(withdrawAmount) == withdrawAmountBefore, "move did execute the withdraw external call when it did not correspond 3";
+ assert to != buffer => depositCounter == depositCounterBefore + 1, "move did not execute exactly one deposit external call";
+ assert to != buffer => depositAddr == to, "move did not execute the deposit external call to the correct 'to' contract";
+ assert to != buffer => depositIlk == ilk(), "move did not pass the correct ilk to the deposit external call";
+ assert to != buffer => depositGem == gem, "move did not pass the correct gen to the deposit external call";
+ assert to != buffer => to_mathint(depositAmount) == lotFromToGem, "move did not pass the correct amount to the deposit external call";
+ assert to == buffer => depositCounter == depositCounterBefore, "move did execute one or more deposit external call when it did not correspond";
+ assert to == buffer => depositIlk == depositIlkBefore, "move did execute the deposit external call when it did not correspond";
+ assert to == buffer => depositGem == depositGemBefore, "move did execute the deposit external call when it did not correspond 2";
+ assert to == buffer => to_mathint(depositAmount) == depositAmountBefore, "move did execute the deposit external call when it did not correspond 3";
+}
+
+// Verify revert rules on move
+rule move_revert(address from, address to, address gem) {
+ env e;
+
+ require e.block.timestamp <= max_uint32;
+ require !nonZeroExtcodesize[to];
+
+ address buffer = buffer();
+
+ mathint budsSender = buds(e.msg.sender);
+ mathint numFromToGem; mathint hopFromToGem; mathint zzzFromToGem; mathint lotFromToGem;
+ numFromToGem, hopFromToGem, zzzFromToGem, lotFromToGem = configs(from, to, gem);
+
+ require to_mathint(withdrawReturn) == lotFromToGem;
+
+ move@withrevert(e, from, to, gem);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = budsSender != 1;
+ bool revert3 = numFromToGem == 0;
+ bool revert4 = to_mathint(e.block.timestamp) < zzzFromToGem + hopFromToGem;
+ bool revert5 = to_mathint(withdrawReturn) != lotFromToGem;
+ bool revert6 = to != buffer && !nonZeroExtcodesize[to];
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6, "Revert rules failed";
+}
diff --git a/certora/funnels/automation/StableDepositorUniV3.conf b/certora/funnels/automation/StableDepositorUniV3.conf
new file mode 100644
index 00000000..0a60d833
--- /dev/null
+++ b/certora/funnels/automation/StableDepositorUniV3.conf
@@ -0,0 +1,10 @@
+{
+ "files": [
+ "src/funnels/automation/StableDepositorUniV3.sol",
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize": "200",
+ "verify": "StableDepositorUniV3:certora/funnels/automation/StableDepositorUniV3.spec",
+ "wait_for_results": "all"
+}
diff --git a/certora/funnels/automation/StableDepositorUniV3.spec b/certora/funnels/automation/StableDepositorUniV3.spec
new file mode 100644
index 00000000..f2813356
--- /dev/null
+++ b/certora/funnels/automation/StableDepositorUniV3.spec
@@ -0,0 +1,479 @@
+// StableDepositorUniV3.spec
+
+methods {
+ function wards(address) external returns (uint256) envfree;
+ function buds(address) external returns (uint256) envfree;
+ function configs(address, address, uint24, int24, int24) external returns (int32, uint32, uint96, uint96, uint96, uint96, uint32) envfree;
+ function depositor() external returns (address) envfree;
+ function _.deposit(DepositorUniV3Like.LiquidityParams p) external => depositSummary(calledContract, p) expect uint128, uint256, uint256;
+ function _.withdraw(DepositorUniV3Like.LiquidityParams p, bool takeFees) external => withdrawSummary(calledContract, p, takeFees) expect uint128, uint256, uint256, uint256, uint256;
+ function _.collect(DepositorUniV3Like.CollectParams p) external => collectSummary(calledContract, p) expect uint256, uint256;
+}
+
+ghost uint128 retValue;
+ghost uint256 retValue2;
+ghost uint256 retValue3;
+ghost uint256 retValue4;
+ghost uint256 retValue5;
+
+ghost mathint depositCounter;
+ghost address depositAddr;
+ghost address depositGem0;
+ghost address depositGem1;
+ghost uint24 depositFee;
+ghost int24 depositTickLower;
+ghost int24 depositTickUpper;
+ghost uint128 depositLiquidity;
+ghost uint256 depositAmt0Desired;
+ghost uint256 depositAmt1Desired;
+ghost uint256 depositAmt0Min;
+ghost uint256 depositAmt1Min;
+function depositSummary(address addr, DepositorUniV3Like.LiquidityParams p) returns (uint128, uint256, uint256) {
+ depositCounter = depositCounter + 1;
+ depositAddr = addr;
+ depositGem0 = p.gem0;
+ depositGem1 = p.gem1;
+ depositFee = p.fee;
+ depositTickLower = p.tickLower;
+ depositTickUpper = p.tickUpper;
+ depositLiquidity = p.liquidity;
+ depositAmt0Desired = p.amt0Desired;
+ depositAmt1Desired = p.amt1Desired;
+ depositAmt0Min = p.amt0Min;
+ depositAmt1Min = p.amt1Min;
+ return (retValue, retValue2, retValue3);
+}
+
+ghost mathint withdrawCounter;
+ghost address withdrawAddr;
+ghost address withdrawGem0;
+ghost address withdrawGem1;
+ghost uint24 withdrawFee;
+ghost int24 withdrawTickLower;
+ghost int24 withdrawTickUpper;
+ghost uint128 withdrawLiquidity;
+ghost uint256 withdrawAmt0Desired;
+ghost uint256 withdrawAmt1Desired;
+ghost uint256 withdrawAmt0Min;
+ghost uint256 withdrawAmt1Min;
+ghost bool withdrawTakeFees;
+function withdrawSummary(address addr, DepositorUniV3Like.LiquidityParams p, bool takeFees) returns (uint128, uint256, uint256, uint256, uint256) {
+ withdrawCounter = withdrawCounter + 1;
+ withdrawAddr = addr;
+ withdrawGem0 = p.gem0;
+ withdrawGem1 = p.gem1;
+ withdrawFee = p.fee;
+ withdrawTickLower = p.tickLower;
+ withdrawTickUpper = p.tickUpper;
+ withdrawLiquidity = p.liquidity;
+ withdrawAmt0Desired = p.amt0Desired;
+ withdrawAmt1Desired = p.amt1Desired;
+ withdrawAmt0Min = p.amt0Min;
+ withdrawAmt1Min = p.amt1Min;
+ withdrawTakeFees = takeFees;
+ return (retValue, retValue2, retValue3, retValue4, retValue5);
+}
+
+ghost mathint collectCounter;
+ghost address collectAddr;
+ghost address collectGem0;
+ghost address collectGem1;
+ghost uint24 collectFee;
+ghost int24 collectTickLower;
+ghost int24 collectTickUpper;
+function collectSummary(address addr, DepositorUniV3Like.CollectParams p) returns (uint256, uint256) {
+ collectCounter = collectCounter + 1;
+ collectAddr = addr;
+ collectGem0 = p.gem0;
+ collectGem1 = p.gem1;
+ collectFee = p.fee;
+ collectTickLower = p.tickLower;
+ collectTickUpper = p.tickUpper;
+ return (retValue2, retValue3);
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+ address anyAddr_2;
+ uint24 anyUint24;
+ int24 anyInt24;
+ int24 anyInt24_2;
+
+ mathint wardsBefore = wards(anyAddr);
+ mathint budsBefore = buds(anyAddr);
+ mathint numBefore; mathint zzzBefore; mathint amt0Before; mathint amt1Before; mathint req0Before; mathint req1Before; mathint hopBefore;
+ numBefore, zzzBefore, amt0Before, amt1Before, req0Before, req1Before, hopBefore = configs(anyAddr, anyAddr_2, anyUint24, anyInt24, anyInt24_2);
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ mathint budsAfter = buds(anyAddr);
+ mathint numAfter; mathint zzzAfter; mathint amt0After; mathint amt1After; mathint req0After; mathint req1After; mathint hopAfter;
+ numAfter, zzzAfter, amt0After, amt1After, req0After, req1After, hopAfter = configs(anyAddr, anyAddr_2, anyUint24, anyInt24, anyInt24_2);
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert budsAfter != budsBefore => f.selector == sig:kiss(address).selector || f.selector == sig:diss(address).selector, "buds[x] changed in an unexpected function";
+ assert numAfter != numBefore => f.selector == sig:setConfig(address,address,uint24,int24,int24,int32,uint32,uint96,uint96,uint96,uint96).selector || f.selector == sig:deposit(address,address,uint24,int24,int24,uint128,uint128).selector || f.selector == sig:withdraw(address,address,uint24,int24,int24,uint128,uint128).selector, "configs[x][y][z][a][b].num changed in an unexpected function";
+ assert zzzAfter != zzzBefore => f.selector == sig:setConfig(address,address,uint24,int24,int24,int32,uint32,uint96,uint96,uint96,uint96).selector || f.selector == sig:deposit(address,address,uint24,int24,int24,uint128,uint128).selector || f.selector == sig:withdraw(address,address,uint24,int24,int24,uint128,uint128).selector, "configs[x][y][z][a][b].zzz changed in an unexpected function";
+ assert amt0After != amt0Before => f.selector == sig:setConfig(address,address,uint24,int24,int24,int32,uint32,uint96,uint96,uint96,uint96).selector, "configs[x][y][z][a][b].amt0 changed in an unexpected function";
+ assert amt1After != amt1Before => f.selector == sig:setConfig(address,address,uint24,int24,int24,int32,uint32,uint96,uint96,uint96,uint96).selector, "configs[x][y][z][a][b].amt1 changed in an unexpected function";
+ assert req0After != req0Before => f.selector == sig:setConfig(address,address,uint24,int24,int24,int32,uint32,uint96,uint96,uint96,uint96).selector, "configs[x][y][z][a][b].req0 changed in an unexpected function";
+ assert req1After != req1Before => f.selector == sig:setConfig(address,address,uint24,int24,int24,int32,uint32,uint96,uint96,uint96,uint96).selector, "configs[x][y][z][a][b].req1 changed in an unexpected function";
+ assert hopAfter != hopBefore => f.selector == sig:setConfig(address,address,uint24,int24,int24,int32,uint32,uint96,uint96,uint96,uint96).selector, "configs[x][y][z][a][b].hop changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting kiss
+rule kiss(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint budsOtherBefore = buds(other);
+
+ kiss(e, usr);
+
+ mathint budsUsrAfter = buds(usr);
+ mathint budsOtherAfter = buds(other);
+
+ assert budsUsrAfter == 1, "kiss did not set the buds";
+ assert budsOtherAfter == budsOtherBefore, "kiss did not keep unchanged the rest of buds[x]";
+}
+
+// Verify revert rules on kiss
+rule kiss_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ kiss@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting diss
+rule diss(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint budsOtherBefore = buds(other);
+
+ diss(e, usr);
+
+ mathint budsUsrAfter = buds(usr);
+ mathint budsOtherAfter = buds(other);
+
+ assert budsUsrAfter == 0, "diss did not set the buds";
+ assert budsOtherAfter == budsOtherBefore, "diss did not keep unchanged the rest of buds[x]";
+}
+
+// Verify revert rules on diss
+rule diss_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ diss@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setConfig
+rule setConfig(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ uint24 otherUint24;
+ int24 otherInt24;
+ int24 otherInt24_2;
+ require otherAddr != gem0 || otherAddr_2 != gem1 || fee != otherUint24 || tickLower != otherInt24 || tickUpper != otherInt24_2;
+
+ mathint numOtherBefore; mathint zzzOtherBefore; mathint amt0OtherBefore; mathint amt1OtherBefore; mathint req0OtherBefore; mathint req1OtherBefore; mathint hopOtherBefore;
+ numOtherBefore, zzzOtherBefore, amt0OtherBefore, amt1OtherBefore, req0OtherBefore, req1OtherBefore, hopOtherBefore = configs(otherAddr, otherAddr_2, otherUint24, otherInt24, otherInt24_2);
+
+ setConfig(e, gem0, gem1, fee, tickLower, tickUpper, num, hop, amt0, amt1, req0, req1);
+
+ mathint numGem0Gem1After; mathint zzzGem0Gem1After; mathint amt0Gem0Gem1After; mathint amt1Gem0Gem1After; mathint req0Gem0Gem1After; mathint req1Gem0Gem1After; mathint hopGem0Gem1After;
+ numGem0Gem1After, zzzGem0Gem1After, amt0Gem0Gem1After, amt1Gem0Gem1After, req0Gem0Gem1After, req1Gem0Gem1After, hopGem0Gem1After = configs(gem0, gem1, fee, tickLower, tickUpper);
+ mathint numOtherAfter; mathint zzzOtherAfter; mathint amt0OtherAfter; mathint amt1OtherAfter; mathint req0OtherAfter; mathint req1OtherAfter; mathint hopOtherAfter;
+ numOtherAfter, zzzOtherAfter, amt0OtherAfter, amt1OtherAfter, req0OtherAfter, req1OtherAfter, hopOtherAfter = configs(otherAddr, otherAddr_2, otherUint24, otherInt24, otherInt24_2);
+
+ assert numGem0Gem1After == to_mathint(num), "setConfig did not set configs[gem0][gem1][fee][tickLower][tickUpper].num to num";
+ assert zzzGem0Gem1After == 0, "setConfig did not set configs[gem0][gem1][fee][tickLower][tickUpper].zzz to 0";
+ assert amt0Gem0Gem1After == to_mathint(amt0), "setConfig did not set configs[gem0][gem1][fee][tickLower][tickUpper].amt0 to amt0";
+ assert amt1Gem0Gem1After == to_mathint(amt1), "setConfig did not set configs[gem0][gem1][fee][tickLower][tickUpper].amt1 to amt1";
+ assert req0Gem0Gem1After == to_mathint(req0), "setConfig did not set configs[gem0][gem1][fee][tickLower][tickUpper].req0 to req0";
+ assert req1Gem0Gem1After == to_mathint(req1), "setConfig did not set configs[gem0][gem1][fee][tickLower][tickUpper].req1 to req1";
+ assert hopGem0Gem1After == to_mathint(hop), "setConfig did not set configs[gem0][gem1][fee][tickLower][tickUpper].hop to hop";
+ assert numOtherAfter == numOtherBefore, "setConfig did not keep the rest of configs[x][y][z][a][b].num";
+ assert zzzOtherAfter == zzzOtherBefore, "setConfig did not keep the rest of configs[x][y][z][a][b].zzz";
+ assert amt0OtherAfter == amt0OtherBefore, "setConfig did not keep the rest of configs[x][y][z][a][b].amt0";
+ assert amt1OtherAfter == amt1OtherBefore, "setConfig did not keep the rest of configs[x][y][z][a][b].amt1";
+ assert req0OtherAfter == req0OtherBefore, "setConfig did not keep the rest of configs[x][y][z][a][b].req0";
+ assert req1OtherAfter == req1OtherBefore, "setConfig did not keep the rest of configs[x][y][z][a][b].req1";
+ assert hopOtherAfter == hopOtherBefore, "setConfig did not keep the rest of configs[x][y][z][a][b].hop";
+}
+
+// Verify revert rules on setConfig
+rule setConfig_revert(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ setConfig@withrevert(e, gem0, gem1, fee, tickLower, tickUpper, num, hop, amt0, amt1, req0, req1);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+ bool revert3 = gem0 >= gem1;
+
+ assert lastReverted <=> revert1 || revert2 || revert3, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deposit
+rule deposit(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ uint24 otherUint24;
+ int24 otherInt24;
+ int24 otherInt24_2;
+ require otherAddr != gem0 || otherAddr_2 != gem1 || fee != otherUint24 || tickLower != otherInt24 || tickUpper != otherInt24_2;
+
+ require e.block.timestamp <= max_uint32;
+
+ mathint a; mathint b; mathint c; mathint d; mathint f;
+
+ mathint numGem0Gem1Before; mathint zzzGem0Gem1Before; mathint amt0Gem0Gem1; mathint amt1Gem0Gem1; mathint req0Gem0Gem1; mathint req1Gem0Gem1;
+ numGem0Gem1Before, zzzGem0Gem1Before, amt0Gem0Gem1, amt1Gem0Gem1, req0Gem0Gem1, req1Gem0Gem1, a = configs(gem0, gem1, fee, tickLower, tickUpper);
+ mathint numOtherBefore; mathint zzzOtherBefore;
+ numOtherBefore, zzzOtherBefore, a, b, c, d, f = configs(otherAddr, otherAddr_2, otherUint24, otherInt24, otherInt24_2);
+
+ mathint depositCounterBefore = depositCounter;
+
+ deposit(e, gem0, gem1, fee, tickLower, tickUpper, amt0Min, amt1Min);
+
+ mathint numGem0Gem1After; mathint zzzGem0Gem1After;
+ numGem0Gem1After, zzzGem0Gem1After, a, b, c, d, f = configs(gem0, gem1, fee, tickLower, tickUpper);
+ mathint numOtherAfter; mathint zzzOtherAfter;
+ numOtherAfter, zzzOtherAfter, a, b, c, d, f = configs(otherAddr, otherAddr_2, otherUint24, otherInt24, otherInt24_2);
+
+ assert numGem0Gem1After == numGem0Gem1Before - 1, "deposit did not decrease configs[gem0][gem1][fee][tickLower][tickUpper].num by 1";
+ assert zzzGem0Gem1After == to_mathint(e.block.timestamp), "deposit did not set configs[gem0][gem1][fee][tickLower][tickUpper].zzz to block.timestamp";
+ assert numOtherAfter == numOtherBefore, "deposit did not keep unchanged the rest of configs[x][y][z][a][b].num";
+ assert zzzOtherAfter == zzzOtherBefore, "deposit did not keep unchanged the rest of configs[x][y][z][a][b].zzz";
+ assert depositCounter == depositCounterBefore + 1, "deposit did not execute exactly one deposit external call";
+ assert depositAddr == depositor(), "deposit did not execute the deposit external call to the correct 'depositor()' contract";
+ assert depositGem0 == gem0, "deposit did not pass the correct gem0 to the external call";
+ assert depositGem1 == gem1, "deposit did not pass the correct gem1 to the external call";
+ assert depositFee == fee, "deposit did not pass the correct fee to the external call";
+ assert depositTickLower == tickLower, "deposit did not pass the correct tickLower to the external call";
+ assert depositTickUpper == tickUpper, "deposit did not pass the correct tickUpper to the external call";
+ assert depositLiquidity == 0, "deposit did not pass the correct liquidity to the external call";
+ assert to_mathint(depositAmt0Desired) == amt0Gem0Gem1, "deposit did not pass the correct amt0Desired to the external call";
+ assert to_mathint(depositAmt1Desired) == amt1Gem0Gem1, "deposit did not pass the correct amt1Desired to the external call";
+ assert to_mathint(depositAmt0Min) == (amt0Min == 0 ? req0Gem0Gem1 : to_mathint(amt0Min)), "deposit did not pass the correct amt0Min to the external call";
+ assert to_mathint(depositAmt1Min) == (amt1Min == 0 ? req1Gem0Gem1 : to_mathint(amt1Min)), "deposit did not pass the correct amt1Min to the external call";
+}
+
+// Verify revert rules on deposit
+rule deposit_revert(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min) {
+ env e;
+
+ require e.block.timestamp <= max_uint32;
+
+ mathint budsSender = buds(e.msg.sender);
+ mathint numGem0Gem1; mathint zzzGem0Gem1; mathint amt0Gem0Gem1; mathint amt1Gem0Gem1; mathint req0Gem0Gem1; mathint req1Gem0Gem1; mathint hopGem0Gem1;
+ numGem0Gem1, zzzGem0Gem1, amt0Gem0Gem1, amt1Gem0Gem1, req0Gem0Gem1, req1Gem0Gem1, hopGem0Gem1 = configs(gem0, gem1, fee, tickLower, tickUpper);
+
+ deposit@withrevert(e, gem0, gem1, fee, tickLower, tickUpper, amt0Min, amt1Min);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = budsSender != 1;
+ bool revert3 = numGem0Gem1 <= 0;
+ bool revert4 = to_mathint(e.block.timestamp) < zzzGem0Gem1 + hopGem0Gem1;
+ bool revert5 = to_mathint(amt0Min) > 0 && to_mathint(amt0Min) < req0Gem0Gem1;
+ bool revert6 = to_mathint(amt1Min) > 0 && to_mathint(amt1Min) < req1Gem0Gem1;
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting withdraw
+rule withdraw(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ uint24 otherUint24;
+ int24 otherInt24;
+ int24 otherInt24_2;
+ require otherAddr != gem0 || otherAddr_2 != gem1 || fee != otherUint24 || tickLower != otherInt24 || tickUpper != otherInt24_2;
+
+ require e.block.timestamp <= max_uint32;
+
+ mathint a; mathint b; mathint c; mathint d; mathint f;
+
+ mathint numGem0Gem1Before; mathint zzzGem0Gem1Before; mathint amt0Gem0Gem1; mathint amt1Gem0Gem1; mathint req0Gem0Gem1; mathint req1Gem0Gem1;
+ numGem0Gem1Before, zzzGem0Gem1Before, amt0Gem0Gem1, amt1Gem0Gem1, req0Gem0Gem1, req1Gem0Gem1, a = configs(gem0, gem1, fee, tickLower, tickUpper);
+ mathint numOtherBefore; mathint zzzOtherBefore;
+ numOtherBefore, zzzOtherBefore, a, b, c, d, f = configs(otherAddr, otherAddr_2, otherUint24, otherInt24, otherInt24_2);
+
+ mathint withdrawCounterBefore = withdrawCounter;
+
+ withdraw(e, gem0, gem1, fee, tickLower, tickUpper, amt0Min, amt1Min);
+
+ mathint numGem0Gem1After; mathint zzzGem0Gem1After; mathint amt0Gem0Gem1After; mathint amt1Gem0Gem1After; mathint req0Gem0Gem1After; mathint req1Gem0Gem1After; mathint hopGem0Gem1After;
+ numGem0Gem1After, zzzGem0Gem1After, a, b, c, d, f = configs(gem0, gem1, fee, tickLower, tickUpper);
+ mathint numOtherAfter; mathint zzzOtherAfter;
+ numOtherAfter, zzzOtherAfter, a, b, c, d, f = configs(otherAddr, otherAddr_2, otherUint24, otherInt24, otherInt24_2);
+
+ assert numGem0Gem1After == numGem0Gem1Before + 1, "withdraw did not increase configs[gem0][gem1][fee][tickLower][tickUpper].num by 1";
+ assert zzzGem0Gem1After == to_mathint(e.block.timestamp), "withdraw did not set configs[gem0][gem1][fee][tickLower][tickUpper].zzz to block.timestamp";
+ assert numOtherAfter == numOtherBefore, "withdraw did not keep unchanged the rest of configs[x][y][z][a][b].num";
+ assert zzzOtherAfter == zzzOtherBefore, "withdraw did not keep unchanged the rest of configs[x][y][z][a][b].zzz";
+ assert withdrawCounter == withdrawCounterBefore + 1, "withdraw did not execute exactly one withdraw external call";
+ assert withdrawAddr == depositor(), "withdraw did not execute the withdraw external call to the correct 'depositor()' contract";
+ assert withdrawGem0 == gem0, "withdraw did not pass the correct gem0 to the external call";
+ assert withdrawGem1 == gem1, "withdraw did not pass the correct gem1 to the external call";
+ assert withdrawFee == fee, "withdraw did not pass the correct fee to the external call";
+ assert withdrawTickLower == tickLower, "withdraw did not pass the correct tickLower to the external call";
+ assert withdrawTickUpper == tickUpper, "withdraw did not pass the correct tickUpper to the external call";
+ assert withdrawLiquidity == 0, "withdraw did not pass the correct liquidity to the external call";
+ assert to_mathint(withdrawAmt0Desired) == amt0Gem0Gem1, "withdraw did not pass the correct amt0Desired to the external call";
+ assert to_mathint(withdrawAmt1Desired) == amt1Gem0Gem1, "withdraw did not pass the correct amt1Desired to the external call";
+ assert to_mathint(withdrawAmt0Min) == (amt0Min == 0 ? req0Gem0Gem1 : to_mathint(amt0Min)), "withdraw did not pass the correct amt0Min to the external call";
+ assert to_mathint(withdrawAmt1Min) == (amt1Min == 0 ? req1Gem0Gem1 : to_mathint(amt1Min)), "withdraw did not pass the correct amt1Min to the external call";
+ assert withdrawTakeFees, "withdraw did not pass the correct takeFees to the external call";
+}
+
+// Verify revert rules on withdraw
+rule withdraw_revert(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min) {
+ env e;
+
+ require e.block.timestamp <= max_uint32;
+
+ mathint budsSender = buds(e.msg.sender);
+ mathint numGem0Gem1; mathint zzzGem0Gem1; mathint amt0Gem0Gem1; mathint amt1Gem0Gem1; mathint req0Gem0Gem1; mathint req1Gem0Gem1; mathint hopGem0Gem1;
+ numGem0Gem1, zzzGem0Gem1, amt0Gem0Gem1, amt1Gem0Gem1, req0Gem0Gem1, req1Gem0Gem1, hopGem0Gem1 = configs(gem0, gem1, fee, tickLower, tickUpper);
+
+ withdraw@withrevert(e, gem0, gem1, fee, tickLower, tickUpper, amt0Min, amt1Min);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = budsSender != 1;
+ bool revert3 = numGem0Gem1 >= 0;
+ bool revert4 = to_mathint(e.block.timestamp) < zzzGem0Gem1 + hopGem0Gem1;
+ bool revert5 = to_mathint(amt0Min) > 0 && to_mathint(amt0Min) < req0Gem0Gem1;
+ bool revert6 = to_mathint(amt1Min) > 0 && to_mathint(amt1Min) < req1Gem0Gem1;
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5 || revert6, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting collect
+rule collect(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper) {
+ env e;
+
+ mathint collectCounterBefore = collectCounter;
+
+ collect(e, gem0, gem1, fee, tickLower, tickUpper);
+
+ assert collectCounter == collectCounterBefore + 1, "collect did not execute exactly one collect external call";
+ assert collectAddr == depositor(), "collect did not execute the collect external call to the correct 'depositor()' contract";
+ assert collectGem0 == gem0, "collect did not pass the correct gem0 to the external call";
+ assert collectGem1 == gem1, "collect did not pass the correct gem1 to the external call";
+ assert collectFee == fee, "collect did not pass the correct fee to the external call";
+ assert collectTickLower == tickLower, "collect did not pass the correct tickLower to the external call";
+ assert collectTickUpper == tickUpper, "collect did not pass the correct tickUpper to the external call";
+}
+
+// Verify revert rules on collect
+rule collect_revert(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper) {
+ env e;
+
+ mathint budsSender = buds(e.msg.sender);
+
+ collect@withrevert(e, gem0, gem1, fee, tickLower, tickUpper);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = budsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
diff --git a/certora/funnels/automation/StableSwapper.conf b/certora/funnels/automation/StableSwapper.conf
new file mode 100644
index 00000000..6977f741
--- /dev/null
+++ b/certora/funnels/automation/StableSwapper.conf
@@ -0,0 +1,10 @@
+{
+ "files": [
+ "src/funnels/automation/StableSwapper.sol",
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize": "200",
+ "verify": "StableSwapper:certora/funnels/automation/StableSwapper.spec",
+ "wait_for_results": "all"
+}
diff --git a/certora/funnels/automation/StableSwapper.spec b/certora/funnels/automation/StableSwapper.spec
new file mode 100644
index 00000000..1e42ac9a
--- /dev/null
+++ b/certora/funnels/automation/StableSwapper.spec
@@ -0,0 +1,294 @@
+// StableSwapper.spec
+
+methods {
+ function wards(address) external returns (uint256) envfree;
+ function buds(address) external returns (uint256) envfree;
+ function configs(address, address) external returns (uint128, uint32, uint32, uint96, uint96) envfree;
+ function swapper() external returns (address) envfree;
+ function _.swap(address src, address dst, uint256 lot, uint256 minOut, address callee, bytes data) external => swapSummary(calledContract, src, dst, lot, minOut, callee, data) expect uint256;
+}
+
+ghost mathint swapCounter;
+ghost address swapAddr;
+ghost uint256 swapRetValue;
+ghost address swapSrc;
+ghost address swapDst;
+ghost uint256 swapLot;
+ghost uint256 swapMinOut;
+ghost address swapCallee;
+ghost uint256 swapDataLength;
+function swapSummary(address addr, address src, address dst, uint256 lot, uint256 minOut, address callee, bytes data) returns uint256 {
+ swapCounter = swapCounter + 1;
+ swapAddr = addr;
+ swapSrc = src;
+ swapDst = dst;
+ swapLot = lot;
+ swapMinOut = minOut;
+ swapCallee = callee;
+ swapDataLength = data.length;
+ return swapRetValue;
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+ address anyAddr_2;
+
+ mathint wardsBefore = wards(anyAddr);
+ mathint budsBefore = buds(anyAddr);
+ mathint numBefore; mathint hopBefore; mathint zzzBefore; mathint lotBefore; mathint reqBefore;
+ numBefore, hopBefore, zzzBefore, lotBefore, reqBefore = configs(anyAddr, anyAddr_2);
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ mathint budsAfter = buds(anyAddr);
+ mathint numAfter; mathint hopAfter; mathint zzzAfter; mathint lotAfter; mathint reqAfter;
+ numAfter, hopAfter, zzzAfter, lotAfter, reqAfter = configs(anyAddr, anyAddr_2);
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert budsAfter != budsBefore => f.selector == sig:kiss(address).selector || f.selector == sig:diss(address).selector, "buds[x] changed in an unexpected function";
+ assert numAfter != numBefore => f.selector == sig:setConfig(address,address,uint128,uint32,uint96,uint96).selector || f.selector == sig:swap(address,address,uint256,address,bytes).selector, "configs[x][y].num changed in an unexpected function";
+ assert hopAfter != hopBefore => f.selector == sig:setConfig(address,address,uint128,uint32,uint96,uint96).selector, "configs[x][y].hop changed in an unexpected function";
+ assert zzzAfter != zzzBefore => f.selector == sig:setConfig(address,address,uint128,uint32,uint96,uint96).selector || f.selector == sig:swap(address,address,uint256,address,bytes).selector, "configs[x][y].zzz changed in an unexpected function";
+ assert lotAfter != lotBefore => f.selector == sig:setConfig(address,address,uint128,uint32,uint96,uint96).selector, "configs[x][y].lot changed in an unexpected function";
+ assert reqAfter != reqBefore => f.selector == sig:setConfig(address,address,uint128,uint32,uint96,uint96).selector, "configs[x][y].req changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting kiss
+rule kiss(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint budsOtherBefore = buds(other);
+
+ kiss(e, usr);
+
+ mathint budsUsrAfter = buds(usr);
+ mathint budsOtherAfter = buds(other);
+
+ assert budsUsrAfter == 1, "kiss did not set the buds";
+ assert budsOtherAfter == budsOtherBefore, "kiss did not keep unchanged the rest of buds[x]";
+}
+
+// Verify revert rules on kiss
+rule kiss_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ kiss@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting diss
+rule diss(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint budsOtherBefore = buds(other);
+
+ diss(e, usr);
+
+ mathint budsUsrAfter = buds(usr);
+ mathint budsOtherAfter = buds(other);
+
+ assert budsUsrAfter == 0, "diss did not set the buds";
+ assert budsOtherAfter == budsOtherBefore, "diss did not keep unchanged the rest of buds[x]";
+}
+
+// Verify revert rules on diss
+rule diss_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ diss@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setConfig
+rule setConfig(address src, address dst, uint128 num, uint32 hop, uint96 lot, uint96 req) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ require otherAddr != src || otherAddr_2 != dst;
+
+ mathint numOtherBefore; mathint hopOtherBefore; mathint zzzOtherBefore; mathint lotOtherBefore; mathint reqOtherBefore;
+ numOtherBefore, hopOtherBefore, zzzOtherBefore, lotOtherBefore, reqOtherBefore = configs(otherAddr, otherAddr_2);
+
+ setConfig(e, src, dst, num, hop, lot, req);
+
+ mathint numSrcDstAfter; mathint hopSrcDstAfter; mathint zzzSrcDstAfter; mathint lotSrcDstAfter; mathint reqSrcDstAfter;
+ numSrcDstAfter, hopSrcDstAfter, zzzSrcDstAfter, lotSrcDstAfter, reqSrcDstAfter = configs(src, dst);
+ mathint numOtherAfter; mathint hopOtherAfter; mathint zzzOtherAfter; mathint lotOtherAfter; mathint reqOtherAfter;
+ numOtherAfter, hopOtherAfter, zzzOtherAfter, lotOtherAfter, reqOtherAfter = configs(otherAddr, otherAddr_2);
+
+ assert numSrcDstAfter == to_mathint(num), "setConfig did not set configs[src][dst].num to num";
+ assert hopSrcDstAfter == to_mathint(hop), "setConfig did not set configs[src][dst].hop to hop";
+ assert zzzSrcDstAfter == 0, "setConfig did not set configs[src][dst].zzz to 0";
+ assert lotSrcDstAfter == to_mathint(lot), "setConfig did not set configs[src][dst].lot to lot";
+ assert reqSrcDstAfter == to_mathint(req), "setConfig did not set configs[src][dst].req to req";
+ assert numOtherAfter == numOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y].num";
+ assert hopOtherAfter == hopOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y].hop";
+ assert zzzOtherAfter == zzzOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y].zzz";
+ assert lotOtherAfter == lotOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y].lot";
+ assert reqOtherAfter == reqOtherBefore, "setConfig did not keep unchanged the rest of configs[x][y].req";
+}
+
+// Verify revert rules on setConfig
+rule setConfig_revert(address src, address dst, uint128 num, uint32 hop, uint96 lot, uint96 req) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ setConfig@withrevert(e, src, dst, num, hop, lot, req);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting swap
+rule swap(address src, address dst, uint256 minOut, address callee, bytes data) {
+ env e;
+
+ address otherAddr;
+ address otherAddr_2;
+ require otherAddr != src || otherAddr_2 != dst;
+
+ require e.block.timestamp <= max_uint32;
+
+ mathint a; mathint b; mathint c;
+
+ mathint numSrcDstBefore; mathint lotSrcDst; mathint reqSrcDst;
+ numSrcDstBefore, a, b, lotSrcDst, reqSrcDst = configs(src, dst);
+ mathint numOtherBefore; mathint zzzOtherBefore;
+ numOtherBefore, a, zzzOtherBefore, b, c = configs(otherAddr, otherAddr_2);
+
+ mathint swapCounterBefore = swapCounter;
+
+ swap(e, src, dst, minOut, callee, data);
+
+ mathint numSrcDstAfter; mathint zzzSrcDstAfter;
+ numSrcDstAfter, a, zzzSrcDstAfter, b, c = configs(src, dst);
+ mathint numOtherAfter; mathint zzzOtherAfter;
+ numOtherAfter, a, zzzOtherAfter, b, c = configs(otherAddr, otherAddr_2);
+
+ assert numSrcDstAfter == numSrcDstBefore - 1, "swap did not decrease configs[src][dst].num by 1";
+ assert zzzSrcDstAfter == to_mathint(e.block.timestamp), "swap did not set configs[src][dst].zzz to block.timestamp";
+ assert numOtherAfter == numOtherBefore, "swap did not keep unchanged the rest of configs[x][y].num";
+ assert zzzOtherAfter == zzzOtherBefore, "swap did not keep unchanged the rest of configs[x][y].zzz";
+ assert swapCounter == swapCounterBefore + 1, "swap did not execute exactly one swap external call";
+ assert swapAddr == swapper(), "swap did not execute the swap external call to the correct 'swapper()' contract";
+ assert swapSrc == src, "swap did not not pass the correct src to the external call";
+ assert swapDst == dst, "swap did not not pass the correct dst to the external call";
+ assert to_mathint(swapLot) == lotSrcDst, "swap did not not pass the correct lot to the external call";
+ assert to_mathint(swapMinOut) == (minOut == 0 ? reqSrcDst : to_mathint(minOut)), "swap did not not pass the correct minOut to the external call";
+ assert swapCallee == callee, "swap did not not pass the correct callee to the external call";
+ assert swapDataLength == data.length, "swap did not not pass the correct data to the external call";
+}
+
+// Verify revert rules on swap
+rule swap_revert(address src, address dst, uint256 minOut, address callee, bytes data) {
+ env e;
+
+ require data.length < max_uint32;
+ require e.block.timestamp <= max_uint32;
+
+ mathint budsSender = buds(e.msg.sender);
+ mathint numSrcDst; mathint hopSrcDst; mathint zzzSrcDst; mathint lotSrcDst; mathint reqSrcDst;
+ numSrcDst, hopSrcDst, zzzSrcDst, lotSrcDst, reqSrcDst = configs(src, dst);
+
+ swap@withrevert(e, src, dst, minOut, callee, data);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = budsSender != 1;
+ bool revert3 = numSrcDst == 0;
+ bool revert4 = to_mathint(e.block.timestamp) < zzzSrcDst + hopSrcDst;
+ bool revert5 = to_mathint(minOut) > 0 && to_mathint(minOut) < reqSrcDst;
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5, "Revert rules failed";
+}
diff --git a/certora/funnels/automation/VaultMinter.conf b/certora/funnels/automation/VaultMinter.conf
new file mode 100644
index 00000000..56c7f076
--- /dev/null
+++ b/certora/funnels/automation/VaultMinter.conf
@@ -0,0 +1,10 @@
+{
+ "files": [
+ "src/funnels/automation/VaultMinter.sol"
+ ],
+ "rule_sanity": "basic",
+ "solc": "solc-0.8.16",
+ "solc_optimize": "200",
+ "verify": "VaultMinter:certora/funnels/automation/VaultMinter.spec",
+ "wait_for_results": "all"
+}
diff --git a/certora/funnels/automation/VaultMinter.spec b/certora/funnels/automation/VaultMinter.spec
new file mode 100644
index 00000000..3991738e
--- /dev/null
+++ b/certora/funnels/automation/VaultMinter.spec
@@ -0,0 +1,325 @@
+// VaultMinter.spec
+
+methods {
+ function wards(address) external returns (uint256) envfree;
+ function buds(address) external returns (uint256) envfree;
+ function config() external returns (int64, uint32, uint32, uint128) envfree;
+ function vault() external returns (address) envfree;
+ function _.draw(uint256 wad) external => drawSummary(calledContract, wad) expect bool; // Forcing to have a return value as otherwise Certora will throw a compiler error
+ function _.wipe(uint256 wad) external => wipeSummary(calledContract, wad) expect bool; // Forcing to have a return value as otherwise Certora will throw a compiler error
+}
+
+ghost mapping(address => bool) nonZeroExtcodesize;
+hook EXTCODESIZE(address addr) uint v {
+ nonZeroExtcodesize[addr] = (v != 0);
+}
+
+ghost mathint drawCounter;
+ghost address drawAddr;
+ghost uint256 drawAmount;
+function drawSummary(address addr, uint256 amount) returns bool {
+ drawCounter = drawCounter + 1;
+ drawAddr = addr;
+ drawAmount = amount;
+ return true;
+}
+
+ghost mathint wipeCounter;
+ghost address wipeAddr;
+ghost uint256 wipeAmount;
+function wipeSummary(address addr, uint256 amount) returns bool {
+ wipeCounter = wipeCounter + 1;
+ wipeAddr = addr;
+ wipeAmount = amount;
+ return true;
+}
+
+// Verify that each storage layout is only modified in the corresponding functions
+rule storageAffected(method f) {
+ env e;
+
+ address anyAddr;
+
+ mathint wardsBefore = wards(anyAddr);
+ mathint budsBefore = buds(anyAddr);
+ mathint numBefore; mathint hopBefore; mathint zzzBefore; mathint lotBefore;
+ numBefore, hopBefore, zzzBefore, lotBefore = config();
+
+ calldataarg args;
+ f(e, args);
+
+ mathint wardsAfter = wards(anyAddr);
+ mathint budsAfter = buds(anyAddr);
+ mathint numAfter; mathint hopAfter; mathint zzzAfter; mathint lotAfter;
+ numAfter, hopAfter, zzzAfter, lotAfter = config();
+
+ assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function";
+ assert budsAfter != budsBefore => f.selector == sig:kiss(address).selector || f.selector == sig:diss(address).selector, "buds[x] changed in an unexpected function";
+ assert numAfter != numBefore => f.selector == sig:setConfig(int64,uint32,uint128).selector || f.selector == sig:draw().selector || f.selector == sig:wipe().selector, "config.num changed in an unexpected function";
+ assert hopAfter != hopBefore => f.selector == sig:setConfig(int64,uint32,uint128).selector, "config.hop changed in an unexpected function";
+ assert zzzAfter != zzzBefore => f.selector == sig:setConfig(int64,uint32,uint128).selector || f.selector == sig:draw().selector || f.selector == sig:wipe().selector, "config.zzz changed in an unexpected function";
+ assert lotAfter != lotBefore => f.selector == sig:setConfig(int64,uint32,uint128).selector, "config.lot changed in an unexpected function";
+}
+
+// Verify correct storage changes for non reverting rely
+rule rely(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ rely(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 1, "rely did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on rely
+rule rely_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ rely@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting deny
+rule deny(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint wardsOtherBefore = wards(other);
+
+ deny(e, usr);
+
+ mathint wardsUsrAfter = wards(usr);
+ mathint wardsOtherAfter = wards(other);
+
+ assert wardsUsrAfter == 0, "deny did not set the wards";
+ assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]";
+}
+
+// Verify revert rules on deny
+rule deny_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ deny@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting kiss
+rule kiss(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint budsOtherBefore = buds(other);
+
+ kiss(e, usr);
+
+ mathint budsUsrAfter = buds(usr);
+ mathint budsOtherAfter = buds(other);
+
+ assert budsUsrAfter == 1, "kiss did not set the buds";
+ assert budsOtherAfter == budsOtherBefore, "kiss did not keep unchanged the rest of buds[x]";
+}
+
+// Verify revert rules on kiss
+rule kiss_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ kiss@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting diss
+rule diss(address usr) {
+ env e;
+
+ address other;
+ require other != usr;
+
+ mathint budsOtherBefore = buds(other);
+
+ diss(e, usr);
+
+ mathint budsUsrAfter = buds(usr);
+ mathint budsOtherAfter = buds(other);
+
+ assert budsUsrAfter == 0, "diss did not set the buds";
+ assert budsOtherAfter == budsOtherBefore, "diss did not keep unchanged the rest of buds[x]";
+}
+
+// Verify revert rules on diss
+rule diss_revert(address usr) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ diss@withrevert(e, usr);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting setConfig
+rule setConfig(int64 num, uint32 hop, uint128 lot) {
+ env e;
+
+ setConfig(e, num, hop, lot);
+
+ mathint numAfter; mathint hopAfter; mathint zzzAfter; mathint lotAfter;
+ numAfter, hopAfter, zzzAfter, lotAfter = config();
+
+ assert numAfter == to_mathint(num), "setConfig did not set config.num to num";
+ assert hopAfter == to_mathint(hop), "setConfig did not set config.hop to hop";
+ assert zzzAfter == 0, "setConfig did not set config.zzz to 0";
+ assert lotAfter == to_mathint(lot), "setConfig did not set config.lot to lot";
+}
+
+// Verify revert rules on setConfig
+rule setConfig_revert(int64 num, uint32 hop, uint128 lot) {
+ env e;
+
+ mathint wardsSender = wards(e.msg.sender);
+
+ setConfig@withrevert(e, num, hop, lot);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = wardsSender != 1;
+
+ assert lastReverted <=> revert1 || revert2, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting draw
+rule draw() {
+ env e;
+
+ require e.block.timestamp <= max_uint32;
+
+ address vault = vault();
+
+ mathint a; mathint b;
+
+ mathint numBefore; mathint lot;
+ numBefore, a, b, lot = config();
+
+ mathint drawCounterBefore = drawCounter;
+
+ draw(e);
+
+ mathint numAfter; mathint zzzAfter;
+ numAfter, a, zzzAfter, a = config();
+
+ assert numAfter == numBefore - 1, "draw did not decrease config.num by 1";
+ assert zzzAfter == to_mathint(e.block.timestamp), "draw did not set config.zzz to block.timestamp";
+ assert drawCounter == drawCounterBefore + 1, "draw did not execute exactly one draw external call";
+ assert drawAddr == vault, "draw did not execute the draw external call to the correct vault contract";
+ assert to_mathint(drawAmount) == lot, "draw did not pass the correct amount to the draw external call";
+}
+
+// Verify revert rules on draw
+rule draw_revert() {
+ env e;
+
+ address vault = vault();
+
+ require e.block.timestamp <= max_uint32;
+ require !nonZeroExtcodesize[vault];
+
+ mathint budsSender = buds(e.msg.sender);
+ mathint a;
+ mathint num; mathint hop; mathint zzz;
+ num, hop, zzz, a = config();
+
+ draw@withrevert(e);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = budsSender != 1;
+ bool revert3 = num == 0;
+ bool revert4 = to_mathint(e.block.timestamp) < zzz + hop;
+ bool revert5 = !nonZeroExtcodesize[vault];
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5, "Revert rules failed";
+}
+
+// Verify correct storage changes for non reverting wipe
+rule wipe() {
+ env e;
+
+ require e.block.timestamp <= max_uint32;
+
+ address vault = vault();
+
+ mathint a; mathint b;
+
+ mathint numBefore; mathint lot;
+ numBefore, a, b, lot = config();
+
+ mathint wipeCounterBefore = wipeCounter;
+
+ wipe(e);
+
+ mathint numAfter; mathint zzzAfter;
+ numAfter, a, zzzAfter, a = config();
+
+ assert numAfter == numBefore + 1, "wipe did not decrease config.num by 1";
+ assert zzzAfter == to_mathint(e.block.timestamp), "wipe did not set config.zzz to block.timestamp";
+ assert wipeCounter == wipeCounterBefore + 1, "wipe did not execute exactly one wipe external call";
+ assert wipeAddr == vault, "wipe did not execute the wipe external call to the correct vault contract";
+ assert to_mathint(wipeAmount) == lot, "wipe did not pass the correct amount to the wipe external call";
+}
+
+// Verify revert rules on wipe
+rule wipe_revert() {
+ env e;
+
+ address vault = vault();
+
+ require e.block.timestamp <= max_uint32;
+ require !nonZeroExtcodesize[vault];
+
+ mathint budsSender = buds(e.msg.sender);
+ mathint a;
+ mathint num; mathint hop; mathint zzz;
+ num, hop, zzz, a = config();
+
+ wipe@withrevert(e);
+
+ bool revert1 = e.msg.value > 0;
+ bool revert2 = budsSender != 1;
+ bool revert3 = num == 0;
+ bool revert4 = to_mathint(e.block.timestamp) < zzz + hop;
+ bool revert5 = !nonZeroExtcodesize[vault];
+
+ assert lastReverted <=> revert1 || revert2 || revert3 ||
+ revert4 || revert5, "Revert rules failed";
+}
diff --git a/deploy/AllocatorDeploy.sol b/deploy/AllocatorDeploy.sol
new file mode 100644
index 00000000..bf0a2917
--- /dev/null
+++ b/deploy/AllocatorDeploy.sol
@@ -0,0 +1,67 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+import { ScriptTools } from "dss-test/ScriptTools.sol";
+
+import { AllocatorOracle } from "src/AllocatorOracle.sol";
+import { AllocatorRoles } from "src/AllocatorRoles.sol";
+import { AllocatorRegistry } from "src/AllocatorRegistry.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+import { AllocatorVault } from "src/AllocatorVault.sol";
+
+import { AllocatorSharedInstance, AllocatorIlkInstance } from "./AllocatorInstances.sol";
+
+library AllocatorDeploy {
+
+ // Note: owner is assumed to be the pause proxy
+ function deployShared(
+ address deployer,
+ address owner
+ ) internal returns (AllocatorSharedInstance memory sharedInstance) {
+ address _oracle = address(new AllocatorOracle());
+
+ address _roles = address(new AllocatorRoles());
+ ScriptTools.switchOwner(_roles, deployer, owner);
+
+ address _registry = address(new AllocatorRegistry());
+ ScriptTools.switchOwner(_registry, deployer, owner);
+
+ sharedInstance.oracle = _oracle;
+ sharedInstance.roles = _roles;
+ sharedInstance.registry = _registry;
+ }
+
+ // Note: owner is assumed to be the pause proxy, allocator proxy will receive ownerships on init
+ function deployIlk(
+ address deployer,
+ address owner,
+ address roles,
+ bytes32 ilk,
+ address usdsJoin
+ ) internal returns (AllocatorIlkInstance memory ilkInstance) {
+ address _buffer = address(new AllocatorBuffer());
+ ScriptTools.switchOwner(_buffer, deployer, owner);
+ ilkInstance.buffer = _buffer;
+
+ address _vault = address(new AllocatorVault(roles, _buffer, ilk, usdsJoin));
+ ScriptTools.switchOwner(_vault, deployer, owner);
+ ilkInstance.vault = _vault;
+
+ ilkInstance.owner = owner;
+ }
+}
diff --git a/deploy/AllocatorInit.sol b/deploy/AllocatorInit.sol
new file mode 100644
index 00000000..e5986bf3
--- /dev/null
+++ b/deploy/AllocatorInit.sol
@@ -0,0 +1,165 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity >=0.8.0;
+
+import { ScriptTools } from "dss-test/ScriptTools.sol";
+import { DssInstance } from "dss-test/MCD.sol";
+import { AllocatorSharedInstance, AllocatorIlkInstance } from "./AllocatorInstances.sol";
+
+interface IlkRegistryLike {
+ function put(
+ bytes32 _ilk,
+ address _join,
+ address _gem,
+ uint256 _dec,
+ uint256 _class,
+ address _pip,
+ address _xlip,
+ string calldata _name,
+ string calldata _symbol
+ ) external;
+}
+
+interface RolesLike {
+ function setIlkAdmin(bytes32, address) external;
+}
+
+interface RegistryLike {
+ function file(bytes32, bytes32, address) external;
+}
+
+interface VaultLike {
+ function ilk() external view returns (bytes32);
+ function roles() external view returns (address);
+ function buffer() external view returns (address);
+ function vat() external view returns (address);
+ function usds() external view returns (address);
+ function file(bytes32, address) external;
+}
+
+interface BufferLike {
+ function approve(address, address, uint256) external;
+}
+
+interface AutoLineLike {
+ function setIlk(bytes32, uint256, uint256, uint256) external;
+}
+
+struct AllocatorIlkConfig {
+ bytes32 ilk;
+ uint256 duty;
+ uint256 gap;
+ uint256 maxLine;
+ uint256 ttl;
+ address allocatorProxy;
+ address ilkRegistry;
+}
+
+function bytes32ToStr(bytes32 _bytes32) pure returns (string memory) {
+ uint256 len;
+ while(len < 32 && _bytes32[len] != 0) len++;
+ bytes memory bytesArray = new bytes(len);
+ for (uint256 i; i < len; i++) {
+ bytesArray[i] = _bytes32[i];
+ }
+ return string(bytesArray);
+}
+
+library AllocatorInit {
+ uint256 constant WAD = 10 ** 18;
+ uint256 constant RAY = 10 ** 27;
+
+ uint256 constant RATES_ONE_HUNDRED_PCT = 1000000021979553151239153027;
+
+ function initShared(
+ DssInstance memory dss,
+ AllocatorSharedInstance memory sharedInstance
+ ) internal {
+ dss.chainlog.setAddress("ALLOCATOR_ROLES", sharedInstance.roles);
+ dss.chainlog.setAddress("ALLOCATOR_REGISTRY", sharedInstance.registry);
+ }
+
+ // Please note this should be executed by the pause proxy
+ function initIlk(
+ DssInstance memory dss,
+ AllocatorSharedInstance memory sharedInstance,
+ AllocatorIlkInstance memory ilkInstance,
+ AllocatorIlkConfig memory cfg
+ ) internal {
+ bytes32 ilk = cfg.ilk;
+
+ // Sanity checks
+ require(VaultLike(ilkInstance.vault).ilk() == ilk, "AllocatorInit/vault-ilk-mismatch");
+ require(VaultLike(ilkInstance.vault).roles() == sharedInstance.roles, "AllocatorInit/vault-roles-mismatch");
+ require(VaultLike(ilkInstance.vault).buffer() == ilkInstance.buffer, "AllocatorInit/vault-buffer-mismatch");
+ require(VaultLike(ilkInstance.vault).vat() == address(dss.vat), "AllocatorInit/vault-vat-mismatch");
+ // Once usdsJoin is in the chainlog and adapted to dss-test should also check against it
+
+ // Onboard the ilk
+ dss.vat.init(ilk);
+ dss.jug.init(ilk);
+
+ require((cfg.duty >= RAY) && (cfg.duty <= RATES_ONE_HUNDRED_PCT), "AllocatorInit/ilk-duty-out-of-bounds");
+ dss.jug.file(ilk, "duty", cfg.duty);
+
+ dss.vat.file(ilk, "line", cfg.gap);
+ dss.vat.file("Line", dss.vat.Line() + cfg.gap);
+ AutoLineLike(dss.chainlog.getAddress("MCD_IAM_AUTO_LINE")).setIlk(ilk, cfg.maxLine, cfg.gap, cfg.ttl);
+
+ dss.spotter.file(ilk, "pip", sharedInstance.oracle);
+ dss.spotter.file(ilk, "mat", RAY);
+ dss.spotter.poke(ilk);
+
+ // Add buffer to registry
+ RegistryLike(sharedInstance.registry).file(ilk, "buffer", ilkInstance.buffer);
+
+ // Initiate the allocator vault
+ dss.vat.slip(ilk, ilkInstance.vault, int256(10**12 * WAD));
+ dss.vat.grab(ilk, ilkInstance.vault, ilkInstance.vault, address(0), int256(10**12 * WAD), 0);
+
+ VaultLike(ilkInstance.vault).file("jug", address(dss.jug));
+
+ // Allow vault to pull funds from the buffer
+ BufferLike(ilkInstance.buffer).approve(VaultLike(ilkInstance.vault).usds(), ilkInstance.vault, type(uint256).max);
+
+ // Set the allocator proxy as the ilk admin instead of the Pause Proxy
+ RolesLike(sharedInstance.roles).setIlkAdmin(ilk, cfg.allocatorProxy);
+
+ // Move ownership of the ilk contracts to the allocator proxy
+ ScriptTools.switchOwner(ilkInstance.vault, ilkInstance.owner, cfg.allocatorProxy);
+ ScriptTools.switchOwner(ilkInstance.buffer, ilkInstance.owner, cfg.allocatorProxy);
+
+ // Add allocator-specific contracts to changelog
+ string memory ilkString = ScriptTools.ilkToChainlogFormat(ilk);
+ dss.chainlog.setAddress(ScriptTools.stringToBytes32(string(abi.encodePacked(ilkString, "_VAULT"))), ilkInstance.vault);
+ dss.chainlog.setAddress(ScriptTools.stringToBytes32(string(abi.encodePacked(ilkString, "_BUFFER"))), ilkInstance.buffer);
+ dss.chainlog.setAddress(ScriptTools.stringToBytes32(string(abi.encodePacked("PIP_", ilkString))), sharedInstance.oracle);
+
+ // Add to ilk registry
+ IlkRegistryLike(cfg.ilkRegistry).put({
+ _ilk : ilk,
+ _join : address(0),
+ _gem : address(0),
+ _dec : 0,
+ _class : 5, // RWAs are class 3, D3Ms and Teleport are class 4
+ _pip : sharedInstance.oracle,
+ _xlip : address(0),
+ _name : bytes32ToStr(ilk),
+ _symbol : bytes32ToStr(ilk)
+ });
+ }
+}
diff --git a/deploy/AllocatorInstances.sol b/deploy/AllocatorInstances.sol
new file mode 100644
index 00000000..1fd2a4bc
--- /dev/null
+++ b/deploy/AllocatorInstances.sol
@@ -0,0 +1,29 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity >=0.8.0;
+
+struct AllocatorSharedInstance {
+ address oracle;
+ address roles;
+ address registry;
+}
+
+struct AllocatorIlkInstance {
+ address owner;
+ address vault;
+ address buffer;
+}
diff --git a/deploy/funnels/AllocatorFunnelDeploy.sol b/deploy/funnels/AllocatorFunnelDeploy.sol
new file mode 100644
index 00000000..f525906c
--- /dev/null
+++ b/deploy/funnels/AllocatorFunnelDeploy.sol
@@ -0,0 +1,76 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+import { ScriptTools } from "dss-test/ScriptTools.sol";
+
+import { Swapper } from "src/funnels/Swapper.sol";
+import { DepositorUniV3 } from "src/funnels/DepositorUniV3.sol";
+import { VaultMinter } from "src/funnels/automation/VaultMinter.sol";
+import { StableSwapper } from "src/funnels/automation/StableSwapper.sol";
+import { StableDepositorUniV3 } from "src/funnels/automation/StableDepositorUniV3.sol";
+import { ConduitMover } from "src/funnels/automation/ConduitMover.sol";
+
+import { AllocatorIlkFunnelInstance } from "./AllocatorFunnelInstance.sol";
+
+library AllocatorFunnelDeploy {
+
+ // Note: owner is assumed to be the allocator proxy
+ function deployIlkFunnel(
+ address deployer,
+ address owner,
+ address roles,
+ bytes32 ilk,
+ address uniV3Factory,
+ address vault,
+ address buffer
+ ) internal returns (AllocatorIlkFunnelInstance memory ilkFunnelInstance) {
+ address _swapper = address(new Swapper(roles, ilk, buffer));
+ ScriptTools.switchOwner(_swapper, deployer, owner);
+ ilkFunnelInstance.swapper = _swapper;
+
+ address _depositorUniV3 = address(new DepositorUniV3(roles, ilk, uniV3Factory, buffer));
+ ScriptTools.switchOwner(_depositorUniV3, deployer, owner);
+ ilkFunnelInstance.depositorUniV3 = _depositorUniV3;
+
+ {
+ address _vaultMinter = address(new VaultMinter(vault));
+ ScriptTools.switchOwner(_vaultMinter, deployer, owner);
+ ilkFunnelInstance.vaultMinter = _vaultMinter;
+ }
+
+ {
+ address _stableSwapper = address(new StableSwapper(_swapper));
+ ScriptTools.switchOwner(_stableSwapper, deployer, owner);
+ ilkFunnelInstance.stableSwapper = _stableSwapper;
+ }
+
+ {
+ address _stableDepositorUniV3 = address(new StableDepositorUniV3(_depositorUniV3));
+ ScriptTools.switchOwner(_stableDepositorUniV3, deployer, owner);
+ ilkFunnelInstance.stableDepositorUniV3 = _stableDepositorUniV3;
+ }
+
+ {
+ address _conduitMover = address(new ConduitMover(ilk, buffer));
+ ScriptTools.switchOwner(_conduitMover, deployer, owner);
+ ilkFunnelInstance.conduitMover = _conduitMover;
+ }
+
+ ilkFunnelInstance.owner = owner;
+ }
+}
diff --git a/deploy/funnels/AllocatorFunnelInit.sol b/deploy/funnels/AllocatorFunnelInit.sol
new file mode 100644
index 00000000..044fcbcc
--- /dev/null
+++ b/deploy/funnels/AllocatorFunnelInit.sol
@@ -0,0 +1,196 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity >=0.8.0;
+
+import { AllocatorSharedInstance, AllocatorIlkInstance } from "deploy/AllocatorInstances.sol";
+import { AllocatorIlkFunnelInstance } from "./AllocatorFunnelInstance.sol";
+
+interface WardsLike {
+ function rely(address) external;
+}
+
+interface RolesLike {
+ function setUserRole(bytes32, address, uint8, bool) external;
+ function setRoleAction(bytes32, uint8, address, bytes4, bool) external;
+}
+
+interface VaultLike {
+ function draw(uint256) external;
+ function wipe(uint256) external;
+}
+
+interface BufferLike {
+ function approve(address, address, uint256) external;
+}
+
+interface SwapperLike {
+ function roles() external view returns (address);
+ function ilk() external view returns (bytes32);
+ function buffer() external view returns (address);
+ function swap(address, address, uint256, uint256, address, bytes calldata) external returns (uint256);
+}
+
+interface DepositorUniV3Like {
+ struct LiquidityParams {
+ address gem0;
+ address gem1;
+ uint24 fee;
+ int24 tickLower;
+ int24 tickUpper;
+ uint128 liquidity;
+ uint256 amt0Desired;
+ uint256 amt1Desired;
+ uint256 amt0Min;
+ uint256 amt1Min;
+ }
+
+ struct CollectParams {
+ address gem0;
+ address gem1;
+ uint24 fee;
+ int24 tickLower;
+ int24 tickUpper;
+ }
+
+ function roles() external view returns (address);
+ function ilk() external view returns (bytes32);
+ function uniV3Factory() external view returns (address);
+ function buffer() external view returns (address);
+ function deposit(LiquidityParams memory) external returns (uint128, uint256, uint256);
+ function withdraw(LiquidityParams memory, bool) external returns (uint128, uint256, uint256, uint256, uint256);
+ function collect(CollectParams memory) external returns (uint256, uint256);
+}
+
+interface VaultMinterLike {
+ function vault() external view returns (address);
+}
+
+interface StableSwapperLike {
+ function swapper() external view returns (address);
+}
+
+interface StableDepositorUniV3Like {
+ function depositor() external view returns (address);
+}
+
+interface ConduitMoverLike {
+ function ilk() external view returns (bytes32);
+ function buffer() external view returns (address);
+}
+
+interface KissLike {
+ function kiss(address) external;
+}
+
+struct AllocatorIlkFunnelConfig {
+ bytes32 ilk;
+ address allocatorProxy;
+ uint8 facilitatorRole;
+ uint8 automationRole;
+ address[] facilitators;
+ address[] vaultMinterKeepers;
+ address[] stableSwapperKeepers;
+ address[] stableDepositorUniV3Keepers;
+ address[] conduitMoverKeepers;
+ address[] swapTokens;
+ address[] depositTokens;
+ address uniV3Factory;
+}
+
+library AllocatorFunnelInit {
+
+ // Please note this should be executed by the allocator proxy
+ function initIlkFunnel(
+ AllocatorSharedInstance memory sharedInstance,
+ AllocatorIlkInstance memory ilkInstance,
+ AllocatorIlkFunnelInstance memory ilkFunnelInstance,
+ AllocatorIlkFunnelConfig memory cfg
+ ) internal {
+ bytes32 ilk = cfg.ilk;
+
+ require(SwapperLike(ilkFunnelInstance.swapper).roles() == sharedInstance.roles, "AllocatorInit/swapper-roles-mismatch");
+ require(SwapperLike(ilkFunnelInstance.swapper).ilk() == ilk, "AllocatorInit/swapper-ilk-mismatch");
+ require(SwapperLike(ilkFunnelInstance.swapper).buffer() == ilkInstance.buffer, "AllocatorInit/swapper-buffer-mismatch");
+
+ require(DepositorUniV3Like(ilkFunnelInstance.depositorUniV3).roles() == sharedInstance.roles, "AllocatorInit/depositorUniV3-roles-mismatch");
+ require(DepositorUniV3Like(ilkFunnelInstance.depositorUniV3).ilk() == ilk, "AllocatorInit/depositorUniV3-ilk-mismatch");
+ require(DepositorUniV3Like(ilkFunnelInstance.depositorUniV3).uniV3Factory() == cfg.uniV3Factory, "AllocatorInit/depositorUniV3-uniV3Factory-mismatch");
+ require(DepositorUniV3Like(ilkFunnelInstance.depositorUniV3).buffer() == ilkInstance.buffer, "AllocatorInit/depositorUniV3-buffer-mismatch");
+
+ require(VaultMinterLike(ilkFunnelInstance.vaultMinter).vault() == ilkInstance.vault, "AllocatorInit/vaultMinter-vault-mismatch");
+
+ require(StableSwapperLike(ilkFunnelInstance.stableSwapper).swapper() == ilkFunnelInstance.swapper, "AllocatorInit/stableSwapper-swapper-mismatch");
+ require(StableDepositorUniV3Like(ilkFunnelInstance.stableDepositorUniV3).depositor() == ilkFunnelInstance.depositorUniV3, "AllocatorInit/stableDepositorUniV3-depositorUniV3-mismatch");
+
+ require(ConduitMoverLike(ilkFunnelInstance.conduitMover).ilk() == ilk, "AllocatorInit/conduitMover-ilk-mismatch");
+ require(ConduitMoverLike(ilkFunnelInstance.conduitMover).buffer() == ilkInstance.buffer, "AllocatorInit/conduitMover-buffer-mismatch");
+
+ // Allow vault and funnels to pull funds from the buffer
+ for(uint256 i = 0; i < cfg.swapTokens.length; i++) {
+ BufferLike(ilkInstance.buffer).approve(cfg.swapTokens[i], ilkFunnelInstance.swapper, type(uint256).max);
+ }
+ for(uint256 i = 0; i < cfg.depositTokens.length; i++) {
+ BufferLike(ilkInstance.buffer).approve(cfg.depositTokens[i], ilkFunnelInstance.depositorUniV3, type(uint256).max);
+ }
+
+ // Allow the facilitators to operate on the vault and funnels directly
+ for(uint256 i = 0; i < cfg.facilitators.length; i++) {
+ RolesLike(sharedInstance.roles).setUserRole(ilk, cfg.facilitators[i], cfg.facilitatorRole, true);
+ }
+
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkInstance.vault, VaultLike.draw.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkInstance.vault, VaultLike.wipe.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkFunnelInstance.swapper, SwapperLike.swap.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.deposit.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.withdraw.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.collect.selector, true);
+
+ // Allow the automation contracts to operate on the funnels
+ RolesLike(sharedInstance.roles).setUserRole(ilk, ilkFunnelInstance.vaultMinter, cfg.automationRole, true);
+ RolesLike(sharedInstance.roles).setUserRole(ilk, ilkFunnelInstance.stableSwapper, cfg.automationRole, true);
+ RolesLike(sharedInstance.roles).setUserRole(ilk, ilkFunnelInstance.stableDepositorUniV3, cfg.automationRole, true);
+
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkInstance.vault, VaultLike.draw.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkInstance.vault, VaultLike.wipe.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkFunnelInstance.swapper, SwapperLike.swap.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.deposit.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.withdraw.selector, true);
+ RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.collect.selector, true);
+
+ // Allow facilitator to set configurations in the automation contracts
+ for(uint256 i = 0; i < cfg.facilitators.length; i++) {
+ WardsLike(ilkFunnelInstance.vaultMinter).rely(cfg.facilitators[i]);
+ WardsLike(ilkFunnelInstance.stableSwapper).rely(cfg.facilitators[i]);
+ WardsLike(ilkFunnelInstance.stableDepositorUniV3).rely(cfg.facilitators[i]);
+ WardsLike(ilkFunnelInstance.conduitMover).rely(cfg.facilitators[i]);
+ }
+
+ // Add keepers to the automation contracts
+ for(uint256 i = 0; i < cfg.vaultMinterKeepers.length; i++) {
+ KissLike(ilkFunnelInstance.vaultMinter).kiss(cfg.vaultMinterKeepers[i]);
+ }
+ for(uint256 i = 0; i < cfg.stableSwapperKeepers.length; i++) {
+ KissLike(ilkFunnelInstance.stableSwapper).kiss(cfg.stableSwapperKeepers[i]);
+ }
+ for(uint256 i = 0; i < cfg.stableDepositorUniV3Keepers.length; i++) {
+ KissLike(ilkFunnelInstance.stableDepositorUniV3).kiss(cfg.stableDepositorUniV3Keepers[i]);
+ }
+ for(uint256 i = 0; i < cfg.conduitMoverKeepers.length; i++) {
+ KissLike(ilkFunnelInstance.conduitMover).kiss(cfg.conduitMoverKeepers[i]);
+ }
+ }
+}
diff --git a/deploy/funnels/AllocatorFunnelInstance.sol b/deploy/funnels/AllocatorFunnelInstance.sol
new file mode 100644
index 00000000..bef2881e
--- /dev/null
+++ b/deploy/funnels/AllocatorFunnelInstance.sol
@@ -0,0 +1,27 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity >=0.8.0;
+
+struct AllocatorIlkFunnelInstance {
+ address owner;
+ address swapper;
+ address depositorUniV3;
+ address vaultMinter;
+ address stableSwapper;
+ address stableDepositorUniV3;
+ address conduitMover;
+}
diff --git a/foundry.toml b/foundry.toml
index 4ff40c48..1bc5d09b 100644
--- a/foundry.toml
+++ b/foundry.toml
@@ -2,5 +2,9 @@
src = "src"
out = "out"
libs = ["lib"]
+solc = "0.8.16"
+optimizer = true
+optimizer_runs = 200
+verbosity = 1
-# See more config options https://github.com/foundry-rs/foundry/tree/master/config
\ No newline at end of file
+# See more config options https://github.com/foundry-rs/foundry/tree/master/config
diff --git a/lib/dss-test b/lib/dss-test
new file mode 160000
index 00000000..df7b13ea
--- /dev/null
+++ b/lib/dss-test
@@ -0,0 +1 @@
+Subproject commit df7b13ead253f4b831df2464f7d74f28a091a790
diff --git a/lib/forge-std b/lib/forge-std
deleted file mode 160000
index 73d44ec7..00000000
--- a/lib/forge-std
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 73d44ec7d124e3831bc5f832267889ffb6f9bc3f
diff --git a/script/funnels/automation/run_conduit_mover.sh b/script/funnels/automation/run_conduit_mover.sh
new file mode 100755
index 00000000..6372f0b3
--- /dev/null
+++ b/script/funnels/automation/run_conduit_mover.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+
+# Usage: ./run_conduit_mover.sh $CHAINID $CONDUIT_MOVER_ADDR $FROM_BLOCK
+# Example goerli usage: ./run_conduit_mover.sh 5 0x04e02dEa98410758e52cd0c47F07d9cc0fb15566 9440653
+
+set -e
+
+CHAINID=$1
+CONDUIT_MOVER=$2
+FROM_BLOCK=${3:-"earliest"}
+
+[[ "$ETH_RPC_URL" && "$(cast chain-id)" == "$CHAINID" ]] || { echo -e "Please set a ETH_RPC_URL pointing to chainId $CHAINID"; exit 1; }
+
+SET_CONFIG_LOG="SetConfig(address indexed from, address indexed to, address indexed gem, uint64 num, uint32 hop, uint128 lot)"
+MOVE_SIG="move(address from, address to, address gem)"
+
+JSON=$(cast logs --from-block $FROM_BLOCK --to-block latest --address $CONDUIT_MOVER "$SET_CONFIG_LOG" --json)
+echo $JSON | jq -c '.[]' | while read i; do
+ from=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[1]"))
+ to=$( cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[2]"))
+ gem=$( cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[3]"))
+
+ params="$from $to $gem"
+ var="handled_${params// /_}"
+ if [ -z "${!var}" ]; then
+ declare handled_${params// /_}=1
+ else
+ continue
+ fi
+
+ cfg=$(cast call $CONDUIT_MOVER "configs(address,address,address)(uint64,uint32,uint32,uint128)" $params)
+ num=$(echo $cfg | cut -d" " -f1)
+
+ if (( num > 0 )); then
+ echo "Num=$num. Moving $gem from conduit $from to conduit $to..."
+ gas=$(cast estimate $CONDUIT_MOVER "$MOVE_SIG" $params || true)
+ [[ -z "$gas" ]] && { continue; }
+ cast send --gas-limit $gas $CONDUIT_MOVER "$MOVE_SIG" $params
+ fi
+done
diff --git a/script/funnels/automation/run_stable_depositor.sh b/script/funnels/automation/run_stable_depositor.sh
new file mode 100755
index 00000000..ac5173d6
--- /dev/null
+++ b/script/funnels/automation/run_stable_depositor.sh
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+
+# Usage: ./run_stable_depositor.sh $CHAINID $STABLE_DEPOSITOR_ADDR $FROM_BLOCK
+# Example goerli usage: ./run_stable_depositor.sh 5 0x61928e1813c8883D14a75f31F3daeE53929A45DE 9422770
+
+set -e
+
+CHAINID=$1
+STABLE_DEPOSITOR=$2
+FROM_BLOCK=${3:-"earliest"}
+
+[[ "$ETH_RPC_URL" && "$(cast chain-id)" == "$CHAINID" ]] || { echo -e "Please set a ETH_RPC_URL pointing to chainId $CHAINID"; exit 1; }
+
+SET_CONFIG_LOG="SetConfig(address indexed gem0, address indexed gem1, uint24 indexed fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1)"
+DEPOSIT_SIG="deposit(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min)"
+WITHDRAW_SIG="withdraw(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min)"
+
+JSON=$(cast logs --from-block $FROM_BLOCK --to-block latest --address $STABLE_DEPOSITOR "$SET_CONFIG_LOG" --json)
+echo $JSON | jq -c '.[]' | while read i; do
+ gem0=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[1]"))
+ gem1=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[2]"))
+ fee=$(cast abi-decode --input "x(uint24)" $(echo $i | jq -r ".topics[3]"))
+ data=$(cast abi-decode --input "x(int24,int24)" $(echo $i | jq -r ".data"))
+ tickLower=$(echo $data | cut -d" " -f1)
+ tickUpper=$(echo $data | cut -d" " -f2)
+
+ params="$gem0 $gem1 $fee $tickLower $tickUpper"
+ var="handled_${params//[- ]/_}"
+ if [ -z "${!var}" ]; then
+ declare handled_${params//[- ]/_}=1
+ else
+ continue
+ fi
+
+ cfg_calldata=$(cast calldata "configs(address,address,uint24,int24,int24)" $params)
+ # Note that we run `cast call` using the raw calldata to avoid issues with negative arguments
+ cfg=$(cast call $STABLE_DEPOSITOR $cfg_calldata)
+ decoded_cfg=$(cast abi-decode --input "x(int32,uint32,uint96,uint96,uint96,uint96,uint32)" $cfg)
+ num=$(echo $decoded_cfg | cut -d" " -f1)
+
+ if (( num > 0 )); then
+ echo "Num=$num. Depositing into ($gem0, $gem1, $fee) pool..."
+ sig=$DEPOSIT_SIG
+ elif (( num < 0 )); then
+ echo "Num=$num. Withdrawing from ($gem0, $gem1, $fee) pool..."
+ sig=$WITHDRAW_SIG
+ fi
+
+ if (( num )); then
+ calldata=$(cast calldata "$sig" $params 0 0)
+ # Note that we run `cast estimate` and `cast send` using the raw calldata to avoid issues with negative arguments
+ gas=$(cast estimate $STABLE_DEPOSITOR $calldata || true)
+ [[ -z "$gas" ]] && { continue; }
+ cast send --gas-limit $gas $STABLE_DEPOSITOR $calldata
+ fi
+done
diff --git a/script/funnels/automation/run_stable_swapper.sh b/script/funnels/automation/run_stable_swapper.sh
new file mode 100755
index 00000000..79209996
--- /dev/null
+++ b/script/funnels/automation/run_stable_swapper.sh
@@ -0,0 +1,41 @@
+#!/usr/bin/env bash
+
+# Usage: ./run_stable_swapper.sh $CHAINID $STABLE_SWAPPER_ADDR $CALLEE_ADDR $POOL_FEE $FROM_BLOCK
+# Example goerli usage: ./run_stable_swapper.sh 5 0x4b4271cA5980a436972BEc4ad9870f773e2b3e11 0x8963f53392D35a6c9939804a924058aB981363e4 500 9416503
+
+set -e
+
+CHAINID=$1
+STABLE_SWAPPER=$2
+CALLEE=$3
+POOL_FEE=$4
+FROM_BLOCK=${5:-"earliest"}
+
+[[ "$ETH_RPC_URL" && "$(cast chain-id)" == "$CHAINID" ]] || { echo -e "Please set a ETH_RPC_URL pointing to chainId $CHAINID"; exit 1; }
+
+SET_CONFIG_LOG="SetConfig(address indexed src, address indexed dst, uint128 num, uint32 hop, uint96 lot, uint96 req)"
+SWAP_SIG="swap(address src, address dst, uint256 minOut, address callee, bytes calldata data)"
+
+JSON=$(cast logs --from-block $FROM_BLOCK --to-block latest --address $STABLE_SWAPPER "$SET_CONFIG_LOG" --json)
+echo $JSON | jq -c '.[]' | while read i; do
+ src=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[1]"))
+ dst=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[2]"))
+
+ var="handled_${src}_${dst}"
+ if [ -z "${!var}" ]; then
+ declare handled_${src}_${dst}=1
+ else
+ continue
+ fi
+
+ cfg=$(cast call $STABLE_SWAPPER "configs(address,address)(uint128,uint32,uint32,uint96,uint96)" $src $dst)
+ num=$(echo $cfg | cut -d" " -f1)
+
+ if (( num > 0 )); then
+ echo "Num=$num. Swapping from $src to $dst..."
+ data="$(cast concat-hex $src $(printf "%06X" $(cast to-hex $POOL_FEE)) $dst)"
+ gas=$(cast estimate $STABLE_SWAPPER "$SWAP_SIG" $src $dst 0 $CALLEE $data || true)
+ [[ -z "$gas" ]] && { continue; }
+ cast send --gas-limit $gas $STABLE_SWAPPER "$SWAP_SIG" $src $dst 0 $CALLEE $data
+ fi
+done
diff --git a/src/AllocatorBuffer.sol b/src/AllocatorBuffer.sol
new file mode 100644
index 00000000..73d82294
--- /dev/null
+++ b/src/AllocatorBuffer.sol
@@ -0,0 +1,66 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface GemLike {
+ function approve(address, uint256) external;
+}
+
+contract AllocatorBuffer {
+ // --- storage variables ---
+
+ mapping(address => uint256) public wards;
+
+ // --- events ---
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event Approve(address indexed asset, address indexed spender, uint256 amount);
+
+ // --- modifiers ---
+
+ modifier auth() {
+ require(wards[msg.sender] == 1, "AllocatorBuffer/not-authorized");
+ _;
+ }
+
+ // --- constructor ---
+
+ constructor() {
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ // --- administration ---
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ // --- functions ---
+
+ function approve(address asset, address spender, uint256 amount) external auth {
+ GemLike(asset).approve(spender, amount);
+ emit Approve(asset, spender, amount);
+ }
+}
diff --git a/src/AllocatorOracle.sol b/src/AllocatorOracle.sol
new file mode 100644
index 00000000..ba7171ad
--- /dev/null
+++ b/src/AllocatorOracle.sol
@@ -0,0 +1,39 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+contract AllocatorOracle {
+ uint256 internal constant WAD = 10**18; // For 1:1 price
+
+ /**
+ @notice Return value and status of the oracle
+ @return val PRICE constant
+ @return ok always true
+ */
+ function peek() public pure returns (bytes32 val, bool ok) {
+ val = bytes32(WAD);
+ ok = true;
+ }
+
+ /**
+ @notice Return value
+ @return val PRICE constant
+ */
+ function read() external pure returns (bytes32 val) {
+ val = bytes32(WAD);
+ }
+}
diff --git a/src/AllocatorRegistry.sol b/src/AllocatorRegistry.sol
new file mode 100644
index 00000000..c33592e6
--- /dev/null
+++ b/src/AllocatorRegistry.sol
@@ -0,0 +1,63 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+contract AllocatorRegistry {
+ // --- storage variables ---
+
+ mapping(address => uint256) public wards;
+ mapping(bytes32 => address) public buffers;
+
+ // --- events ---
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event File(bytes32 indexed ilk, bytes32 indexed what, address data);
+
+ // --- modifiers ---
+
+ modifier auth() {
+ require(wards[msg.sender] == 1, "AllocatorRegistry/not-authorized");
+ _;
+ }
+
+ // --- constructor ---
+
+ constructor() {
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ // --- administration ---
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function file(bytes32 ilk, bytes32 what, address data) external auth {
+ if (what == "buffer") {
+ buffers[ilk] = data;
+ } else revert("AllocatorRegistry/file-unrecognized-param");
+ emit File(ilk, what, data);
+ }
+}
diff --git a/src/AllocatorRoles.sol b/src/AllocatorRoles.sol
new file mode 100644
index 00000000..fc25942f
--- /dev/null
+++ b/src/AllocatorRoles.sol
@@ -0,0 +1,109 @@
+// SPDX-FileCopyrightText: © 2017 DappHub, LLC
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+contract AllocatorRoles {
+ // --- storage variables ---
+
+ mapping(address => uint256) public wards;
+ mapping(bytes32 => address) public ilkAdmins;
+ mapping(bytes32 => mapping(address => bytes32)) public userRoles;
+ mapping(bytes32 => mapping(address => mapping(bytes4 => bytes32))) public actionsRoles;
+
+ // --- events ---
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event SetIlkAdmin(bytes32 indexed ilk, address user);
+ event SetUserRole(bytes32 indexed ilk, address indexed who, uint8 indexed role, bool enabled);
+ event SetRoleAction(bytes32 indexed ilk, uint8 indexed role, address indexed target, bytes4 sig, bool enabled);
+
+ // --- modifiers ---
+
+ modifier auth() {
+ require(wards[msg.sender] == 1, "AllocatorRoles/not-authorized");
+ _;
+ }
+
+ modifier ilkAuth(bytes32 ilk) {
+ require(ilkAdmins[ilk] == msg.sender, "AllocatorRoles/ilk-not-authorized");
+ _;
+ }
+
+ // --- constructor ---
+
+ constructor() {
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ // --- getters ---
+
+ function hasUserRole(bytes32 ilk, address who, uint8 role) external view returns (bool has) {
+ has = userRoles[ilk][who] & bytes32(uint256(1) << role) != bytes32(0);
+ }
+
+ function hasActionRole(bytes32 ilk, address target, bytes4 sig, uint8 role) external view returns (bool has) {
+ has = actionsRoles[ilk][target][sig] & bytes32(uint256(1) << role) != bytes32(0);
+ }
+
+ // --- general administration ---
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function setIlkAdmin(bytes32 ilk, address usr) external auth {
+ ilkAdmins[ilk] = usr;
+ emit SetIlkAdmin(ilk, usr);
+ }
+
+ // --- ilk administration ---
+
+ function setUserRole(bytes32 ilk, address who, uint8 role, bool enabled) public ilkAuth(ilk) {
+ bytes32 mask = bytes32(uint256(1) << role);
+ if (enabled) {
+ userRoles[ilk][who] |= mask;
+ } else {
+ userRoles[ilk][who] &= ~mask;
+ }
+ emit SetUserRole(ilk, who, role, enabled);
+ }
+
+ function setRoleAction(bytes32 ilk, uint8 role, address target, bytes4 sig, bool enabled) external ilkAuth(ilk) {
+ bytes32 mask = bytes32(uint256(1) << role);
+ if (enabled) {
+ actionsRoles[ilk][target][sig] |= mask;
+ } else {
+ actionsRoles[ilk][target][sig] &= ~mask;
+ }
+ emit SetRoleAction(ilk, role, target, sig, enabled);
+ }
+
+ // --- caller ---
+
+ function canCall(bytes32 ilk, address caller, address target, bytes4 sig) external view returns (bool ok) {
+ ok = userRoles[ilk][caller] & actionsRoles[ilk][target][sig] != bytes32(0);
+ }
+}
diff --git a/src/AllocatorVault.sol b/src/AllocatorVault.sol
new file mode 100644
index 00000000..163c6d0e
--- /dev/null
+++ b/src/AllocatorVault.sol
@@ -0,0 +1,148 @@
+// SPDX-FileCopyrightText: © 2020 Lev Livnev
+// SPDX-FileCopyrightText: © 2021 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface RolesLike {
+ function canCall(bytes32, address, address, bytes4) external view returns (bool);
+}
+
+interface VatLike {
+ function frob(bytes32, address, address, address, int256, int256) external;
+ function hope(address) external;
+}
+
+interface JugLike {
+ function drip(bytes32) external returns (uint256);
+}
+
+interface GemLike {
+ function approve(address, uint256) external;
+ function transferFrom(address, address, uint256) external;
+}
+
+interface UsdsJoinLike {
+ function usds() external view returns (GemLike);
+ function vat() external view returns (VatLike);
+ function exit(address, uint256) external;
+ function join(address, uint256) external;
+}
+
+contract AllocatorVault {
+ // --- storage variables ---
+
+ mapping(address => uint256) public wards;
+ JugLike public jug;
+
+ // --- constants ---
+
+ uint256 constant WAD = 10**18;
+ uint256 constant RAY = 10**27;
+
+ // --- immutables ---
+
+ RolesLike immutable public roles;
+ address immutable public buffer;
+ VatLike immutable public vat;
+ bytes32 immutable public ilk;
+ UsdsJoinLike immutable public usdsJoin;
+ GemLike immutable public usds;
+
+ // --- events ---
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event File(bytes32 indexed what, address data);
+ event Draw(address indexed sender, uint256 wad);
+ event Wipe(address indexed sender, uint256 wad);
+
+ // --- modifiers ---
+
+ modifier auth() {
+ require(roles.canCall(ilk, msg.sender, address(this), msg.sig) ||
+ wards[msg.sender] == 1, "AllocatorVault/not-authorized");
+ _;
+ }
+
+ // --- constructor ---
+
+ constructor(address roles_, address buffer_, bytes32 ilk_, address usdsJoin_) {
+ roles = RolesLike(roles_);
+
+ buffer = buffer_;
+ ilk = ilk_;
+ usdsJoin = UsdsJoinLike(usdsJoin_);
+
+ vat = usdsJoin.vat();
+ usds = usdsJoin.usds();
+
+ vat.hope(usdsJoin_);
+ usds.approve(usdsJoin_, type(uint256).max);
+
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ // --- math ---
+
+ function _divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
+ // Note: _divup(0,0) will return 0 differing from natural solidity division
+ unchecked {
+ z = x != 0 ? ((x - 1) / y) + 1 : 0;
+ }
+ }
+
+ // --- administration ---
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function file(bytes32 what, address data) external auth {
+ if (what == "jug") {
+ jug = JugLike(data);
+ } else revert("AllocatorVault/file-unrecognized-param");
+ emit File(what, data);
+ }
+
+ // --- funnels execution ---
+
+ function draw(uint256 wad) external auth {
+ uint256 rate = jug.drip(ilk);
+ uint256 dart = _divup(wad * RAY, rate);
+ require(dart <= uint256(type(int256).max), "AllocatorVault/overflow");
+ vat.frob(ilk, address(this), address(0), address(this), 0, int256(dart));
+ usdsJoin.exit(buffer, wad);
+ emit Draw(msg.sender, wad);
+ }
+
+ function wipe(uint256 wad) external auth {
+ usds.transferFrom(buffer, address(this), wad);
+ usdsJoin.join(address(this), wad);
+ uint256 rate = jug.drip(ilk);
+ uint256 dart = wad * RAY / rate;
+ require(dart <= uint256(type(int256).max), "AllocatorVault/overflow");
+ vat.frob(ilk, address(this), address(0), address(this), 0, -int256(dart));
+ emit Wipe(msg.sender, wad);
+ }
+}
diff --git a/src/IAllocatorConduit.sol b/src/IAllocatorConduit.sol
new file mode 100644
index 00000000..a5256f95
--- /dev/null
+++ b/src/IAllocatorConduit.sol
@@ -0,0 +1,75 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity >=0.8.0;
+
+/**
+ * @title IAllocatorConduit
+ * @dev Conduits are to be used to manage investment positions for multiple Allocators.
+ */
+interface IAllocatorConduit {
+ /**
+ * @dev Event emitted when a deposit is made to the Conduit.
+ * @param ilk The unique identifier of the ilk.
+ * @param asset The address of the asset deposited.
+ * @param origin The address where the asset is coming from.
+ * @param amount The amount of asset deposited.
+ */
+ event Deposit(bytes32 indexed ilk, address indexed asset, address origin, uint256 amount);
+
+ /**
+ * @dev Event emitted when a withdrawal is made from the Conduit.
+ * @param ilk The unique identifier of the ilk.
+ * @param asset The address of the asset withdrawn.
+ * @param destination The address where the asset is sent.
+ * @param amount The amount of asset withdrawn.
+ */
+ event Withdraw(bytes32 indexed ilk, address indexed asset, address destination, uint256 amount);
+
+ /**
+ * @dev Function for depositing tokens into a Fund Manager.
+ * @param ilk The unique identifier of the ilk.
+ * @param asset The asset to deposit.
+ * @param amount The amount of tokens to deposit.
+ */
+ function deposit(bytes32 ilk, address asset, uint256 amount) external;
+
+ /**
+ * @dev Function for withdrawing tokens from a Fund Manager.
+ * @param ilk The unique identifier of the ilk.
+ * @param asset The asset to withdraw.
+ * @param maxAmount The max amount of tokens to withdraw. Setting to "type(uint256).max" will ensure to withdraw all available liquidity.
+ * @return amount The amount of tokens withdrawn.
+ */
+ function withdraw(bytes32 ilk, address asset, uint256 maxAmount) external returns (uint256 amount);
+
+ /**
+ * @dev Function to get the maximum deposit possible for a specific asset and ilk.
+ * @param ilk The unique identifier of the ilk.
+ * @param asset The asset to check.
+ * @return maxDeposit_ The maximum possible deposit for the asset.
+ */
+ function maxDeposit(bytes32 ilk, address asset) external view returns (uint256 maxDeposit_);
+
+ /**
+ * @dev Function to get the maximum withdrawal possible for a specific asset and ilk.
+ * @param ilk The unique identifier of the ilk.
+ * @param asset The asset to check.
+ * @return maxWithdraw_ The maximum possible withdrawal for the asset.
+ */
+ function maxWithdraw(bytes32 ilk, address asset) external view returns (uint256 maxWithdraw_);
+
+}
diff --git a/src/funnels/DepositorUniV3.sol b/src/funnels/DepositorUniV3.sol
new file mode 100644
index 00000000..3217e58f
--- /dev/null
+++ b/src/funnels/DepositorUniV3.sol
@@ -0,0 +1,329 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+import {LiquidityAmounts} from "src/funnels/uniV3/LiquidityAmounts.sol";
+import {TickMath} from "src/funnels/uniV3/TickMath.sol";
+
+interface RolesLike {
+ function canCall(bytes32, address, address, bytes4) external view returns (bool);
+}
+
+interface GemLike {
+ function transferFrom(address, address, uint256) external;
+}
+
+// https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/UniswapV3Pool.sol
+interface UniV3PoolLike {
+ function positions(bytes32) external view returns (
+ uint128 liquidity,
+ uint256 feeGrowthInside0LastX128,
+ uint256 feeGrowthInside1LastX128,
+ uint128 tokensOwed0,
+ uint128 tokensOwed1
+ );
+
+ function slot0() external view returns (
+ uint160 sqrtPriceX96,
+ int24 tick,
+ uint16 observationIndex,
+ uint16 observationCardinality,
+ uint16 observationCardinalityNext,
+ uint8 feeProtocol,
+ bool unlocked
+ );
+
+ function mint(
+ address recipient,
+ int24 tickLower,
+ int24 tickUpper,
+ uint128 amount,
+ bytes calldata data
+ ) external returns (uint256 amount0, uint256 amount1);
+
+ function burn(
+ int24 tickLower,
+ int24 tickUpper,
+ uint128 amount
+ ) external returns (uint256 amount0, uint256 amount1);
+
+ function collect(
+ address recipient,
+ int24 tickLower,
+ int24 tickUpper,
+ uint128 amount0Requested,
+ uint128 amount1Requested
+ ) external returns (uint128 amount0, uint128 amount1);
+}
+
+contract DepositorUniV3 {
+ mapping (address => uint256) public wards; // Admins
+ mapping (address => mapping (address => mapping (uint24 => PairLimit))) public limits; // Rate limit parameters per (gem0, gem1, fee) pool
+
+ RolesLike public immutable roles; // Contract managing access control for this DepositorUniV3
+ bytes32 public immutable ilk; // Collateral type
+ address public immutable uniV3Factory; // Uniswap V3 factory
+ address public immutable buffer; // Contract from/to which the two tokens that make up the liquidity position are pulled/pushed
+
+ struct PairLimit {
+ uint96 cap0; // Maximum amount of gem0 that can be added or removed as liquidity each era for a (gem0, gem1, fee) pool
+ uint96 cap1; // Maximum amount of gem1 that can be added or removed as liquidity each era for a (gem0, gem1, fee) pool
+ uint32 era; // Cooldown period it has to wait for renewing the due amounts to each cap for a (gem0, gem1, fee) pool
+ uint96 due0; // Pending amount of gem0 that can still be added or removed until next era for a (gem0, gem1, fee) pool
+ uint96 due1; // Pending amount of gem1 that can still be added or removed until next era for a (gem0, gem1, fee) pool
+ uint32 end; // Timestamp of when the current batch ends for a (gem0, gem1, fee) pool
+ }
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event SetLimits(address indexed gem0, address indexed gem1, uint24 indexed fee, uint96 cap0, uint96 cap1, uint32 era);
+ event Deposit(address indexed sender, address indexed gem0, address indexed gem1, uint24 fee, uint128 liquidity, uint256 amt0, uint256 amt1);
+ event Withdraw(address indexed sender, address indexed gem0, address indexed gem1, uint24 fee, uint128 liquidity, uint256 amt0, uint256 amt1, uint256 fees0, uint256 fees1);
+ event Collect(address indexed sender, address indexed gem0, address indexed gem1, uint24 fee, uint256 fees0, uint256 fees1);
+
+ constructor(address roles_, bytes32 ilk_, address uniV3Factory_, address buffer_) {
+ roles = RolesLike(roles_);
+ ilk = ilk_;
+ uniV3Factory = uniV3Factory_;
+ buffer = buffer_;
+
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ modifier auth() {
+ require(roles.canCall(ilk, msg.sender, address(this), msg.sig) || wards[msg.sender] == 1, "DepositorUniV3/not-authorized");
+ _;
+ }
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function setLimits(address gem0, address gem1, uint24 fee, uint96 cap0, uint96 cap1, uint32 era) external auth {
+ require(gem0 < gem1, "DepositorUniV3/wrong-gem-order");
+ limits[gem0][gem1][fee] = PairLimit({
+ cap0: cap0,
+ cap1: cap1,
+ era: era,
+ due0: 0,
+ due1: 0,
+ end: 0
+ });
+ emit SetLimits(gem0, gem1, fee, cap0, cap1, era);
+ }
+
+ // https://github.com/Uniswap/v3-periphery/blob/464a8a49611272f7349c970e0fadb7ec1d3c1086/contracts/libraries/PoolAddress.sol#L33
+ function _getPool(address gem0, address gem1, uint24 fee) internal view returns (UniV3PoolLike pool) {
+ pool = UniV3PoolLike(address(uint160(uint256(keccak256(abi.encodePacked(
+ hex'ff',
+ uniV3Factory,
+ keccak256(abi.encode(gem0, gem1, fee)),
+ bytes32(0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54) // POOL_INIT_CODE_HASH
+ ))))));
+ }
+
+ function getPosition(
+ address gem0,
+ address gem1,
+ uint24 fee,
+ int24 tickLower,
+ int24 tickUpper
+ ) external view returns (
+ uint128 liquidity,
+ uint256 feeGrowthInside0LastX128,
+ uint256 feeGrowthInside1LastX128,
+ uint128 tokensOwed0,
+ uint128 tokensOwed1
+ ) {
+ return _getPool(gem0, gem1, fee).
+ positions(keccak256(abi.encodePacked(address(this), tickLower, tickUpper)));
+ }
+
+ function _getLiquidityForAmts(
+ UniV3PoolLike pool,
+ int24 tickLower,
+ int24 tickUpper,
+ uint256 amt0Desired,
+ uint256 amt1Desired
+ ) internal view returns (uint128 liquidity) {
+ (uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
+ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
+ uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
+
+ liquidity = LiquidityAmounts.getLiquidityForAmounts(
+ sqrtPriceX96,
+ sqrtRatioAX96,
+ sqrtRatioBX96,
+ amt0Desired,
+ amt1Desired
+ );
+ }
+
+ struct MintCallbackData {
+ address gem0;
+ address gem1;
+ uint24 fee;
+ }
+
+ // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/interfaces/callback/IUniswapV3MintCallback.sol#L6
+ function uniswapV3MintCallback(
+ uint256 amt0Owed,
+ uint256 amt1Owed,
+ bytes calldata data
+ ) external {
+ MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
+ address pool = address(_getPool(decoded.gem0, decoded.gem1, decoded.fee));
+ require(msg.sender == pool, "DepositorUniV3/sender-not-a-pool");
+
+ if (amt0Owed > 0) GemLike(decoded.gem0).transferFrom(buffer, msg.sender, amt0Owed);
+ if (amt1Owed > 0) GemLike(decoded.gem1).transferFrom(buffer, msg.sender, amt1Owed);
+ }
+
+ struct LiquidityParams {
+ address gem0;
+ address gem1;
+ uint24 fee;
+ int24 tickLower;
+ int24 tickUpper;
+ uint128 liquidity; // Useful for clearing out the entire liquidity of a position
+ uint256 amt0Desired; // Relevant only if liquidity == 0
+ uint256 amt1Desired; // Relevant only if liquidity == 0
+ uint256 amt0Min;
+ uint256 amt1Min;
+ }
+
+ function deposit(LiquidityParams memory p)
+ external
+ auth
+ returns (uint128 liquidity, uint256 amt0, uint256 amt1)
+ {
+ require(p.gem0 < p.gem1, "DepositorUniV3/wrong-gem-order");
+
+ PairLimit memory limit;
+ limit.due0 = limits[p.gem0][p.gem1][p.fee].due0;
+ limit.due1 = limits[p.gem0][p.gem1][p.fee].due1;
+ limit.end = limits[p.gem0][p.gem1][p.fee].end;
+
+ if (block.timestamp >= limit.end) {
+ // Reset batch
+ limit.due0 = limits[p.gem0][p.gem1][p.fee].cap0;
+ limit.due1 = limits[p.gem0][p.gem1][p.fee].cap1;
+ limit.end = uint32(block.timestamp) + limits[p.gem0][p.gem1][p.fee].era;
+ }
+
+ UniV3PoolLike pool = _getPool(p.gem0, p.gem1, p.fee);
+ liquidity = (p.liquidity == 0)
+ ? _getLiquidityForAmts(pool, p.tickLower, p.tickUpper, p.amt0Desired, p.amt1Desired)
+ : p.liquidity;
+
+ (amt0, amt1) = pool.mint({
+ recipient: address(this),
+ tickLower: p.tickLower,
+ tickUpper: p.tickUpper,
+ amount : liquidity,
+ data : abi.encode(MintCallbackData({gem0: p.gem0, gem1: p.gem1, fee: p.fee}))
+ });
+ require(amt0 >= p.amt0Min && amt1 >= p.amt1Min, "DepositorUniV3/exceeds-slippage");
+ require(amt0 <= limit.due0 && amt1 <= limit.due1, "DepositorUniV3/exceeds-due-amt");
+
+ limits[p.gem0][p.gem1][p.fee].due0 = limit.due0 - uint96(amt0);
+ limits[p.gem0][p.gem1][p.fee].due1 = limit.due1 - uint96(amt1);
+ limits[p.gem0][p.gem1][p.fee].end = limit.end;
+
+ emit Deposit(msg.sender, p.gem0, p.gem1, p.fee, liquidity, amt0, amt1);
+ }
+
+ function withdraw(LiquidityParams memory p, bool takeFees)
+ external
+ auth
+ returns (uint128 liquidity, uint256 amt0, uint256 amt1, uint256 fees0, uint256 fees1)
+ {
+ require(p.gem0 < p.gem1, "DepositorUniV3/wrong-gem-order");
+
+ PairLimit memory limit;
+ limit.due0 = limits[p.gem0][p.gem1][p.fee].due0;
+ limit.due1 = limits[p.gem0][p.gem1][p.fee].due1;
+ limit.end = limits[p.gem0][p.gem1][p.fee].end;
+
+ if (block.timestamp >= limit.end) {
+ // Reset batch
+ limit.due0 = limits[p.gem0][p.gem1][p.fee].cap0;
+ limit.due1 = limits[p.gem0][p.gem1][p.fee].cap1;
+ limit.end = uint32(block.timestamp) + limits[p.gem0][p.gem1][p.fee].era;
+ }
+
+ UniV3PoolLike pool = _getPool(p.gem0, p.gem1, p.fee);
+ liquidity = (p.liquidity == 0)
+ ? _getLiquidityForAmts(pool, p.tickLower, p.tickUpper, p.amt0Desired, p.amt1Desired)
+ : p.liquidity;
+
+ (amt0, amt1) = pool.burn({ tickLower: p.tickLower, tickUpper: p.tickUpper, amount: liquidity });
+ require(amt0 >= p.amt0Min && amt1 >= p.amt1Min, "DepositorUniV3/exceeds-slippage");
+ require(amt0 <= limit.due0 && amt1 <= limit.due1, "DepositorUniV3/exceeds-due-amt");
+
+ limits[p.gem0][p.gem1][p.fee].due0 = limit.due0 - uint96(amt0);
+ limits[p.gem0][p.gem1][p.fee].due1 = limit.due1 - uint96(amt1);
+ limits[p.gem0][p.gem1][p.fee].end = limit.end;
+
+ (uint256 collected0, uint256 collected1) = pool.collect({
+ recipient : buffer,
+ tickLower : p.tickLower,
+ tickUpper : p.tickUpper,
+ amount0Requested: takeFees ? type(uint128).max : uint128(amt0),
+ amount1Requested: takeFees ? type(uint128).max : uint128(amt1)
+ });
+ (fees0, fees1) = (collected0 - amt0, collected1 - amt1);
+
+ emit Withdraw(msg.sender, p.gem0, p.gem1, p.fee, liquidity, amt0, amt1, fees0, fees1);
+ }
+
+ struct CollectParams {
+ address gem0;
+ address gem1;
+ uint24 fee;
+ int24 tickLower;
+ int24 tickUpper;
+ }
+
+ function collect(CollectParams memory p)
+ external
+ auth
+ returns (uint256 fees0, uint256 fees1)
+ {
+ require(p.gem0 < p.gem1, "DepositorUniV3/wrong-gem-order");
+
+ UniV3PoolLike pool = _getPool(p.gem0, p.gem1, p.fee);
+ pool.burn({ tickLower: p.tickLower, tickUpper: p.tickUpper, amount: 0 }); // Update the position's owed fees
+
+ (fees0, fees1) = pool.collect({
+ recipient : buffer,
+ tickLower : p.tickLower,
+ tickUpper : p.tickUpper,
+ amount0Requested: type(uint128).max,
+ amount1Requested: type(uint128).max
+ });
+
+ emit Collect(msg.sender, p.gem0, p.gem1, p.fee, fees0, fees1);
+ }
+}
diff --git a/src/funnels/Swapper.sol b/src/funnels/Swapper.sol
new file mode 100644
index 00000000..7de12fcb
--- /dev/null
+++ b/src/funnels/Swapper.sol
@@ -0,0 +1,113 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface RolesLike {
+ function canCall(bytes32, address, address, bytes4) external view returns (bool);
+}
+
+interface GemLike {
+ function balanceOf(address) external view returns (uint256);
+ function transfer(address, uint256) external;
+ function transferFrom(address, address, uint256) external;
+}
+
+interface CalleeLike {
+ function swapCallback(address, address, uint256, uint256, address, bytes calldata) external;
+}
+
+contract Swapper {
+ mapping (address => uint256) public wards; // Admins
+ mapping (address => mapping (address => PairLimit)) public limits; // Rate limit parameters per src->dst pair
+
+ RolesLike public immutable roles; // Contract managing access control for this Swapper
+ bytes32 public immutable ilk; // Collateral type
+ address public immutable buffer; // Contract from which the GEM to sell is pulled and to which the bought GEM is pushed
+
+ struct PairLimit {
+ uint96 cap; // Maximum amount of src token that can be swapped each era for a src->dst pair
+ uint32 era; // Cooldown period it has to wait for renewing the due amount to cap for src to dst swap
+ uint96 due; // Pending amount of src token that can still be swapped until next era
+ uint32 end; // Timestamp of when the current batch ends
+ }
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event SetLimits(address indexed src, address indexed dst, uint96 cap, uint32 era);
+ event Swap(address indexed sender, address indexed src, address indexed dst, uint256 amt, uint256 out);
+
+ constructor(address roles_, bytes32 ilk_, address buffer_) {
+ roles = RolesLike(roles_);
+ ilk = ilk_;
+ buffer = buffer_;
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ modifier auth() {
+ require(roles.canCall(ilk, msg.sender, address(this), msg.sig) || wards[msg.sender] == 1, "Swapper/not-authorized");
+ _;
+ }
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function setLimits(address src, address dst, uint96 cap, uint32 era) external auth {
+ limits[src][dst] = PairLimit({
+ cap: cap,
+ era: era,
+ due: 0,
+ end: 0
+ });
+ emit SetLimits(src, dst, cap, era);
+ }
+
+ function swap(address src, address dst, uint256 amt, uint256 minOut, address callee, bytes calldata data) external auth returns (uint256 out) {
+ PairLimit memory limit = limits[src][dst];
+
+ if (block.timestamp >= limit.end) {
+ // Reset batch
+ limit.due = limit.cap;
+ limit.end = uint32(block.timestamp) + limit.era;
+ }
+
+ require(amt <= limit.due, "Swapper/exceeds-due-amt");
+
+ unchecked {
+ limits[src][dst].due = limit.due - uint96(amt);
+ limits[src][dst].end = limit.end;
+ }
+
+ GemLike(src).transferFrom(buffer, callee, amt);
+
+ // Avoid swapping directly to buffer to prevent piggybacking another operation to satisfy the balance check
+ CalleeLike(callee).swapCallback(src, dst, amt, minOut, address(this), data);
+
+ out = GemLike(dst).balanceOf(address(this));
+ require(out >= minOut, "Swapper/too-few-dst-received");
+
+ GemLike(dst).transfer(buffer, out);
+ emit Swap(msg.sender, src, dst, amt, out);
+ }
+}
diff --git a/src/funnels/automation/ConduitMover.sol b/src/funnels/automation/ConduitMover.sol
new file mode 100644
index 00000000..610bfd4d
--- /dev/null
+++ b/src/funnels/automation/ConduitMover.sol
@@ -0,0 +1,111 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface ConduitLike {
+ function deposit(bytes32, address, uint256) external;
+ function withdraw(bytes32, address, uint256) external returns (uint256);
+}
+
+contract ConduitMover {
+ mapping (address => uint256) public wards; // Admins
+ mapping (address => uint256) public buds; // Whitelisted keepers
+ mapping (address => mapping (address => mapping (address => MoveConfig))) public configs; // Configuration for keepers
+
+ bytes32 public immutable ilk; // Collateral type
+ address public immutable buffer; // The address of the buffer contract
+
+ struct MoveConfig {
+ uint64 num; // The remaining number of times that a `from` to `to` gem move can be performed by keepers
+ uint32 hop; // Cooldown period it has to wait between `from` to `to` gem moves
+ uint32 zzz; // Timestamp of the last `from` to `to` gem move
+ uint128 lot; // The amount to move every hop for a `from` to `to` gem move
+ }
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event Kiss(address indexed usr);
+ event Diss(address indexed usr);
+ event SetConfig(address indexed from, address indexed to, address indexed gem, uint64 num, uint32 hop, uint128 lot);
+ event Move(address indexed from, address indexed to, address indexed gem, uint128 lot);
+
+ constructor(bytes32 ilk_, address buffer_) {
+ buffer = buffer_;
+ ilk = ilk_;
+
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ modifier auth {
+ require(wards[msg.sender] == 1, "ConduitMover/not-authorized");
+ _;
+ }
+
+ modifier toll {
+ require(buds[msg.sender] == 1, "ConduitMover/non-keeper");
+ _;
+ }
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function kiss(address usr) external auth {
+ buds[usr] = 1;
+ emit Kiss(usr);
+ }
+
+ function diss(address usr) external auth {
+ buds[usr] = 0;
+ emit Diss(usr);
+ }
+
+ function setConfig(address from, address to, address gem, uint64 num, uint32 hop, uint128 lot) external auth {
+ configs[from][to][gem] = MoveConfig({
+ num: num,
+ hop: hop,
+ zzz: 0,
+ lot: lot
+ });
+ emit SetConfig(from, to, gem, num, hop, lot);
+ }
+
+ function move(address from, address to, address gem) toll external {
+ MoveConfig memory cfg = configs[from][to][gem];
+
+ require(cfg.num > 0, "ConduitMover/exceeds-num");
+ require(block.timestamp >= cfg.zzz + cfg.hop, "ConduitMover/too-soon");
+ unchecked { configs[from][to][gem].num = cfg.num - 1; }
+ configs[from][to][gem].zzz = uint32(block.timestamp);
+
+ if (from != buffer) {
+ require(ConduitLike(from).withdraw(ilk, gem, cfg.lot) == cfg.lot, "ConduitMover/lot-withdraw-failed");
+ }
+ if (to != buffer) {
+ ConduitLike(to).deposit(ilk, gem, cfg.lot);
+ }
+
+ emit Move(from, to, gem, cfg.lot);
+ }
+}
diff --git a/src/funnels/automation/StableDepositorUniV3.sol b/src/funnels/automation/StableDepositorUniV3.sol
new file mode 100644
index 00000000..1b569c7c
--- /dev/null
+++ b/src/funnels/automation/StableDepositorUniV3.sol
@@ -0,0 +1,218 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface DepositorUniV3Like {
+ struct LiquidityParams {
+ address gem0;
+ address gem1;
+ uint24 fee;
+ int24 tickLower;
+ int24 tickUpper;
+ uint128 liquidity;
+ uint256 amt0Desired; // Relevant only if liquidity == 0
+ uint256 amt1Desired; // Relevant only if liquidity == 0
+ uint256 amt0Min;
+ uint256 amt1Min;
+ }
+
+ function deposit(LiquidityParams memory params) external returns (
+ uint128 liquidity,
+ uint256 amt0,
+ uint256 amt1
+ );
+
+ function withdraw(LiquidityParams memory p, bool takeFee) external returns (
+ uint128 liquidity,
+ uint256 amt0,
+ uint256 amt1,
+ uint256 fees0,
+ uint256 fees1
+ );
+
+ struct CollectParams {
+ address gem0;
+ address gem1;
+ uint24 fee;
+ int24 tickLower;
+ int24 tickUpper;
+ }
+
+ function collect(CollectParams memory p) external returns (
+ uint256 fees0,
+ uint256 fees1
+ );
+}
+
+contract StableDepositorUniV3 {
+ mapping (address => uint256) public wards; // Admins
+ mapping (address => uint256) public buds; // Whitelisted keepers
+ mapping (address => mapping (address => mapping (uint24 => mapping (int24 => mapping (int24 => PairConfig))))) public configs; // Configuration for keepers
+
+ DepositorUniV3Like public immutable depositor; // DepositorUniV3 for this StableDepositorUniV3
+
+ struct PairConfig {
+ int32 num; // The remaining number of times that a (gem0, gem1) operation can be performed by keepers (> 0: deposit, < 0: withdraw)
+ uint32 zzz; // Timestamp of the last deposit/withdraw execution
+ uint96 amt0; // Amount of gem0 to deposit/withdraw each (gem0, gem1) operation
+ uint96 amt1; // Amount of gem1 to deposit/withdraw each (gem0, gem1) operation
+ uint96 req0; // The minimum required deposit/withdraw amount of gem0 to insist on in each (gem0, gem1) operation
+ uint96 req1; // The minimum required deposit/withdraw amount of gem1 to insist on in each (gem0, gem1) operation
+ uint32 hop; // Cooldown period it has to wait between deposit/withdraw executions
+ }
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event Kiss(address indexed usr);
+ event Diss(address indexed usr);
+ event SetConfig(address indexed gem0, address indexed gem1, uint24 indexed fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1);
+
+ constructor(address _depositor) {
+ depositor = DepositorUniV3Like(_depositor);
+
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ modifier auth {
+ require(wards[msg.sender] == 1, "StableDepositorUniV3/not-authorized");
+ _;
+ }
+
+ // Permissionned to whitelisted keepers
+ modifier toll {
+ require(buds[msg.sender] == 1, "StableDepositorUniV3/non-keeper");
+ _;
+ }
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function kiss(address usr) external auth {
+ buds[usr] = 1;
+ emit Kiss(usr);
+ }
+
+ function diss(address usr) external auth {
+ buds[usr] = 0;
+ emit Diss(usr);
+ }
+
+ function setConfig(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1) external auth {
+ require(gem0 < gem1, "StableDepositorUniV3/wrong-gem-order");
+ configs[gem0][gem1][fee][tickLower][tickUpper] = PairConfig({
+ num: num,
+ zzz: 0,
+ amt0: amt0,
+ amt1: amt1,
+ req0: req0,
+ req1: req1,
+ hop: hop
+ });
+ emit SetConfig(gem0, gem1, fee, tickLower, tickUpper, num, hop, amt0, amt1, req0, req1);
+ }
+
+ // Note: the keeper's minAmts value must be updated whenever configs[gem0][gem1][fee][tickLower][tickUpper] is changed.
+ // Failing to do so may result in this call reverting or in taking on more slippage than intended (up to a limit controlled by configs[gem0][gem1][fee][tickLower][tickUpper].req0/1).
+ function deposit(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min)
+ toll
+ external
+ returns (uint128 liquidity, uint256 amt0, uint256 amt1)
+ {
+ PairConfig memory cfg = configs[gem0][gem1][fee][tickLower][tickUpper];
+
+ require(cfg.num > 0, "StableDepositorUniV3/exceeds-num");
+ require(block.timestamp >= cfg.zzz + cfg.hop, "StableDepositorUniV3/too-soon");
+ unchecked { configs[gem0][gem1][fee][tickLower][tickUpper].num = cfg.num - 1; }
+ configs[gem0][gem1][fee][tickLower][tickUpper].zzz = uint32(block.timestamp);
+
+ if (amt0Min == 0) amt0Min = cfg.req0;
+ if (amt1Min == 0) amt1Min = cfg.req1;
+ require(amt0Min >= cfg.req0, "StableDepositorUniV3/min-amt0-too-small");
+ require(amt1Min >= cfg.req1, "StableDepositorUniV3/min-amt1-too-small");
+
+ DepositorUniV3Like.LiquidityParams memory p = DepositorUniV3Like.LiquidityParams({
+ gem0 : gem0,
+ gem1 : gem1,
+ fee : fee,
+ tickLower : tickLower,
+ tickUpper : tickUpper,
+ liquidity : 0, // Use desired amounts
+ amt0Desired: cfg.amt0,
+ amt1Desired: cfg.amt1,
+ amt0Min : amt0Min,
+ amt1Min : amt1Min
+ });
+ (liquidity, amt0, amt1) = depositor.deposit(p);
+ }
+
+ // Note: the keeper's minAmts value must be updated whenever configs[gem0][gem1][fee][tickLower][tickUpper] is changed.
+ // Failing to do so may result in this call reverting or in taking on more slippage than intended (up to a limit controlled by configs[gem0][gem1][fee][tickLower][tickUpper].req0/1).
+ function withdraw(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min)
+ toll
+ external
+ returns (uint128 liquidity, uint256 amt0, uint256 amt1, uint256 fees0, uint256 fees1)
+ {
+ PairConfig memory cfg = configs[gem0][gem1][fee][tickLower][tickUpper];
+
+ require(cfg.num < 0, "StableDepositorUniV3/exceeds-num");
+ require(block.timestamp >= cfg.zzz + cfg.hop, "StableDepositorUniV3/too-soon");
+ unchecked { configs[gem0][gem1][fee][tickLower][tickUpper].num = cfg.num + 1; }
+ configs[gem0][gem1][fee][tickLower][tickUpper].zzz = uint32(block.timestamp);
+
+ if (amt0Min == 0) amt0Min = cfg.req0;
+ if (amt1Min == 0) amt1Min = cfg.req1;
+ require(amt0Min >= cfg.req0, "StableDepositorUniV3/min-amt0-too-small");
+ require(amt1Min >= cfg.req1, "StableDepositorUniV3/min-amt1-too-small");
+
+ DepositorUniV3Like.LiquidityParams memory p = DepositorUniV3Like.LiquidityParams({
+ gem0 : gem0,
+ gem1 : gem1,
+ fee : fee,
+ tickLower : tickLower,
+ tickUpper : tickUpper,
+ liquidity : 0, // Use desired amounts
+ amt0Desired: cfg.amt0,
+ amt1Desired: cfg.amt1,
+ amt0Min : amt0Min,
+ amt1Min : amt1Min
+ });
+ (liquidity, amt0, amt1, fees0, fees1) = depositor.withdraw(p, true);
+ }
+
+ function collect(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper)
+ toll
+ external
+ returns (uint256 fees0, uint256 fees1)
+ {
+ DepositorUniV3Like.CollectParams memory collectParams = DepositorUniV3Like.CollectParams({
+ gem0 : gem0,
+ gem1 : gem1,
+ fee : fee,
+ tickLower: tickLower,
+ tickUpper: tickUpper
+ });
+ (fees0, fees1) = depositor.collect(collectParams);
+ }
+}
diff --git a/src/funnels/automation/StableSwapper.sol b/src/funnels/automation/StableSwapper.sol
new file mode 100644
index 00000000..d1a35194
--- /dev/null
+++ b/src/funnels/automation/StableSwapper.sol
@@ -0,0 +1,107 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface SwapperLike {
+ function swap(address, address, uint256, uint256, address, bytes calldata) external returns (uint256);
+}
+
+contract StableSwapper {
+ mapping (address => uint256) public wards; // Admins
+ mapping (address => uint256) public buds; // Whitelisted keepers
+ mapping (address => mapping (address => PairConfig)) public configs; // Configuration for keepers
+
+ SwapperLike public immutable swapper; // Swapper for this StableSwapper
+
+ struct PairConfig {
+ uint128 num; // The remaining number of times that a src to dst swap can be performed by keepers
+ uint32 hop; // Cooldown period it has to wait between swap executions
+ uint32 zzz; // Timestamp of the last swap execution
+ uint96 lot; // The amount swapped by keepers from src to dst every hop
+ uint96 req; // The minimum required output amount to insist on in the swap from src to dst
+ }
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event Kiss(address indexed usr);
+ event Diss(address indexed usr);
+ event SetConfig(address indexed src, address indexed dst, uint128 num, uint32 hop, uint96 lot, uint96 req);
+
+ constructor(address swapper_) {
+ swapper = SwapperLike(swapper_);
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ modifier auth {
+ require(wards[msg.sender] == 1, "StableSwapper/not-authorized");
+ _;
+ }
+
+ // permissioned to whitelisted keepers
+ modifier toll {
+ require(buds[msg.sender] == 1, "StableSwapper/non-keeper");
+ _;
+ }
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function kiss(address usr) external auth {
+ buds[usr] = 1;
+ emit Kiss(usr);
+ }
+
+ function diss(address usr) external auth {
+ buds[usr] = 0;
+ emit Diss(usr);
+ }
+
+ function setConfig(address src, address dst, uint128 num, uint32 hop, uint96 lot, uint96 req) external auth {
+ configs[src][dst] = PairConfig({
+ num: num,
+ hop: hop,
+ zzz: 0,
+ lot: lot,
+ req: req
+ });
+ emit SetConfig(src, dst, num, hop, lot, req);
+ }
+
+ // Note: the keeper's minOut value must be updated whenever configs[src][dst] is changed.
+ // Failing to do so may result in this call reverting or in taking on more slippage than intended (up to a limit controlled by configs[src][dst].min).
+ function swap(address src, address dst, uint256 minOut, address callee, bytes calldata data) toll external returns (uint256 out) {
+ PairConfig memory cfg = configs[src][dst];
+
+ require(cfg.num > 0, "StableSwapper/exceeds-num");
+ require(block.timestamp >= cfg.zzz + cfg.hop, "StableSwapper/too-soon");
+ unchecked { configs[src][dst].num = cfg.num - 1; }
+ configs[src][dst].zzz = uint32(block.timestamp);
+
+ if (minOut == 0) minOut = cfg.req;
+ require(minOut >= cfg.req, "StableSwapper/min-too-small");
+
+ out = swapper.swap(src, dst, cfg.lot, minOut, callee, data);
+ }
+}
diff --git a/src/funnels/automation/VaultMinter.sol b/src/funnels/automation/VaultMinter.sol
new file mode 100644
index 00000000..0746a926
--- /dev/null
+++ b/src/funnels/automation/VaultMinter.sol
@@ -0,0 +1,118 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface AllocatorVaultLike {
+ function draw(uint256) external;
+ function wipe(uint256) external;
+}
+
+contract VaultMinter {
+ mapping (address => uint256) public wards; // Admins
+ mapping (address => uint256) public buds; // Whitelisted keepers
+ MinterConfig public config; // Configuration for keepers
+
+ address public immutable vault; // The address of the vault contract
+
+ struct MinterConfig {
+ int64 num; // The remaining number of times that a draw or wipe can be executed by keepers (> 0: draw, < 0: wipe)
+ uint32 hop; // Cooldown period it has to wait between each action
+ uint32 zzz; // Timestamp of the last action
+ uint128 lot; // The amount to draw or wipe every hop
+ }
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event Kiss(address indexed usr);
+ event Diss(address indexed usr);
+ event SetConfig(int64 num, uint32 hop, uint128 lot);
+ event Draw(uint128 lot);
+ event Wipe(uint128 lot);
+
+ constructor(address vault_) {
+ vault = vault_;
+
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ modifier auth {
+ require(wards[msg.sender] == 1, "VaultMinter/not-authorized");
+ _;
+ }
+
+ modifier toll {
+ require(buds[msg.sender] == 1, "VaultMinter/non-keeper");
+ _;
+ }
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function kiss(address usr) external auth {
+ buds[usr] = 1;
+ emit Kiss(usr);
+ }
+
+ function diss(address usr) external auth {
+ buds[usr] = 0;
+ emit Diss(usr);
+ }
+
+ function setConfig(int64 num, uint32 hop, uint128 lot) external auth {
+ config = MinterConfig({
+ num: num,
+ hop: hop,
+ zzz: 0,
+ lot: lot
+ });
+ emit SetConfig(num, hop, lot);
+ }
+
+ function draw() toll external {
+ MinterConfig memory cfg = config;
+
+ require(cfg.num > 0, "VaultMinter/exceeds-num");
+ require(block.timestamp >= cfg.zzz + cfg.hop, "VaultMinter/too-soon");
+ unchecked { config.num = cfg.num - 1; }
+ config.zzz = uint32(block.timestamp);
+
+ AllocatorVaultLike(vault).draw(cfg.lot);
+
+ emit Draw(cfg.lot);
+ }
+
+ function wipe() toll external {
+ MinterConfig memory cfg = config;
+
+ require(cfg.num < 0, "VaultMinter/exceeds-num");
+ require(block.timestamp >= cfg.zzz + cfg.hop, "VaultMinter/too-soon");
+ unchecked { config.num = cfg.num + 1; }
+ config.zzz = uint32(block.timestamp);
+
+ AllocatorVaultLike(vault).wipe(cfg.lot);
+
+ emit Wipe(cfg.lot);
+ }
+}
diff --git a/src/funnels/callees/SwapperCalleePsm.sol b/src/funnels/callees/SwapperCalleePsm.sol
new file mode 100644
index 00000000..cadec1e9
--- /dev/null
+++ b/src/funnels/callees/SwapperCalleePsm.sol
@@ -0,0 +1,73 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface GemLike {
+ function approve(address, uint256) external;
+ function decimals() external view returns (uint8);
+}
+
+interface PsmLike {
+ function sellGemNoFee(address, uint256) external returns (uint256);
+ function buyGemNoFee(address, uint256) external returns (uint256);
+ function dai() external returns (address);
+ function gem() external returns (address);
+}
+
+contract SwapperCalleePsm {
+ mapping (address => uint256) public wards;
+
+ address public immutable psm;
+ address public immutable gem;
+ uint256 public immutable to18ConversionFactor;
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+
+ constructor(address _psm) {
+ psm = _psm;
+ gem = PsmLike(psm).gem();
+ GemLike(PsmLike(psm).dai()).approve(address(psm), type(uint256).max);
+ GemLike(gem).approve(address(psm), type(uint256).max);
+ to18ConversionFactor = 10 ** (18 - GemLike(gem).decimals());
+
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ modifier auth() {
+ require(wards[msg.sender] == 1, "SwapperCalleePsm/not-authorized");
+ _;
+ }
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ // Note: To avoid accumulating dust in this contract, `amt` should be a multiple of `to18ConversionFactor` when `src != gem`.
+ // This constraint is intentionally not enforced in this contract.
+ function swapCallback(address src, address /* dst */, uint256 amt, uint256 /* minOut */, address to, bytes calldata /* data */) external auth {
+ if (src == gem) PsmLike(psm).sellGemNoFee(to, amt);
+ else PsmLike(psm).buyGemNoFee (to, amt / to18ConversionFactor);
+ }
+}
diff --git a/src/funnels/callees/SwapperCalleeUniV3.sol b/src/funnels/callees/SwapperCalleeUniV3.sol
new file mode 100644
index 00000000..ed0cc333
--- /dev/null
+++ b/src/funnels/callees/SwapperCalleeUniV3.sol
@@ -0,0 +1,64 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+interface GemLike {
+ function approve(address, uint256) external;
+}
+
+// https://github.com/Uniswap/v3-periphery/blob/b06959dd01f5999aa93e1dc530fe573c7bb295f6/contracts/SwapRouter.sol
+interface SwapRouterLike {
+ function exactInput(ExactInputParams calldata params) external returns (uint256 amountOut);
+
+ // https://github.com/Uniswap/v3-periphery/blob/b06959dd01f5999aa93e1dc530fe573c7bb295f6/contracts/interfaces/ISwapRouter.sol#L26
+ // https://docs.uniswap.org/protocol/guides/swaps/multihop-swaps#input-parameters
+ struct ExactInputParams {
+ bytes path;
+ address recipient;
+ uint256 deadline;
+ uint256 amountIn;
+ uint256 amountOutMinimum;
+ }
+}
+
+contract SwapperCalleeUniV3 {
+ address public immutable uniV3Router;
+
+ constructor(address _uniV3Router) {
+ uniV3Router = _uniV3Router;
+ }
+
+ function swapCallback(address src, address /* dst */, uint256 amt, uint256 minOut, address to, bytes calldata data) external {
+ bytes memory path = data;
+
+ address src_;
+ assembly {
+ src_ := shr(0x60, mload(add(path, 0x20)))
+ }
+ require(src == src_, "SwapperCalleeUniV3/invalid-path"); // forbids lingering approval of src
+
+ GemLike(src).approve(uniV3Router, amt);
+ SwapRouterLike.ExactInputParams memory params = SwapRouterLike.ExactInputParams({
+ path: path,
+ recipient: to,
+ deadline: block.timestamp,
+ amountIn: amt,
+ amountOutMinimum: minOut
+ });
+ SwapRouterLike(uniV3Router).exactInput(params);
+ }
+}
diff --git a/src/funnels/uniV3/FullMath.sol b/src/funnels/uniV3/FullMath.sol
new file mode 100644
index 00000000..b73761f5
--- /dev/null
+++ b/src/funnels/uniV3/FullMath.sol
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: GPL-3.0
+
+// Based on https://github.com/gelatodigital/g-uni-v1-core/blob/bea63422e2155242b051896b635508b7a99d2a1a/contracts/vendor/uniswap/FullMath.sol
+// Uniswap version - https://github.com/Uniswap/v3-core/blob/412d9b236a1e75a98568d49b1aeb21e3a1430544/contracts/libraries/FullMath.sol
+
+pragma solidity ^0.8.16;
+
+/// @title Contains 512-bit math functions
+/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
+/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
+library FullMath {
+ /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
+ /// @param a The multiplicand
+ /// @param b The multiplier
+ /// @param denominator The divisor
+ /// @return result The 256-bit result
+ /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
+ function mulDiv(
+ uint256 a,
+ uint256 b,
+ uint256 denominator
+ ) internal pure returns (uint256 result) {
+ unchecked {
+ // 512-bit multiply [prod1 prod0] = a * b
+ // Compute the product mod 2**256 and mod 2**256 - 1
+ // then use the Chinese Remainder Theorem to reconstruct
+ // the 512 bit result. The result is stored in two 256
+ // variables such that product = prod1 * 2**256 + prod0
+ uint256 prod0; // Least significant 256 bits of the product
+ uint256 prod1; // Most significant 256 bits of the product
+ assembly {
+ let mm := mulmod(a, b, not(0))
+ prod0 := mul(a, b)
+ prod1 := sub(sub(mm, prod0), lt(mm, prod0))
+ }
+
+ // Handle non-overflow cases, 256 by 256 division
+ if (prod1 == 0) {
+ require(denominator > 0);
+ assembly {
+ result := div(prod0, denominator)
+ }
+ return result;
+ }
+
+ // Make sure the result is less than 2**256.
+ // Also prevents denominator == 0
+ require(denominator > prod1);
+
+ ///////////////////////////////////////////////
+ // 512 by 256 division.
+ ///////////////////////////////////////////////
+
+ // Make division exact by subtracting the remainder from [prod1 prod0]
+ // Compute remainder using mulmod
+ uint256 remainder;
+ assembly {
+ remainder := mulmod(a, b, denominator)
+ }
+ // Subtract 256 bit number from 512 bit number
+ assembly {
+ prod1 := sub(prod1, gt(remainder, prod0))
+ prod0 := sub(prod0, remainder)
+ }
+
+ // Factor powers of two out of denominator
+ // Compute largest power of two divisor of denominator.
+ // Always >= 1.
+ // EDIT for 0.8 compatibility:
+ // see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256
+ uint256 twos = denominator & (~denominator + 1);
+
+ // Divide denominator by power of two
+ assembly {
+ denominator := div(denominator, twos)
+ }
+
+ // Divide [prod1 prod0] by the factors of two
+ assembly {
+ prod0 := div(prod0, twos)
+ }
+ // Shift in bits from prod1 into prod0. For this we need
+ // to flip `twos` such that it is 2**256 / twos.
+ // If twos is zero, then it becomes one
+ assembly {
+ twos := add(div(sub(0, twos), twos), 1)
+ }
+ prod0 |= prod1 * twos;
+
+ // Invert denominator mod 2**256
+ // Now that denominator is an odd number, it has an inverse
+ // modulo 2**256 such that denominator * inv = 1 mod 2**256.
+ // Compute the inverse by starting with a seed that is correct
+ // correct for four bits. That is, denominator * inv = 1 mod 2**4
+ uint256 inv = (3 * denominator) ^ 2;
+ // Now use Newton-Raphson iteration to improve the precision.
+ // Thanks to Hensel's lifting lemma, this also works in modular
+ // arithmetic, doubling the correct bits in each step.
+ inv *= 2 - denominator * inv; // inverse mod 2**8
+ inv *= 2 - denominator * inv; // inverse mod 2**16
+ inv *= 2 - denominator * inv; // inverse mod 2**32
+ inv *= 2 - denominator * inv; // inverse mod 2**64
+ inv *= 2 - denominator * inv; // inverse mod 2**128
+ inv *= 2 - denominator * inv; // inverse mod 2**256
+
+ // Because the division is now exact we can divide by multiplying
+ // with the modular inverse of denominator. This will give us the
+ // correct result modulo 2**256. Since the precoditions guarantee
+ // that the outcome is less than 2**256, this is the final result.
+ // We don't need to compute the high bits of the result and prod1
+ // is no longer required.
+ result = prod0 * inv;
+ return result;
+ }
+ }
+
+ /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
+ /// @param a The multiplicand
+ /// @param b The multiplier
+ /// @param denominator The divisor
+ /// @return result The 256-bit result
+ function mulDivRoundingUp(
+ uint256 a,
+ uint256 b,
+ uint256 denominator
+ ) internal pure returns (uint256 result) {
+ result = mulDiv(a, b, denominator);
+ if (mulmod(a, b, denominator) > 0) {
+ require(result < type(uint256).max);
+ result++;
+ }
+ }
+}
diff --git a/src/funnels/uniV3/LiquidityAmounts.sol b/src/funnels/uniV3/LiquidityAmounts.sol
new file mode 100644
index 00000000..a6aeaeb2
--- /dev/null
+++ b/src/funnels/uniV3/LiquidityAmounts.sol
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+// Based on https://github.com/Uniswap/v3-periphery/blob/6cce88e63e176af1ddb6cc56e029110289622317/contracts/libraries/LiquidityAmounts.sol
+
+pragma solidity >=0.5.0;
+
+import "./FullMath.sol";
+
+/// @title FixedPoint96
+/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
+/// @dev Used in SqrtPriceMath.sol
+library FixedPoint96 {
+ uint8 internal constant RESOLUTION = 96;
+ uint256 internal constant Q96 = 0x1000000000000000000000000;
+}
+
+/// @title Liquidity amount functions
+/// @notice Provides functions for computing liquidity amounts from token amounts and prices
+library LiquidityAmounts {
+ /// @notice Downcasts uint256 to uint128
+ /// @param x The uint258 to be downcasted
+ /// @return y The passed value, downcasted to uint128
+ function toUint128(uint256 x) private pure returns (uint128 y) {
+ require((y = uint128(x)) == x);
+ }
+
+ /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
+ /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
+ /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
+ /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
+ /// @param amount0 The amount0 being sent in
+ /// @return liquidity The amount of returned liquidity
+ function getLiquidityForAmount0(
+ uint160 sqrtRatioAX96,
+ uint160 sqrtRatioBX96,
+ uint256 amount0
+ ) internal pure returns (uint128 liquidity) {
+ if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
+ uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
+ return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
+ }
+
+ /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
+ /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
+ /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
+ /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
+ /// @param amount1 The amount1 being sent in
+ /// @return liquidity The amount of returned liquidity
+ function getLiquidityForAmount1(
+ uint160 sqrtRatioAX96,
+ uint160 sqrtRatioBX96,
+ uint256 amount1
+ ) internal pure returns (uint128 liquidity) {
+ if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
+ return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
+ }
+
+ /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
+ /// pool prices and the prices at the tick boundaries
+ /// @param sqrtRatioX96 A sqrt price representing the current pool prices
+ /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
+ /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
+ /// @param amount0 The amount of token0 being sent in
+ /// @param amount1 The amount of token1 being sent in
+ /// @return liquidity The maximum amount of liquidity received
+ function getLiquidityForAmounts(
+ uint160 sqrtRatioX96,
+ uint160 sqrtRatioAX96,
+ uint160 sqrtRatioBX96,
+ uint256 amount0,
+ uint256 amount1
+ ) internal pure returns (uint128 liquidity) {
+ if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
+
+ if (sqrtRatioX96 <= sqrtRatioAX96) {
+ liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
+ } else if (sqrtRatioX96 < sqrtRatioBX96) {
+ uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
+ uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
+
+ liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
+ } else {
+ liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
+ }
+ }
+}
diff --git a/src/funnels/uniV3/TickMath.sol b/src/funnels/uniV3/TickMath.sol
new file mode 100644
index 00000000..4949fc14
--- /dev/null
+++ b/src/funnels/uniV3/TickMath.sol
@@ -0,0 +1,262 @@
+// SPDX-License-Identifier: GPL-3.0
+
+// Based on https://github.com/gelatodigital/g-uni-v1-core/blob/bea63422e2155242b051896b635508b7a99d2a1a/contracts/vendor/uniswap/TickMath.sol
+// Uniswap version - https://github.com/Uniswap/v3-core/blob/412d9b236a1e75a98568d49b1aeb21e3a1430544/contracts/libraries/TickMath.sol
+
+pragma solidity ^0.8.16;
+
+/// @title Math library for computing sqrt prices from ticks and vice versa
+/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
+/// prices between 2**-128 and 2**128
+library TickMath {
+ /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
+ int24 internal constant MIN_TICK = -887272;
+ /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
+ int24 internal constant MAX_TICK = -MIN_TICK;
+
+ /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
+ uint160 internal constant MIN_SQRT_RATIO = 4295128739;
+ /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
+ uint160 internal constant MAX_SQRT_RATIO =
+ 1461446703485210103287273052203988822378723970342;
+
+ /// @notice Calculates sqrt(1.0001^tick) * 2^96
+ /// @dev Throws if |tick| > max tick
+ /// @param tick The input tick for the above formula
+ /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
+ /// at the given tick
+ function getSqrtRatioAtTick(int24 tick)
+ internal
+ pure
+ returns (uint160 sqrtPriceX96)
+ {
+ unchecked {
+ uint256 absTick =
+ tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
+
+ // EDIT: 0.8 compatibility
+ require(absTick <= uint256(int256(MAX_TICK)), "T");
+
+ uint256 ratio =
+ absTick & 0x1 != 0
+ ? 0xfffcb933bd6fad37aa2d162d1a594001
+ : 0x100000000000000000000000000000000;
+ if (absTick & 0x2 != 0)
+ ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
+ if (absTick & 0x4 != 0)
+ ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
+ if (absTick & 0x8 != 0)
+ ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
+ if (absTick & 0x10 != 0)
+ ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
+ if (absTick & 0x20 != 0)
+ ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
+ if (absTick & 0x40 != 0)
+ ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
+ if (absTick & 0x80 != 0)
+ ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
+ if (absTick & 0x100 != 0)
+ ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
+ if (absTick & 0x200 != 0)
+ ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
+ if (absTick & 0x400 != 0)
+ ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
+ if (absTick & 0x800 != 0)
+ ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
+ if (absTick & 0x1000 != 0)
+ ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
+ if (absTick & 0x2000 != 0)
+ ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
+ if (absTick & 0x4000 != 0)
+ ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
+ if (absTick & 0x8000 != 0)
+ ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
+ if (absTick & 0x10000 != 0)
+ ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
+ if (absTick & 0x20000 != 0)
+ ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
+ if (absTick & 0x40000 != 0)
+ ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
+ if (absTick & 0x80000 != 0)
+ ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
+
+ if (tick > 0) ratio = type(uint256).max / ratio;
+
+ // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
+ // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
+ // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
+ sqrtPriceX96 = uint160(
+ (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)
+ );
+ }
+ }
+
+ /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
+ /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
+ /// ever return.
+ /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
+ /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
+ function getTickAtSqrtRatio(uint160 sqrtPriceX96)
+ internal
+ pure
+ returns (int24 tick)
+ {
+ unchecked {
+ // second inequality must be < because the price can never reach the price at the max tick
+ require(
+ sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,
+ "R"
+ );
+ uint256 ratio = uint256(sqrtPriceX96) << 32;
+
+ uint256 r = ratio;
+ uint256 msb = 0;
+
+ assembly {
+ let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
+ msb := or(msb, f)
+ r := shr(f, r)
+ }
+ assembly {
+ let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
+ msb := or(msb, f)
+ r := shr(f, r)
+ }
+ assembly {
+ let f := shl(5, gt(r, 0xFFFFFFFF))
+ msb := or(msb, f)
+ r := shr(f, r)
+ }
+ assembly {
+ let f := shl(4, gt(r, 0xFFFF))
+ msb := or(msb, f)
+ r := shr(f, r)
+ }
+ assembly {
+ let f := shl(3, gt(r, 0xFF))
+ msb := or(msb, f)
+ r := shr(f, r)
+ }
+ assembly {
+ let f := shl(2, gt(r, 0xF))
+ msb := or(msb, f)
+ r := shr(f, r)
+ }
+ assembly {
+ let f := shl(1, gt(r, 0x3))
+ msb := or(msb, f)
+ r := shr(f, r)
+ }
+ assembly {
+ let f := gt(r, 0x1)
+ msb := or(msb, f)
+ }
+
+ if (msb >= 128) r = ratio >> (msb - 127);
+ else r = ratio << (127 - msb);
+
+ int256 log_2 = (int256(msb) - 128) << 64;
+
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(63, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(62, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(61, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(60, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(59, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(58, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(57, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(56, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(55, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(54, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(53, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(52, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(51, f))
+ r := shr(f, r)
+ }
+ assembly {
+ r := shr(127, mul(r, r))
+ let f := shr(128, r)
+ log_2 := or(log_2, shl(50, f))
+ }
+
+ int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
+
+ int24 tickLow =
+ int24(
+ (log_sqrt10001 - 3402992956809132418596140100660247210) >> 128
+ );
+ int24 tickHi =
+ int24(
+ (log_sqrt10001 + 291339464771989622907027621153398088495) >> 128
+ );
+
+ tick = tickLow == tickHi
+ ? tickLow
+ : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96
+ ? tickHi
+ : tickLow;
+ }
+ }
+}
diff --git a/test/AllocatorBuffer.t.sol b/test/AllocatorBuffer.t.sol
new file mode 100644
index 00000000..0c367e89
--- /dev/null
+++ b/test/AllocatorBuffer.t.sol
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+import { GemMock } from "test/mocks/GemMock.sol";
+
+contract AllocatorBufferTest is DssTest {
+ using stdStorage for StdStorage;
+
+ GemMock public gem;
+ AllocatorBuffer public buffer;
+
+ event Approve(address indexed asset, address indexed spender, uint256 amount);
+
+ function setUp() public {
+ gem = new GemMock(1_000_000 * 10**18);
+ buffer = new AllocatorBuffer();
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ AllocatorBuffer b = new AllocatorBuffer();
+ assertEq(b.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(buffer), "AllocatorBuffer");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](1);
+ authedMethods[0] = buffer.approve.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(buffer), "AllocatorBuffer/not-authorized", authedMethods);
+ vm.stopPrank();
+ }
+
+ function testTransferApproveWithdraw() public {
+ assertEq(gem.balanceOf(address(this)), gem.totalSupply());
+ assertEq(gem.balanceOf(address(buffer)), 0);
+ gem.transfer(address(buffer), 10);
+ assertEq(gem.balanceOf(address(this)), gem.totalSupply() - 10);
+ assertEq(gem.balanceOf(address(buffer)), 10);
+ assertEq(gem.allowance(address(buffer), address(this)), 0);
+ vm.expectEmit(true, true, true, true);
+ emit Approve(address(gem), address(this), 4);
+ buffer.approve(address(gem), address(this), 4);
+ assertEq(gem.allowance(address(buffer), address(this)), 4);
+ gem.transferFrom(address(buffer), address(123), 4);
+ assertEq(gem.balanceOf(address(buffer)), 6);
+ assertEq(gem.balanceOf(address(123)), 4);
+ }
+}
diff --git a/test/AllocatorOracle.t.sol b/test/AllocatorOracle.t.sol
new file mode 100644
index 00000000..50116a9a
--- /dev/null
+++ b/test/AllocatorOracle.t.sol
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import "src/AllocatorOracle.sol";
+
+contract AllocatorOracleTest is DssTest {
+ AllocatorOracle public oracle;
+
+ function setUp() public {
+ oracle = new AllocatorOracle();
+ }
+
+ function testOracle() public {
+ (bytes32 val, bool ok) = oracle.peek();
+ assertEq(val, bytes32(uint256(10**18)));
+ assertTrue(ok);
+ assertEq(oracle.read(), bytes32(uint256(10**18)));
+ }
+
+ function testPricing() public {
+ uint256 par = 1 * 10**27;
+ uint256 price = uint256(oracle.read()); // 1 * 10**18;
+ uint256 colSupply = 1 * 10**12 * 10**18;
+ uint256 colDebt = 1 * 10**6 * 10**45; // Imagine a scenario where the ilk only has 1M debt
+ uint256 totDebt = 50 * 10**9 * 10**45; // Imagine a scenario where the tot Supply of DAI is 50B
+
+ console.log("cage(ilk):");
+ console.log("");
+ uint256 tag = par * 10**18 / price;
+ console.log("tag[ilk] =", tag);
+ console.log("");
+ console.log("skim(ilk, buffer):");
+ console.log("");
+ uint256 owe = (colDebt / 10**27) * tag / 10**27;
+ console.log("owe =", owe);
+ uint256 wad = owe <= colSupply ? owe : colSupply;
+ console.log("wad =", wad);
+ uint256 gap = owe - wad;
+ console.log("gap[ilk] =", gap);
+ console.log("");
+ console.log("flow(ilk):");
+ console.log("");
+ wad = (colDebt / 10**27) * tag / 10**27;
+ console.log("wad =", wad);
+ uint256 fix = (wad - gap) * 10**27 / (totDebt / 10**27);
+ console.log("fix[ilk] =", fix);
+ console.log("");
+ console.log("cash(ilk,...):");
+ console.log("");
+ console.log("1 = wad * fix / 10^27 => wad = 10^27 / fix");
+ uint256 amtDaiNeeded = 10**27 / fix;
+ console.log("Amount of wei DAI needed to get 1 wei of gem =", amtDaiNeeded);
+ assertEq(amtDaiNeeded, 50_000);
+ }
+}
diff --git a/test/AllocatorRegistry.t.sol b/test/AllocatorRegistry.t.sol
new file mode 100644
index 00000000..1d03ed67
--- /dev/null
+++ b/test/AllocatorRegistry.t.sol
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { AllocatorRegistry } from "src/AllocatorRegistry.sol";
+
+contract AllocatorRegistryTest is DssTest {
+ AllocatorRegistry public registry;
+
+ event File(bytes32 indexed ilk, bytes32 indexed what, address data);
+
+ function setUp() public {
+ registry = new AllocatorRegistry();
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ AllocatorRegistry r = new AllocatorRegistry();
+ assertEq(r.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(registry), "AllocatorRegistry");
+ }
+
+ function testFileIlkAddress() public {
+ // First check an invalid value
+ vm.expectRevert("AllocatorRegistry/file-unrecognized-param");
+ registry.file("any", "an invalid value", address(123));
+
+ // Update value
+ vm.expectEmit(true, true, true, true);
+ emit File("any", "buffer", address(123));
+ registry.file("any", "buffer", address(123));
+ assertEq(registry.buffers("any"), address(123));
+
+ // Finally check that file is authed
+ registry.deny(address(this));
+ vm.expectRevert("AllocatorRegistry/not-authorized");
+ registry.file("any", "data", address(123));
+ }
+}
diff --git a/test/AllocatorRoles.t.sol b/test/AllocatorRoles.t.sol
new file mode 100644
index 00000000..34f862b1
--- /dev/null
+++ b/test/AllocatorRoles.t.sol
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import "src/AllocatorRoles.sol";
+import { AuthedMock } from "test/mocks/AuthedMock.sol";
+
+contract AllocatorRolesTest is DssTest {
+ AllocatorRoles roles;
+ AuthedMock authed;
+ bytes32 ilk;
+
+ event SetIlkAdmin(bytes32 indexed ilk, address user);
+ event SetUserRole(bytes32 indexed ilk, address indexed who, uint8 indexed role, bool enabled);
+ event SetRoleAction(bytes32 indexed ilk, uint8 indexed role, address indexed target, bytes4 sig, bool enabled);
+
+ function setUp() public {
+ ilk = "aaa";
+ roles = new AllocatorRoles();
+ authed = new AuthedMock(address(roles), ilk);
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ AllocatorRoles r = new AllocatorRoles();
+ assertEq(r.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(roles), "AllocatorRoles");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](1);
+ authedMethods[0] = roles.setIlkAdmin.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(roles), "AllocatorRoles/not-authorized", authedMethods);
+ vm.stopPrank();
+ }
+
+ function testBasics() public {
+ uint8 admin_role = 0;
+ uint8 mod_role = 1;
+ uint8 user_role = 2;
+ uint8 max_role = 255;
+
+ assertTrue(!roles.hasUserRole(ilk, address(this), admin_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), mod_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), user_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), max_role));
+ assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000000"), roles.userRoles(ilk, address(this)));
+
+ vm.expectRevert("AllocatorRoles/ilk-not-authorized");
+ roles.setUserRole(ilk, address(this), admin_role, true);
+
+ vm.expectEmit(true, true, true, true);
+ emit SetIlkAdmin(ilk, address(this));
+ roles.setIlkAdmin(ilk, address(this));
+ vm.expectEmit(true, true, true, true);
+ emit SetUserRole(ilk, address(this), admin_role, true);
+ roles.setUserRole(ilk, address(this), admin_role, true);
+
+ assertTrue( roles.hasUserRole(ilk, address(this), admin_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), mod_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), user_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), max_role));
+ assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000001"), roles.userRoles(ilk, address(this)));
+
+ assertTrue(!roles.canCall(ilk, address(this), address(authed), bytes4(keccak256("exec()"))));
+ vm.expectRevert("AuthedMock/not-authorized");
+ authed.exec();
+
+ assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), admin_role));
+ assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), mod_role));
+ assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), user_role));
+ assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), max_role));
+ vm.expectEmit(true, true, true, true);
+ emit SetRoleAction(ilk, admin_role, address(authed), bytes4(keccak256("exec()")), true);
+ roles.setRoleAction(ilk, admin_role, address(authed), bytes4(keccak256("exec()")), true);
+ assertTrue( roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), admin_role));
+ assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), mod_role));
+ assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), user_role));
+ assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), max_role));
+
+ assertTrue(roles.canCall(ilk, address(this), address(authed), bytes4(keccak256("exec()"))));
+ authed.exec();
+ assertTrue(authed.flag());
+
+ vm.expectEmit(true, true, true, true);
+ emit SetRoleAction(ilk, admin_role, address(authed), bytes4(keccak256("exec()")), false);
+ roles.setRoleAction(ilk, admin_role, address(authed), bytes4(keccak256("exec()")), false);
+ assertTrue(!roles.canCall(ilk, address(this), address(authed), bytes4(keccak256("exec()"))));
+ vm.expectRevert("AuthedMock/not-authorized");
+ authed.exec();
+
+ vm.expectEmit(true, true, true, true);
+ emit SetUserRole(ilk, address(this), mod_role, true);
+ roles.setUserRole(ilk, address(this), mod_role, true);
+
+ assertTrue( roles.hasUserRole(ilk, address(this), admin_role));
+ assertTrue( roles.hasUserRole(ilk, address(this), mod_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), user_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), max_role));
+ assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000003"), roles.userRoles(ilk, address(this)));
+
+ vm.expectEmit(true, true, true, true);
+ emit SetUserRole(ilk, address(this), user_role, true);
+ roles.setUserRole(ilk, address(this), user_role, true);
+
+ assertTrue( roles.hasUserRole(ilk, address(this), admin_role));
+ assertTrue( roles.hasUserRole(ilk, address(this), mod_role));
+ assertTrue( roles.hasUserRole(ilk, address(this), user_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), max_role));
+ assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000007"), roles.userRoles(ilk, address(this)));
+
+ vm.expectEmit(true, true, true, true);
+ emit SetUserRole(ilk, address(this), mod_role, false);
+ roles.setUserRole(ilk, address(this), mod_role, false);
+
+ assertTrue( roles.hasUserRole(ilk, address(this), admin_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), mod_role));
+ assertTrue( roles.hasUserRole(ilk, address(this), user_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), max_role));
+ assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000005"), roles.userRoles(ilk, address(this)));
+
+ vm.expectEmit(true, true, true, true);
+ emit SetUserRole(ilk, address(this), max_role, true);
+ roles.setUserRole(ilk, address(this), max_role, true);
+
+ assertTrue( roles.hasUserRole(ilk, address(this), admin_role));
+ assertTrue(!roles.hasUserRole(ilk, address(this), mod_role));
+ assertTrue( roles.hasUserRole(ilk, address(this), user_role));
+ assertTrue( roles.hasUserRole(ilk, address(this), max_role));
+ assertEq32(bytes32(hex"8000000000000000000000000000000000000000000000000000000000000005"), roles.userRoles(ilk, address(this)));
+
+ vm.expectEmit(true, true, true, true);
+ emit SetRoleAction(ilk, max_role, address(authed), bytes4(keccak256("exec()")), true);
+ roles.setRoleAction(ilk, max_role, address(authed), bytes4(keccak256("exec()")), true);
+ assertTrue(roles.canCall(ilk, address(this), address(authed), bytes4(keccak256("exec()"))));
+ authed.exec();
+ }
+}
diff --git a/test/AllocatorVault.t.sol b/test/AllocatorVault.t.sol
new file mode 100644
index 00000000..c693f5b6
--- /dev/null
+++ b/test/AllocatorVault.t.sol
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { AllocatorVault } from "src/AllocatorVault.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+import { RolesMock } from "test/mocks/RolesMock.sol";
+import { VatMock } from "test/mocks/VatMock.sol";
+import { JugMock } from "test/mocks/JugMock.sol";
+import { GemMock } from "test/mocks/GemMock.sol";
+import { UsdsJoinMock } from "test/mocks/UsdsJoinMock.sol";
+
+contract AllocatorVaultTest is DssTest {
+ using stdStorage for StdStorage;
+
+ VatMock public vat;
+ JugMock public jug;
+ GemMock public usds;
+ UsdsJoinMock public usdsJoin;
+ AllocatorBuffer public buffer;
+ RolesMock public roles;
+ AllocatorVault public vault;
+ bytes32 public ilk;
+
+ event Init();
+ event Draw(address indexed sender, uint256 wad);
+ event Wipe(address indexed sender, uint256 wad);
+
+ function _divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
+ // Note: _divup(0,0) will return 0 differing from natural solidity division
+ unchecked {
+ z = x != 0 ? ((x - 1) / y) + 1 : 0;
+ }
+ }
+
+ function setUp() public {
+ ilk = "TEST-ILK";
+ vat = new VatMock();
+ jug = new JugMock(vat);
+ usds = new GemMock(0);
+ usdsJoin = new UsdsJoinMock(vat, usds);
+ buffer = new AllocatorBuffer();
+ roles = new RolesMock();
+ vault = new AllocatorVault(address(roles), address(buffer), ilk, address(usdsJoin));
+ buffer.approve(address(usds), address(vault), type(uint256).max);
+
+ vat.slip(ilk, address(vault), int256(1_000_000 * WAD));
+ vat.grab(ilk, address(vault), address(vault), address(0), int256(1_000_000 * WAD), 0);
+
+ // Add some existing DAI assigned to usdsJoin to avoid a particular error
+ stdstore.target(address(vat)).sig("dai(address)").with_key(address(usdsJoin)).depth(0).checked_write(100_000 * RAD);
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ address join = address(new UsdsJoinMock(vat, usds));
+ AllocatorVault v = new AllocatorVault(address(0xBEEF), address(0xCCC), "SubDAO 1", join);
+ assertEq(address(v.roles()), address(0xBEEF));
+ assertEq(v.buffer(), address(0xCCC));
+ assertEq(v.ilk(), "SubDAO 1");
+ assertEq(address(v.usdsJoin()), join);
+ assertEq(v.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(vault), "AllocatorVault");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](2);
+ authedMethods[0] = vault.draw.selector;
+ authedMethods[1] = vault.wipe.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(vault), "AllocatorVault/not-authorized", authedMethods);
+ vm.stopPrank();
+ }
+
+ function testFile() public {
+ checkFileAddress(address(vault), "AllocatorVault", ["jug"]);
+ }
+
+ function testRoles() public {
+ vm.startPrank(address(0xBEEF));
+ vm.expectRevert("AllocatorVault/not-authorized");
+ vault.file("jug", address(0));
+ roles.setOk(true);
+ vault.file("jug", address(0));
+ }
+
+ function testDrawWipe() public {
+ vault.file("jug", address(jug));
+ (, uint256 art) = vat.urns(ilk, address(buffer));
+ assertEq(art, 0);
+ vm.expectEmit(true, true, true, true);
+ emit Draw(address(this), 50 * 10**18);
+ vault.draw(50 * 10**18);
+ (, art) = vat.urns(ilk, address(vault));
+ assertEq(art, 50 * 10**18);
+ assertEq(vat.rate(), 10**27);
+ assertEq(usds.balanceOf(address(buffer)), 50 * 10**18);
+ vm.warp(block.timestamp + 1);
+ vm.expectEmit(true, true, true, true);
+ emit Draw(address(this), 50 * 10**18);
+ vault.draw(50 * 10**18);
+ (, art) = vat.urns(ilk, address(vault));
+ uint256 expectedArt = 50 * 10**18 + _divup(50 * 10**18 * 1000, 1001);
+ assertEq(art, expectedArt);
+ assertEq(vat.rate(), 1001 * 10**27 / 1000);
+ assertEq(usds.balanceOf(address(buffer)), 100 * 10**18);
+ assertGt(art * vat.rate(), 100.05 * 10**45);
+ assertLt(art * vat.rate(), 100.06 * 10**45);
+ vm.expectRevert("Gem/insufficient-balance");
+ vault.wipe(100.06 * 10**18);
+ deal(address(usds), address(buffer), 100.06 * 10**18, true);
+ assertEq(usds.balanceOf(address(buffer)), 100.06 * 10**18);
+ vm.expectRevert();
+ vault.wipe(100.06 * 10**18); // It will try to wipe more art than existing, then reverts
+ vm.expectEmit(true, true, true, true);
+ emit Wipe(address(this), 100.05 * 10**18);
+ vault.wipe(100.05 * 10**18);
+ assertEq(usds.balanceOf(address(buffer)), 0.01 * 10**18);
+ (, art) = vat.urns(ilk, address(vault));
+ assertEq(art, 1); // Dust which is impossible to wipe
+ }
+}
diff --git a/test/funnels/DepositorUniV3.t.sol b/test/funnels/DepositorUniV3.t.sol
new file mode 100644
index 00000000..7d627b8c
--- /dev/null
+++ b/test/funnels/DepositorUniV3.t.sol
@@ -0,0 +1,759 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { DepositorUniV3 } from "src/funnels/DepositorUniV3.sol";
+import { SwapperCalleeUniV3 } from "src/funnels/callees/SwapperCalleeUniV3.sol";
+import { AllocatorRoles } from "src/AllocatorRoles.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+
+import { UniV3Utils } from "test/funnels/UniV3Utils.sol";
+
+interface GemLike {
+ function approve(address, uint256) external;
+ function balanceOf(address) external view returns (uint256);
+}
+
+interface SwapRouterLike {
+ function exactInput(ExactInputParams calldata params) external returns (uint256 amountOut);
+
+ struct ExactInputParams {
+ bytes path;
+ address recipient;
+ uint256 deadline;
+ uint256 amountIn;
+ uint256 amountOutMinimum;
+ }
+}
+
+contract DepositorUniV3Test is DssTest {
+ event SetLimits(address indexed gem0, address indexed gem1, uint24 indexed fee, uint96 cap0, uint96 cap1, uint32 era);
+ event Deposit(address indexed sender, address indexed gem0, address indexed gem1, uint24 fee, uint128 liquidity, uint256 amt0, uint256 amt1);
+ event Withdraw(address indexed sender, address indexed gem0, address indexed gem1, uint24 fee, uint128 liquidity, uint256 amt0, uint256 amt1, uint256 fees0, uint256 fees1);
+ event Collect(address indexed sender, address indexed gem0, address indexed gem1, uint24 fee, uint256 fees0, uint256 fees1);
+
+ AllocatorRoles public roles;
+ AllocatorBuffer public buffer;
+ DepositorUniV3 public depositor;
+
+ bytes32 constant ilk = "aaa";
+ bytes constant DAI_USDC_PATH = abi.encodePacked(DAI, uint24(100), USDC);
+
+ address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
+ address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
+ address constant DAI_USDC_POOL = 0x5777d92f208679DB4b9778590Fa3CAB3aC9e2168;
+ address constant UNIV3_ROUTER = UniV3Utils.UNIV3_ROUTER;
+ address constant UNIV3_FACTORY = UniV3Utils.UNIV3_FACTORY;
+
+ address constant FACILITATOR = address(0x1337);
+ uint8 constant DEPOSITOR_ROLE = uint8(2);
+
+ int24 REF_TICK;
+
+ function setUp() public {
+ vm.createSelectFork(vm.envString("ETH_RPC_URL"));
+
+ buffer = new AllocatorBuffer();
+ roles = new AllocatorRoles();
+ depositor = new DepositorUniV3(address(roles), ilk, UNIV3_FACTORY, address(buffer));
+
+ roles.setIlkAdmin(ilk, address(this));
+ roles.setRoleAction(ilk, DEPOSITOR_ROLE, address(depositor), depositor.deposit.selector, true);
+ roles.setRoleAction(ilk, DEPOSITOR_ROLE, address(depositor), depositor.withdraw.selector, true);
+ roles.setRoleAction(ilk, DEPOSITOR_ROLE, address(depositor), depositor.collect.selector, true);
+ roles.setUserRole(ilk, FACILITATOR, DEPOSITOR_ROLE, true);
+
+ depositor.setLimits(DAI, USDC, 100, uint96(10_000 * WAD), uint96(10_000 * 10**6), 3600 seconds);
+
+ deal(DAI, address(buffer), 1_000_000 * WAD, true);
+ deal(USDC, address(buffer), 1_000_000 * 10**6, true);
+ buffer.approve(USDC, address(depositor), type(uint256).max);
+ buffer.approve(DAI, address(depositor), type(uint256).max);
+
+ REF_TICK = UniV3Utils.getCurrentTick(DAI, USDC, uint24(100));
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ DepositorUniV3 d = new DepositorUniV3(address(0xBEEF), "SubDAO 1", address(0xAAA), address(0xCCC));
+ assertEq(address(d.roles()), address(0xBEEF));
+ assertEq(d.ilk(), "SubDAO 1");
+ assertEq(d.uniV3Factory(), address(0xAAA));
+ assertEq(d.buffer(), address(0xCCC));
+ assertEq(d.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(depositor), "DepositorUniV3");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](4);
+ authedMethods[0] = depositor.setLimits.selector;
+ authedMethods[1] = depositor.deposit.selector;
+ authedMethods[2] = depositor.withdraw.selector;
+ authedMethods[3] = depositor.collect.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(depositor), "DepositorUniV3/not-authorized", authedMethods);
+ vm.stopPrank();
+ }
+
+ function testSetLimits() public {
+ // deposit to make sure end and both due are set
+ DepositorUniV3.LiquidityParams memory dp = _getTestDepositParams(0, 500 * WAD, 500 * 10**6);
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+
+ (,,, uint96 due0Before, uint96 due1Before, uint32 endBefore) = depositor.limits(DAI, USDC, 100);
+ assertGt(due0Before, 0);
+ assertGt(due1Before, 0);
+ assertGt(endBefore, 0);
+
+ vm.warp(block.timestamp + 1 hours);
+
+ vm.expectEmit(true, true, true, true);
+ emit SetLimits(DAI, USDC, 100, 3, 4, 5);
+ vm.prank(address(this)); depositor.setLimits(DAI, USDC, 100, 3, 4, 5);
+ (uint96 cap0, uint96 cap1, uint32 era, uint96 due0, uint96 due1, uint32 end) = depositor.limits(DAI, USDC, 100);
+ assertEq(cap0, 3);
+ assertEq(cap1, 4);
+ assertEq(era, 5);
+ assertEq(due0, 0);
+ assertEq(due1, 0);
+ assertEq(end, 0);
+ }
+
+ function testRoles() public {
+ vm.expectRevert("DepositorUniV3/not-authorized");
+ vm.prank(address(0xBEEF)); depositor.setLimits(address(0), address(1), 0, 0, 0, 0);
+ roles.setRoleAction(ilk, uint8(0xF1), address(depositor), depositor.setLimits.selector, true);
+ roles.setUserRole(ilk, address(0xBEEF), uint8(0xF1), true);
+ vm.prank(address(0xBEEF)); depositor.setLimits(address(0), address(1), 0, 0, 0, 0);
+ }
+
+ // helps avoid stack too deep errors
+ function _getTestDepositParams(uint128 liquidity, uint256 amt0Desired, uint256 amt1Desired) internal view returns (DepositorUniV3.LiquidityParams memory dp) {
+ (uint256 expectedAmt0, uint256 expectedAmt1) = UniV3Utils.getExpectedAmounts(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, liquidity, amt0Desired, amt1Desired, false);
+ dp = DepositorUniV3.LiquidityParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: liquidity,
+ amt0Desired: amt0Desired,
+ amt1Desired: amt1Desired,
+ amt0Min: expectedAmt0,
+ amt1Min: expectedAmt1
+ });
+ }
+
+ function _getTestWithdrawParams(uint128 liquidity, uint256 amt0Desired, uint256 amt1Desired) internal view returns (DepositorUniV3.LiquidityParams memory dp) {
+ (uint256 expectedAmt0, uint256 expectedAmt1) = UniV3Utils.getExpectedAmounts(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, liquidity, amt0Desired, amt1Desired, true);
+ dp = DepositorUniV3.LiquidityParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: liquidity,
+ amt0Desired: amt0Desired,
+ amt1Desired: amt1Desired,
+ amt0Min: expectedAmt0,
+ amt1Min: expectedAmt1
+ });
+ }
+
+ function testDeposit() public {
+ assertEq(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), 0);
+ uint256 prevUSDC = GemLike(USDC).balanceOf(address(buffer));
+ uint256 prevDAI = GemLike(DAI).balanceOf(address(buffer));
+ uint32 initialTime = uint32(block.timestamp);
+
+ DepositorUniV3.LiquidityParams memory dp = _getTestDepositParams(0, 5_000 * WAD, 5_000 * 10**6);
+
+ uint256 snapshot = vm.snapshot();
+ (uint128 liq, uint256 amt0, uint256 amt1) = depositor.deposit(dp);
+ vm.revertTo(snapshot);
+
+ vm.expectEmit(true, true, true, true);
+ emit Deposit(FACILITATOR, DAI, USDC, uint24(100), liq, amt0, amt1);
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+
+ assertLt(GemLike(DAI).balanceOf(address(buffer)), prevDAI);
+ assertLt(GemLike(USDC).balanceOf(address(buffer)), prevUSDC);
+ assertEq(GemLike(DAI).balanceOf(address(depositor)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(depositor)), 0);
+ uint128 liquidityAfterDeposit = UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100);
+ assertGt(liquidityAfterDeposit, 0);
+ (,,, uint96 due0, uint96 due1, uint32 end) = depositor.limits(DAI, USDC, 100);
+ assertEq(end, initialTime + 3600);
+ assertEq(due0, 10_000 * WAD - amt0);
+ assertEq(due1, 10_000 * 10**6 - amt1);
+
+ prevUSDC = GemLike(USDC).balanceOf(address(buffer));
+ prevDAI = GemLike(DAI).balanceOf(address(buffer));
+
+ dp = _getTestDepositParams(0, 2_000 * WAD, 2_000 * 10**6);
+
+ vm.warp(initialTime + 1800);
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+
+ (,,, due0, due1, end) = depositor.limits(DAI, USDC, 100);
+ assertEq(end, initialTime + 3600);
+ assertLt(GemLike(DAI).balanceOf(address(buffer)), prevDAI);
+ assertLt(GemLike(USDC).balanceOf(address(buffer)), prevUSDC);
+ assertEq(GemLike(DAI).balanceOf(address(depositor)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(depositor)), 0);
+ assertGt(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), liquidityAfterDeposit);
+ assertLt(due0, 10_000 * WAD - amt0);
+ assertLt(due1, 10_000 * 10**6 - amt1);
+
+ dp = _getTestDepositParams(0, 8_000 * WAD, 8_000 * 10**6);
+
+ vm.expectRevert("DepositorUniV3/exceeds-due-amt");
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+
+ vm.warp(initialTime + 3600);
+ vm.prank(FACILITATOR); (, amt0, amt1) = depositor.deposit(dp);
+
+ (,,, due0, due1, end) = depositor.limits(DAI, USDC, 100);
+ assertEq(end, initialTime + 7200);
+ assertEq(due0, 10_000 * WAD - amt0);
+ assertEq(due1, 10_000 * 10**6 - amt1);
+ }
+
+ function testGetPosition() public {
+ // initially the position doesn't exist
+ (
+ uint128 liquidity,
+ uint256 feeGrowthInside0LastX128,
+ uint256 feeGrowthInside1LastX128,
+ uint128 tokensOwed0,
+ uint128 tokensOwed1
+ ) = depositor.getPosition(DAI, USDC, 100, REF_TICK-100, REF_TICK+100);
+ assertEq(liquidity, 0);
+ assertEq(feeGrowthInside0LastX128, 0);
+ assertEq(feeGrowthInside1LastX128, 0);
+ assertEq(tokensOwed0, 0);
+ assertEq(tokensOwed1, 0);
+
+ // deposit
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: 99777667447878834,
+ amt0Desired: 0,
+ amt1Desired: 0,
+ amt0Min: 0,
+ amt1Min: 0
+ });
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+
+ (
+ liquidity,
+ feeGrowthInside0LastX128,
+ feeGrowthInside1LastX128,
+ tokensOwed0,
+ tokensOwed1
+ ) = depositor.getPosition(DAI, USDC, 100, REF_TICK-100, REF_TICK+100);
+ assertEq(liquidity, 99777667447878834);
+ assertGe(feeGrowthInside0LastX128, 0); // initial value now that the position is created
+ assertGe(feeGrowthInside1LastX128, 0); // initial value now that the position is created
+ assertEq(tokensOwed0, 0);
+ assertEq(tokensOwed1, 0);
+
+ // execute a trade to generate fees for the LP position
+ deal(DAI, address(this), 1_000_000 * WAD, true);
+ GemLike(DAI).approve(UNIV3_ROUTER, 1_000_000 * WAD);
+ SwapRouterLike.ExactInputParams memory params = SwapRouterLike.ExactInputParams({
+ path: DAI_USDC_PATH,
+ recipient: address(this),
+ deadline: block.timestamp,
+ amountIn: 1_000_000 * WAD,
+ amountOutMinimum: 990_000 * 10**6
+ });
+ SwapRouterLike(UNIV3_ROUTER).exactInput(params);
+
+ // withdraw without collecting fees
+ vm.warp(block.timestamp + 3600);
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+
+ uint256 updatedfeeGrowthInside0LastX128;
+ uint256 updatedfeeGrowthInside1LastX128;
+ (
+ liquidity,
+ updatedfeeGrowthInside0LastX128,
+ updatedfeeGrowthInside1LastX128,
+ tokensOwed0,
+ tokensOwed1
+ ) = depositor.getPosition(DAI, USDC, 100, REF_TICK-100, REF_TICK+100);
+ assertEq(liquidity, 0);
+ assertTrue(updatedfeeGrowthInside0LastX128 > feeGrowthInside0LastX128 || updatedfeeGrowthInside1LastX128 > feeGrowthInside1LastX128);
+ assertTrue(tokensOwed0 > 0 || tokensOwed1 > 0);
+ }
+
+ function testCollect() public {
+
+ DepositorUniV3.LiquidityParams memory dp = _getTestDepositParams(0, 500 * WAD, 500 * 10**6);
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+ uint256 prevUSDC = GemLike(USDC).balanceOf(address(buffer));
+ uint256 prevDAI = GemLike(DAI).balanceOf(address(buffer));
+
+ // execute a trade to generate fees for the LP position
+ deal(DAI, address(this), 1_000_000 * WAD, true);
+ GemLike(DAI).approve(UNIV3_ROUTER, 1_000_000 * WAD);
+ SwapRouterLike.ExactInputParams memory params = SwapRouterLike.ExactInputParams({
+ path: DAI_USDC_PATH,
+ recipient: address(this),
+ deadline: block.timestamp,
+ amountIn: 1_000_000 * WAD,
+ amountOutMinimum: 990_000 * 10**6
+ });
+ SwapRouterLike(UNIV3_ROUTER).exactInput(params);
+
+ DepositorUniV3.CollectParams memory cp = DepositorUniV3.CollectParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100
+ });
+
+ uint256 snapshot = vm.snapshot();
+ (uint256 expectedFees0, uint256 expectedFees1) = depositor.collect(cp);
+ vm.revertTo(snapshot);
+
+ vm.expectEmit(true, true, true, true);
+ emit Collect(FACILITATOR, DAI, USDC, uint24(100), expectedFees0, expectedFees1);
+ vm.prank(FACILITATOR); (uint256 fees0, uint256 fees1) = depositor.collect(cp);
+
+ assertTrue(fees0 > 0 || fees1 > 0);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevDAI + fees0);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevUSDC + fees1);
+ assertEq(GemLike(DAI).balanceOf(address(depositor)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(depositor)), 0);
+ }
+
+ function testWithdrawWithNoFeeCollection() public {
+ uint256 initialUSDC = GemLike(USDC).balanceOf(address(buffer));
+ uint256 initialDAI = GemLike(DAI).balanceOf(address(buffer));
+ uint256 initialTime = uint32(block.timestamp);
+
+ DepositorUniV3.LiquidityParams memory dp = _getTestDepositParams(0, 500 * WAD, 500 * 10**6);
+ vm.prank(FACILITATOR); (uint128 liq, uint256 deposited0, uint256 deposited1) = depositor.deposit(dp);
+ assertGt(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), 0);
+
+ dp = _getTestWithdrawParams(liq, 0, 0);
+
+ uint256 snapshot = vm.snapshot();
+ (uint128 liquidity, uint256 withdrawn0, uint256 withdrawn1, uint256 fees0, uint256 fees1) = depositor.withdraw(dp, false);
+ vm.revertTo(snapshot);
+
+ vm.expectEmit(true, true, true, true);
+ emit Withdraw(FACILITATOR, DAI, USDC, uint24(100), liquidity, withdrawn0, withdrawn1, fees0, fees1);
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+
+ assertGe(withdrawn0 + 1, deposited0);
+ assertGe(withdrawn1 + 1, deposited1);
+ assertGe(GemLike(DAI).balanceOf(address(buffer)) + 1, initialDAI);
+ assertGe(GemLike(USDC).balanceOf(address(buffer)) + 1, initialUSDC);
+ assertEq(GemLike(DAI).balanceOf(address(depositor)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(depositor)), 0);
+ assertEq(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), 0);
+ assertEq(fees0, 0);
+ assertEq(fees1, 0);
+ assertEq(liquidity, liq);
+ (,,, uint96 due0, uint96 due1, uint32 end) = depositor.limits(DAI, USDC, 100);
+ assertEq(end, initialTime + 3600);
+ assertEq(due0, 10_000 * WAD - deposited0 - withdrawn0);
+ assertEq(due1, 10_000 * 10**6 - deposited1 - withdrawn1);
+
+ dp = _getTestDepositParams(0, 8_000 * WAD, 8_000 * 10**6);
+
+ vm.warp(initialTime + 1800);
+ vm.prank(FACILITATOR); (liq,,) = depositor.deposit(dp);
+
+ (,,, due0, due1, end) = depositor.limits(DAI, USDC, 100);
+ assertEq(end, initialTime + 3600);
+ assertLt(due0, 10_000 * WAD - deposited0 - withdrawn0);
+ assertLt(due1, 10_000 * 10**6 - deposited1 - withdrawn1);
+
+ dp = _getTestWithdrawParams(liq, 0, 0);
+
+ vm.expectRevert("DepositorUniV3/exceeds-due-amt");
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+
+ vm.warp(initialTime + 3600);
+ vm.prank(FACILITATOR); (, withdrawn0, withdrawn1,,) = depositor.withdraw(dp, false);
+
+ (,,, due0, due1, end) = depositor.limits(DAI, USDC, 100);
+ assertEq(end, initialTime + 7200);
+ assertEq(due0, 10_000 * WAD - withdrawn0);
+ assertEq(due1, 10_000 * 10**6 - withdrawn1);
+ }
+
+ function testWithdrawWithFeeCollection() public {
+ DepositorUniV3.LiquidityParams memory dp = _getTestDepositParams(0, 500 * WAD, 500 * 10**6);
+ vm.prank(FACILITATOR); (uint128 liq,,) = depositor.deposit(dp);
+ assertGt(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), 0);
+ uint256 prevUSDC = GemLike(USDC).balanceOf(address(buffer));
+ uint256 prevDAI = GemLike(DAI).balanceOf(address(buffer));
+
+ // execute a trade to generate fees for the LP position
+ deal(DAI, address(this), 1_000_000 * WAD, true);
+ GemLike(DAI).approve(UNIV3_ROUTER, 1_000_000 * WAD);
+ SwapRouterLike.ExactInputParams memory params = SwapRouterLike.ExactInputParams({
+ path: DAI_USDC_PATH,
+ recipient: address(this),
+ deadline: block.timestamp,
+ amountIn: 1_000_000 * WAD,
+ amountOutMinimum: 990_000 * 10**6
+ });
+ SwapRouterLike(UNIV3_ROUTER).exactInput(params);
+
+ dp = _getTestWithdrawParams(liq, 0, 0);
+ vm.warp(block.timestamp + 3600);
+
+ uint256 snapshot = vm.snapshot();
+ vm.prank(FACILITATOR); (uint128 liquidity, uint256 withdrawn0, uint256 withdrawn1, uint256 fees0, uint256 fees1) = depositor.withdraw(dp, true);
+ vm.revertTo(snapshot);
+
+ vm.expectEmit(true, true, true, true);
+ emit Withdraw(FACILITATOR, DAI, USDC, uint24(100), liquidity, withdrawn0, withdrawn1, fees0, fees1);
+ vm.prank(FACILITATOR); depositor.withdraw(dp, true);
+
+ assertTrue(fees0 > 0 || fees1 > 0);
+ assertTrue(withdrawn0 > 0 || withdrawn1 > 0);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevDAI + withdrawn0 + fees0);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevUSDC + withdrawn1 + fees1);
+ assertEq(GemLike(DAI).balanceOf(address(depositor)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(depositor)), 0);
+ assertEq(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), 0);
+ assertEq(liquidity, liq);
+ }
+
+ function testWithdrawZeroWithFeeCollection() public {
+ DepositorUniV3.LiquidityParams memory dp = _getTestDepositParams(0, 500 * WAD, 500 * 10**6);
+ vm.prank(FACILITATOR); (uint128 liq,,) = depositor.deposit(dp);
+ assertGt(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), 0);
+ uint256 prevUSDC = GemLike(USDC).balanceOf(address(buffer));
+ uint256 prevDAI = GemLike(DAI).balanceOf(address(buffer));
+
+ // execute a trade to generate fees for the LP position
+ deal(DAI, address(this), 1_000_000 * WAD, true);
+ GemLike(DAI).approve(UNIV3_ROUTER, 1_000_000 * WAD);
+ SwapRouterLike.ExactInputParams memory params = SwapRouterLike.ExactInputParams({
+ path: DAI_USDC_PATH,
+ recipient: address(this),
+ deadline: block.timestamp,
+ amountIn: 1_000_000 * WAD,
+ amountOutMinimum: 990_000 * 10**6
+ });
+ SwapRouterLike(UNIV3_ROUTER).exactInput(params);
+
+ dp.amt0Desired = 0;
+ dp.amt1Desired = 0;
+ dp.amt0Min = 0;
+ dp.amt1Min = 0;
+ vm.warp(block.timestamp + 3600);
+
+ uint256 snapshot = vm.snapshot();
+ vm.prank(FACILITATOR); (uint128 liquidity, uint256 withdrawn0, uint256 withdrawn1, uint256 fees0, uint256 fees1) = depositor.withdraw(dp, true);
+ vm.revertTo(snapshot);
+
+ vm.expectEmit(true, true, true, true);
+ emit Withdraw(FACILITATOR, DAI, USDC, uint24(100), liquidity, withdrawn0, withdrawn1, fees0, fees1);
+ vm.prank(FACILITATOR); depositor.withdraw(dp, true);
+
+ assertEq(liquidity, 0);
+ assertEq(withdrawn0, 0);
+ assertEq(withdrawn1, 0);
+ assertTrue(fees0 > 0 || fees1 > 0);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevDAI + fees0);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevUSDC + fees1);
+ assertEq(GemLike(DAI).balanceOf(address(depositor)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(depositor)), 0);
+ assertEq(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), liq);
+ }
+
+ function testWithdrawAmounts() public {
+ DepositorUniV3.LiquidityParams memory dp = _getTestDepositParams(0, 500 * WAD, 500 * 10**6);
+ vm.prank(FACILITATOR); (, uint256 deposited0, uint256 deposited1) = depositor.deposit(dp);
+ assertGt(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), 0);
+
+ dp = _getTestWithdrawParams(0, deposited0, deposited1);
+
+ uint256 liquidityBeforeWithdraw = UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100);
+
+ vm.warp(block.timestamp + 3600);
+
+ uint256 snapshot = vm.snapshot();
+ vm.prank(FACILITATOR); (uint128 liquidity, uint256 withdrawn0, uint256 withdrawn1, uint256 fees0, uint256 fees1) = depositor.withdraw(dp, true);
+ vm.revertTo(snapshot);
+
+ vm.expectEmit(true, true, true, true);
+ emit Withdraw(FACILITATOR, DAI, USDC, uint24(100), liquidity, withdrawn0, withdrawn1, fees0, fees1);
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+
+ // due to liquidity from amounts calculation there is rounding dust
+ assertGe(withdrawn0 * 100001 / 100000, deposited0);
+ assertGe(withdrawn1 * 100001 / 100000, deposited1);
+ assertEq(GemLike(DAI).balanceOf(address(depositor)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(depositor)), 0);
+ assertLt(UniV3Utils.getLiquidity(address(depositor), DAI, USDC, 100, REF_TICK-100, REF_TICK+100), liquidityBeforeWithdraw);
+ assertEq(fees0, 0);
+ assertEq(fees1, 0);
+ assertGt(liquidity, 0);
+ }
+
+ function testDepositWrongGemOrder() public {
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0: USDC,
+ gem1: DAI,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: 0,
+ amt0Desired: 0,
+ amt1Desired: 0,
+ amt0Min: 0,
+ amt1Min: 0
+ });
+ vm.expectRevert("DepositorUniV3/wrong-gem-order");
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+ }
+
+ function testDepositExceedingAmt() public {
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: 0,
+ amt0Desired: 2 * uint128(1 * WAD),
+ amt1Desired: 2 * uint128(1 * 10**6),
+ amt0Min: 0,
+ amt1Min: 0
+ });
+ depositor.setLimits(DAI, USDC, 100, uint96(1 * WAD), type(uint96).max, 3600);
+
+ vm.expectRevert("DepositorUniV3/exceeds-due-amt");
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+
+ depositor.setLimits(DAI, USDC, 100, type(uint96).max, 1 * 10**6, 3600);
+
+ vm.expectRevert("DepositorUniV3/exceeds-due-amt");
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+
+ depositor.setLimits(DAI, USDC, 100, type(uint96).max, type(uint96).max, 3600);
+
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+ }
+
+ function testDepositExceedingSlippage() public {
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: 0,
+ amt0Desired: 500 * WAD,
+ amt1Desired: 500 * 10**6,
+ amt0Min: 3 * 500 * WAD,
+ amt1Min: 0
+ });
+
+ vm.expectRevert("DepositorUniV3/exceeds-slippage");
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+
+ dp.amt0Min = 0;
+ dp.amt1Min = 3 * 500 * 10**6;
+
+ vm.expectRevert("DepositorUniV3/exceeds-slippage");
+ vm.prank(FACILITATOR); depositor.deposit(dp);
+ }
+
+ function testWithdrawWrongGemOrder() public {
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0: USDC,
+ gem1: DAI,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: 0,
+ amt0Desired: 0,
+ amt1Desired: 0,
+ amt0Min: 0,
+ amt1Min: 0
+ });
+
+ vm.expectRevert("DepositorUniV3/wrong-gem-order");
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+ }
+
+ function testWithdrawNoPosition() public {
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: 1,
+ amt0Desired: 0,
+ amt1Desired: 0,
+ amt0Min: 0,
+ amt1Min: 0
+ });
+
+ // "Liquidity Sub" error - https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/LiquidityMath.sol#L12
+ vm.expectRevert(bytes("LS"));
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+ }
+
+ function testWithdrawExceedingAmt() public {
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: 0,
+ amt0Desired: 2 * WAD,
+ amt1Desired: 2 * 10**6,
+ amt0Min: 0,
+ amt1Min: 0
+ });
+ vm.prank(FACILITATOR); (uint128 liq,,) = depositor.deposit(dp);
+ dp.liquidity = liq;
+ vm.warp(block.timestamp + 3600);
+
+ depositor.setLimits(DAI, USDC, 100, type(uint96).max, 1 * 10**6, 3600);
+
+ vm.expectRevert("DepositorUniV3/exceeds-due-amt");
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+
+ depositor.setLimits(DAI, USDC, 100, uint96(1 * WAD), type(uint96).max, 3600);
+
+ vm.expectRevert("DepositorUniV3/exceeds-due-amt");
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+
+ depositor.setLimits(DAI, USDC, 100, type(uint96).max, type(uint96).max, 3600);
+
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+ }
+
+ function testWithdrawExceedingSlippage() public {
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100,
+ liquidity: 0,
+ amt0Desired: 500 * WAD,
+ amt1Desired: 500 * 10**6,
+ amt0Min: 0,
+ amt1Min: 0
+ });
+ vm.prank(FACILITATOR); (uint128 liq,,) = depositor.deposit(dp);
+ dp.liquidity = liq;
+ vm.warp(block.timestamp + 3600);
+ dp.amt0Min = 3 * 500 * WAD;
+
+ vm.expectRevert("DepositorUniV3/exceeds-slippage");
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+
+ dp.amt0Min = 0;
+ dp.amt1Min = 3 * 500 * 10**6;
+
+ vm.expectRevert("DepositorUniV3/exceeds-slippage");
+ vm.prank(FACILITATOR); depositor.withdraw(dp, false);
+ }
+
+ function testCollectWrongGemOrder() public {
+ DepositorUniV3.CollectParams memory cp = DepositorUniV3.CollectParams({
+ gem0: USDC,
+ gem1: DAI,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100
+ });
+
+ vm.expectRevert("DepositorUniV3/wrong-gem-order");
+ vm.prank(FACILITATOR); depositor.collect(cp);
+ }
+
+ function testCollectNoPosition() public {
+ DepositorUniV3.CollectParams memory cp = DepositorUniV3.CollectParams({
+ gem0: DAI,
+ gem1: USDC,
+ fee: uint24(100),
+ tickLower: REF_TICK-100,
+ tickUpper: REF_TICK+100
+ });
+
+ // 0 liquidity position - https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/Position.sol#L54
+ vm.expectRevert(bytes("NP"));
+ vm.prank(FACILITATOR); depositor.collect(cp);
+ }
+
+ function testMintCallback() public {
+ uint256 initialDAI = GemLike(DAI).balanceOf(address(buffer));
+ uint256 initialPoolDAI = GemLike(DAI).balanceOf(DAI_USDC_POOL);
+ uint256 initialUSDC = GemLike(USDC).balanceOf(address(buffer));
+ uint256 initialPoolUSDC = GemLike(USDC).balanceOf(DAI_USDC_POOL);
+
+ vm.prank(DAI_USDC_POOL);
+ depositor.uniswapV3MintCallback({
+ amt0Owed: 1,
+ amt1Owed: 0,
+ data: abi.encode(DepositorUniV3.MintCallbackData({gem0: DAI, gem1: USDC, fee: 100}))
+ });
+
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), initialDAI - 1);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), initialUSDC);
+ assertEq(GemLike(DAI).balanceOf(DAI_USDC_POOL), initialPoolDAI + 1);
+ assertEq(GemLike(USDC).balanceOf(DAI_USDC_POOL), initialPoolUSDC);
+
+ vm.prank(DAI_USDC_POOL);
+ depositor.uniswapV3MintCallback({
+ amt0Owed: 0,
+ amt1Owed: 2,
+ data: abi.encode(DepositorUniV3.MintCallbackData({gem0: DAI, gem1: USDC, fee: 100}))
+ });
+
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), initialDAI - 1);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), initialUSDC - 2);
+ assertEq(GemLike(DAI).balanceOf(DAI_USDC_POOL), initialPoolDAI + 1);
+ assertEq(GemLike(USDC).balanceOf(DAI_USDC_POOL), initialPoolUSDC + 2);
+
+ vm.prank(DAI_USDC_POOL);
+ depositor.uniswapV3MintCallback({
+ amt0Owed: 10,
+ amt1Owed: 20,
+ data: abi.encode(DepositorUniV3.MintCallbackData({gem0: DAI, gem1: USDC, fee: 100}))
+ });
+
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), initialDAI - 11);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), initialUSDC - 22);
+ assertEq(GemLike(DAI).balanceOf(DAI_USDC_POOL), initialPoolDAI + 11);
+ assertEq(GemLike(USDC).balanceOf(DAI_USDC_POOL), initialPoolUSDC + 22);
+ }
+
+ function testMintCallbackNotFromPool() public {
+ vm.expectRevert("DepositorUniV3/sender-not-a-pool");
+ depositor.uniswapV3MintCallback({
+ amt0Owed: 1,
+ amt1Owed: 2,
+ data: abi.encode(DepositorUniV3.MintCallbackData({gem0: DAI, gem1: USDC, fee: 100}))
+ });
+ }
+}
diff --git a/test/funnels/Swapper.t.sol b/test/funnels/Swapper.t.sol
new file mode 100644
index 00000000..99855870
--- /dev/null
+++ b/test/funnels/Swapper.t.sol
@@ -0,0 +1,241 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { Swapper } from "src/funnels/Swapper.sol";
+import { SwapperCalleeUniV3 } from "src/funnels/callees/SwapperCalleeUniV3.sol";
+import { SwapperCalleePsm } from "src/funnels/callees/SwapperCalleePsm.sol";
+import { AllocatorRoles } from "src/AllocatorRoles.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+import { PsmMock } from "test/mocks/PsmMock.sol";
+
+interface GemLike {
+ function balanceOf(address) external view returns (uint256);
+ function transfer(address, uint256) external;
+}
+
+contract CalleeMock is DssTest {
+ function swapCallback(address src, address dst, uint256 amt, uint256, address to, bytes calldata) external {
+ GemLike(src).transfer(address(0xDEAD), amt);
+ deal(dst, address(this), amt, true);
+ GemLike(dst).transfer(to, amt);
+ }
+}
+
+contract SwapperTest is DssTest {
+ event SetLimits(address indexed src, address indexed dst, uint96 cap, uint32 era);
+ event Swap(address indexed sender, address indexed src, address indexed dst, uint256 amt, uint256 out);
+
+ AllocatorRoles public roles;
+ AllocatorBuffer public buffer;
+ Swapper public swapper;
+ SwapperCalleeUniV3 public uniV3Callee;
+
+ bytes32 constant ilk = "aaa";
+ bytes constant USDC_DAI_PATH = abi.encodePacked(USDC, uint24(100), DAI);
+ bytes constant DAI_USDC_PATH = abi.encodePacked(DAI, uint24(100), USDC);
+
+ address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
+ address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
+ address constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
+
+ address constant FACILITATOR = address(0x1337);
+ address constant KEEPER = address(0xb0b);
+
+ uint8 constant SWAPPER_ROLE = uint8(1);
+
+ function setUp() public {
+ vm.createSelectFork(vm.envString("ETH_RPC_URL"));
+
+ buffer = new AllocatorBuffer();
+ roles = new AllocatorRoles();
+ swapper = new Swapper(address(roles), ilk, address(buffer));
+ uniV3Callee = new SwapperCalleeUniV3(UNIV3_ROUTER);
+
+ roles.setIlkAdmin(ilk, address(this));
+ roles.setRoleAction(ilk, SWAPPER_ROLE, address(swapper), swapper.swap.selector, true);
+ roles.setUserRole(ilk, FACILITATOR, SWAPPER_ROLE, true);
+
+ swapper.setLimits(DAI, USDC, uint96(10_000 * WAD), 3600 seconds);
+ swapper.setLimits(USDC, DAI, uint96(10_000 * 10**6), 3600 seconds);
+
+ deal(DAI, address(buffer), 1_000_000 * WAD, true);
+ deal(USDC, address(buffer), 1_000_000 * 10**6, true);
+ buffer.approve(USDC, address(swapper), type(uint256).max);
+ buffer.approve(DAI, address(swapper), type(uint256).max);
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ Swapper s = new Swapper(address(0xBEEF), "SubDAO 1", address(0xAAA));
+ assertEq(address(s.roles()), address(0xBEEF));
+ assertEq(s.ilk(), "SubDAO 1");
+ assertEq(s.buffer(), address(0xAAA));
+ assertEq(s.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(swapper), "Swapper");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](2);
+ authedMethods[0] = swapper.setLimits.selector;
+ authedMethods[1] = swapper.swap.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(swapper), "Swapper/not-authorized", authedMethods);
+ vm.stopPrank();
+ }
+
+ function testSetLimits() public {
+ // swap to make sure due and end are set
+ vm.prank(FACILITATOR); swapper.swap(USDC, DAI, 1_000 * 10**6, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+ (,, uint96 dueBefore, uint32 endBefore) = swapper.limits(USDC, DAI);
+ assertGt(endBefore, 0);
+ assertGt(dueBefore, 0);
+
+ vm.warp(block.timestamp + 1 hours);
+
+ vm.expectEmit(true, true, true, true);
+ emit SetLimits(USDC, DAI, 4, 3);
+ vm.prank(address(this)); swapper.setLimits(USDC, DAI, 4, 3);
+ (uint96 cap, uint32 era, uint96 due, uint32 end) = swapper.limits(USDC, DAI);
+ assertEq(cap, 4);
+ assertEq(era, 3);
+ assertEq(due, 0);
+ assertEq(end, 0);
+ }
+
+ function testRoles() public {
+ vm.expectRevert("Swapper/not-authorized");
+ vm.prank(address(0xBEEF)); swapper.setLimits(address(0), address(0), 0, 0);
+ roles.setRoleAction(ilk, uint8(0xF1), address(swapper), swapper.setLimits.selector, true);
+ roles.setUserRole(ilk, address(0xBEEF), uint8(0xF1), true);
+ vm.prank(address(0xBEEF)); swapper.setLimits(address(0), address(0), 0, 0);
+ }
+
+ function testSwap() public {
+ uint256 prevSrc = GemLike(USDC).balanceOf(address(buffer));
+ uint256 prevDst = GemLike(DAI).balanceOf(address(buffer));
+
+ uint32 initialTime = uint32(block.timestamp);
+
+ uint256 snapshot = vm.snapshot();
+ vm.prank(FACILITATOR); uint256 expectedOut = swapper.swap(USDC, DAI, 1_000 * 10**6, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+ vm.revertTo(snapshot);
+
+ vm.expectEmit(true, true, true, true);
+ emit Swap(FACILITATOR, USDC, DAI, 1_000 * 10**6, expectedOut);
+ vm.prank(FACILITATOR); uint256 out = swapper.swap(USDC, DAI, 1_000 * 10**6, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+
+ assertGe(out, 990 * WAD);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevSrc - 1_000 * 10**6);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevDst + out);
+ assertEq(GemLike(DAI).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(DAI).balanceOf(address(uniV3Callee)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(uniV3Callee)), 0);
+ (,, uint96 due, uint32 end) = swapper.limits(USDC, DAI);
+ assertEq(due, 9_000 * 10**6);
+ assertEq(end, initialTime + 3600);
+
+ vm.warp(initialTime + 1800);
+ vm.prank(FACILITATOR); swapper.swap(USDC, DAI, 5_000 * 10**6, 4_950 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+ (,, due, end) = swapper.limits(USDC, DAI);
+ assertEq(due, 4_000 * 10**6);
+ assertEq(end, initialTime + 3600);
+
+ vm.expectRevert("Swapper/exceeds-due-amt");
+ vm.prank(FACILITATOR); swapper.swap(USDC, DAI, 8_000 * 10**6, 7_920 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+
+ vm.warp(initialTime + 3600);
+ vm.prank(FACILITATOR); swapper.swap(USDC, DAI, 8_000 * 10**6, 7_920 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+ (,, due, end) = swapper.limits(USDC, DAI);
+ assertEq(due, 2_000 * 10**6);
+ assertEq(end, initialTime + 7200);
+
+ prevSrc = GemLike(DAI).balanceOf(address(buffer));
+ prevDst = GemLike(USDC).balanceOf(address(buffer));
+
+ vm.expectEmit(true, true, true, false);
+ emit Swap(FACILITATOR, DAI, USDC, 1_000 * WAD, 0);
+ vm.prank(FACILITATOR); out = swapper.swap(DAI, USDC, 1_000 * WAD, 990 * 10**6, address(uniV3Callee), DAI_USDC_PATH);
+
+ assertGe(out, 990 * 10**6);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevSrc - 1_000 * WAD);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevDst + out);
+ assertEq(GemLike(DAI).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(DAI).balanceOf(address(uniV3Callee)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(uniV3Callee)), 0);
+ (,, due, end) = swapper.limits(DAI, USDC);
+ assertEq(due, 9_000 * WAD);
+ assertEq(end, initialTime + 7200);
+ }
+
+ function testSwapPsmCallee() public {
+ PsmMock psm = new PsmMock(DAI, USDC);
+ SwapperCalleePsm swapperCalleePsm = new SwapperCalleePsm(address(psm));
+ psm.rely(address(swapperCalleePsm));
+ swapperCalleePsm.rely(address(swapper));
+ deal(DAI, address(psm), 1_000 * WAD, true);
+
+ uint256 prevSrc = GemLike(USDC).balanceOf(address(buffer));
+ uint256 prevDst = GemLike(DAI).balanceOf(address(buffer));
+
+ vm.expectEmit(true, true, true, true);
+ emit Swap(FACILITATOR, USDC, DAI, 1_000 * 10**6, 1_000 * WAD);
+ vm.prank(FACILITATOR); uint256 out = swapper.swap(USDC, DAI, 1_000 * 10**6, 1_000 * WAD, address(swapperCalleePsm), "");
+
+ assertEq(out, 1_000 * WAD);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevSrc - 1_000 * 10**6);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevDst + 1_000 * WAD);
+ assertEq(GemLike(DAI).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(DAI).balanceOf(address(swapperCalleePsm)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(swapperCalleePsm)), 0);
+
+ vm.warp(uint32(block.timestamp) + 3600);
+
+ prevSrc = GemLike(DAI).balanceOf(address(buffer));
+ prevDst = GemLike(USDC).balanceOf(address(buffer));
+
+ vm.expectEmit(true, true, true, false);
+ emit Swap(FACILITATOR, DAI, USDC, 1_000 * WAD, 1_000 * 10**6);
+ vm.prank(FACILITATOR); out = swapper.swap(DAI, USDC, 1_000 * WAD, 1_000 * 10**6, address(swapperCalleePsm), "");
+
+ assertEq(out, 1_000 * 10**6);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevSrc - 1_000 * WAD);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevDst + 1_000 * 10**6);
+ assertEq(GemLike(DAI).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(DAI).balanceOf(address(swapperCalleePsm)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(swapperCalleePsm)), 0);
+ }
+
+ function testSwapAllAferEra() public {
+ vm.prank(FACILITATOR); swapper.swap(USDC, DAI, 10_000 * 10**6, 9900 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+ (, uint64 era,,) = swapper.limits(USDC, DAI);
+ vm.warp(block.timestamp + era);
+
+ vm.expectEmit(true, true, true, false);
+ emit Swap(FACILITATOR, USDC, DAI, 10_000 * 10**6, 0);
+ vm.prank(FACILITATOR); swapper.swap(USDC, DAI, 10_000 * 10**6, 9900 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+ }
+
+ function testSwapExceedingMax() public {
+ (uint128 cap,,,) = swapper.limits(USDC, DAI);
+ uint256 amt = cap + 1;
+ vm.expectRevert("Swapper/exceeds-due-amt");
+ vm.prank(FACILITATOR); swapper.swap(USDC, DAI, amt, 0, address(uniV3Callee), USDC_DAI_PATH);
+ }
+
+ function testSwapReceivingTooLittle() public {
+ CalleeMock callee = new CalleeMock();
+ vm.expectRevert("Swapper/too-few-dst-received");
+ vm.prank(FACILITATOR); swapper.swap(USDC, DAI, 100 * 10**6, 200 * WAD, address(callee), USDC_DAI_PATH);
+ }
+}
diff --git a/test/funnels/UniV3Utils.sol b/test/funnels/UniV3Utils.sol
new file mode 100644
index 00000000..8bd20ad6
--- /dev/null
+++ b/test/funnels/UniV3Utils.sol
@@ -0,0 +1,218 @@
+pragma solidity ^0.8.16;
+
+import {LiquidityAmounts, FixedPoint96} from "src/funnels/uniV3/LiquidityAmounts.sol";
+import {TickMath} from "src/funnels/uniV3/TickMath.sol";
+import {FullMath} from "src/funnels/uniV3/FullMath.sol";
+
+interface UniV3PoolLike {
+ function slot0() external view returns (
+ uint160 sqrtPriceX96,
+ int24 tick,
+ uint16 observationIndex,
+ uint16 observationCardinality,
+ uint16 observationCardinalityNext,
+ uint8 feeProtocol,
+ bool unlocked
+ );
+
+ struct PositionInfo {
+ uint128 liquidity;
+ uint256 feeGrowthInside0LastX128;
+ uint256 feeGrowthInside1LastX128;
+ uint128 tokensOwed0;
+ uint128 tokensOwed1;
+ }
+
+ function positions(bytes32) external view returns (PositionInfo memory);
+}
+
+// https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SafeCast.sol
+library SafeCast {
+ function toInt128(int256 y) internal pure returns (int128 z) {
+ require((z = int128(y)) == y);
+ }
+
+ function toInt256(uint256 y) internal pure returns (int256 z) {
+ require(y < 2**255);
+ z = int256(y);
+ }
+}
+
+library UniV3Utils {
+ using SafeCast for uint256;
+ using SafeCast for int256;
+
+ address constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
+ address constant UNIV3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
+ // https://github.com/Uniswap/v3-periphery/blob/464a8a49611272f7349c970e0fadb7ec1d3c1086/contracts/libraries/PoolAddress.sol#L33
+ function getPool(address gem0, address gem1, uint24 fee) internal pure returns (UniV3PoolLike pool) {
+ pool = UniV3PoolLike(address(uint160(uint256(keccak256(abi.encodePacked(
+ hex'ff',
+ UNIV3_FACTORY,
+ keccak256(abi.encode(gem0, gem1, fee)),
+ bytes32(0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54) // POOL_INIT_CODE_HASH
+ ))))));
+ }
+
+ function getLiquidity(
+ address owner,
+ address gem0,
+ address gem1,
+ uint24 fee,
+ int24 tickLower,
+ int24 tickUpper
+ ) internal view returns (uint128 liquidity) {
+ return getPool(gem0, gem1, fee).positions(keccak256(abi.encodePacked(owner, tickLower, tickUpper))).liquidity;
+ }
+
+ function getCurrentTick(address gem0, address gem1, uint24 fee) internal view returns (int24 tick) {
+ (, tick,,,,,) = getPool(gem0, gem1, fee).slot0();
+ }
+
+ function getLiquidityForAmts(
+ UniV3PoolLike pool,
+ int24 tickLower,
+ int24 tickUpper,
+ uint256 amt0Desired,
+ uint256 amt1Desired
+ ) internal view returns (uint128 liquidity) {
+ (uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
+ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
+ uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
+
+ liquidity = LiquidityAmounts.getLiquidityForAmounts(
+ sqrtPriceX96,
+ sqrtRatioAX96,
+ sqrtRatioBX96,
+ amt0Desired,
+ amt1Desired
+ );
+ }
+
+ // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/UnsafeMath.sol#L12
+ function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
+ assembly {
+ z := add(div(x, y), gt(mod(x, y), 0))
+ }
+ }
+
+ // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SqrtPriceMath.sol#L153
+ function getAmount0Delta(
+ uint160 sqrtRatioAX96,
+ uint160 sqrtRatioBX96,
+ uint128 liquidity,
+ bool roundUp
+ ) internal pure returns (uint256 amount0) {
+ unchecked {
+ if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
+
+ uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
+ uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
+
+ require(sqrtRatioAX96 > 0);
+
+ return
+ roundUp
+ ? divRoundingUp(
+ FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
+ sqrtRatioAX96
+ )
+ : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
+ }
+ }
+
+ // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SqrtPriceMath.sol#L182
+ function getAmount1Delta(
+ uint160 sqrtRatioAX96,
+ uint160 sqrtRatioBX96,
+ uint128 liquidity,
+ bool roundUp
+ ) internal pure returns (uint256 amount1) {
+ unchecked {
+ if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
+
+ return
+ roundUp
+ ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
+ : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
+ }
+ }
+
+ // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SqrtPriceMath.sol#L201
+ function getAmount0Delta(
+ uint160 sqrtRatioAX96,
+ uint160 sqrtRatioBX96,
+ int128 liquidity
+ ) internal pure returns (int256 amount0) {
+ unchecked {
+ return
+ liquidity < 0
+ ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
+ : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
+ }
+ }
+
+ // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SqrtPriceMath.sol#L217C7-L217C7
+ function getAmount1Delta(
+ uint160 sqrtRatioAX96,
+ uint160 sqrtRatioBX96,
+ int128 liquidity
+ ) internal pure returns (int256 amount1) {
+ unchecked {
+ return
+ liquidity < 0
+ ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
+ : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
+ }
+ }
+
+ // adapted from https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/UniswapV3Pool.sol#L327
+ function getExpectedAmounts(
+ address gem0,
+ address gem1,
+ uint24 fee,
+ int24 tickLower,
+ int24 tickUpper,
+ uint128 liquidity,
+ uint256 amt0Desired,
+ uint256 amt1Desired,
+ bool withdrawal
+ ) internal view returns (uint256 expectedAmt0, uint256 expectedAmt1) {
+ unchecked {
+ UniV3PoolLike pool = getPool(gem0, gem1, fee);
+ (uint160 sqrtPriceX96, int24 tick,,,,,) = pool.slot0();
+ int128 liqDelta = (int256(uint256(liquidity == 0 ? getLiquidityForAmts(pool, tickLower, tickUpper, amt0Desired, amt1Desired) : liquidity))).toInt128();
+ if (withdrawal) liqDelta = -liqDelta;
+
+ int256 expectedAmt0_;
+ int256 expectedAmt1_;
+ if (tick < tickLower) {
+ expectedAmt0_ = getAmount0Delta(
+ TickMath.getSqrtRatioAtTick(tickLower),
+ TickMath.getSqrtRatioAtTick(tickUpper),
+ liqDelta
+ );
+ } else if (tick < tickUpper) {
+ expectedAmt0_ = getAmount0Delta(
+ sqrtPriceX96,
+ TickMath.getSqrtRatioAtTick(tickUpper),
+ liqDelta
+ );
+ expectedAmt1_ = getAmount1Delta(
+ TickMath.getSqrtRatioAtTick(tickLower),
+ sqrtPriceX96,
+ liqDelta
+ );
+ } else {
+ expectedAmt1_ = getAmount1Delta(
+ TickMath.getSqrtRatioAtTick(tickLower),
+ TickMath.getSqrtRatioAtTick(tickUpper),
+ liqDelta
+ );
+ }
+
+ expectedAmt0 = uint256(withdrawal ? -expectedAmt0_: expectedAmt0_);
+ expectedAmt1 = uint256(withdrawal ? -expectedAmt1_: expectedAmt1_);
+ }
+ }
+}
diff --git a/test/funnels/automation/ConduitMover.t.sol b/test/funnels/automation/ConduitMover.t.sol
new file mode 100644
index 00000000..b8f0ff6b
--- /dev/null
+++ b/test/funnels/automation/ConduitMover.t.sol
@@ -0,0 +1,211 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { ConduitMover } from "src/funnels/automation/ConduitMover.sol";
+import { AllocatorRegistry } from "src/AllocatorRegistry.sol";
+import { AllocatorRoles } from "src/AllocatorRoles.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+import { AllocatorConduitMock } from "test/mocks/AllocatorConduitMock.sol";
+
+interface GemLike {
+ function balanceOf(address) external view returns (uint256);
+}
+
+contract ConduitMoverTest is DssTest {
+ event Kiss(address indexed usr);
+ event Diss(address indexed usr);
+ event SetConfig(address indexed from, address indexed to, address indexed gem, uint64 num, uint32 hop, uint128 lot);
+ event Move(address indexed from, address indexed to, address indexed gem, uint128 lot);
+
+ address public buffer;
+ address public conduit1;
+ address public conduit2;
+ ConduitMover public mover;
+
+ bytes32 constant ILK = "aaa";
+ address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
+ address constant FACILITATOR = address(0x1337);
+ address constant KEEPER = address(0xb0b);
+ uint8 constant MOVER_ROLE = uint8(1);
+
+ function setUp() public {
+ vm.createSelectFork(vm.envString("ETH_RPC_URL"));
+
+ buffer = address(new AllocatorBuffer());
+ AllocatorRoles roles = new AllocatorRoles();
+ AllocatorRegistry registry = new AllocatorRegistry();
+ registry.file(ILK, "buffer", buffer);
+
+ conduit1 = address(new AllocatorConduitMock(address(roles), address(registry)));
+ conduit2 = address(new AllocatorConduitMock(address(roles), address(registry)));
+ mover = new ConduitMover(ILK, buffer);
+
+ // Allow mover to perform ILK operations on the conduits
+ roles.setIlkAdmin(ILK, address(this));
+ roles.setRoleAction(ILK, MOVER_ROLE, conduit1, AllocatorConduitMock.deposit.selector, true);
+ roles.setRoleAction(ILK, MOVER_ROLE, conduit1, AllocatorConduitMock.withdraw.selector, true);
+ roles.setRoleAction(ILK, MOVER_ROLE, conduit2, AllocatorConduitMock.deposit.selector, true);
+ roles.setUserRole(ILK, address(mover), MOVER_ROLE, true);
+
+ // Allow conduits to transfer out funds out of the buffer
+ AllocatorBuffer(buffer).approve(USDC, conduit1, type(uint256).max);
+ AllocatorBuffer(buffer).approve(USDC, conduit2, type(uint256).max);
+
+ // Give conduit1 some funds
+ deal(USDC, buffer, 3_000 * 10**6, true);
+ vm.prank(address(mover)); AllocatorConduitMock(conduit1).deposit(ILK, USDC, 3_000 * 10**6);
+
+ // Set up keeper to move from conduit1 to conduit2
+ mover.rely(FACILITATOR);
+ vm.startPrank(FACILITATOR);
+ mover.kiss(KEEPER);
+ mover.setConfig(conduit1, conduit2, USDC, 10, 1 hours, uint128(1_000 * 10**6));
+ vm.stopPrank();
+
+ // Confirm initial parameters and amounts
+ (uint64 num, uint32 hop, uint32 zzz, uint128 lot) = mover.configs(conduit1, conduit2, USDC);
+ assertEq(num, 10);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, 0);
+ assertEq(lot, 1_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(buffer), 0);
+ assertEq(GemLike(USDC).balanceOf(conduit1), 3_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(conduit2), 0);
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ ConduitMover m = new ConduitMover("xyz", address(0xABC));
+ assertEq(m.ilk(), "xyz");
+ assertEq(m.buffer(), address(0xABC));
+ assertEq(m.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(mover), "ConduitMover");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](3);
+ authedMethods[0] = ConduitMover.kiss.selector;
+ authedMethods[1] = ConduitMover.diss.selector;
+ authedMethods[2] = ConduitMover.setConfig.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(mover), "ConduitMover/not-authorized", authedMethods);
+ vm.stopPrank();
+
+ bytes4[] memory keeperMethods = new bytes4[](1);
+ keeperMethods[0] = ConduitMover.move.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(mover), "ConduitMover/non-keeper", keeperMethods);
+ vm.stopPrank();
+ }
+
+ function testKissDiss() public {
+ address testAddress = address(0x123);
+ assertEq(mover.buds(testAddress), 0);
+
+ vm.expectEmit(true, true, true, true);
+ emit Kiss(testAddress);
+ mover.kiss(testAddress);
+ assertEq(mover.buds(testAddress), 1);
+
+ vm.expectEmit(true, true, true, true);
+ emit Diss(testAddress);
+ mover.diss(testAddress);
+ assertEq(mover.buds(testAddress), 0);
+ }
+
+ function testSetConfig() public {
+ vm.expectEmit(true, true, true, true);
+ emit SetConfig(address(0x123), address(0x456), address(0x789), uint64(23), uint32(360 seconds), uint96(314));
+ mover.setConfig(address(0x123), address(0x456), address(0x789), uint64(23), uint32(360 seconds), uint96(314));
+
+ (uint64 num, uint32 hop, uint32 zzz, uint128 lot) = mover.configs(address(0x123), address(0x456), address(0x789));
+ assertEq(num, 23);
+ assertEq(hop, 360);
+ assertEq(zzz, 0);
+ assertEq(lot, 314);
+ }
+
+ function testMoveByKeeper() public {
+ vm.expectEmit(true, true, true, true);
+ emit Move(conduit1, conduit2, USDC, 1_000 * 10**6);
+ vm.prank(KEEPER); mover.move(conduit1, conduit2, USDC);
+
+ assertEq(GemLike(USDC).balanceOf(conduit1), 2_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(conduit2), 1_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(buffer), 0);
+ (uint64 num, uint32 hop, uint32 zzz, uint128 lot) = mover.configs(conduit1, conduit2, USDC);
+ assertEq(num, 9);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, block.timestamp);
+ assertEq(lot, 1_000 * 10**6);
+
+ vm.warp(block.timestamp + 1 hours - 1);
+ vm.expectRevert("ConduitMover/too-soon");
+ vm.prank(KEEPER); mover.move(conduit1, conduit2, USDC);
+
+ vm.warp(block.timestamp + 1);
+ vm.prank(KEEPER); mover.move(conduit1, conduit2, USDC);
+
+ assertEq(GemLike(USDC).balanceOf(conduit1), 1_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(conduit2), 2_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(buffer), 0);
+ (num, hop, zzz, lot) = mover.configs(conduit1, conduit2, USDC);
+ assertEq(num, 8);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, block.timestamp);
+ assertEq(lot, 1_000 * 10**6);
+ }
+
+ function testMoveByKeeperToAndFromBuffer() public {
+ // Set up keeper to move USDC between conduit1 and buffer
+ vm.prank(FACILITATOR); mover.setConfig(conduit1, buffer, USDC, 10, 1 hours, uint128(1_000 * 10**6));
+ vm.prank(FACILITATOR); mover.setConfig(buffer, conduit1, USDC, 10, 1 hours, uint128(1_000 * 10**6));
+ assertEq(GemLike(USDC).balanceOf(conduit1), 3_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(buffer), 0);
+
+ vm.expectEmit(true, true, true, true);
+ emit Move(conduit1, buffer, USDC, 1_000 * 10**6);
+ vm.prank(KEEPER); mover.move(conduit1, buffer, USDC);
+
+ assertEq(GemLike(USDC).balanceOf(conduit1), 2_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(buffer), 1_000 * 10**6);
+ (uint64 num, uint32 hop, uint32 zzz, uint128 lot) = mover.configs(conduit1, buffer, USDC);
+ assertEq(num, 9);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, block.timestamp);
+ assertEq(lot, 1_000 * 10**6);
+
+ vm.expectEmit(true, true, true, true);
+ emit Move(buffer, conduit1, USDC, 1_000 * 10**6);
+ vm.prank(KEEPER); mover.move(buffer, conduit1, USDC);
+
+ assertEq(GemLike(USDC).balanceOf(conduit1), 3_000 * 10**6);
+ assertEq(GemLike(USDC).balanceOf(buffer), 0);
+ (num, hop, zzz, lot) = mover.configs(buffer, conduit1, USDC);
+ assertEq(num, 9);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, block.timestamp);
+ assertEq(lot, 1_000 * 10**6);
+ }
+
+ function testMoveExceedingNum() public {
+ vm.expectRevert("ConduitMover/exceeds-num");
+ vm.prank(KEEPER); mover.move(conduit1, conduit2, address(0x123));
+ }
+
+ function testMoveLotWithdrawFail() public {
+ vm.prank(FACILITATOR); mover.setConfig(conduit1, buffer, USDC, 10, 1 hours, uint128(3_100 * 10**6));
+ assertEq(GemLike(USDC).balanceOf(conduit1), 3_000 * 10**6);
+
+ vm.expectRevert("ConduitMover/lot-withdraw-failed");
+ vm.prank(KEEPER); mover.move(conduit1, buffer, USDC);
+ }
+}
diff --git a/test/funnels/automation/StableDepositorUniV3.t.sol b/test/funnels/automation/StableDepositorUniV3.t.sol
new file mode 100644
index 00000000..9b61d690
--- /dev/null
+++ b/test/funnels/automation/StableDepositorUniV3.t.sol
@@ -0,0 +1,298 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { DepositorUniV3 } from "src/funnels/DepositorUniV3.sol";
+import { StableDepositorUniV3 } from "src/funnels/automation/StableDepositorUniV3.sol";
+import { AllocatorRoles } from "src/AllocatorRoles.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+
+import { UniV3Utils } from "test/funnels/UniV3Utils.sol";
+
+interface GemLike {
+ function balanceOf(address) external view returns (uint256);
+ function transfer(address, uint256) external;
+ function approve(address, uint256) external;
+}
+
+interface SwapRouterLike {
+ function exactInput(ExactInputParams calldata params) external returns (uint256 amountOut);
+
+ struct ExactInputParams {
+ bytes path;
+ address recipient;
+ uint256 deadline;
+ uint256 amountIn;
+ uint256 amountOutMinimum;
+ }
+}
+
+contract StableDepositorUniV3Test is DssTest {
+ event Kiss(address indexed usr);
+ event Diss(address indexed usr);
+ event SetConfig(address indexed gem0, address indexed gem1, uint24 indexed fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1);
+
+ AllocatorBuffer public buffer;
+ DepositorUniV3 public depositor;
+ StableDepositorUniV3 public stableDepositor;
+
+ bytes32 constant ilk = "aaa";
+ bytes constant DAI_USDC_PATH = abi.encodePacked(DAI, uint24(100), USDC);
+
+ address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
+ address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
+ address constant UNIV3_ROUTER = UniV3Utils.UNIV3_ROUTER;
+ address constant UNIV3_FACTORY = UniV3Utils.UNIV3_FACTORY;
+
+ address constant FACILITATOR = address(0x1337);
+ address constant KEEPER = address(0xb0b);
+
+ uint8 constant DEPOSITOR_ROLE = uint8(1);
+
+ int24 REF_TICK;
+
+ uint96 req0;
+ uint96 req1;
+
+ function setUp() public {
+ vm.createSelectFork(vm.envString("ETH_RPC_URL"));
+
+ buffer = new AllocatorBuffer();
+ AllocatorRoles roles = new AllocatorRoles();
+ depositor = new DepositorUniV3(address(roles), ilk, UNIV3_FACTORY, address(buffer));
+ stableDepositor = new StableDepositorUniV3(address(depositor));
+
+ roles.setIlkAdmin(ilk, address(this));
+ roles.setRoleAction(ilk, DEPOSITOR_ROLE, address(depositor), depositor.deposit.selector, true);
+ roles.setRoleAction(ilk, DEPOSITOR_ROLE, address(depositor), depositor.withdraw.selector, true);
+ roles.setRoleAction(ilk, DEPOSITOR_ROLE, address(depositor), depositor.collect.selector, true);
+ roles.setUserRole(ilk, FACILITATOR, DEPOSITOR_ROLE, true);
+ roles.setUserRole(ilk, address(stableDepositor), DEPOSITOR_ROLE, true);
+
+ depositor.setLimits(DAI, USDC, 100, uint96(10_000 * WAD), uint96(10_000 * 10**6), 3600 seconds);
+
+ deal(DAI, address(buffer), 1_000_000 * WAD, true);
+ deal(USDC, address(buffer), 1_000_000 * 10**6, true);
+ buffer.approve(USDC, address(depositor), type(uint256).max);
+ buffer.approve(DAI, address(depositor), type(uint256).max);
+
+ REF_TICK = UniV3Utils.getCurrentTick(DAI, USDC, uint24(100));
+
+ stableDepositor.rely(FACILITATOR);
+ vm.startPrank(FACILITATOR);
+ (uint256 expectedAmt0, uint256 expectedAmt1) = UniV3Utils.getExpectedAmounts(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 0, 500 * WAD, 500 * 10**6, false);
+ req0 = uint96(expectedAmt0 * 90 / 100);
+ req1 = uint96(expectedAmt1 * 90 / 100);
+ stableDepositor.setConfig(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 10, 360, uint96(500 * WAD), uint96(500 * 10**6), req0, req1);
+
+ stableDepositor.kiss(KEEPER);
+ vm.stopPrank();
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ StableDepositorUniV3 s = new StableDepositorUniV3(address(0xABC));
+ assertEq(address(s.depositor()), address(0xABC));
+ assertEq(s.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(stableDepositor), "StableDepositorUniV3");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](3);
+ authedMethods[0] = StableDepositorUniV3.kiss.selector;
+ authedMethods[1] = StableDepositorUniV3.diss.selector;
+ authedMethods[2] = StableDepositorUniV3.setConfig.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(stableDepositor), "StableDepositorUniV3/not-authorized", authedMethods);
+ vm.stopPrank();
+
+ bytes4[] memory keeperMethods = new bytes4[](3);
+ keeperMethods[0] = StableDepositorUniV3.deposit.selector;
+ keeperMethods[1] = StableDepositorUniV3.withdraw.selector;
+ keeperMethods[2] = StableDepositorUniV3.collect.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(stableDepositor), "StableDepositorUniV3/non-keeper", keeperMethods);
+ vm.stopPrank();
+ }
+
+ function testKissDiss() public {
+ address testAddress = address(0x123);
+
+ assertEq(stableDepositor.buds(testAddress), 0);
+ vm.expectEmit(true, true, true, true);
+ emit Kiss(testAddress);
+ stableDepositor.kiss(testAddress);
+ assertEq(stableDepositor.buds(testAddress), 1);
+ vm.expectEmit(true, true, true, true);
+ emit Diss(testAddress);
+ stableDepositor.diss(testAddress);
+ assertEq(stableDepositor.buds(testAddress), 0);
+ }
+
+ function testSetConfig() public {
+ vm.expectRevert("StableDepositorUniV3/wrong-gem-order");
+ stableDepositor.setConfig(address(0x456), address(0x123), uint24(314), 5, 6, 23, 3600, uint96(7), uint96(8), uint96(9), uint96(10));
+
+ vm.expectEmit(true, true, true, true);
+ emit SetConfig(address(0x123), address(0x456), uint24(314), 5, 6, 23, 3600, uint96(7), uint96(8), uint96(9), uint96(10));
+ stableDepositor.setConfig(address(0x123), address(0x456), uint24(314), 5, 6, 23, 3600, uint96(7), uint96(8), uint96(9), uint96(10));
+
+ (
+ int32 num,
+ uint32 zzz,
+ uint96 amt0,
+ uint96 amt1,
+ uint96 req0_,
+ uint96 req1_,
+ uint32 hop
+ ) = stableDepositor.configs(address(0x123), address(0x456), uint24(314), 5, 6);
+ assertEq(num, 23);
+ assertEq(zzz, 0);
+ assertEq(amt0, uint96(7));
+ assertEq(amt1, uint96(8));
+ assertEq(req0_, uint96(9));
+ assertEq(req1_, uint96(10));
+ assertEq(hop, 3600);
+ }
+
+ function testDepositWithdrawByKeeper() public {
+ uint256 prevDai = GemLike(DAI).balanceOf(address(buffer));
+ uint256 prevUsdc = GemLike(USDC).balanceOf(address(buffer));
+ (int32 initNum,,,,,,) = stableDepositor.configs(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+ assertEq(initNum, 10);
+ uint32 initialTime = uint32(block.timestamp);
+
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0, req1);
+
+ uint256 afterDepositDai = GemLike(DAI).balanceOf(address(buffer));
+ uint256 afterDepositUsdc = GemLike(USDC).balanceOf(address(buffer));
+ (int32 num, uint32 zzz,,,,,) = stableDepositor.configs(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+ assertLt(afterDepositDai, prevDai);
+ assertLt(afterDepositUsdc, prevUsdc);
+ assertEq(num, initNum - 1);
+ assertEq(zzz, initialTime);
+
+ vm.warp(initialTime + 180);
+ vm.expectRevert("StableDepositorUniV3/too-soon");
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0, req1);
+
+ vm.warp(initialTime + 360);
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0, req1);
+ (num, zzz,,,,,) = stableDepositor.configs(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+
+ assertEq(num, initNum - 2);
+ assertEq(zzz, initialTime + 360);
+
+ vm.warp(initialTime + 2*360);
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0 + 1, req1 + 1); // also making sure that amt{i}Min is allowed to be > req{i}
+ (num, zzz,,,,,) = stableDepositor.configs(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+
+ assertEq(num, initNum - 3);
+ assertEq(zzz, initialTime + 2*360);
+
+ (uint256 expectedAmt0, uint256 expectedAmt1) = UniV3Utils.getExpectedAmounts(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 0, 500 * WAD, 500 * 10**6, true);
+ uint96 req0_ = uint96(expectedAmt0 * 90 / 100);
+ uint96 req1_ = uint96(expectedAmt1 * 90 / 100);
+ stableDepositor.setConfig(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, -10, 360, uint96(500 * WAD), uint96(500 * 10**6), req0_, req1_);
+ (initNum,,,,,,) = stableDepositor.configs(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+ assertEq(initNum, -10);
+
+ vm.prank(KEEPER); stableDepositor.withdraw(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0_, req1_);
+ (num, zzz,,,,,) = stableDepositor.configs(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+ assertEq(num, initNum + 1);
+ assertEq(zzz, initialTime + 2*360);
+
+ vm.warp(initialTime + 2*360 + 180);
+ vm.expectRevert("StableDepositorUniV3/too-soon");
+ vm.prank(KEEPER); stableDepositor.withdraw(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0_, req1_);
+
+ vm.warp(initialTime + 3*360);
+ vm.prank(KEEPER); stableDepositor.withdraw(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0_, req1_);
+ (num, zzz,,,,,) = stableDepositor.configs(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+
+ assertEq(num, initNum + 2);
+ assertEq(zzz, initialTime + 3*360);
+
+ vm.warp(initialTime + 4*360);
+ vm.prank(KEEPER); stableDepositor.withdraw(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0_ + 1, req1_ + 1); // also making sure that amt{i}Min is allowed to be > req{i}
+ (num, zzz,,,,,) = stableDepositor.configs(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+
+ assertGt(GemLike(DAI).balanceOf(address(buffer)), afterDepositDai);
+ assertGt(GemLike(USDC).balanceOf(address(buffer)), afterDepositUsdc);
+ assertEq(num, initNum + 3);
+ assertEq(zzz, initialTime + 4*360);
+ }
+
+ function testDepositWithdrawMinZero() public {
+ uint256 prevDai = GemLike(DAI).balanceOf(address(buffer));
+ uint256 prevUsdc = GemLike(USDC).balanceOf(address(buffer));
+
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 0, 0);
+
+ uint256 afterDepositDai = GemLike(DAI).balanceOf(address(buffer));
+ uint256 afterDepositUsdc = GemLike(USDC).balanceOf(address(buffer));
+ assertLt(afterDepositDai, prevDai);
+ assertLt(afterDepositUsdc, prevUsdc);
+
+ (uint256 expectedAmt0, uint256 expectedAmt1) = UniV3Utils.getExpectedAmounts(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 0, 500 * WAD, 500 * 10**6, true);
+ uint96 req0_ = uint96(expectedAmt0 * 90 / 100);
+ uint96 req1_ = uint96(expectedAmt1 * 90 / 100);
+ stableDepositor.setConfig(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, -10, 360, uint96(500 * WAD), uint96(500 * 10**6), req0_, req1_);
+ vm.prank(KEEPER); stableDepositor.withdraw(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 0, 0);
+
+ assertGt(GemLike(DAI).balanceOf(address(buffer)), afterDepositDai);
+ assertGt(GemLike(USDC).balanceOf(address(buffer)), afterDepositUsdc);
+ }
+
+ function testDepositWithdrawExceedingNum() public {
+ stableDepositor.setConfig(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, -10, 360, uint96(500 * WAD), uint96(500 * 10**6), 0, 0);
+ vm.expectRevert("StableDepositorUniV3/exceeds-num");
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 0, 0);
+
+ stableDepositor.setConfig(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 10, 360, uint96(500 * WAD), uint96(500 * 10**6), 0, 0);
+ vm.expectRevert("StableDepositorUniV3/exceeds-num");
+ vm.prank(KEEPER); stableDepositor.withdraw(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, 0, 0);
+ }
+
+ function testDepositWithMin0TooSmall() public {
+ vm.expectRevert("StableDepositorUniV3/min-amt0-too-small");
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0 - 1, req1);
+ }
+
+ function testDepositWithMin1TooSmall() public {
+ vm.expectRevert("StableDepositorUniV3/min-amt1-too-small");
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0, req1 - 1);
+ }
+
+ function testCollectByKeeper() public {
+ vm.prank(KEEPER); stableDepositor.deposit(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100, req0, req1);
+
+ uint256 prevDai = GemLike(DAI).balanceOf(address(buffer));
+ uint256 prevUsdc = GemLike(USDC).balanceOf(address(buffer));
+
+ // execute a trade to generate fees for the LP position
+ deal(DAI, address(this), 1_000_000 * WAD, true);
+ GemLike(DAI).approve(UNIV3_ROUTER, 1_000_000 * WAD);
+ SwapRouterLike.ExactInputParams memory params = SwapRouterLike.ExactInputParams({
+ path: DAI_USDC_PATH,
+ recipient: address(this),
+ deadline: block.timestamp,
+ amountIn: 1_000_000 * WAD,
+ amountOutMinimum: 990_000 * 10**6
+ });
+ SwapRouterLike(UNIV3_ROUTER).exactInput(params);
+
+ vm.prank(KEEPER); (uint256 fees0, uint256 fees1) = stableDepositor.collect(DAI, USDC, uint24(100), REF_TICK-100, REF_TICK+100);
+
+ assertTrue(fees0 > 0 || fees1 > 0);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevDai + fees0);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevUsdc + fees1);
+ }
+}
diff --git a/test/funnels/automation/StableSwapper.t.sol b/test/funnels/automation/StableSwapper.t.sol
new file mode 100644
index 00000000..fc6d7eed
--- /dev/null
+++ b/test/funnels/automation/StableSwapper.t.sol
@@ -0,0 +1,195 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { Swapper, GemLike } from "src/funnels/Swapper.sol";
+import { StableSwapper } from "src/funnels/automation/StableSwapper.sol";
+import { SwapperCalleeUniV3 } from "src/funnels/callees/SwapperCalleeUniV3.sol";
+import { AllocatorRoles } from "src/AllocatorRoles.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+
+contract StableSwapperTest is DssTest {
+ event Kiss(address indexed usr);
+ event Diss(address indexed usr);
+ event SetConfig(address indexed src, address indexed dst, uint128 num, uint32 hop, uint96 lot, uint96 req);
+ event Swap(address indexed sender, address indexed src, address indexed dst, uint256 amt, uint256 out);
+
+ AllocatorBuffer public buffer;
+ Swapper public swapper;
+ StableSwapper public stableSwapper;
+ SwapperCalleeUniV3 public uniV3Callee;
+
+ bytes32 constant ilk = "aaa";
+ bytes constant USDC_DAI_PATH = abi.encodePacked(USDC, uint24(100), DAI);
+ bytes constant DAI_USDC_PATH = abi.encodePacked(DAI, uint24(100), USDC);
+
+ address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
+ address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
+ address constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
+
+ address constant FACILITATOR = address(0x1337);
+ address constant KEEPER = address(0xb0b);
+
+ uint8 constant SWAPPER_ROLE = uint8(1);
+
+ function setUp() public {
+ vm.createSelectFork(vm.envString("ETH_RPC_URL"));
+
+ buffer = new AllocatorBuffer();
+ AllocatorRoles roles = new AllocatorRoles();
+ swapper = new Swapper(address(roles), ilk, address(buffer));
+ uniV3Callee = new SwapperCalleeUniV3(UNIV3_ROUTER);
+ stableSwapper = new StableSwapper(address(swapper));
+
+ roles.setIlkAdmin(ilk, address(this));
+ roles.setRoleAction(ilk, SWAPPER_ROLE, address(swapper), swapper.swap.selector, true);
+ roles.setUserRole(ilk, FACILITATOR, SWAPPER_ROLE, true);
+ roles.setUserRole(ilk, address(stableSwapper), SWAPPER_ROLE, true);
+
+ swapper.setLimits(DAI, USDC, uint96(10_000 * WAD), 3600 seconds);
+ swapper.setLimits(USDC, DAI, uint96(10_000 * 10**6), 3600 seconds);
+
+ deal(DAI, address(buffer), 1_000_000 * WAD, true);
+ deal(USDC, address(buffer), 1_000_000 * 10**6, true);
+ buffer.approve(USDC, address(swapper), type(uint256).max);
+ buffer.approve(DAI, address(swapper), type(uint256).max);
+
+ stableSwapper.rely(FACILITATOR);
+ vm.startPrank(FACILITATOR);
+ stableSwapper.setConfig(DAI, USDC, 10, 360 seconds, uint96(1_000 * WAD), uint96(990 * 10**6));
+ stableSwapper.setConfig(USDC, DAI, 10, 360 seconds, uint96(1_000 * 10**6), uint96(990 * WAD));
+ stableSwapper.kiss(KEEPER);
+ vm.stopPrank();
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ StableSwapper s = new StableSwapper(address(0xABC));
+ assertEq(address(s.swapper()), address(0xABC));
+ assertEq(s.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(stableSwapper), "StableSwapper");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](3);
+ authedMethods[0] = StableSwapper.kiss.selector;
+ authedMethods[1] = StableSwapper.diss.selector;
+ authedMethods[2] = StableSwapper.setConfig.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(stableSwapper), "StableSwapper/not-authorized", authedMethods);
+ vm.stopPrank();
+
+ bytes4[] memory keeperMethods = new bytes4[](1);
+ keeperMethods[0] = StableSwapper.swap.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(stableSwapper), "StableSwapper/non-keeper", keeperMethods);
+ vm.stopPrank();
+ }
+
+ function testKissDiss() public {
+ address testAddress = address(0x123);
+
+ assertEq(stableSwapper.buds(testAddress), 0);
+ vm.expectEmit(true, true, true, true);
+ emit Kiss(testAddress);
+ stableSwapper.kiss(testAddress);
+ assertEq(stableSwapper.buds(testAddress), 1);
+ vm.expectEmit(true, true, true, true);
+ emit Diss(testAddress);
+ stableSwapper.diss(testAddress);
+ assertEq(stableSwapper.buds(testAddress), 0);
+ }
+
+ function testSetConfig() public {
+ vm.expectEmit(true, true, true, true);
+ emit SetConfig(address(0x123), address(0x456), uint128(23), uint32(360 seconds), uint96(314), uint96(42));
+ stableSwapper.setConfig(address(0x123), address(0x456), uint128(23), uint32(360 seconds), uint96(314), uint96(42));
+
+ (uint128 num, uint32 hop, uint32 zzz, uint96 lot, uint96 req) = stableSwapper.configs(address(0x123), address(0x456));
+ assertEq(num, 23);
+ assertEq(hop, 360);
+ assertEq(zzz, 0);
+ assertEq(lot, 314);
+ assertEq(req, 42);
+ }
+
+ function testSwapByKeeper() public {
+ uint256 prevSrc = GemLike(USDC).balanceOf(address(buffer));
+ uint256 prevDst = GemLike(DAI).balanceOf(address(buffer));
+ (uint128 initUsdcDaiNum,,,,) = stableSwapper.configs(USDC, DAI);
+ (uint128 initDaiUsdcNum,,,,) = stableSwapper.configs(DAI, USDC);
+ uint32 initialTime = uint32(block.timestamp);
+
+ vm.expectEmit(true, true, true, false);
+ emit Swap(address(stableSwapper), USDC, DAI, 0, 0);
+ vm.prank(KEEPER); uint256 out = stableSwapper.swap(USDC, DAI, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+
+ assertGe(out, 990 * WAD);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevSrc - 1_000 * 10**6);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevDst + out);
+ assertEq(GemLike(DAI).balanceOf(address(stableSwapper)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(stableSwapper)), 0);
+ assertEq(GemLike(DAI).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(DAI).balanceOf(address(uniV3Callee)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(uniV3Callee)), 0);
+ (uint128 usdcDaiNum,, uint32 usdcDaiZzz,,) = stableSwapper.configs(USDC, DAI);
+ assertEq(usdcDaiNum, initUsdcDaiNum - 1);
+ assertEq(usdcDaiZzz, initialTime);
+
+ vm.warp(initialTime + 180);
+ vm.expectRevert("StableSwapper/too-soon");
+ vm.prank(KEEPER); stableSwapper.swap(USDC, DAI, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+
+ vm.warp(initialTime + 360);
+ vm.prank(KEEPER); stableSwapper.swap(USDC, DAI, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH);
+
+ (usdcDaiNum,, usdcDaiZzz,,) = stableSwapper.configs(USDC, DAI);
+ assertEq(usdcDaiNum, initUsdcDaiNum - 2);
+ assertEq(usdcDaiZzz, initialTime + 360);
+
+ prevSrc = GemLike(DAI).balanceOf(address(buffer));
+ prevDst = GemLike(USDC).balanceOf(address(buffer));
+
+ vm.expectEmit(true, true, true, false);
+ emit Swap(address(stableSwapper), DAI, USDC, 0, 0);
+ vm.prank(KEEPER); out = stableSwapper.swap(DAI, USDC, 990 * 10**6, address(uniV3Callee), DAI_USDC_PATH);
+
+ assertGe(out, 990 * 10**6);
+ assertEq(GemLike(DAI).balanceOf(address(buffer)), prevSrc - 1_000 * WAD);
+ assertEq(GemLike(USDC).balanceOf(address(buffer)), prevDst + out);
+ assertEq(GemLike(DAI).balanceOf(address(stableSwapper)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(stableSwapper)), 0);
+ assertEq(GemLike(DAI).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(swapper)), 0);
+ assertEq(GemLike(DAI).balanceOf(address(uniV3Callee)), 0);
+ assertEq(GemLike(USDC).balanceOf(address(uniV3Callee)), 0);
+ (uint128 daiUsdcNum,, uint32 daiUsdcZzz,,) = stableSwapper.configs(DAI, USDC);
+ assertEq(daiUsdcNum, initDaiUsdcNum - 1);
+ assertEq(daiUsdcZzz, initialTime + 360);
+ }
+
+ function testSwapMinZero() public {
+ vm.expectEmit(true, true, true, false);
+ emit Swap(address(stableSwapper), USDC, DAI, 0, 0);
+ vm.prank(KEEPER); stableSwapper.swap(USDC, DAI, 0, address(uniV3Callee), USDC_DAI_PATH);
+ }
+
+ function testSwapExceedingNum() public {
+ vm.expectRevert("StableSwapper/exceeds-num");
+ vm.prank(KEEPER); stableSwapper.swap(USDC, USDC, 0, address(uniV3Callee), USDC_DAI_PATH);
+ }
+
+ function testSwapWithMinTooSmall() public {
+ (,,,, uint96 req) = stableSwapper.configs(USDC, DAI);
+ vm.expectRevert("StableSwapper/min-too-small");
+ vm.prank(KEEPER); stableSwapper.swap(USDC, DAI, req - 1, address(uniV3Callee), USDC_DAI_PATH);
+ }
+}
diff --git a/test/funnels/automation/VaultMinter.t.sol b/test/funnels/automation/VaultMinter.t.sol
new file mode 100644
index 00000000..a4d78a3c
--- /dev/null
+++ b/test/funnels/automation/VaultMinter.t.sol
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { VaultMinter } from "src/funnels/automation/VaultMinter.sol";
+import { AllocatorRoles } from "src/AllocatorRoles.sol";
+import { AllocatorVault } from "src/AllocatorVault.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+import { VatMock } from "test/mocks/VatMock.sol";
+import { JugMock } from "test/mocks/JugMock.sol";
+import { GemMock } from "test/mocks/GemMock.sol";
+import { UsdsJoinMock } from "test/mocks/UsdsJoinMock.sol";
+
+contract VaultMinterTest is DssTest {
+ using stdStorage for StdStorage;
+
+ event Kiss(address indexed usr);
+ event Diss(address indexed usr);
+ event SetConfig(int64 num, uint32 hop, uint128 lot);
+ event Draw(uint128 lot);
+ event Wipe(uint128 lot);
+
+ VatMock public vat;
+ JugMock public jug;
+ GemMock public usds;
+ UsdsJoinMock public usdsJoin;
+ AllocatorBuffer public buffer;
+ AllocatorRoles public roles;
+ AllocatorVault public vault;
+ VaultMinter public minter;
+
+ bytes32 constant ILK = "aaa";
+ address constant FACILITATOR = address(0x1337);
+ address constant KEEPER = address(0xb0b);
+ uint8 constant MINTER_ROLE = uint8(1);
+
+ function setUp() public {
+ vat = new VatMock();
+ jug = new JugMock(vat);
+ usds = new GemMock(0);
+ usdsJoin = new UsdsJoinMock(vat, usds);
+ buffer = new AllocatorBuffer();
+ roles = new AllocatorRoles();
+ vault = new AllocatorVault(address(roles), address(buffer), ILK, address(usdsJoin));
+ vault.file("jug", address(jug));
+ buffer.approve(address(usds), address(vault), type(uint256).max);
+
+ vat.slip(ILK, address(vault), int256(1_000_000 * WAD));
+ vat.grab(ILK, address(vault), address(vault), address(0), int256(1_000_000 * WAD), 0);
+
+ minter = new VaultMinter(address(vault));
+
+ // Allow minter to perform operations in the vault
+ roles.setIlkAdmin(ILK, address(this));
+ roles.setRoleAction(ILK, MINTER_ROLE, address(vault), AllocatorVault.draw.selector, true);
+ roles.setRoleAction(ILK, MINTER_ROLE, address(vault), AllocatorVault.wipe.selector, true);
+ roles.setUserRole(ILK, address(minter), MINTER_ROLE, true);
+
+ // Set up keeper to mint and burn
+ minter.rely(FACILITATOR);
+ vm.prank(FACILITATOR); minter.kiss(KEEPER);
+
+ vm.warp(1 hours);
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ VaultMinter m = new VaultMinter(address(0xABC));
+ assertEq(m.vault(), address(0xABC));
+ assertEq(m.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(minter), "VaultMinter");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](3);
+ authedMethods[0] = VaultMinter.kiss.selector;
+ authedMethods[1] = VaultMinter.diss.selector;
+ authedMethods[2] = VaultMinter.setConfig.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(minter), "VaultMinter/not-authorized", authedMethods);
+ vm.stopPrank();
+
+ bytes4[] memory keeperMethods = new bytes4[](2);
+ keeperMethods[0] = VaultMinter.draw.selector;
+ keeperMethods[1] = VaultMinter.wipe.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(minter), "VaultMinter/non-keeper", keeperMethods);
+ vm.stopPrank();
+ }
+
+ function testKissDiss() public {
+ address testAddress = address(0x123);
+ assertEq(minter.buds(testAddress), 0);
+
+ vm.expectEmit(true, true, true, true);
+ emit Kiss(testAddress);
+ minter.kiss(testAddress);
+ assertEq(minter.buds(testAddress), 1);
+
+ vm.expectEmit(true, true, true, true);
+ emit Diss(testAddress);
+ minter.diss(testAddress);
+ assertEq(minter.buds(testAddress), 0);
+ }
+
+ function testSetConfig() public {
+ vm.expectEmit(true, true, true, true);
+ emit SetConfig(int64(23), uint32(360 seconds), uint128(314));
+ minter.setConfig(int64(23), uint32(360 seconds), uint128(314));
+
+ (int64 num, uint32 hop, uint32 zzz, uint128 lot) = minter.config();
+ assertEq(num, 23);
+ assertEq(hop, 360);
+ assertEq(zzz, 0);
+ assertEq(lot, 314);
+
+ vm.expectEmit(true, true, true, true);
+ emit SetConfig(-int64(10), uint32(180 seconds), uint128(411));
+ minter.setConfig(-int64(10), uint32(180 seconds), uint128(411));
+
+ (num, hop, zzz, lot) = minter.config();
+ assertEq(num, -int64(10));
+ assertEq(hop, 180);
+ assertEq(zzz, 0);
+ assertEq(lot, 411);
+ }
+
+ function testDrawWipeByKeeper() public {
+ minter.setConfig(int64(10), uint32(1 hours), uint128(1_000 * WAD));
+
+ assertEq(usds.balanceOf(address(buffer)), 0);
+ (int64 num, uint32 hop, uint32 zzz, uint128 lot) = minter.config();
+ assertEq(num, 10);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, 0);
+ assertEq(lot, 1_000 * WAD);
+
+ vm.expectEmit(true, true, true, true);
+ emit Draw(uint128(1_000 * WAD));
+ vm.prank(KEEPER); minter.draw();
+
+ assertEq(usds.balanceOf(address(buffer)), 1_000 * WAD);
+ (num, hop, zzz, lot) = minter.config();
+ assertEq(num, 9);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, block.timestamp);
+ assertEq(lot, 1_000 * WAD);
+
+ vm.warp(block.timestamp + 1 hours - 1);
+ vm.expectRevert("VaultMinter/too-soon");
+ vm.prank(KEEPER); minter.draw();
+
+ vm.warp(block.timestamp + 1);
+ vm.prank(KEEPER); minter.draw();
+
+ assertEq(usds.balanceOf(address(buffer)), 2_000 * WAD);
+ (num, hop, zzz, lot) = minter.config();
+ assertEq(num, 8);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, block.timestamp);
+ assertEq(lot, 1_000 * WAD);
+
+ minter.setConfig(-int64(10), uint32(1 hours), uint128(100 * WAD));
+
+ (num, hop, zzz, lot) = minter.config();
+ assertEq(num, -10);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, 0);
+ assertEq(lot, 100 * WAD);
+
+ vm.expectEmit(true, true, true, true);
+ emit Wipe(uint128(100 * WAD));
+ vm.prank(KEEPER); minter.wipe();
+
+ assertEq(usds.balanceOf(address(buffer)), 1_900 * WAD);
+ (num, hop, zzz, lot) = minter.config();
+ assertEq(num, -9);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, block.timestamp);
+ assertEq(lot, 100 * WAD);
+
+ vm.warp(block.timestamp + 1 hours - 1);
+ vm.expectRevert("VaultMinter/too-soon");
+ vm.prank(KEEPER); minter.wipe();
+
+ vm.warp(block.timestamp + 1);
+ vm.prank(KEEPER); minter.wipe();
+
+ assertEq(usds.balanceOf(address(buffer)), 1_800 * WAD);
+ (num, hop, zzz, lot) = minter.config();
+ assertEq(num, -8);
+ assertEq(hop, 1 hours);
+ assertEq(zzz, block.timestamp);
+ assertEq(lot, 100 * WAD);
+ }
+
+ function testMintBurnExceedingNum() public {
+ vm.expectRevert("VaultMinter/exceeds-num");
+ vm.prank(KEEPER); minter.draw();
+ vm.expectRevert("VaultMinter/exceeds-num");
+ vm.prank(KEEPER); minter.wipe();
+ }
+}
diff --git a/test/funnels/callees/SwapperCalleePsm.t.sol b/test/funnels/callees/SwapperCalleePsm.t.sol
new file mode 100644
index 00000000..10e68590
--- /dev/null
+++ b/test/funnels/callees/SwapperCalleePsm.t.sol
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { SwapperCalleePsm } from "src/funnels/callees/SwapperCalleePsm.sol";
+import { PsmMock } from "test/mocks/PsmMock.sol";
+
+interface GemLike {
+ function balanceOf(address) external view returns (uint256);
+ function transfer(address, uint256) external;
+ function decimals() external view returns (uint8);
+}
+
+contract SwapperCalleePsmTest is DssTest {
+
+ PsmMock psm;
+ PsmMock psmUSDT;
+ SwapperCalleePsm callee;
+ SwapperCalleePsm calleeUSDT;
+
+ address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
+ address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
+ address constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
+
+ function setUp() public {
+ vm.createSelectFork(vm.envString("ETH_RPC_URL"));
+
+ psm = new PsmMock(DAI, USDC);
+ callee = new SwapperCalleePsm(address(psm));
+ psm.rely(address(callee));
+ callee.rely(address(this));
+
+ psmUSDT = new PsmMock(DAI, USDT);
+ calleeUSDT = new SwapperCalleePsm(address(psmUSDT));
+ psmUSDT.rely(address(calleeUSDT));
+ calleeUSDT.rely(address(this));
+
+ deal(DAI, address(this), 1_000_000 * WAD, true);
+ deal(DAI, address(psm), 1_000_000 * WAD, true);
+ deal(DAI, address(psmUSDT), 1_000_000 * WAD, true);
+ deal(USDC, address(this), 1_000_000 * 10**6, true);
+ deal(USDC, psm.pocket(), 1_000_000 * 10**6, true);
+ deal(USDT, address(this), 1_000_000 * 10**6, true);
+ deal(USDT, psmUSDT.pocket(), 1_000_000 * 10**6, true);
+ }
+
+ function testConstructor() public {
+ vm.expectEmit(true, true, true, true);
+ emit Rely(address(this));
+ SwapperCalleePsm c = new SwapperCalleePsm(address(psm));
+ assertEq(c.psm(), address(psm));
+ assertEq(c.gem(), USDC);
+ assertEq(c.to18ConversionFactor(), 10**12);
+ assertEq(c.wards(address(this)), 1);
+ }
+
+ function testAuth() public {
+ checkAuth(address(callee), "SwapperCalleePsm");
+ }
+
+ function testModifiers() public {
+ bytes4[] memory authedMethods = new bytes4[](1);
+ authedMethods[0] = callee.swapCallback.selector;
+
+ vm.startPrank(address(0xBEEF));
+ checkModifier(address(callee), "SwapperCalleePsm/not-authorized", authedMethods);
+ vm.stopPrank();
+ }
+
+ function checkPsmSwap(SwapperCalleePsm callee_, address from, address to) public {
+ uint256 prevFrom = GemLike(from).balanceOf(address(this));
+ uint256 prevTo = GemLike(to).balanceOf(address(this));
+ uint8 fromDecimals = GemLike(from).decimals();
+ uint8 toDecimals = GemLike(to).decimals();
+
+ GemLike(from).transfer(address(callee_), 10_000 * 10**fromDecimals);
+ callee_.swapCallback(from, to, 10_000 * 10**fromDecimals, 0, address(this), "");
+
+ assertEq(GemLike(from).balanceOf(address(this)), prevFrom - 10_000 * 10**fromDecimals);
+ assertEq(GemLike(to ).balanceOf(address(this)), prevTo + 10_000 * 10**toDecimals );
+ assertEq(GemLike(from).balanceOf(address(callee_)), 0);
+ assertEq(GemLike(to ).balanceOf(address(callee_)), 0);
+ }
+
+ function testDaiToGemSwap() public {
+ checkPsmSwap(callee, DAI, USDC);
+ checkPsmSwap(calleeUSDT, DAI, USDT);
+ }
+
+ function testGemToDaiSwap() public {
+ checkPsmSwap(callee, USDC, DAI);
+ checkPsmSwap(calleeUSDT, DAI, USDT);
+ }
+}
diff --git a/test/funnels/callees/SwapperCalleeUniV3.t.sol b/test/funnels/callees/SwapperCalleeUniV3.t.sol
new file mode 100644
index 00000000..b8e4730e
--- /dev/null
+++ b/test/funnels/callees/SwapperCalleeUniV3.t.sol
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+import { SwapperCalleeUniV3 } from "src/funnels/callees/SwapperCalleeUniV3.sol";
+
+interface GemLike {
+ function balanceOf(address) external view returns (uint256);
+ function transfer(address, uint256) external;
+ function decimals() external view returns (uint8);
+}
+
+contract SwapperCalleeUniV3Test is DssTest {
+
+ SwapperCalleeUniV3 public callee;
+
+ address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
+ address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
+ address constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
+ address constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
+
+ function setUp() public {
+ vm.createSelectFork(vm.envString("ETH_RPC_URL"));
+
+ callee = new SwapperCalleeUniV3(UNIV3_ROUTER);
+
+ deal(DAI, address(this), 1_000_000 * WAD, true);
+ deal(USDC, address(this), 1_000_000 * 10**6, true);
+ deal(USDT, address(this), 1_000_000 * 10**6, true);
+ }
+
+ function testConstructor() public {
+ SwapperCalleeUniV3 c = new SwapperCalleeUniV3(address(0xBEEF));
+ assertEq(address(c.uniV3Router()), address(0xBEEF));
+ }
+
+ function checkStableSwap(address from, address to, bytes memory path) public {
+ uint256 prevFrom = GemLike(from).balanceOf(address(this));
+ uint256 prevTo = GemLike(to).balanceOf(address(this));
+ uint8 fromDecimals = GemLike(from).decimals();
+ uint8 toDecimals = GemLike(to).decimals();
+
+ GemLike(from).transfer(address(callee), 10_000 * 10**fromDecimals);
+ callee.swapCallback(from, to, 10_000 * 10**fromDecimals, 9000 * 10**toDecimals, address(this), path);
+
+ assertEq(GemLike(from).balanceOf(address(this)), prevFrom - 10_000 * 10**fromDecimals);
+ assertGe(GemLike(to).balanceOf(address(this)), prevTo + 9000 * 10**toDecimals);
+ assertEq(GemLike(from).balanceOf(address(callee)), 0);
+ assertEq(GemLike(to).balanceOf(address(callee)), 0);
+ }
+
+ function testSwapUsdt() public {
+ bytes memory USDT_DAI_PATH = abi.encodePacked(USDT, uint24(100), DAI);
+ checkStableSwap(USDT, DAI, USDT_DAI_PATH);
+ checkStableSwap(USDT, DAI, USDT_DAI_PATH); // swapping a 2nd time to verify that USDT allowance has been cleared after the 1st swap
+ }
+
+ function testSwapShortPath() public {
+ bytes memory DAI_USDC_PATH = abi.encodePacked(DAI, uint24(100), USDC);
+ checkStableSwap(DAI, USDC, DAI_USDC_PATH);
+ }
+
+ function testSwapLongPath() public {
+ bytes memory USDC_USDT_DAI_PATH = abi.encodePacked(USDC, uint24(100), USDT, uint24(100), DAI);
+ checkStableSwap(USDC, DAI, USDC_USDT_DAI_PATH);
+ }
+
+ function testSwapInvalidPath() public {
+ bytes memory USDT_DAI_PATH = abi.encodePacked(USDT, uint24(100), DAI);
+
+ vm.expectRevert("SwapperCalleeUniV3/invalid-path");
+ this.checkStableSwap(USDC, DAI, USDT_DAI_PATH); // src != path[0]
+ }
+}
diff --git a/test/integration/Deployment.t.sol b/test/integration/Deployment.t.sol
new file mode 100644
index 00000000..5cb80411
--- /dev/null
+++ b/test/integration/Deployment.t.sol
@@ -0,0 +1,497 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+import "dss-test/DssTest.sol";
+
+import { AllocatorSharedInstance, AllocatorIlkInstance } from "deploy/AllocatorInstances.sol";
+import { AllocatorIlkFunnelInstance } from "deploy/funnels/AllocatorFunnelInstance.sol";
+import { AllocatorDeploy } from "deploy/AllocatorDeploy.sol";
+import { AllocatorFunnelDeploy } from "deploy/funnels/AllocatorFunnelDeploy.sol";
+import { AllocatorInit, AllocatorIlkConfig } from "deploy/AllocatorInit.sol";
+import { AllocatorFunnelInit, AllocatorIlkFunnelConfig } from "deploy/funnels/AllocatorFunnelInit.sol";
+
+import { SwapperCalleeUniV3 } from "src/funnels/callees/SwapperCalleeUniV3.sol";
+
+import { GemMock } from "test/mocks/GemMock.sol";
+import { UsdsJoinMock } from "test/mocks/UsdsJoinMock.sol";
+import { VatMock } from "test/mocks/VatMock.sol";
+import { AllocatorConduitMock } from "test/mocks/AllocatorConduitMock.sol";
+
+import { AllocatorRoles } from "src/AllocatorRoles.sol";
+import { AllocatorRegistry } from "src/AllocatorRegistry.sol";
+import { AllocatorVault } from "src/AllocatorVault.sol";
+import { AllocatorBuffer } from "src/AllocatorBuffer.sol";
+import { Swapper } from "src/funnels/Swapper.sol";
+import { DepositorUniV3 } from "src/funnels/DepositorUniV3.sol";
+import { VaultMinter } from "src/funnels/automation/VaultMinter.sol";
+import { StableSwapper } from "src/funnels/automation/StableSwapper.sol";
+import { StableDepositorUniV3 } from "src/funnels/automation/StableDepositorUniV3.sol";
+import { ConduitMover } from "src/funnels/automation/ConduitMover.sol";
+
+interface GemLike {
+ function allowance(address, address) external view returns (uint256);
+}
+
+interface WardsLike {
+ function wards(address) external view returns (uint256);
+}
+
+interface ChainlogLike {
+ function getAddress(bytes32) external view returns (address);
+}
+
+interface IlkRegistryLike {
+ function count() external view returns (uint256);
+ function pos(bytes32) external view returns (uint256);
+ function class(bytes32) external view returns (uint256);
+ function gem(bytes32) external view returns (address);
+ function pip(bytes32) external view returns (address);
+ function join(bytes32) external view returns (address);
+ function xlip(bytes32) external view returns (address);
+ function dec(bytes32) external view returns (uint256);
+ function symbol(bytes32) external view returns (string memory);
+ function name(bytes32) external view returns (string memory);
+}
+
+interface AutoLineLike {
+ function ilks(bytes32) external view returns (uint256, uint256, uint48, uint48, uint48);
+}
+
+contract DeploymentTest is DssTest {
+
+ using stdStorage for StdStorage;
+
+ // existing contracts
+ address constant LOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F;
+ address constant UNIV3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
+ address constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
+
+ // existing contracts to be fetched from chainlog
+ DssInstance dss;
+ address ILK_REGISTRY;
+ address PAUSE_PROXY;
+ address USDC;
+
+ // actors
+ address constant allocatorProxy = address(0x1);
+ address constant facilitator1 = address(0x2);
+ address constant facilitator2 = address(0x3);
+ address constant vaultMinterKeeper1 = address(0x4);
+ address constant vaultMinterKeeper2 = address(0x5);
+ address constant stableSwapperKeeper1 = address(0x6);
+ address constant stableSwapperKeeper2 = address(0x7);
+ address constant stableDepositorUniV3Keeper1 = address(0x8);
+ address constant stableDepositorUniV3Keeper2 = address(0x9);
+ address constant conduitMoverKeeper1 = address(0xA);
+ address constant conduitMoverKeeper2 = address(0xB);
+
+ // roles
+ uint8 constant facilitatorRole = uint8(1);
+ uint8 constant automationRole = uint8(2);
+
+ // contracts to be deployed
+ address usds;
+ address usdsJoin;
+ address uniV3Callee;
+ address conduit1;
+ address conduit2;
+
+ // storage to be initiated on setup
+ AllocatorSharedInstance sharedInst;
+ AllocatorIlkInstance ilkInst;
+ AllocatorIlkFunnelInstance ilkFunnelInst;
+ bytes usdcDaiPath;
+ bytes daiUsdcPath;
+
+ // constants
+ int24 constant REF_TICK = -276324; // tick corresponding to 1 DAI = 1 USDC calculated as ~= math.log(10**(-12))/math.log(1.0001)
+ bytes32 constant ILK = "ILK-A";
+
+ function setUp() public {
+ vm.createSelectFork(vm.envString("ETH_RPC_URL"));
+
+ dss = MCD.loadFromChainlog(LOG);
+ PAUSE_PROXY = ChainlogLike(LOG).getAddress("MCD_PAUSE_PROXY");
+ ILK_REGISTRY = ChainlogLike(LOG).getAddress("ILK_REGISTRY");
+ USDC = ChainlogLike(LOG).getAddress("USDC");
+
+ usds = address(new GemMock(0));
+ usdsJoin = address(new UsdsJoinMock(VatMock(address(dss.vat)), GemMock(usds)));
+ uniV3Callee = address(new SwapperCalleeUniV3(UNIV3_ROUTER));
+
+ usdcDaiPath = abi.encodePacked(USDC, uint24(100), address(dss.dai));
+ daiUsdcPath = abi.encodePacked(address(dss.dai), uint24(100), USDC);
+
+ sharedInst = AllocatorDeploy.deployShared(address(this), PAUSE_PROXY);
+ ilkInst = AllocatorDeploy.deployIlk({
+ deployer : address(this),
+ owner : PAUSE_PROXY,
+ roles : sharedInst.roles,
+ ilk : ILK,
+ usdsJoin : usdsJoin
+ });
+ ilkFunnelInst = AllocatorFunnelDeploy.deployIlkFunnel({
+ deployer : address(this),
+ owner : allocatorProxy,
+ roles : sharedInst.roles,
+ ilk : ILK,
+ uniV3Factory : UNIV3_FACTORY,
+ vault : ilkInst.vault,
+ buffer : ilkInst.buffer
+ });
+
+ // Deploy conduits (assumed to be done separately than the current allocator ilkInst deploy)
+ conduit1 = address(new AllocatorConduitMock(sharedInst.roles, sharedInst.registry));
+ conduit2 = address(new AllocatorConduitMock(sharedInst.roles, sharedInst.registry));
+ }
+
+ function emulateSpell() internal {
+ vm.startPrank(PAUSE_PROXY);
+ AllocatorInit.initShared(dss, sharedInst);
+
+ address[] memory swapTokens = new address[](1);
+ swapTokens[0] = address(dss.dai);
+
+ address[] memory depositTokens = new address[](2);
+ depositTokens[0] = address(dss.dai);
+ depositTokens[1] = USDC;
+
+ address[] memory facilitators = new address[](2);
+ facilitators[0] = facilitator1;
+ facilitators[1] = facilitator2;
+
+ address[] memory vaultMinterKeepers = new address[](2);
+ vaultMinterKeepers[0] = vaultMinterKeeper1;
+ vaultMinterKeepers[1] = vaultMinterKeeper2;
+
+ address[] memory stableSwapperKeepers = new address[](2);
+ stableSwapperKeepers[0] = stableSwapperKeeper1;
+ stableSwapperKeepers[1] = stableSwapperKeeper2;
+
+ address[] memory stableDepositorUniV3Keepers = new address[](2);
+ stableDepositorUniV3Keepers[0] = stableDepositorUniV3Keeper1;
+ stableDepositorUniV3Keepers[1] = stableDepositorUniV3Keeper2;
+
+ address[] memory conduitMoverKeepers = new address[](2);
+ conduitMoverKeepers[0] = conduitMoverKeeper1;
+ conduitMoverKeepers[1] = conduitMoverKeeper2;
+
+ AllocatorIlkConfig memory cfg = AllocatorIlkConfig({
+ ilk : ILK,
+ duty : 1000000001243680656318820312,
+ maxLine : 100_000_000 * RAD,
+ gap : 10_000_000 * RAD,
+ ttl : 1 days,
+ allocatorProxy : allocatorProxy,
+ ilkRegistry : ILK_REGISTRY
+ });
+
+ AllocatorInit.initIlk(dss, sharedInst, ilkInst, cfg);
+ vm.stopPrank();
+
+ // Init conduits (assumed to be done separately than the current allocator ilkInst init)
+ vm.startPrank(allocatorProxy);
+ AllocatorIlkFunnelConfig memory funnelCfg = AllocatorIlkFunnelConfig({
+ ilk : ILK,
+ allocatorProxy : allocatorProxy,
+ facilitatorRole : facilitatorRole,
+ automationRole : automationRole,
+ facilitators : facilitators,
+ vaultMinterKeepers : vaultMinterKeepers,
+ stableSwapperKeepers : stableSwapperKeepers,
+ stableDepositorUniV3Keepers : stableDepositorUniV3Keepers,
+ conduitMoverKeepers : conduitMoverKeepers,
+ swapTokens : swapTokens,
+ depositTokens : depositTokens,
+ uniV3Factory : UNIV3_FACTORY
+ });
+ AllocatorFunnelInit.initIlkFunnel(sharedInst, ilkInst, ilkFunnelInst, funnelCfg);
+
+ AllocatorRoles(sharedInst.roles).setUserRole(ILK, address(ilkFunnelInst.conduitMover), automationRole, true);
+
+ AllocatorRoles(sharedInst.roles).setRoleAction(ILK, automationRole, conduit1, AllocatorConduitMock.deposit.selector, true);
+ AllocatorRoles(sharedInst.roles).setRoleAction(ILK, automationRole, conduit1, AllocatorConduitMock.withdraw.selector, true);
+ AllocatorRoles(sharedInst.roles).setRoleAction(ILK, automationRole, conduit2, AllocatorConduitMock.deposit.selector, true);
+ AllocatorRoles(sharedInst.roles).setRoleAction(ILK, automationRole, conduit2, AllocatorConduitMock.withdraw.selector, true);
+
+ AllocatorBuffer(ilkInst.buffer).approve(USDC, conduit1, type(uint256).max);
+ AllocatorBuffer(ilkInst.buffer).approve(USDC, conduit2, type(uint256).max);
+ vm.stopPrank();
+ }
+
+ function testInitSharedValues() public {
+ emulateSpell();
+
+ assertEq(ChainlogLike(LOG).getAddress("ALLOCATOR_ROLES"), sharedInst.roles);
+ assertEq(ChainlogLike(LOG).getAddress("ALLOCATOR_REGISTRY"), sharedInst.registry);
+ }
+
+ function testInitIlkValues() public {
+ uint256 previousLine = dss.vat.Line();
+ uint256 previousIlkRegistryCount = IlkRegistryLike(ILK_REGISTRY).count();
+
+ emulateSpell();
+
+ (, uint256 rate, uint256 spot, uint256 line,) = dss.vat.ilks(ILK);
+ assertEq(rate, RAY);
+ assertEq(spot, 10**18 * RAY * 10**9 / dss.spotter.par());
+ assertEq(line, 10_000_000 * RAD);
+ assertEq(dss.vat.Line(), previousLine + 10_000_000 * RAD);
+
+ {
+ AutoLineLike autoLine = AutoLineLike(ChainlogLike(LOG).getAddress("MCD_IAM_AUTO_LINE"));
+ (uint256 maxline, uint256 gap, uint48 ttl, uint48 last, uint48 lastInc) = autoLine.ilks(ILK);
+ assertEq(maxline, 100_000_000 * RAD);
+ assertEq(gap, 10_000_000 * RAD);
+ assertEq(ttl, 1 days);
+ assertEq(last, 0);
+ assertEq(lastInc, 0);
+ }
+
+ (uint256 duty, uint256 rho) = dss.jug.ilks(ILK);
+ assertEq(duty, 1000000001243680656318820312);
+ assertEq(rho, block.timestamp);
+
+ (address pip, uint256 mat) = dss.spotter.ilks(ILK);
+ assertEq(pip, sharedInst.oracle);
+ assertEq(mat, RAY);
+
+ assertEq(dss.vat.gem(ILK, ilkInst.vault), 0);
+ (uint256 ink, uint256 art) = dss.vat.urns(ILK, ilkInst.vault);
+ assertEq(ink, 1_000_000_000_000 * WAD);
+ assertEq(art, 0);
+
+ assertEq(AllocatorRegistry(sharedInst.registry).buffers(ILK), ilkInst.buffer);
+ assertEq(address(AllocatorVault(ilkInst.vault).jug()), address(dss.jug));
+
+ assertEq(GemLike(usds).allowance(ilkInst.buffer, ilkInst.vault), type(uint256).max);
+ assertEq(GemLike(address(dss.dai)).allowance(ilkInst.buffer, ilkFunnelInst.swapper), type(uint256).max);
+ assertEq(GemLike(address(dss.dai)).allowance(ilkInst.buffer, ilkFunnelInst.depositorUniV3), type(uint256).max);
+ assertEq(GemLike(USDC).allowance(ilkInst.buffer, ilkFunnelInst.depositorUniV3), type(uint256).max);
+
+ assertEq(AllocatorRoles(sharedInst.roles).ilkAdmins(ILK), allocatorProxy);
+
+ assertEq(AllocatorRoles(sharedInst.roles).hasUserRole(ILK, facilitator1, facilitatorRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasUserRole(ILK, facilitator2, facilitatorRole), true);
+
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkInst.vault, AllocatorVault.draw.selector, facilitatorRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkInst.vault, AllocatorVault.wipe.selector, facilitatorRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkFunnelInst.swapper, Swapper.swap.selector, facilitatorRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkFunnelInst.depositorUniV3, DepositorUniV3.deposit.selector, facilitatorRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkFunnelInst.depositorUniV3, DepositorUniV3.withdraw.selector, facilitatorRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkFunnelInst.depositorUniV3, DepositorUniV3.collect.selector, facilitatorRole), true);
+
+ assertEq(AllocatorRoles(sharedInst.roles).hasUserRole(ILK, ilkFunnelInst.stableSwapper, automationRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasUserRole(ILK, ilkFunnelInst.stableDepositorUniV3, automationRole), true);
+
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkFunnelInst.swapper, Swapper.swap.selector, automationRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkFunnelInst.depositorUniV3, DepositorUniV3.deposit.selector, automationRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkFunnelInst.depositorUniV3, DepositorUniV3.withdraw.selector, automationRole), true);
+ assertEq(AllocatorRoles(sharedInst.roles).hasActionRole(ILK, ilkFunnelInst.depositorUniV3, DepositorUniV3.collect.selector, automationRole), true);
+
+ assertEq(WardsLike(ilkFunnelInst.vaultMinter).wards(facilitator1), 1);
+ assertEq(WardsLike(ilkFunnelInst.vaultMinter).wards(facilitator2), 1);
+ assertEq(WardsLike(ilkFunnelInst.stableSwapper).wards(facilitator1), 1);
+ assertEq(WardsLike(ilkFunnelInst.stableSwapper).wards(facilitator2), 1);
+ assertEq(WardsLike(ilkFunnelInst.stableDepositorUniV3).wards(facilitator1), 1);
+ assertEq(WardsLike(ilkFunnelInst.stableDepositorUniV3).wards(facilitator2), 1);
+ assertEq(WardsLike(ilkFunnelInst.conduitMover).wards(facilitator1), 1);
+ assertEq(WardsLike(ilkFunnelInst.conduitMover).wards(facilitator2), 1);
+
+ assertEq(VaultMinter(ilkFunnelInst.vaultMinter).buds(vaultMinterKeeper1), 1);
+ assertEq(VaultMinter(ilkFunnelInst.vaultMinter).buds(vaultMinterKeeper2), 1);
+ assertEq(StableSwapper(ilkFunnelInst.stableSwapper).buds(stableSwapperKeeper1), 1);
+ assertEq(StableSwapper(ilkFunnelInst.stableSwapper).buds(stableSwapperKeeper2), 1);
+ assertEq(StableDepositorUniV3(ilkFunnelInst.stableDepositorUniV3).buds(stableDepositorUniV3Keeper1), 1);
+ assertEq(StableDepositorUniV3(ilkFunnelInst.stableDepositorUniV3).buds(stableDepositorUniV3Keeper2), 1);
+ assertEq(ConduitMover(ilkFunnelInst.conduitMover).buds(conduitMoverKeeper1), 1);
+ assertEq(ConduitMover(ilkFunnelInst.conduitMover).buds(conduitMoverKeeper2), 1);
+
+ assertEq(WardsLike(ilkInst.vault).wards(PAUSE_PROXY), 0);
+ assertEq(WardsLike(ilkInst.vault).wards(allocatorProxy), 1);
+
+ assertEq(WardsLike(ilkInst.buffer).wards(PAUSE_PROXY), 0);
+ assertEq(WardsLike(ilkInst.buffer).wards(allocatorProxy), 1);
+
+ assertEq(WardsLike(ilkFunnelInst.swapper).wards(PAUSE_PROXY), 0);
+ assertEq(WardsLike(ilkFunnelInst.swapper).wards(allocatorProxy), 1);
+
+ assertEq(WardsLike(ilkFunnelInst.depositorUniV3).wards(PAUSE_PROXY), 0);
+ assertEq(WardsLike(ilkFunnelInst.depositorUniV3).wards(allocatorProxy), 1);
+
+ assertEq(WardsLike(ilkFunnelInst.vaultMinter).wards(PAUSE_PROXY), 0);
+ assertEq(WardsLike(ilkFunnelInst.vaultMinter).wards(allocatorProxy), 1);
+
+ assertEq(WardsLike(ilkFunnelInst.stableSwapper).wards(PAUSE_PROXY), 0);
+ assertEq(WardsLike(ilkFunnelInst.stableSwapper).wards(allocatorProxy), 1);
+
+ assertEq(WardsLike(ilkFunnelInst.stableDepositorUniV3).wards(PAUSE_PROXY), 0);
+ assertEq(WardsLike(ilkFunnelInst.stableDepositorUniV3).wards(allocatorProxy), 1);
+
+ assertEq(WardsLike(ilkFunnelInst.conduitMover).wards(PAUSE_PROXY), 0);
+ assertEq(WardsLike(ilkFunnelInst.conduitMover).wards(allocatorProxy), 1);
+
+ assertEq(ChainlogLike(LOG).getAddress("ILK_A_VAULT"), ilkInst.vault);
+ assertEq(ChainlogLike(LOG).getAddress("ILK_A_BUFFER"), ilkInst.buffer);
+ assertEq(ChainlogLike(LOG).getAddress("PIP_ILK_A"), sharedInst.oracle);
+
+ assertEq(IlkRegistryLike(ILK_REGISTRY).count(), previousIlkRegistryCount + 1);
+ assertEq(IlkRegistryLike(ILK_REGISTRY).pos(ILK), previousIlkRegistryCount);
+ assertEq(IlkRegistryLike(ILK_REGISTRY).join(ILK), address(0));
+ assertEq(IlkRegistryLike(ILK_REGISTRY).gem(ILK), address(0));
+ assertEq(IlkRegistryLike(ILK_REGISTRY).dec(ILK), 0);
+ assertEq(IlkRegistryLike(ILK_REGISTRY).class(ILK), 5);
+ assertEq(IlkRegistryLike(ILK_REGISTRY).pip(ILK), sharedInst.oracle);
+ assertEq(IlkRegistryLike(ILK_REGISTRY).xlip(ILK), address(0));
+ assertEq(IlkRegistryLike(ILK_REGISTRY).name(ILK), string("ILK-A"));
+ assertEq(IlkRegistryLike(ILK_REGISTRY).symbol(ILK), string("ILK-A"));
+ }
+
+ function testVaultDrawWipeFromFacilitator() public {
+ emulateSpell();
+
+ vm.prank(facilitator1); AllocatorVault(ilkInst.vault).draw(1_000 * WAD);
+ vm.prank(facilitator1); AllocatorVault(ilkInst.vault).wipe(1_000 * WAD);
+ }
+
+ function testVaultDrawWipeFromFromKeeper() public {
+ emulateSpell();
+
+ vm.prank(facilitator1); VaultMinter(ilkFunnelInst.vaultMinter).setConfig(1, 1 hours, uint96(1_000 * WAD));
+ vm.prank(vaultMinterKeeper1); VaultMinter(ilkFunnelInst.vaultMinter).draw();
+
+ vm.prank(facilitator1); VaultMinter(ilkFunnelInst.vaultMinter).setConfig(-1, 1 hours, uint96(1_000 * WAD));
+ vm.prank(vaultMinterKeeper1); VaultMinter(ilkFunnelInst.vaultMinter).wipe();
+ }
+
+ function testSwapFromFacilitator() public {
+ emulateSpell();
+
+ deal(address(dss.dai), ilkInst.buffer, 1_000 * WAD);
+
+ vm.prank(allocatorProxy); Swapper(ilkFunnelInst.swapper).setLimits(address(dss.dai), USDC, uint96(1_000 * WAD), 1 hours);
+ vm.prank(facilitator1); Swapper(ilkFunnelInst.swapper).swap(address(dss.dai), USDC, 1_000 * WAD, 990 * 10**6 , uniV3Callee, daiUsdcPath);
+ }
+
+ function testSwapFromKeeper() public {
+ emulateSpell();
+
+ deal(address(dss.dai), ilkInst.buffer, 1_000 * WAD);
+
+ vm.prank(allocatorProxy); Swapper(ilkFunnelInst.swapper).setLimits(address(dss.dai), USDC, uint96(1_000 * WAD), 1 hours);
+ vm.prank(facilitator1); StableSwapper(ilkFunnelInst.stableSwapper).setConfig(address(dss.dai), USDC, 1, 1 hours, uint96(1_000 * WAD), uint96(990 * 10**6));
+ vm.prank(stableSwapperKeeper1); StableSwapper(ilkFunnelInst.stableSwapper).swap(address(dss.dai), USDC, 990 * 10**6, uniV3Callee, daiUsdcPath);
+ }
+
+ function testDepositWithdrawCollectFromFacilitator() public {
+ emulateSpell();
+
+ deal(address(dss.dai), ilkInst.buffer, 1_000 * WAD);
+ deal(USDC, ilkInst.buffer, 1_000 * 10**6);
+
+ vm.prank(allocatorProxy); DepositorUniV3(ilkFunnelInst.depositorUniV3).setLimits(address(dss.dai), USDC, uint24(100), uint96(2_000 * WAD), uint96(2_000 * 10**6), 1 hours);
+ DepositorUniV3.LiquidityParams memory dp = DepositorUniV3.LiquidityParams({
+ gem0 : address(dss.dai),
+ gem1 : USDC,
+ fee : uint24(100),
+ tickLower : REF_TICK - 100,
+ tickUpper : REF_TICK + 100,
+ liquidity : 0,
+ amt0Desired: 1_000 * WAD,
+ amt1Desired: 1_000 * 10**6,
+ amt0Min : 900 * WAD,
+ amt1Min : 900 * 10**6
+ });
+
+ vm.prank(facilitator1); DepositorUniV3(ilkFunnelInst.depositorUniV3).deposit(dp);
+ vm.prank(facilitator1); DepositorUniV3(ilkFunnelInst.depositorUniV3).withdraw(dp, false);
+
+ DepositorUniV3.CollectParams memory cp = DepositorUniV3.CollectParams({
+ gem0 : address(dss.dai),
+ gem1 : USDC,
+ fee : uint24(100),
+ tickLower: REF_TICK - 100,
+ tickUpper: REF_TICK + 100
+ });
+
+ vm.expectRevert(bytes("NP")); // we make sure it reverts since no fees to collect and not because the call is unauthorized
+ vm.prank(facilitator1); DepositorUniV3(ilkFunnelInst.depositorUniV3).collect(cp);
+ }
+
+ function testDepositWithdrawCollectFromKeeper() public {
+ emulateSpell();
+
+ deal(address(dss.dai), ilkInst.buffer, 1_000 * WAD);
+ deal(USDC, ilkInst.buffer, 1_000 * 10**6);
+
+ vm.prank(allocatorProxy); DepositorUniV3(ilkFunnelInst.depositorUniV3).setLimits(address(dss.dai), USDC, uint24(100), uint96(2_000 * WAD), uint96(2_000 * 10**6), 1 hours);
+
+ vm.prank(facilitator1); StableDepositorUniV3(ilkFunnelInst.stableDepositorUniV3).setConfig(address(dss.dai), USDC, uint24(100), REF_TICK - 100, REF_TICK + 100, 1, 1 hours, uint96(1_000 * WAD), uint96(1000 * 10**6), 0, 0);
+ vm.prank(stableDepositorUniV3Keeper1); StableDepositorUniV3(ilkFunnelInst.stableDepositorUniV3).deposit(address(dss.dai), USDC, uint24(100), REF_TICK - 100, REF_TICK + 100, 0, 0);
+
+ vm.prank(facilitator1); StableDepositorUniV3(ilkFunnelInst.stableDepositorUniV3).setConfig(address(dss.dai), USDC, uint24(100), REF_TICK - 100, REF_TICK + 100, -1, 1 hours, uint96(1_000 * WAD), uint96(1000 * 10**6), 0, 0);
+ vm.prank(stableDepositorUniV3Keeper1); StableDepositorUniV3(ilkFunnelInst.stableDepositorUniV3).withdraw(address(dss.dai), USDC, uint24(100), REF_TICK - 100, REF_TICK + 100, 0, 0);
+
+ vm.expectRevert(bytes("NP")); // Reverts since no fees to collect and not because the call is unauthorized
+ vm.prank(stableDepositorUniV3Keeper1); StableDepositorUniV3(ilkFunnelInst.stableDepositorUniV3).collect(address(dss.dai), USDC, uint24(100), REF_TICK - 100, REF_TICK + 100);
+ }
+
+ function testMoveFromKeeper() public {
+ emulateSpell();
+
+ // Note that although the Conduits setup and init were not done by the tested contracts, we are testing the
+ // ConduitMover deployment, the facilitators ward on it and the keeper addition to it.
+
+ // Give conduit1 some funds
+ deal(USDC, ilkInst.buffer, 3_000 * 10**6, true);
+ vm.prank(ilkFunnelInst.conduitMover); AllocatorConduitMock(conduit1).deposit(ILK, USDC, 3_000 * 10**6);
+
+ vm.prank(facilitator1); ConduitMover(ilkFunnelInst.conduitMover).setConfig(conduit1, conduit2, USDC, 1, 1 hours, 3_000 * 10**6);
+ vm.prank(conduitMoverKeeper1); ConduitMover(ilkFunnelInst.conduitMover).move(conduit1, conduit2, USDC);
+ }
+
+ function testEndCage() public {
+ // This test doesn't mean ES is supported, just aims to check that in case of planned governance shutdown is needed, the End could handle well a huge number of ink
+ emulateSpell();
+
+ vm.prank(facilitator1); AllocatorVault(ilkInst.vault).draw(1_000_000 * WAD);
+
+ uint256 ink; uint256 art;
+ (ink, art) = dss.vat.urns(ILK, address(ilkInst.vault));
+ assertEq(ink, 1_000_000_000_000 * WAD);
+ assertEq(art, 1_000_000 * WAD);
+ assertEq(dss.vat.gem(ILK, address(dss.end)), 0);
+
+ vm.prank(PAUSE_PROXY); dss.end.cage();
+ dss.end.cage(ILK);
+ assertEq(dss.end.tag(ILK), RAY);
+ dss.end.skim(ILK, address(ilkInst.vault));
+
+ (ink, art) = dss.vat.urns(ILK, address(ilkInst.vault));
+ assertEq(ink, (1_000_000_000_000 - 1_000_000) * WAD);
+ assertEq(art, 0);
+ assertEq(dss.vat.gem(ILK, address(dss.end)), 1_000_000 * WAD);
+
+ stdstore.target(address(dss.vat)).sig("dai(address)").with_key(address(dss.vow)).depth(0).checked_write(uint256(0));
+ vm.warp(block.timestamp + dss.end.wait());
+ dss.end.thaw();
+
+ dss.end.flow(ILK);
+ assertEq(dss.end.fix(ILK), 1_000_000 * RAD / (dss.vat.debt() / RAY));
+ }
+}
diff --git a/test/mocks/AllocatorConduitMock.sol b/test/mocks/AllocatorConduitMock.sol
new file mode 100644
index 00000000..5f158024
--- /dev/null
+++ b/test/mocks/AllocatorConduitMock.sol
@@ -0,0 +1,110 @@
+// SPDX-FileCopyrightText: © 2023 Dai Foundation
+// SPDX-License-Identifier: AGPL-3.0-or-later
+//
+// 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 .
+
+pragma solidity ^0.8.16;
+
+import "src/IAllocatorConduit.sol";
+
+interface RolesLike {
+ function canCall(bytes32, address, address, bytes4) external view returns (bool);
+}
+
+interface RegistryLike {
+ function buffers(bytes32) external view returns (address);
+}
+
+interface GemLike {
+ function transfer(address, uint256) external;
+ function transferFrom(address, address, uint256) external;
+}
+
+contract AllocatorConduitMock is IAllocatorConduit {
+ // --- storage variables ---
+
+ mapping(address => uint256) public wards;
+ mapping(bytes32 => mapping(address => uint256)) public positions;
+
+ // --- immutables ---
+
+ RolesLike public immutable roles;
+ RegistryLike public immutable registry;
+
+ // --- events ---
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event SetRoles(bytes32 indexed ilk, address roles_);
+
+ // --- modifiers ---
+
+ modifier auth() {
+ require(wards[msg.sender] == 1, "AllocatorConduitMock/not-authorized");
+ _;
+ }
+
+ modifier ilkAuth(bytes32 ilk) {
+ require(roles.canCall(ilk, msg.sender, address(this), msg.sig), "AllocatorConduitMock/ilk-not-authorized");
+ _;
+ }
+
+ // --- constructor ---
+
+ constructor(address roles_, address registry_) {
+ roles = RolesLike(roles_);
+ registry = RegistryLike(registry_);
+ }
+
+ // --- getters ---
+
+ function maxDeposit(bytes32 ilk, address asset) external pure returns (uint256 maxDeposit_) {
+ ilk;asset;
+ maxDeposit_ = type(uint256).max;
+ }
+
+ function maxWithdraw(bytes32 ilk, address asset) external view returns (uint256 maxWithdraw_) {
+ maxWithdraw_ = positions[ilk][asset];
+ }
+
+ // --- admininstration ---
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ // --- functions ---
+
+ function deposit(bytes32 ilk, address asset, uint256 amount) external ilkAuth(ilk) {
+ address buffer = registry.buffers(ilk);
+ GemLike(asset).transferFrom(buffer, address(this), amount);
+ positions[ilk][asset] += amount;
+ emit Deposit(ilk, asset, buffer, amount);
+ }
+
+ function withdraw(bytes32 ilk, address asset, uint256 maxAmount) external ilkAuth(ilk) returns (uint256 amount) {
+ uint256 balance = positions[ilk][asset];
+ amount = balance < maxAmount ? balance : maxAmount;
+ positions[ilk][asset] = balance - amount;
+ address buffer = registry.buffers(ilk);
+ GemLike(asset).transfer(buffer, amount);
+ emit Withdraw(ilk, asset, buffer, amount);
+ }
+}
diff --git a/test/mocks/AuthedMock.sol b/test/mocks/AuthedMock.sol
new file mode 100644
index 00000000..52fec157
--- /dev/null
+++ b/test/mocks/AuthedMock.sol
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+interface RolesLike {
+ function canCall(bytes32, address, address, bytes4) external view returns (bool);
+}
+
+contract AuthedMock {
+ bool public flag;
+
+ RolesLike public immutable roles;
+ bytes32 public immutable ilk;
+
+ constructor(address roles_, bytes32 ilk_) {
+ roles = RolesLike(roles_);
+ ilk = ilk_;
+ }
+
+ modifier auth() {
+ require(roles.canCall(ilk, msg.sender, address(this), msg.sig), "AuthedMock/not-authorized");
+ _;
+ }
+
+ function exec() public auth {
+ flag = true;
+ }
+}
diff --git a/test/mocks/CalleeMock.sol b/test/mocks/CalleeMock.sol
new file mode 100644
index 00000000..d414fa7d
--- /dev/null
+++ b/test/mocks/CalleeMock.sol
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+interface GemLike {
+ function balanceOf(address) external view returns (uint256);
+ function transfer(address, uint256) external;
+}
+
+contract CalleeMock {
+ uint256 random;
+
+ function swapCallback(address, address dst, uint256, uint256, address, bytes calldata) external {
+ GemLike(dst).transfer(msg.sender, GemLike(dst).balanceOf(address(this)));
+ }
+}
diff --git a/test/mocks/Gem0Mock.sol b/test/mocks/Gem0Mock.sol
new file mode 100644
index 00000000..1c64022f
--- /dev/null
+++ b/test/mocks/Gem0Mock.sol
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import { GemMock } from "test/mocks/GemMock.sol";
+
+contract Gem0Mock is GemMock(1_000_000*10**18) {
+}
diff --git a/test/mocks/Gem1Mock.sol b/test/mocks/Gem1Mock.sol
new file mode 100644
index 00000000..2f437acc
--- /dev/null
+++ b/test/mocks/Gem1Mock.sol
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import { GemMock } from "test/mocks/GemMock.sol";
+
+contract Gem1Mock is GemMock(1_000_000*10**18) {
+}
diff --git a/test/mocks/GemMock.sol b/test/mocks/GemMock.sol
new file mode 100644
index 00000000..789e88a4
--- /dev/null
+++ b/test/mocks/GemMock.sol
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+contract GemMock {
+ mapping (address => uint256) public balanceOf;
+ mapping (address => mapping (address => uint256)) public allowance;
+
+ uint256 public totalSupply;
+
+ constructor(uint256 initialSupply) {
+ mint(msg.sender, initialSupply);
+ }
+
+ function approve(address spender, uint256 value) external returns (bool) {
+ allowance[msg.sender][spender] = value;
+ return true;
+ }
+
+ function transfer(address to, uint256 value) external returns (bool) {
+ uint256 balance = balanceOf[msg.sender];
+ require(balance >= value, "Gem/insufficient-balance");
+
+ unchecked {
+ balanceOf[msg.sender] = balance - value;
+ balanceOf[to] += value;
+ }
+ return true;
+ }
+
+ function transferFrom(address from, address to, uint256 value) external returns (bool) {
+ uint256 balance = balanceOf[from];
+ require(balance >= value, "Gem/insufficient-balance");
+
+ if (from != msg.sender) {
+ uint256 allowed = allowance[from][msg.sender];
+ if (allowed != type(uint256).max) {
+ require(allowed >= value, "Gem/insufficient-allowance");
+
+ unchecked {
+ allowance[from][msg.sender] = allowed - value;
+ }
+ }
+ }
+
+ unchecked {
+ balanceOf[from] = balance - value;
+ balanceOf[to] += value;
+ }
+ return true;
+ }
+
+ function mint(address to, uint256 value) public {
+ unchecked {
+ balanceOf[to] = balanceOf[to] + value;
+ }
+ totalSupply = totalSupply + value;
+ }
+
+ function burn(address from, uint256 value) external {
+ uint256 balance = balanceOf[from];
+ require(balance >= value, "Gem/insufficient-balance");
+
+ if (from != msg.sender) {
+ uint256 allowed = allowance[from][msg.sender];
+ if (allowed != type(uint256).max) {
+ require(allowed >= value, "Gem/insufficient-allowance");
+
+ unchecked {
+ allowance[from][msg.sender] = allowed - value;
+ }
+ }
+ }
+
+ unchecked {
+ balanceOf[from] = balance - value;
+ totalSupply = totalSupply - value;
+ }
+ }
+}
diff --git a/test/mocks/JugMock.sol b/test/mocks/JugMock.sol
new file mode 100644
index 00000000..33c2f080
--- /dev/null
+++ b/test/mocks/JugMock.sol
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import { VatMock } from "test/mocks/VatMock.sol";
+
+contract JugMock {
+ VatMock vat;
+
+ uint256 public duty = 1001 * 10**27 / 1000;
+ uint256 public rho = block.timestamp;
+
+ constructor(VatMock vat_) {
+ vat = vat_;
+ }
+
+ function drip(bytes32) external returns (uint256 rate) {
+ uint256 add = (duty - 10**27) * (block.timestamp - rho);
+ rate = vat.rate() + add;
+ vat.fold(add);
+ rho = block.timestamp;
+ }
+}
diff --git a/test/mocks/PoolUniV3Mock.sol b/test/mocks/PoolUniV3Mock.sol
new file mode 100644
index 00000000..8c3bce8f
--- /dev/null
+++ b/test/mocks/PoolUniV3Mock.sol
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+interface DepositorLike {
+ function uniswapV3MintCallback(uint256, uint256, bytes calldata) external;
+}
+
+interface GemLike {
+ function transfer(address, uint256) external;
+}
+
+contract PoolUniV3Mock {
+ address public gem0;
+ address public gem1;
+ uint24 public fee;
+
+ uint128 public random0;
+ uint128 public random1;
+ uint128 public random2;
+ uint128 public random3;
+
+ mapping (bytes32 => Position) public positions;
+
+ struct Position {
+ uint128 liquidity;
+ uint256 feeGrowthInside0LastX128;
+ uint256 feeGrowthInside1LastX128;
+ uint128 tokensOwed0;
+ uint128 tokensOwed1;
+ }
+
+ function mint(address, int24, int24, uint128, bytes calldata) external returns (uint128, uint128) {
+ DepositorLike(msg.sender).uniswapV3MintCallback(random0, random1, abi.encode(gem0, gem1, fee));
+
+ return (random0, random1);
+ }
+
+ function burn(int24, int24, uint128) external view returns (uint128, uint128) {
+ return (random0, random1);
+ }
+
+ function collect(address recipient, int24, int24, uint128 amt0R, uint128 amt1R) external returns (uint128, uint128) {
+ uint128 col0 = amt0R > random2 ? random2 : amt0R;
+ uint128 col1 = amt1R > random3 ? random3 : amt1R;
+ GemLike(gem0).transfer(recipient, col0);
+ GemLike(gem1).transfer(recipient, col1);
+ return (col0, col1);
+ }
+}
diff --git a/test/mocks/PsmMock.sol b/test/mocks/PsmMock.sol
new file mode 100644
index 00000000..bf3401be
--- /dev/null
+++ b/test/mocks/PsmMock.sol
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+pragma solidity ^0.8.16;
+
+interface GemLike {
+ function approve(address, uint256) external;
+ function transfer(address, uint256) external;
+ function transferFrom(address, address, uint256) external;
+ function decimals() external view returns (uint8);
+}
+
+contract PsmMock {
+ mapping(address => uint256) public wards;
+
+ address public immutable dai;
+ address public immutable gem;
+ uint256 public immutable to18ConversionFactor;
+
+ event Rely(address indexed usr);
+ event Deny(address indexed usr);
+ event SellGem(address indexed owner, uint256 value, uint256 fee);
+ event BuyGem(address indexed owner, uint256 value, uint256 fee);
+
+ modifier auth() {
+ require(wards[msg.sender] == 1, "PsmMock/not-authorized");
+ _;
+ }
+
+ constructor(address dai_, address gem_) {
+ dai = dai_;
+ gem = gem_;
+ to18ConversionFactor = 10**(18 - GemLike(gem_).decimals());
+
+ wards[msg.sender] = 1;
+ emit Rely(msg.sender);
+ }
+
+ function rely(address usr) external auth {
+ wards[usr] = 1;
+ emit Rely(usr);
+ }
+
+ function deny(address usr) external auth {
+ wards[usr] = 0;
+ emit Deny(usr);
+ }
+
+ function pocket() external view returns (address) {
+ return address(this);
+ }
+
+ function sellGemNoFee(address usr, uint256 gemAmt) external auth returns (uint256 daiOutWad) {
+ daiOutWad = gemAmt * to18ConversionFactor;
+
+ GemLike(gem).transferFrom(msg.sender, address(this), gemAmt);
+ GemLike(dai).transfer(usr, daiOutWad);
+
+ emit SellGem(usr, gemAmt, 0);
+ }
+
+ function buyGemNoFee(address usr, uint256 gemAmt) external auth returns (uint256 daiInWad) {
+ daiInWad = gemAmt * to18ConversionFactor;
+
+ GemLike(dai).transferFrom(msg.sender, address(this), daiInWad);
+ GemLike(gem).transfer(usr, gemAmt);
+
+ emit BuyGem(usr, gemAmt, 0);
+ }
+}
diff --git a/test/mocks/RolesMock.sol b/test/mocks/RolesMock.sol
new file mode 100644
index 00000000..ccd43d10
--- /dev/null
+++ b/test/mocks/RolesMock.sol
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+contract RolesMock {
+ bool ok;
+
+ function setOk(bool ok_) external {
+ ok = ok_;
+ }
+
+ function canCall(bytes32, address, address, bytes4) external view returns (bool) {
+ return ok;
+ }
+}
diff --git a/test/mocks/UsdsJoinMock.sol b/test/mocks/UsdsJoinMock.sol
new file mode 100644
index 00000000..5350848a
--- /dev/null
+++ b/test/mocks/UsdsJoinMock.sol
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+import { VatMock } from "test/mocks/VatMock.sol";
+import { GemMock } from "test/mocks/GemMock.sol";
+
+contract UsdsJoinMock {
+ VatMock public vat;
+ GemMock public usds;
+
+ constructor(VatMock vat_, GemMock usds_) {
+ vat = vat_;
+ usds = usds_;
+ }
+
+ function join(address usr, uint256 wad) external {
+ vat.move(address(this), usr, wad * 10**27);
+ usds.burn(msg.sender, wad);
+ }
+
+ function exit(address usr, uint256 wad) external {
+ vat.move(msg.sender, address(this), wad * 10**27);
+ usds.mint(usr, wad);
+ }
+}
diff --git a/test/mocks/UsdsMock.sol b/test/mocks/UsdsMock.sol
new file mode 100644
index 00000000..6b033e0e
--- /dev/null
+++ b/test/mocks/UsdsMock.sol
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+contract UsdsMock {
+ mapping (address => uint256) public balanceOf;
+ mapping (address => mapping (address => uint256)) public allowance;
+
+ uint256 public totalSupply;
+
+ constructor(uint256 initialSupply) {
+ mint(msg.sender, initialSupply);
+ }
+
+ function approve(address spender, uint256 value) external returns (bool) {
+ allowance[msg.sender][spender] = value;
+ return true;
+ }
+
+ function transfer(address to, uint256 value) external returns (bool) {
+ uint256 balance = balanceOf[msg.sender];
+ require(balance >= value, "Usds/insufficient-balance");
+
+ unchecked {
+ balanceOf[msg.sender] = balance - value;
+ balanceOf[to] += value;
+ }
+ return true;
+ }
+
+ function transferFrom(address from, address to, uint256 value) external returns (bool) {
+ uint256 balance = balanceOf[from];
+ require(balance >= value, "Usds/insufficient-balance");
+
+ if (from != msg.sender) {
+ uint256 allowed = allowance[from][msg.sender];
+ if (allowed != type(uint256).max) {
+ require(allowed >= value, "Usds/insufficient-allowance");
+
+ unchecked {
+ allowance[from][msg.sender] = allowed - value;
+ }
+ }
+ }
+
+ unchecked {
+ balanceOf[from] = balance - value;
+ balanceOf[to] += value;
+ }
+ return true;
+ }
+
+ function mint(address to, uint256 value) public {
+ unchecked {
+ balanceOf[to] = balanceOf[to] + value;
+ }
+ totalSupply = totalSupply + value;
+ }
+
+ function burn(address from, uint256 value) external {
+ uint256 balance = balanceOf[from];
+ require(balance >= value, "Usds/insufficient-balance");
+
+ if (from != msg.sender) {
+ uint256 allowed = allowance[from][msg.sender];
+ if (allowed != type(uint256).max) {
+ require(allowed >= value, "Usds/insufficient-allowance");
+
+ unchecked {
+ allowance[from][msg.sender] = allowed - value;
+ }
+ }
+ }
+
+ unchecked {
+ balanceOf[from] = balance - value;
+ totalSupply = totalSupply - value;
+ }
+ }
+}
diff --git a/test/mocks/VatMock.sol b/test/mocks/VatMock.sol
new file mode 100644
index 00000000..6298560f
--- /dev/null
+++ b/test/mocks/VatMock.sol
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+pragma solidity ^0.8.16;
+
+contract VatMock {
+ uint256 public Art;
+ uint256 public rate = 10**27;
+ uint256 public line = 20_000_000 * 10**45;
+
+ struct Urn {
+ uint256 ink;
+ uint256 art;
+ }
+
+ mapping (address => mapping (address => uint256)) public can;
+ mapping (bytes32 => mapping (address => Urn )) public urns;
+ mapping (bytes32 => mapping (address => uint)) public gem;
+ mapping (address => uint256) public dai;
+
+ function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256) {
+ return (Art, rate, 0, line, 0);
+ }
+
+ function hope(address usr) external {
+ can[msg.sender][usr] = 1;
+ }
+
+ function frob(bytes32 i, address u, address v, address w, int256 dink, int256 dart) external {
+ require(u == msg.sender || can[u][msg.sender] == 1);
+ Urn memory urn = urns[i][u];
+
+ urn.ink = dink >= 0 ? urn.ink + uint256(dink) : urn.ink - uint256(-dink);
+ Art = urn.art = dart >= 0 ? urn.art + uint256(dart) : urn.art - uint256(-dart);
+
+ gem[i][v] = dink >= 0 ? gem[i][v] - uint256(dink) : gem[i][v] + uint256(-dink);
+ require(dart == 0 || rate <= uint256(type(int256).max));
+ int256 dtab = int256(rate) * dart;
+ dai[w] = dtab >= 0 ? dai[w] + uint256(dtab) : dai[w] - uint256(-dtab);
+
+ urns[i][u] = urn;
+ }
+
+ function move(address src, address dst, uint256 rad) external {
+ require(src == msg.sender || can[src][msg.sender] == 1);
+ dai[src] = dai[src] - rad;
+ dai[dst] = dai[dst] + rad;
+ }
+
+ function slip(bytes32 ilk, address usr, int256 wad) external {
+ gem[ilk][usr] = wad >= 0 ? gem[ilk][usr] + uint256(wad) : gem[ilk][usr] - uint256(-wad);
+ }
+
+ function grab(bytes32 i, address u, address v, address, int dink, int dart) external {
+ Urn storage urn = urns[i][u];
+
+ urn.ink = dink >= 0 ? urn.ink + uint256(dink) : urn.ink - uint256(-dink);
+ urn.art = dart >= 0 ? urn.art + uint256(dart) : urn.art - uint256(-dart);
+ Art = dart >= 0 ? Art + uint256(dart) : Art - uint256(-dart);
+ gem[i][v] = dink >= 0 ? gem[i][v] - uint256(dink) : gem[i][v] + uint256(-dink);
+ }
+
+ function fold(uint256 rate_) external {
+ rate = rate + rate_;
+ }
+}