├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── audits ├── cantinasec-sparklend-conduits.pdf └── chainsecurity-sparklend-conduits.pdf ├── foundry.toml ├── src ├── SparkLendConduit.sol └── interfaces │ └── ISparkLendConduit.sol └── test ├── IntegrationTests.t.sol ├── SparkLendConduit.t.sol ├── harnesses └── SparkLendConduitHarness.sol └── mocks ├── ATokenMock.sol └── Mocks.sol /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | push: 7 | branches: 8 | - master 9 | 10 | env: 11 | FOUNDRY_PROFILE: ci 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v3 18 | 19 | - name: Install Foundry 20 | uses: foundry-rs/foundry-toolchain@v1 21 | 22 | - name: Build contracts 23 | run: | 24 | forge --version 25 | forge build --sizes 26 | 27 | test: 28 | runs-on: ubuntu-latest 29 | steps: 30 | - uses: actions/checkout@v3 31 | 32 | - name: Install Foundry 33 | uses: foundry-rs/foundry-toolchain@v1 34 | 35 | - name: Run tests 36 | run: FOUNDRY_PROFILE=ci forge test 37 | 38 | # coverage: 39 | # runs-on: ubuntu-latest 40 | # steps: 41 | # - uses: actions/checkout@v3 42 | 43 | # - name: Install Foundry 44 | # uses: foundry-rs/foundry-toolchain@v1 45 | 46 | # - name: Run coverage 47 | # run: forge coverage --report summary --report lcov 48 | 49 | # # To ignore coverage for certain directories modify the paths in this step as needed. The 50 | # # below default ignores coverage results for the test and script directories. Alternatively, 51 | # # to include coverage in all directories, comment out this step. Note that because this 52 | # # filtering applies to the lcov file, the summary table generated in the previous step will 53 | # # still include all files and directories. 54 | # # The `--rc lcov_branch_coverage=1` part keeps branch info in the filtered report, since lcov 55 | # # defaults to removing branch info. 56 | # - name: Filter directories 57 | # run: | 58 | # sudo apt update && sudo apt install -y lcov 59 | # lcov --remove lcov.info 'test/*' 'script/*' --output-file lcov.info --rc lcov_branch_coverage=1 60 | 61 | # # This step posts a detailed coverage report as a comment and deletes previous comments on 62 | # # each push. The below step is used to fail coverage if the specified coverage threshold is 63 | # # not met. The below step can post a comment (when it's `github-token` is specified) but it's 64 | # # not as useful, and this action cannot fail CI based on a minimum coverage threshold, which 65 | # # is why we use both in this way. 66 | # - name: Post coverage report 67 | # if: github.event_name == 'pull_request' # This action fails when ran outside of a pull request. 68 | # uses: romeovs/lcov-reporter-action@v0.3.1 69 | # with: 70 | # delete-old-comments: true 71 | # lcov-file: ./lcov.info 72 | # github-token: ${{ secrets.GITHUB_TOKEN }} # Adds a coverage summary comment to the PR. 73 | 74 | # - name: Verify minimum coverage 75 | # uses: zgosalvez/github-actions-report-lcov@v2 76 | # with: 77 | # coverage-files: ./lcov.info 78 | # minimum-coverage: 90 # Set coverage threshold. 79 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiler files 2 | cache/ 3 | out/ 4 | 5 | # Ignores development broadcast logs 6 | !/broadcast 7 | /broadcast/*/31337/ 8 | /broadcast/**/dry-run/ 9 | 10 | # Docs 11 | docs/ 12 | 13 | # Dotenv file 14 | .env 15 | 16 | lcov.info 17 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/forge-std"] 2 | path = lib/forge-std 3 | url = https://github.com/foundry-rs/forge-std 4 | [submodule "lib/aave-v3-core"] 5 | path = lib/aave-v3-core 6 | url = https://github.com/aave/aave-v3-core 7 | branch = v1.18.0 8 | [submodule "lib/dss-test"] 9 | path = lib/dss-test 10 | url = https://github.com/makerdao/dss-test 11 | [submodule "lib/dss-allocator"] 12 | path = lib/dss-allocator 13 | url = https://github.com/makerdao/dss-allocator 14 | [submodule "lib/upgradeable-proxy"] 15 | path = lib/upgradeable-proxy 16 | url = https://github.com/marsfoundation/upgradeable-proxy 17 | [submodule "lib/erc20-helpers"] 18 | path = lib/erc20-helpers 19 | url = https://github.com/marsfoundation/erc20-helpers 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SparkLend Conduits ⚡ 2 | 3 | ![Foundry CI](https://github.com/marsfoundation/spark-conduits/actions/workflows/ci.yml/badge.svg) 4 | [![Foundry][foundry-badge]][foundry] 5 | [![License: AGPL v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg)](https://github.com/marsfoundation/spark-conduits/blob/master/LICENSE) 6 | 7 | [foundry]: https://getfoundry.sh/ 8 | [foundry-badge]: https://img.shields.io/badge/Built%20with-Foundry-FFDB1C.svg 9 | 10 | ## Overview 11 | 12 | The SparkLend Conduit is a conduit contract designed to be used within the Maker Allocation System. It implements the IAllocatorConduit interface, so it will be able to work within the constraints on the Allocation System design. There is one contract in this repo: 13 | 14 | `SparkLendConduit`: Facilitates the movement of funds between the Maker Allocation System and the SparkLend instance. 15 | 16 | In later iterations of this code's development, it is expected for other SparkLend Conduits to be developed to support multichain deployments. 17 | 18 | ## Roles/Permissions 19 | 20 | 1. `wards`: The `wards` mapping tracks the administrative permissions on this contract. Admin can upgrade the contract and set key storage values. 21 | 2. `operator`: The `operator` performs actions on behalf of a given `ilk` (SubDAO identifier in the Maker Allocation System). The operator can deposit, withdraw, request funds, and cancel fund requests in the Conduit. Onboarding and offboarding of `operator` actors is done by Maker admin in the core system. 22 | 23 | ### Admin Configuration 24 | 25 | 1. `roles`: The roles contract to perform operator authentication. 26 | 2. `registry`: Returns the `buffer` contract for a given ilk (source of funds). 27 | 28 | ## Functionality 29 | 30 | ### `deposit` 31 | 32 | The `deposit` function is used to move funds from a given `ilk`'s `buffer` into the Conduit. From the Conduit, the funds are used to `supply` in the SparkLend Pool. The result is that: 33 | 1. Funds are moved from the `buffer` to SparkLend's aToken for that asset. 34 | 2. aTokens are minted and sent to the Conduit. 35 | 3. The Conduit state to track the `ilk`'s portion of the aTokens in the Conduit is increased. 36 | 37 |

38 | 39 |

40 | 41 | ### `withdraw` 42 | 43 | The `withdraw` function is used to `withdraw` funds from the SparkLend Pool into the Conduit. From the Conduit, the funds are sent to the `ilk`'s `buffer`. The result is that: 44 | 45 | 1. Funds are moved from SparkLend's aToken for that asset to the `buffer`. 46 | 2. The Conduit's aTokens corresponding to the underlying asset withdrawn are burned. 47 | 3. The Conduit state to track the `ilk`'s portion of the aTokens in the Conduit is reduced. 48 | 49 |

50 | 51 |

52 | 53 | ## Invariants 54 | 55 | $$ totalShares[asset] = \sum_{n=0}^{numIlks}{shares[asset][ilk]} $$ 56 | 57 | $$ getTotalDeposits(asset) = \sum_{n=0}^{numIlks}{getDeposits(asset, ilk)} $$ 58 | 59 | $$ totalRequestedShares[asset] = \sum_{n=0}^{numIlks}{requestedShares[asset][ilk]} $$ 60 | 61 | $$ totalShares[asset] \le aToken.scaledBalanceOf(conduit) $$ 62 | 63 | $$ getTotalDeposits(asset) \le aToken.balanceOf(conduit) $$ 64 | 65 | **NOTE**: The last two invariants are not strict equalities because of A) the potential for a permissionless transfer of the aToken into the conduit and/or B) the rounding behaviour difference (round on SparkLend vs round-down on SparkLend Conduit). 66 | 67 | ## Upgradeability 68 | 69 | Since the SparkLend Conduit will likely require maintenance as its desired usage evolves, it will be an upgradeable contract, using [`upgradeable-proxy`](https://github.com/marsfoundation/upgradeable-proxy) for upgradeable logic. This is a non-transparent proxy contract that gives upgrade rights to the PauseProxy. 70 | 71 | ## Technical Assumptions 72 | 73 | As with most MakerDAO contracts, non standard token implementations are assumed to not be supported. As examples, this includes tokens that: 74 | - Do not have a decimals field or have more than 18 decimals. 75 | - Do not revert and instead rely on a return value. 76 | - Implement fee on transfer. 77 | - Include rebasing logic. 78 | - Implement callbacks/hooks. 79 | 80 | ## Testing 81 | 82 | To run the tests, do the following: 83 | 84 | ``` 85 | forge test 86 | ``` 87 | -------------------------------------------------------------------------------- /audits/cantinasec-sparklend-conduits.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparkdotfi/sparklend-conduits/5c5d83437fbf74d5dc88c078263304384c271f40/audits/cantinasec-sparklend-conduits.pdf -------------------------------------------------------------------------------- /audits/chainsecurity-sparklend-conduits.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparkdotfi/sparklend-conduits/5c5d83437fbf74d5dc88c078263304384c271f40/audits/chainsecurity-sparklend-conduits.pdf -------------------------------------------------------------------------------- /foundry.toml: -------------------------------------------------------------------------------- 1 | [profile.default] 2 | src = "src" 3 | out = "out" 4 | libs = ["lib"] 5 | solc_version = '0.8.20' 6 | optimizer = true 7 | optimizer_runs = 200 8 | 9 | [fuzz] 10 | runs = 1000 11 | 12 | # See more config options https://github.com/foundry-rs/foundry/tree/master/config 13 | -------------------------------------------------------------------------------- /src/SparkLendConduit.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.13; 3 | 4 | import { IPool } from 'aave-v3-core/contracts/interfaces/IPool.sol'; 5 | 6 | import { IERC20 } from 'erc20-helpers/interfaces/IERC20.sol'; 7 | import { SafeERC20 } from 'erc20-helpers/SafeERC20.sol'; 8 | 9 | import { UpgradeableProxied } from 'upgradeable-proxy/UpgradeableProxied.sol'; 10 | 11 | import { ISparkLendConduit } from './interfaces/ISparkLendConduit.sol'; 12 | 13 | interface RolesLike { 14 | function canCall(bytes32, address, address, bytes4) external view returns (bool); 15 | } 16 | 17 | interface RegistryLike { 18 | function buffers(bytes32 ilk) external view returns (address buffer); 19 | } 20 | 21 | contract SparkLendConduit is UpgradeableProxied, ISparkLendConduit { 22 | 23 | using SafeERC20 for address; 24 | 25 | /**********************************************************************************************/ 26 | /*** Storage ***/ 27 | /**********************************************************************************************/ 28 | 29 | address public override immutable pool; 30 | 31 | address public override roles; 32 | address public override registry; 33 | 34 | mapping(address => bool) public override enabled; 35 | 36 | mapping(address => uint256) public override totalShares; 37 | 38 | mapping(address => mapping(bytes32 => uint256)) public override shares; 39 | 40 | /**********************************************************************************************/ 41 | /*** Modifiers ***/ 42 | /**********************************************************************************************/ 43 | 44 | modifier auth() { 45 | require(wards[msg.sender] == 1, "SparkLendConduit/not-authorized"); 46 | _; 47 | } 48 | 49 | modifier ilkAuth(bytes32 ilk) { 50 | require( 51 | RolesLike(roles).canCall(ilk, msg.sender, address(this), msg.sig), 52 | "SparkLendConduit/ilk-not-authorized" 53 | ); 54 | _; 55 | } 56 | 57 | /**********************************************************************************************/ 58 | /*** Constructor ***/ 59 | /**********************************************************************************************/ 60 | 61 | constructor(address _pool) { 62 | pool = _pool; 63 | } 64 | 65 | /**********************************************************************************************/ 66 | /*** Admin Functions ***/ 67 | /**********************************************************************************************/ 68 | 69 | function setRoles(address _roles) external override auth { 70 | roles = _roles; 71 | 72 | emit SetRoles(_roles); 73 | } 74 | 75 | function setRegistry(address _registry) external override auth { 76 | registry = _registry; 77 | 78 | emit SetRegistry(_registry); 79 | } 80 | 81 | function setAssetEnabled(address asset, bool enabled_) external override auth { 82 | enabled[asset] = enabled_; 83 | asset.safeApprove(pool, enabled_ ? type(uint256).max : 0); 84 | 85 | emit SetAssetEnabled(asset, enabled_); 86 | } 87 | 88 | /**********************************************************************************************/ 89 | /*** Operator Functions ***/ 90 | /**********************************************************************************************/ 91 | 92 | function deposit(bytes32 ilk, address asset, uint256 amount) external override ilkAuth(ilk) { 93 | require(enabled[asset], "SparkLendConduit/asset-disabled"); 94 | 95 | address source = RegistryLike(registry).buffers(ilk); 96 | 97 | require(source != address(0), "SparkLendConduit/no-buffer-registered"); 98 | 99 | // Convert asset amount to shares 100 | uint256 newShares = _convertToShares(asset, amount); 101 | 102 | shares[asset][ilk] += newShares; 103 | totalShares[asset] += newShares; 104 | 105 | asset.safeTransferFrom(source, address(this), amount); 106 | IPool(pool).supply(asset, amount, address(this), 0); 107 | 108 | emit Deposit(ilk, asset, source, amount); 109 | } 110 | 111 | function withdraw(bytes32 ilk, address asset, uint256 maxAmount) 112 | external override ilkAuth(ilk) returns (uint256 amount) 113 | { 114 | // Constrain the amount that can be withdrawn by the max amount 115 | amount = _min(maxAmount, maxWithdraw(ilk, asset)); 116 | 117 | // Convert the amount to withdraw to shares 118 | // Round up to be conservative but prevent underflow 119 | uint256 withdrawalShares 120 | = _min(shares[asset][ilk], _convertToSharesRoundUp(asset, amount)); 121 | 122 | // Reduce share accounting by the amount withdrawn 123 | shares[asset][ilk] -= withdrawalShares; 124 | totalShares[asset] -= withdrawalShares; 125 | 126 | address destination = RegistryLike(registry).buffers(ilk); 127 | 128 | require(destination != address(0), "SparkLendConduit/no-buffer-registered"); 129 | 130 | IPool(pool).withdraw(asset, amount, destination); 131 | 132 | emit Withdraw(ilk, asset, destination, amount); 133 | } 134 | 135 | /**********************************************************************************************/ 136 | /*** View Functions ***/ 137 | /**********************************************************************************************/ 138 | 139 | function maxDeposit(bytes32, address asset) public view override returns (uint256 maxDeposit_) { 140 | // Note: Purposefully ignoring any potential supply cap limits on SparkLend. 141 | // This is because we assume the supply cap on this asset to be turned off. 142 | return enabled[asset] ? type(uint256).max : 0; 143 | } 144 | 145 | function maxWithdraw(bytes32 ilk, address asset) 146 | public view override returns (uint256 maxWithdraw_) 147 | { 148 | return _min(_convertToAssets(asset, shares[asset][ilk]), getAvailableLiquidity(asset)); 149 | } 150 | 151 | function getTotalDeposits(address asset) external view override returns (uint256) { 152 | return _convertToAssets(asset, totalShares[asset]); 153 | } 154 | 155 | function getDeposits(address asset, bytes32 ilk) external view override returns (uint256) { 156 | return _convertToAssets(asset, shares[asset][ilk]); 157 | } 158 | 159 | function getAvailableLiquidity(address asset) public view override returns (uint256) { 160 | return IERC20(asset).balanceOf(IPool(pool).getReserveData(asset).aTokenAddress); 161 | } 162 | 163 | /**********************************************************************************************/ 164 | /*** Helper Functions ***/ 165 | /**********************************************************************************************/ 166 | 167 | function _convertToAssets(address asset, uint256 amount) internal view returns (uint256) { 168 | return _rayMul(amount, IPool(pool).getReserveNormalizedIncome(asset)); 169 | } 170 | 171 | function _convertToShares(address asset, uint256 amount) internal view returns (uint256) { 172 | return _rayDiv(amount, IPool(pool).getReserveNormalizedIncome(asset)); 173 | } 174 | 175 | function _convertToSharesRoundUp(address asset, uint256 amount) 176 | internal view returns (uint256) 177 | { 178 | return _divUp(amount * 1e27, IPool(pool).getReserveNormalizedIncome(asset)); 179 | } 180 | 181 | // Please note this function returns 0 instead of reverting when x and y are 0 182 | function _divUp(uint256 x, uint256 y) internal pure returns (uint256 z) { 183 | unchecked { 184 | z = x != 0 ? ((x - 1) / y) + 1 : 0; 185 | } 186 | } 187 | 188 | function _min(uint256 a, uint256 b) internal pure returns (uint256) { 189 | return a < b ? a : b; 190 | } 191 | 192 | function _rayMul(uint256 x, uint256 y) internal pure returns (uint256 z) { 193 | z = x * y / 1e27; 194 | } 195 | 196 | function _rayDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { 197 | z = x * 1e27 / y; 198 | } 199 | 200 | } 201 | -------------------------------------------------------------------------------- /src/interfaces/ISparkLendConduit.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { IAllocatorConduit } from 'dss-allocator/IAllocatorConduit.sol'; 5 | 6 | /** 7 | * @title ISparkLendConduit 8 | * @notice This interface extends the IAllocatorConduit interfaces and manages asset 9 | * and fund operations 10 | */ 11 | interface ISparkLendConduit is IAllocatorConduit { 12 | 13 | /**********************************************************************************************/ 14 | /*** Events ***/ 15 | /**********************************************************************************************/ 16 | 17 | /** 18 | * @notice Event emitted when roles address is set. 19 | * @param roles The new roles address. 20 | */ 21 | event SetRoles(address roles); 22 | 23 | /** 24 | * @notice Event emitted when registry address is set. 25 | * @param registry The new registry address. 26 | */ 27 | event SetRegistry(address registry); 28 | 29 | /** 30 | * @notice Event emitted when an asset's status is enabled or disabled. 31 | * @dev This will give infinite token approval to the pool as well. 32 | * @param asset The address of the asset. 33 | * @param enabled The new status of the asset. 34 | */ 35 | event SetAssetEnabled(address indexed asset, bool enabled); 36 | 37 | /**********************************************************************************************/ 38 | /*** State Variables ***/ 39 | /**********************************************************************************************/ 40 | 41 | /** 42 | * @notice Returns the pool associated with the SparkLend instance. 43 | * @return The address of the pool. 44 | */ 45 | function pool() external view returns (address); 46 | 47 | /** 48 | * @notice Returns the roles contract. 49 | * @return The address representing the roles. 50 | */ 51 | function roles() external view returns (address); 52 | 53 | /** 54 | * @notice Returns the registry contract. 55 | * @return The address representing the registry. 56 | */ 57 | function registry() external view returns (address); 58 | 59 | /** 60 | * @notice Determines whether a given asset is whitelisted or not. 61 | * @param asset The address of the asset. 62 | * @return A boolean representing the enabled state. 63 | */ 64 | function enabled(address asset) external view returns (bool); 65 | 66 | /** 67 | * @notice Get the total number of shares that are held custody for a given asset. 68 | * @param asset The address of the asset. 69 | * @return The total number of shares for the asset. 70 | */ 71 | function totalShares(address asset) external view returns (uint256); 72 | 73 | /** 74 | * @notice Get the number of shares a given ilk has ownership of for a given asset. 75 | * @param asset The address of the asset. 76 | * @param ilk The unique identifier for a subDAO. 77 | * @return The number of shares for the asset and ilk. 78 | */ 79 | function shares(address asset, bytes32 ilk) external view returns (uint256); 80 | 81 | /**********************************************************************************************/ 82 | /*** External Functions ***/ 83 | /**********************************************************************************************/ 84 | 85 | /** 86 | * @notice Sets the roles address. 87 | * @param _roles The new roles address. 88 | */ 89 | function setRoles(address _roles) external; 90 | 91 | /** 92 | * @notice Sets the registry address. 93 | * @param _registry The new registry address. 94 | */ 95 | function setRegistry(address _registry) external; 96 | 97 | /** 98 | * @notice Enables or disables an asset. 99 | * @param asset The address of the asset. 100 | * @param enabled The new status of the asset. 101 | */ 102 | function setAssetEnabled(address asset, bool enabled) external; 103 | 104 | /**********************************************************************************************/ 105 | /*** View Functions ***/ 106 | /**********************************************************************************************/ 107 | 108 | /** 109 | * @notice Returns the amount of available liquidity in the SparkLend pool for a given asset. 110 | * @return The balance of tokens in the asset's reserve's aToken address. 111 | */ 112 | function getAvailableLiquidity(address asset) external view returns (uint256); 113 | 114 | /** 115 | * @notice Gets the total deposits of an asset. 116 | * @param asset The address of the asset. 117 | * @return The total amount of deposits for the asset. 118 | */ 119 | function getTotalDeposits(address asset) external view returns (uint256); 120 | 121 | /** 122 | * @notice Gets the deposits for a given ilk and asset. 123 | * @param asset The asset to get the deposits for. 124 | * @param ilk The ilk to get the deposits for. 125 | * @return The total amount of deposits for the given ilk and asset. 126 | */ 127 | function getDeposits(address asset, bytes32 ilk) external view returns (uint256); 128 | 129 | } 130 | 131 | -------------------------------------------------------------------------------- /test/IntegrationTests.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.13; 3 | 4 | import "dss-test/DssTest.sol"; 5 | 6 | import { IPool } from "aave-v3-core/contracts/interfaces/IPool.sol"; 7 | import { IAToken } from "aave-v3-core/contracts/interfaces/IAToken.sol"; 8 | 9 | import { AllocatorRegistry } from "dss-allocator/AllocatorRegistry.sol"; 10 | import { AllocatorRoles } from "dss-allocator/AllocatorRoles.sol"; 11 | 12 | import { IERC20 } from "erc20-helpers/interfaces/IERC20.sol"; 13 | 14 | import { UpgradeableProxy } from "upgradeable-proxy/UpgradeableProxy.sol"; 15 | 16 | import { SparkLendConduit } from 'src/SparkLendConduit.sol'; 17 | 18 | contract ConduitIntegrationTestBase is DssTest { 19 | 20 | address DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; 21 | address ADAI = 0x4DEDf26112B3Ec8eC46e7E31EA5e123490B05B8B; 22 | address POOL = 0xC13e21B648A5Ee794902342038FF3aDAB66BE987; 23 | 24 | address admin = makeAddr("admin"); 25 | address buffer1 = makeAddr("buffer1"); 26 | address buffer2 = makeAddr("buffer2"); 27 | address operator1 = makeAddr("operator1"); 28 | address operator2 = makeAddr("operator2"); 29 | 30 | bytes32 constant ILK1 = 'ilk1'; 31 | bytes32 constant ILK2 = 'ilk2'; 32 | 33 | uint256 LIQUIDITY; // dai.balanceOf(ADAI) 34 | uint256 ADAI_SUPPLY; // aToken.totalSupply() 35 | uint256 ADAI_SCALED_SUPPLY; // aToken.totalSupply() 36 | uint256 INDEX; // pool.getReserveNormalizedIncome(DAI) 37 | 38 | AllocatorRegistry registry; 39 | AllocatorRoles roles; 40 | 41 | IERC20 dai = IERC20(DAI); 42 | IAToken aToken = IAToken(ADAI); 43 | IPool pool = IPool(POOL); 44 | 45 | SparkLendConduit conduit; 46 | 47 | function setUp() public virtual { 48 | vm.createSelectFork(getChain('mainnet').rpcUrl, 18_090_400); 49 | 50 | // Starting state at block 18_090_400 51 | LIQUIDITY = 3042.894995046294009693 ether; 52 | ADAI_SUPPLY = 200_668_890.552846452355198767 ether; 53 | ADAI_SCALED_SUPPLY = 199_358_171.788361925857232792 ether; 54 | INDEX = 1.006574692939479711169088718e27; 55 | 56 | UpgradeableProxy proxy = new UpgradeableProxy(); 57 | SparkLendConduit impl = new SparkLendConduit(POOL); 58 | 59 | proxy.setImplementation(address(impl)); 60 | 61 | conduit = SparkLendConduit(address(proxy)); 62 | 63 | registry = new AllocatorRegistry(); 64 | roles = new AllocatorRoles(); 65 | 66 | conduit.setRoles(address(roles)); 67 | conduit.setRegistry(address(registry)); 68 | 69 | registry.file(ILK1, "buffer", buffer1); 70 | registry.file(ILK2, "buffer", buffer2); 71 | 72 | _setupOperatorRole(ILK1, operator1); // TODO: Change 73 | _setupOperatorRole(ILK2, operator2); 74 | 75 | // TODO: Use real buffer 76 | vm.prank(buffer1); 77 | IERC20(DAI).approve(address(conduit), type(uint256).max); 78 | 79 | vm.prank(buffer2); 80 | IERC20(DAI).approve(address(conduit), type(uint256).max); 81 | 82 | conduit.setAssetEnabled(DAI, true); 83 | } 84 | 85 | function test_assertInitialState() external { 86 | assertEq(LIQUIDITY, 3042.894995046294009693 ether); 87 | assertEq(ADAI_SUPPLY, 200_668_890.552846452355198767 ether); 88 | assertEq(ADAI_SCALED_SUPPLY, 199_358_171.788361925857232792 ether); 89 | assertEq(INDEX, 1.006574692939479711169088718e27); 90 | } 91 | 92 | function _setupOperatorRole(bytes32 ilk_, address operator_) internal { 93 | uint8 ROLE = 0; 94 | 95 | // Ensure address(this) can always set for a new ilk 96 | roles.setIlkAdmin(ilk_, address(this)); 97 | 98 | roles.setUserRole(ilk_, operator_, ROLE, true); 99 | 100 | address conduit_ = address(conduit); 101 | 102 | roles.setRoleAction(ilk_, ROLE, conduit_, conduit.deposit.selector, true); 103 | roles.setRoleAction(ilk_, ROLE, conduit_, conduit.withdraw.selector, true); 104 | } 105 | 106 | function _assertInvariants() internal { 107 | assertEq( 108 | conduit.totalShares(DAI), 109 | conduit.shares(DAI, ILK1) + conduit.shares(DAI, ILK2), 110 | "Invariant A" 111 | ); 112 | 113 | // NOTE: 1 error because 2 ilks, rounding error scales with number of ilks 114 | assertApproxEqAbs( 115 | conduit.getTotalDeposits(DAI), 116 | conduit.getDeposits(DAI, ILK1) + conduit.getDeposits(DAI, ILK2), 117 | 1, 118 | "Invariant B" 119 | ); 120 | 121 | assertApproxEqAbs( 122 | conduit.totalShares(DAI), 123 | aToken.scaledBalanceOf(address(conduit)), 124 | 2, 125 | "Invariant C" 126 | ); 127 | 128 | assertApproxEqAbs( 129 | conduit.getTotalDeposits(DAI), 130 | aToken.balanceOf(address(conduit)), 131 | 2, 132 | "Invariant D" 133 | ); 134 | } 135 | 136 | function _assertATokenState( 137 | uint256 scaledBalance, 138 | uint256 scaledTotalSupply, 139 | uint256 balance, 140 | uint256 totalSupply 141 | ) internal { 142 | assertEq(aToken.scaledBalanceOf(address(conduit)), scaledBalance, "scaledBalance"); 143 | assertEq(aToken.scaledTotalSupply(), scaledTotalSupply, "scaledTotalSupply"); 144 | assertEq(aToken.balanceOf(address(conduit)), balance, "balance"); 145 | assertEq(aToken.totalSupply(), totalSupply, "totalSupply"); 146 | } 147 | 148 | function _assertDaiState(uint256 buffer1Balance, uint256 aTokenBalance) internal { 149 | assertEq(dai.balanceOf(buffer1), buffer1Balance, "buffer1Balance"); 150 | assertEq(dai.balanceOf(address(aToken)), aTokenBalance, "aTokenBalance"); 151 | } 152 | 153 | function _assertDaiState( 154 | uint256 buffer1Balance, 155 | uint256 buffer2Balance, 156 | uint256 aTokenBalance 157 | ) 158 | internal 159 | { 160 | _assertDaiState(buffer1Balance, aTokenBalance); 161 | assertEq(dai.balanceOf(buffer2), buffer2Balance, "buffer2Balance"); 162 | } 163 | 164 | function _assertConduitState(uint256 ilk1Shares, uint256 totalShares) internal { 165 | assertEq(conduit.shares(DAI, ILK1), ilk1Shares, "ilk1Shares"); 166 | assertEq(conduit.totalShares(DAI), totalShares, "totalShares"); 167 | } 168 | 169 | function _assertConduitState( 170 | uint256 ilk1Shares, 171 | uint256 ilk2Shares, 172 | uint256 totalShares 173 | ) 174 | internal 175 | { 176 | _assertConduitState(ilk1Shares, totalShares); 177 | assertEq(conduit.shares(DAI, ILK2), ilk2Shares, "ilk2Shares"); 178 | } 179 | 180 | } 181 | 182 | contract ConduitDepositIntegrationTests is ConduitIntegrationTestBase { 183 | 184 | function test_deposit_insufficientBalanceBoundary() external { 185 | deal(DAI, buffer1, 100 ether); 186 | 187 | vm.startPrank(operator1); 188 | vm.expectRevert("SafeERC20/transfer-from-failed"); 189 | conduit.deposit(ILK1, DAI, 100 ether + 1); 190 | 191 | conduit.deposit(ILK1, DAI, 100 ether); 192 | } 193 | 194 | function test_deposit_zeroAddressBuffer() external { 195 | deal(DAI, buffer1, 100 ether); 196 | 197 | registry.file(ILK1, "buffer", address(0)); 198 | 199 | vm.prank(operator1); 200 | vm.expectRevert("SparkLendConduit/no-buffer-registered"); 201 | conduit.deposit(ILK1, DAI, 100 ether); 202 | 203 | registry.file(ILK1, "buffer", buffer1); 204 | 205 | vm.prank(operator1); 206 | conduit.deposit(ILK1, DAI, 100 ether); 207 | } 208 | 209 | function test_deposit_ilkNotRegistered() external { 210 | bytes32 ILK3 = "ilk3"; 211 | address operator3 = makeAddr("operator3"); 212 | address buffer3 = makeAddr("buffer3"); 213 | 214 | vm.prank(buffer3); 215 | IERC20(DAI).approve(address(conduit), type(uint256).max); 216 | 217 | _setupOperatorRole(ILK3, operator3); 218 | 219 | deal(DAI, buffer3, 100 ether); 220 | 221 | // Same error, but because buffer was never initialized to begin with 222 | vm.prank(operator3); 223 | vm.expectRevert("SparkLendConduit/no-buffer-registered"); 224 | conduit.deposit(ILK3, DAI, 100 ether); 225 | 226 | registry.file(ILK3, "buffer", buffer3); 227 | 228 | vm.prank(operator3); 229 | conduit.deposit(ILK3, DAI, 100 ether); 230 | } 231 | 232 | function test_deposit_singleIlk_valueAccrual() external { 233 | deal(DAI, buffer1, 100 ether); 234 | 235 | _assertInvariants(); 236 | 237 | _assertDaiState({ 238 | buffer1Balance: 100 ether, 239 | aTokenBalance: LIQUIDITY 240 | }); 241 | 242 | _assertATokenState({ 243 | scaledBalance: 0, 244 | scaledTotalSupply: ADAI_SCALED_SUPPLY, 245 | balance: 0, 246 | totalSupply: ADAI_SUPPLY 247 | }); 248 | 249 | _assertConduitState({ 250 | ilk1Shares: 0, 251 | totalShares: 0 252 | }); 253 | 254 | vm.prank(operator1); 255 | conduit.deposit(ILK1, DAI, 100 ether); 256 | 257 | uint256 expectedShares = 100 ether * 1e27 / INDEX; 258 | uint256 expectedScaledBalance = expectedShares + 1; // +1 for rounding 259 | 260 | _assertInvariants(); 261 | 262 | _assertDaiState({ 263 | buffer1Balance: 0, 264 | aTokenBalance: LIQUIDITY + 100 ether 265 | }); 266 | 267 | _assertATokenState({ 268 | scaledBalance: expectedScaledBalance, 269 | scaledTotalSupply: ADAI_SCALED_SUPPLY + expectedScaledBalance, 270 | balance: 100 ether, 271 | totalSupply: ADAI_SUPPLY + 100 ether 272 | }); 273 | 274 | _assertConduitState({ 275 | ilk1Shares: expectedShares, 276 | totalShares: expectedShares 277 | }); 278 | 279 | vm.warp(block.timestamp + 1 days); 280 | 281 | uint256 newIndex = pool.getReserveNormalizedIncome(DAI); 282 | 283 | // +1 for rounding 284 | uint256 expectedValue = expectedScaledBalance * newIndex / 1e27 + 1; 285 | uint256 expectedSupply = (ADAI_SUPPLY + 100 ether) * 1e27 / INDEX * newIndex / 1e27 + 1; 286 | 287 | // Show interest accrual 288 | assertEq(expectedValue, 100.013366958918209602 ether); 289 | 290 | _assertInvariants(); 291 | 292 | _assertATokenState({ 293 | scaledBalance: expectedScaledBalance, 294 | scaledTotalSupply: ADAI_SCALED_SUPPLY + expectedScaledBalance, 295 | balance: expectedValue, 296 | totalSupply: expectedSupply 297 | }); 298 | } 299 | 300 | function test_deposit_multiIlk_valueAccrual() external { 301 | deal(DAI, buffer1, 100 ether); 302 | deal(DAI, buffer2, 50 ether); 303 | 304 | _assertInvariants(); 305 | 306 | _assertDaiState({ 307 | buffer1Balance: 100 ether, 308 | buffer2Balance: 50 ether, 309 | aTokenBalance: LIQUIDITY 310 | }); 311 | 312 | _assertATokenState({ 313 | scaledBalance: 0, 314 | scaledTotalSupply: ADAI_SCALED_SUPPLY, 315 | balance: 0, 316 | totalSupply: ADAI_SUPPLY 317 | }); 318 | 319 | _assertConduitState({ 320 | ilk1Shares: 0, 321 | ilk2Shares: 0, 322 | totalShares: 0 323 | }); 324 | 325 | vm.prank(operator1); 326 | conduit.deposit(ILK1, DAI, 100 ether); 327 | 328 | vm.warp(block.timestamp + 1 days); 329 | 330 | uint256 expectedIlk1Shares = 100 ether * 1e27 / INDEX; 331 | uint256 expectedScaledBalance = expectedIlk1Shares + 1; // +1 for rounding 332 | 333 | uint256 newIndex = pool.getReserveNormalizedIncome(DAI); 334 | 335 | // +1 for rounding 336 | uint256 expectedIlk1Value = expectedScaledBalance * newIndex / 1e27 + 1; 337 | uint256 expectedSupply = (ADAI_SUPPLY + 100 ether) * 1e27 / INDEX * newIndex / 1e27; 338 | 339 | // Show interest accrual 340 | assertEq(expectedIlk1Value, 100.013366958918209602 ether); 341 | 342 | _assertInvariants(); 343 | 344 | _assertDaiState({ 345 | buffer1Balance: 0, 346 | buffer2Balance: 50 ether, 347 | aTokenBalance: LIQUIDITY + 100 ether 348 | }); 349 | 350 | _assertATokenState({ 351 | scaledBalance: expectedScaledBalance, 352 | scaledTotalSupply: ADAI_SCALED_SUPPLY + expectedScaledBalance, 353 | balance: expectedIlk1Value, 354 | totalSupply: expectedSupply + 1 // Rounding 355 | }); 356 | 357 | _assertConduitState({ 358 | ilk1Shares: expectedIlk1Shares, 359 | totalShares: expectedIlk1Shares 360 | }); 361 | 362 | vm.prank(operator2); 363 | conduit.deposit(ILK2, DAI, 50 ether); 364 | 365 | // NOTE: Can use the same index since no time has passed since the above assertions 366 | uint256 expectedIlk2Shares = 50 ether * 1e27 / newIndex; // No rounding because 367 | 368 | expectedScaledBalance = expectedIlk1Shares + expectedIlk2Shares + 1; // Rounding 369 | 370 | _assertInvariants(); 371 | 372 | _assertDaiState({ 373 | buffer1Balance: 0, 374 | buffer2Balance: 0, 375 | aTokenBalance: LIQUIDITY + 100 ether + 50 ether 376 | }); 377 | 378 | _assertATokenState({ 379 | scaledBalance: expectedScaledBalance, 380 | scaledTotalSupply: ADAI_SCALED_SUPPLY + expectedScaledBalance, 381 | balance: expectedIlk1Value + 50 ether, 382 | totalSupply: expectedSupply + 50 ether 383 | }); 384 | 385 | _assertConduitState({ 386 | ilk1Shares: expectedIlk1Shares, 387 | ilk2Shares: expectedIlk2Shares, 388 | totalShares: expectedIlk1Shares + expectedIlk2Shares 389 | }); 390 | } 391 | 392 | } 393 | 394 | contract ConduitWithdrawIntegrationTests is ConduitIntegrationTestBase { 395 | 396 | function test_withdraw_noBufferRegistered() external { 397 | deal(DAI, buffer1, 100 ether); 398 | 399 | vm.prank(operator1); 400 | conduit.deposit(ILK1, DAI, 100 ether); 401 | 402 | registry.file(ILK1, "buffer", address(0)); 403 | 404 | vm.prank(operator1); 405 | vm.expectRevert("SparkLendConduit/no-buffer-registered"); 406 | conduit.withdraw(ILK1, DAI, 100 ether); 407 | 408 | registry.file(ILK1, "buffer", buffer1); 409 | 410 | vm.prank(operator1); 411 | conduit.withdraw(ILK1, DAI, 100 ether); 412 | } 413 | 414 | function test_withdraw_singleIlk_valueAccrual() external { 415 | deal(DAI, buffer1, 100 ether); 416 | 417 | vm.prank(operator1); 418 | conduit.deposit(ILK1, DAI, 100 ether); 419 | 420 | uint256 expectedShares = 100 ether * 1e27 / INDEX; 421 | uint256 expectedScaledBalance = expectedShares + 1; // +1 for rounding 422 | 423 | _assertInvariants(); 424 | 425 | _assertDaiState({ 426 | buffer1Balance: 0, 427 | aTokenBalance: LIQUIDITY + 100 ether 428 | }); 429 | 430 | _assertATokenState({ 431 | scaledBalance: expectedScaledBalance, 432 | scaledTotalSupply: ADAI_SCALED_SUPPLY + expectedScaledBalance, 433 | balance: 100 ether, 434 | totalSupply: ADAI_SUPPLY + 100 ether 435 | }); 436 | 437 | _assertConduitState({ 438 | ilk1Shares: expectedShares, 439 | totalShares: expectedShares 440 | }); 441 | 442 | vm.warp(block.timestamp + 1 days); 443 | 444 | uint256 newIndex = pool.getReserveNormalizedIncome(DAI); 445 | 446 | // +1 for rounding 447 | uint256 expectedValue = expectedScaledBalance * newIndex / 1e27 + 1; 448 | uint256 expectedSupply = (ADAI_SUPPLY + 100 ether) * 1e27 / INDEX * newIndex / 1e27 + 1; 449 | 450 | // Show interest accrual 451 | assertEq(expectedValue, 100.013366958918209602 ether); 452 | 453 | _assertInvariants(); 454 | 455 | _assertATokenState({ 456 | scaledBalance: expectedScaledBalance, 457 | scaledTotalSupply: ADAI_SCALED_SUPPLY + expectedScaledBalance, 458 | balance: expectedValue, 459 | totalSupply: expectedSupply 460 | }); 461 | 462 | vm.prank(operator1); 463 | uint256 amountWithdrawn = conduit.withdraw(ILK1, DAI, expectedValue); 464 | 465 | // Slightly less funds received than withdrawn, causing dust of 2 in accounting 466 | assertApproxEqAbs(amountWithdrawn, expectedValue, 2); 467 | assertLt(amountWithdrawn, expectedValue); 468 | 469 | _assertInvariants(); 470 | 471 | _assertDaiState({ 472 | buffer1Balance: expectedValue - 2, 473 | aTokenBalance: LIQUIDITY + 100 ether - (expectedValue - 2) 474 | }); 475 | 476 | // Dust of 2 left after withdrawal 477 | _assertATokenState({ 478 | scaledBalance: 2, 479 | scaledTotalSupply: ADAI_SCALED_SUPPLY + 2, 480 | balance: 2, 481 | totalSupply: expectedSupply - expectedValue + 2 482 | }); 483 | 484 | _assertConduitState({ 485 | ilk1Shares: 0, 486 | totalShares: 0 487 | }); 488 | } 489 | 490 | function test_withdraw_multiIlk_valueAccrual() external { 491 | // Intentionally using same values for both ilks to show differences in interest accrual 492 | deal(DAI, buffer1, 100 ether); 493 | deal(DAI, buffer2, 100 ether); 494 | 495 | vm.prank(operator1); 496 | conduit.deposit(ILK1, DAI, 100 ether); 497 | 498 | vm.warp(block.timestamp + 1 days); 499 | 500 | vm.prank(operator2); 501 | conduit.deposit(ILK2, DAI, 100 ether); 502 | 503 | // Need new index because time has passed 504 | uint256 index1 = pool.getReserveNormalizedIncome(DAI); 505 | 506 | uint256 expectedIlk1Shares = 100 ether * 1e27 / INDEX; 507 | uint256 expectedIlk2Shares = 100 ether * 1e27 / index1; 508 | uint256 expectedScaledBalance = expectedIlk1Shares + expectedIlk2Shares + 1; // +1 for rounding 509 | 510 | // Warp time to show interest accrual for both ilks 511 | vm.warp(block.timestamp + 10 days); 512 | 513 | // Need new index because time has passed 514 | uint256 index2 = pool.getReserveNormalizedIncome(DAI); 515 | 516 | uint256 expectedIlk1Value = expectedIlk1Shares * index2 / 1e27 + 1; // +1 for rounding 517 | uint256 expectedIlk2Value = expectedIlk2Shares * index2 / 1e27 + 1; // +1 for rounding 518 | 519 | uint256 poolValue1 = (ADAI_SUPPLY + 100 ether) * 1e27 / INDEX * index1 / 1e27; 520 | 521 | // Value accrued for whole pool between deposits plus all new value accrued 522 | uint256 expectedSupply = (poolValue1 + 100 ether) * 1e27 / index1 * index2 / 1e27 + 1; // +1 for rounding 523 | 524 | // Show that ilk1 has more interest accrued than ilk2 because it has been in 525 | // the pool for longer. 526 | assertEq(expectedIlk1Value, 100.147054349327300547 ether); 527 | assertEq(expectedIlk2Value, 100.133669522858884231 ether); 528 | 529 | _assertInvariants(); 530 | 531 | _assertDaiState({ 532 | buffer1Balance: 0, 533 | buffer2Balance: 0, 534 | aTokenBalance: LIQUIDITY + 100 ether + 100 ether 535 | }); 536 | 537 | _assertATokenState({ 538 | scaledBalance: expectedScaledBalance, 539 | scaledTotalSupply: ADAI_SCALED_SUPPLY + expectedScaledBalance, 540 | balance: expectedIlk1Value + expectedIlk2Value, 541 | totalSupply: expectedSupply 542 | }); 543 | 544 | _assertConduitState({ 545 | ilk1Shares: expectedIlk1Shares, 546 | ilk2Shares: expectedIlk2Shares, 547 | totalShares: expectedIlk1Shares + expectedIlk2Shares 548 | }); 549 | 550 | vm.prank(operator1); 551 | uint256 amountWithdrawn = conduit.withdraw(ILK1, DAI, expectedIlk1Value); 552 | 553 | // Slightly less funds received than withdrawn, causing dust of 1 in accounting 554 | assertApproxEqAbs(amountWithdrawn, expectedIlk1Value, 1); 555 | assertLt(amountWithdrawn, expectedIlk1Value); 556 | 557 | _assertInvariants(); 558 | 559 | uint256 combinedDeposits = 100 ether + 100 ether; 560 | 561 | _assertDaiState({ 562 | buffer1Balance: expectedIlk1Value - 1, 563 | buffer2Balance: 0, 564 | aTokenBalance: LIQUIDITY + combinedDeposits - (expectedIlk1Value - 1) 565 | }); 566 | 567 | // Dust of 1 left after withdrawal 568 | _assertATokenState({ 569 | scaledBalance: 1 + expectedIlk2Shares, 570 | scaledTotalSupply: ADAI_SCALED_SUPPLY + 1 + expectedIlk2Shares, 571 | balance: 1 + expectedIlk2Value, 572 | totalSupply: expectedSupply - expectedIlk1Value + 1 573 | }); 574 | 575 | _assertConduitState({ 576 | ilk1Shares: 0, 577 | ilk2Shares: expectedIlk2Shares, 578 | totalShares: expectedIlk2Shares 579 | }); 580 | 581 | vm.warp(block.timestamp + 1 days); 582 | 583 | // Need new index because time has passed 584 | uint256 index3 = pool.getReserveNormalizedIncome(DAI); 585 | 586 | expectedIlk2Value = expectedIlk2Shares * index3 / 1e27 + 1; // +1 for rounding 587 | 588 | vm.prank(operator2); 589 | amountWithdrawn = conduit.withdraw(ILK2, DAI, expectedIlk2Value); 590 | 591 | // Slightly less funds received than withdrawn, causing dust of 1 in accounting 592 | assertApproxEqAbs(amountWithdrawn, expectedIlk2Value, 1); 593 | assertLt(amountWithdrawn, expectedIlk2Value); 594 | 595 | _assertInvariants(); 596 | 597 | _assertDaiState({ 598 | buffer1Balance: expectedIlk1Value - 1, 599 | buffer2Balance: expectedIlk2Value - 1, 600 | aTokenBalance: LIQUIDITY + combinedDeposits - (expectedIlk1Value - 1) - (expectedIlk2Value - 1) 601 | }); 602 | 603 | // Value accrued for whole pool between withdrawals 604 | expectedSupply = (expectedSupply - (expectedIlk1Value - 1)) * 1e27 / index2 * index3 / 1e27 + 1; // +1 for rounding 605 | 606 | // Dust of 1 left after withdrawal 607 | _assertATokenState({ 608 | scaledBalance: 2, 609 | scaledTotalSupply: ADAI_SCALED_SUPPLY + 2, 610 | balance: 2, 611 | totalSupply: expectedSupply - (expectedIlk2Value - 1) // Does not need to subtract ilk1 612 | }); 613 | 614 | _assertConduitState({ 615 | ilk1Shares: 0, 616 | ilk2Shares: 0, 617 | totalShares: 0 618 | }); 619 | 620 | } 621 | 622 | } 623 | -------------------------------------------------------------------------------- /test/SparkLendConduit.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | import 'dss-test/DssTest.sol'; 5 | 6 | import { MockERC20 } from 'erc20-helpers/MockERC20.sol'; 7 | 8 | import { UpgradeableProxy } from 'upgradeable-proxy/UpgradeableProxy.sol'; 9 | 10 | import { SparkLendConduit } from '../src/SparkLendConduit.sol'; 11 | 12 | import { SparkLendConduitHarness } from './harnesses/SparkLendConduitHarness.sol'; 13 | 14 | import { PoolMock, RolesMock, RegistryMock } from "./mocks/Mocks.sol"; 15 | 16 | import { ATokenMock } from "./mocks/ATokenMock.sol"; 17 | 18 | // TODO: Add multiple buffers when multi ilk is used 19 | 20 | contract SparkLendConduitTestBase is DssTest { 21 | 22 | uint256 constant RBPS = RAY / 10_000; 23 | uint256 constant WBPS = WAD / 10_000; 24 | uint256 constant SECONDS_PER_YEAR = 365 days; 25 | 26 | bytes32 constant ILK = 'some-ilk'; 27 | bytes32 constant ILK2 = 'some-ilk2'; 28 | 29 | address buffer = makeAddr("buffer"); 30 | 31 | PoolMock pool; 32 | RolesMock roles; 33 | RegistryMock registry; 34 | MockERC20 token; 35 | ATokenMock atoken; 36 | 37 | SparkLendConduit conduit; 38 | 39 | event Deposit(bytes32 indexed ilk, address indexed asset, address origin, uint256 amount); 40 | event Withdraw(bytes32 indexed ilk, address indexed asset, address destination, uint256 amount); 41 | event SetRoles(address roles); 42 | event SetRegistry(address registry); 43 | event SetAssetEnabled(address indexed asset, bool enabled); 44 | 45 | function setUp() public virtual { 46 | pool = new PoolMock(vm); 47 | roles = new RolesMock(); 48 | registry = new RegistryMock(); 49 | 50 | registry.setBuffer(buffer); // TODO: Update this, make buffer per ilk 51 | 52 | token = new MockERC20('Token', 'TKN', 18); 53 | 54 | atoken = pool.atoken(); 55 | 56 | atoken.setUnderlying(address(token)); 57 | 58 | UpgradeableProxy proxy = new UpgradeableProxy(); 59 | SparkLendConduit impl = new SparkLendConduit(address(pool)); 60 | 61 | proxy.setImplementation(address(impl)); 62 | 63 | conduit = SparkLendConduit(address(proxy)); 64 | 65 | conduit.setRoles(address(roles)); 66 | conduit.setRegistry(address(registry)); 67 | conduit.setAssetEnabled(address(token), true); 68 | 69 | vm.prank(buffer); 70 | token.approve(address(conduit), type(uint256).max); 71 | 72 | // Set default liquidity index to be greater than 1:1 73 | // 100 / 125% = 80 shares for 100 asset deposit 74 | pool.setLiquidityIndex(125_00 * RBPS); 75 | } 76 | 77 | function _assertATokenState( 78 | uint256 scaledBalance, 79 | uint256 scaledTotalSupply, 80 | uint256 balance, 81 | uint256 totalSupply 82 | ) internal { 83 | assertEq(atoken.scaledBalanceOf(address(conduit)), scaledBalance); 84 | assertEq(atoken.scaledTotalSupply(), scaledTotalSupply); 85 | assertEq(atoken.balanceOf(address(conduit)), balance); 86 | assertEq(atoken.totalSupply(), totalSupply); 87 | } 88 | 89 | function _assertTokenState(uint256 bufferBalance, uint256 atokenBalance) internal { 90 | assertEq(token.balanceOf(buffer), bufferBalance); 91 | assertEq(token.balanceOf(address(atoken)), atokenBalance); 92 | } 93 | 94 | } 95 | 96 | contract SparkLendConduitConstructorTests is SparkLendConduitTestBase { 97 | 98 | function test_constructor() public { 99 | assertEq(conduit.pool(), address(pool)); 100 | assertEq(conduit.wards(address(this)), 1); 101 | } 102 | 103 | } 104 | 105 | contract SparkLendConduitModifierTests is SparkLendConduitTestBase { 106 | 107 | function test_authModifiers() public { 108 | UpgradeableProxy(address(conduit)).deny(address(this)); 109 | 110 | checkModifier(address(conduit), "SparkLendConduit/not-authorized", [ 111 | SparkLendConduit.setRoles.selector, 112 | SparkLendConduit.setRegistry.selector, 113 | SparkLendConduit.setAssetEnabled.selector 114 | ]); 115 | } 116 | 117 | function test_ilkAuthModifiers() public { 118 | roles.setCanCall(false); 119 | 120 | checkModifier(address(conduit), "SparkLendConduit/ilk-not-authorized", [ 121 | SparkLendConduit.deposit.selector, 122 | SparkLendConduit.withdraw.selector 123 | ]); 124 | } 125 | 126 | } 127 | 128 | contract SparkLendConduitDepositTests is SparkLendConduitTestBase { 129 | 130 | function setUp() public override { 131 | super.setUp(); 132 | token.mint(buffer, 100 ether); 133 | } 134 | 135 | function test_deposit_revert_notEnabled() public { 136 | conduit.setAssetEnabled(address(token), false); 137 | vm.expectRevert("SparkLendConduit/asset-disabled"); 138 | conduit.deposit(ILK, address(token), 100 ether); 139 | } 140 | 141 | function test_deposit() public { 142 | _assertTokenState({ 143 | bufferBalance: 100 ether, 144 | atokenBalance: 0 145 | }); 146 | 147 | _assertATokenState({ 148 | scaledBalance: 0, 149 | scaledTotalSupply: 0, 150 | balance: 0, 151 | totalSupply: 0 152 | }); 153 | 154 | assertEq(conduit.shares(address(token), ILK), 0); 155 | assertEq(conduit.totalShares(address(token)), 0); 156 | 157 | vm.expectEmit(); 158 | emit Deposit(ILK, address(token), buffer, 100 ether); 159 | conduit.deposit(ILK, address(token), 100 ether); 160 | 161 | _assertTokenState({ 162 | bufferBalance: 0, 163 | atokenBalance: 100 ether 164 | }); 165 | 166 | _assertATokenState({ 167 | scaledBalance: 80 ether, 168 | scaledTotalSupply: 80 ether, 169 | balance: 100 ether, 170 | totalSupply: 100 ether 171 | }); 172 | 173 | assertEq(conduit.shares(address(token), ILK), 80 ether); 174 | assertEq(conduit.totalShares(address(token)), 80 ether); 175 | } 176 | 177 | function test_deposit_multiIlk_increasingIndex() public { 178 | _assertTokenState({ 179 | bufferBalance: 100 ether, 180 | atokenBalance: 0 181 | }); 182 | 183 | _assertATokenState({ 184 | scaledBalance: 0, 185 | scaledTotalSupply: 0, 186 | balance: 0, 187 | totalSupply: 0 188 | }); 189 | 190 | assertEq(conduit.shares(address(token), ILK), 0); 191 | assertEq(conduit.totalShares(address(token)), 0); 192 | 193 | vm.expectEmit(); 194 | emit Deposit(ILK, address(token), buffer, 100 ether); 195 | conduit.deposit(ILK, address(token), 100 ether); 196 | 197 | _assertTokenState({ 198 | bufferBalance: 0, 199 | atokenBalance: 100 ether 200 | }); 201 | 202 | _assertATokenState({ 203 | scaledBalance: 80 ether, 204 | scaledTotalSupply: 80 ether, 205 | balance: 100 ether, 206 | totalSupply: 100 ether 207 | }); 208 | 209 | assertEq(conduit.shares(address(token), ILK), 80 ether); 210 | assertEq(conduit.totalShares(address(token)), 80 ether); 211 | 212 | pool.setLiquidityIndex(160_00 * RBPS); // 50 / 160% = 31.25 shares for 50 asset deposit 213 | 214 | token.mint(buffer, 50 ether); // For second deposit 215 | 216 | vm.expectEmit(); 217 | emit Deposit(ILK2, address(token), buffer, 50 ether); 218 | conduit.deposit(ILK2, address(token), 50 ether); 219 | 220 | _assertTokenState({ 221 | bufferBalance: 0, 222 | atokenBalance: 150 ether 223 | }); 224 | 225 | _assertATokenState({ 226 | scaledBalance: 111.25 ether, // 80 + 31.25 227 | scaledTotalSupply: 111.25 ether, 228 | balance: 178 ether, // 80 * 1.6 + 50 = 178 229 | totalSupply: 178 ether 230 | }); 231 | 232 | assertEq(conduit.shares(address(token), ILK), 80 ether); 233 | assertEq(conduit.shares(address(token), ILK2), 31.25 ether); 234 | assertEq(conduit.totalShares(address(token)), 111.25 ether); 235 | } 236 | 237 | } 238 | 239 | contract SparkLendConduitWithdrawTests is SparkLendConduitTestBase { 240 | 241 | function setUp() public override { 242 | super.setUp(); 243 | token.mint(buffer, 100 ether); 244 | 245 | conduit.deposit(ILK, address(token), 100 ether); 246 | } 247 | 248 | // Assert that one wei can't be withdrawn without burning one share 249 | function test_withdraw_sharesRounding() public { 250 | _assertTokenState({ 251 | bufferBalance: 0, 252 | atokenBalance: 100 ether 253 | }); 254 | 255 | _assertATokenState({ 256 | scaledBalance: 80 ether, 257 | scaledTotalSupply: 80 ether, 258 | balance: 100 ether, 259 | totalSupply: 100 ether 260 | }); 261 | 262 | assertEq(conduit.shares(address(token), ILK), 80 ether); 263 | assertEq(conduit.totalShares(address(token)), 80 ether); 264 | 265 | vm.expectEmit(); 266 | emit Withdraw(ILK, address(token), buffer, 1); 267 | assertEq(conduit.withdraw(ILK, address(token), 1), 1); 268 | 269 | _assertTokenState({ 270 | bufferBalance: 1, 271 | atokenBalance: 100 ether - 1 272 | }); 273 | 274 | // NOTE: SparkLend state doesn't have rounding logic, just conduit state. 275 | _assertATokenState({ 276 | scaledBalance: 80 ether, 277 | scaledTotalSupply: 80 ether, 278 | balance: 100 ether, 279 | totalSupply: 100 ether 280 | }); 281 | 282 | assertEq(conduit.shares(address(token), ILK), 80 ether - 1); 283 | assertEq(conduit.totalShares(address(token)), 80 ether - 1); 284 | } 285 | 286 | function test_withdraw_singleIlk_exactPartialWithdraw() public { 287 | _assertTokenState({ 288 | bufferBalance: 0, 289 | atokenBalance: 100 ether 290 | }); 291 | 292 | _assertATokenState({ 293 | scaledBalance: 80 ether, 294 | scaledTotalSupply: 80 ether, 295 | balance: 100 ether, 296 | totalSupply: 100 ether 297 | }); 298 | 299 | assertEq(conduit.shares(address(token), ILK), 80 ether); 300 | assertEq(conduit.totalShares(address(token)), 80 ether); 301 | 302 | vm.expectEmit(); 303 | emit Withdraw(ILK, address(token), buffer, 40 ether); 304 | assertEq(conduit.withdraw(ILK, address(token), 40 ether), 40 ether); 305 | 306 | _assertTokenState({ 307 | bufferBalance: 40 ether, 308 | atokenBalance: 60 ether 309 | }); 310 | 311 | _assertATokenState({ 312 | scaledBalance: 48 ether, 313 | scaledTotalSupply: 48 ether, 314 | balance: 60 ether, 315 | totalSupply: 60 ether 316 | }); 317 | 318 | assertEq(conduit.shares(address(token), ILK), 48 ether); 319 | assertEq(conduit.totalShares(address(token)), 48 ether); 320 | } 321 | 322 | function test_withdraw_singleIlk_maxUint() public { 323 | _assertTokenState({ 324 | bufferBalance: 0, 325 | atokenBalance: 100 ether 326 | }); 327 | 328 | _assertATokenState({ 329 | scaledBalance: 80 ether, 330 | scaledTotalSupply: 80 ether, 331 | balance: 100 ether, 332 | totalSupply: 100 ether 333 | }); 334 | 335 | assertEq(conduit.shares(address(token), ILK), 80 ether); 336 | assertEq(conduit.totalShares(address(token)), 80 ether); 337 | 338 | vm.expectEmit(); 339 | emit Withdraw(ILK, address(token), buffer, 100 ether); 340 | assertEq(conduit.withdraw(ILK, address(token), type(uint256).max), 100 ether); 341 | 342 | _assertTokenState({ 343 | bufferBalance: 100 ether, 344 | atokenBalance: 0 345 | }); 346 | 347 | _assertATokenState({ 348 | scaledBalance: 0, 349 | scaledTotalSupply: 0, 350 | balance: 0, 351 | totalSupply: 0 352 | }); 353 | 354 | assertEq(conduit.shares(address(token), ILK), 0); 355 | assertEq(conduit.totalShares(address(token)), 0); 356 | } 357 | 358 | function test_withdraw_multiIlk_exactPartialWithdraw() public { 359 | token.mint(buffer, 50 ether); 360 | conduit.deposit(ILK2, address(token), 50 ether); 361 | 362 | _assertTokenState({ 363 | bufferBalance: 0, 364 | atokenBalance: 150 ether 365 | }); 366 | 367 | _assertATokenState({ 368 | scaledBalance: 120 ether, 369 | scaledTotalSupply: 120 ether, 370 | balance: 150 ether, 371 | totalSupply: 150 ether 372 | }); 373 | 374 | assertEq(conduit.shares(address(token), ILK), 80 ether); 375 | assertEq(conduit.shares(address(token), ILK2), 40 ether); 376 | assertEq(conduit.totalShares(address(token)), 120 ether); 377 | 378 | vm.expectEmit(); 379 | emit Withdraw(ILK, address(token), buffer, 50 ether); 380 | assertEq(conduit.withdraw(ILK, address(token), 50 ether), 50 ether); 381 | 382 | _assertTokenState({ 383 | bufferBalance: 50 ether, 384 | atokenBalance: 100 ether 385 | }); 386 | 387 | _assertATokenState({ 388 | scaledBalance: 80 ether, 389 | scaledTotalSupply: 80 ether, 390 | balance: 100 ether, 391 | totalSupply: 100 ether 392 | }); 393 | 394 | assertEq(conduit.shares(address(token), ILK), 40 ether); 395 | assertEq(conduit.shares(address(token), ILK2), 40 ether); 396 | assertEq(conduit.totalShares(address(token)), 80 ether); 397 | } 398 | 399 | // TODO: Partial liquidity 400 | function test_withdraw_multiIlk_maxUint() public { 401 | token.mint(buffer, 50 ether); 402 | conduit.deposit(ILK2, address(token), 50 ether); 403 | 404 | _assertTokenState({ 405 | bufferBalance: 0, 406 | atokenBalance: 150 ether 407 | }); 408 | 409 | _assertATokenState({ 410 | scaledBalance: 120 ether, 411 | scaledTotalSupply: 120 ether, 412 | balance: 150 ether, 413 | totalSupply: 150 ether 414 | }); 415 | 416 | assertEq(conduit.shares(address(token), ILK), 80 ether); 417 | assertEq(conduit.shares(address(token), ILK2), 40 ether); 418 | assertEq(conduit.totalShares(address(token)), 120 ether); 419 | 420 | vm.expectEmit(); 421 | emit Withdraw(ILK, address(token), buffer, 100 ether); 422 | assertEq(conduit.withdraw(ILK, address(token), type(uint256).max), 100 ether); 423 | 424 | _assertTokenState({ 425 | bufferBalance: 100 ether, 426 | atokenBalance: 50 ether 427 | }); 428 | 429 | _assertATokenState({ 430 | scaledBalance: 40 ether, 431 | scaledTotalSupply: 40 ether, 432 | balance: 50 ether, 433 | totalSupply: 50 ether 434 | }); 435 | 436 | assertEq(conduit.shares(address(token), ILK), 0); 437 | assertEq(conduit.shares(address(token), ILK2), 40 ether); 438 | assertEq(conduit.totalShares(address(token)), 40 ether); 439 | } 440 | 441 | function test_withdraw_singleIlk_maxUint_partialLiquidity() public { 442 | deal(address(token), address(atoken), 40 ether); 443 | 444 | _assertTokenState({ 445 | bufferBalance: 0, 446 | atokenBalance: 40 ether 447 | }); 448 | 449 | _assertATokenState({ 450 | scaledBalance: 80 ether, 451 | scaledTotalSupply: 80 ether, 452 | balance: 100 ether, 453 | totalSupply: 100 ether 454 | }); 455 | 456 | assertEq(conduit.shares(address(token), ILK), 80 ether); 457 | assertEq(conduit.totalShares(address(token)), 80 ether); 458 | 459 | vm.expectEmit(); 460 | emit Withdraw(ILK, address(token), buffer, 40 ether); 461 | assertEq(conduit.withdraw(ILK, address(token), type(uint256).max), 40 ether); 462 | 463 | _assertTokenState({ 464 | bufferBalance: 40 ether, 465 | atokenBalance: 0 466 | }); 467 | 468 | _assertATokenState({ 469 | scaledBalance: 48 ether, 470 | scaledTotalSupply: 48 ether, 471 | balance: 60 ether, 472 | totalSupply: 60 ether 473 | }); 474 | 475 | assertEq(conduit.shares(address(token), ILK), 48 ether); 476 | assertEq(conduit.totalShares(address(token)), 48 ether); 477 | } 478 | 479 | function test_withdraw_multiIlk_increasingIndex() public { 480 | token.mint(buffer, 50 ether); 481 | conduit.deposit(ILK2, address(token), 50 ether); 482 | 483 | _assertTokenState({ 484 | bufferBalance: 0, 485 | atokenBalance: 150 ether 486 | }); 487 | 488 | _assertATokenState({ 489 | scaledBalance: 120 ether, 490 | scaledTotalSupply: 120 ether, 491 | balance: 150 ether, 492 | totalSupply: 150 ether 493 | }); 494 | 495 | assertEq(conduit.shares(address(token), ILK), 80 ether); 496 | assertEq(conduit.shares(address(token), ILK2), 40 ether); 497 | assertEq(conduit.totalShares(address(token)), 120 ether); 498 | 499 | // type(uint256).max yields the same underlying funds because of same index 500 | vm.expectEmit(); 501 | emit Withdraw(ILK, address(token), buffer, 100 ether); 502 | assertEq(conduit.withdraw(ILK, address(token), type(uint256).max), 100 ether); 503 | 504 | _assertTokenState({ 505 | bufferBalance: 100 ether, 506 | atokenBalance: 50 ether 507 | }); 508 | 509 | _assertATokenState({ 510 | scaledBalance: 40 ether, 511 | scaledTotalSupply: 40 ether, 512 | balance: 50 ether, 513 | totalSupply: 50 ether 514 | }); 515 | 516 | assertEq(conduit.shares(address(token), ILK), 0); 517 | assertEq(conduit.shares(address(token), ILK2), 40 ether); 518 | assertEq(conduit.totalShares(address(token)), 40 ether); 519 | 520 | // This mimics interest being earned in the pool. However since the liquidity hasn't 521 | // changed, ilk2 will not be able to withdraw the full amount of funds they are entitled to. 522 | // This means that they will instead just burn less shares in order to get their initial 523 | // deposit back. 524 | pool.setLiquidityIndex(160_00 * RBPS); // 100 / 160% = 62.5 shares for 100 asset deposit 525 | 526 | assertEq(conduit.withdraw(ILK2, address(token), type(uint256).max), 50 ether); 527 | 528 | _assertTokenState({ 529 | bufferBalance: 150 ether, 530 | atokenBalance: 0 531 | }); 532 | 533 | _assertATokenState({ 534 | scaledBalance: 8.75 ether, // 40 - (50 / 1.6) = 8.75 535 | scaledTotalSupply: 8.75 ether, 536 | balance: 14 ether, // Interest earned by ilk2 537 | totalSupply: 14 ether 538 | }); 539 | 540 | assertEq(conduit.shares(address(token), ILK), 0); 541 | assertEq(conduit.shares(address(token), ILK2), 8.75 ether); 542 | assertEq(conduit.totalShares(address(token)), 8.75 ether); 543 | } 544 | 545 | function test_withdraw_multiIlk_decreasingIndex() public { 546 | token.mint(buffer, 50 ether); 547 | conduit.deposit(ILK2, address(token), 50 ether); 548 | 549 | _assertTokenState({ 550 | bufferBalance: 0, 551 | atokenBalance: 150 ether 552 | }); 553 | 554 | _assertATokenState({ 555 | scaledBalance: 120 ether, 556 | scaledTotalSupply: 120 ether, 557 | balance: 150 ether, 558 | totalSupply: 150 ether 559 | }); 560 | 561 | assertEq(conduit.shares(address(token), ILK), 80 ether); 562 | assertEq(conduit.shares(address(token), ILK2), 40 ether); 563 | assertEq(conduit.totalShares(address(token)), 120 ether); 564 | 565 | // type(uint256).max yields the same underlying funds because of same index 566 | vm.expectEmit(); 567 | emit Withdraw(ILK, address(token), buffer, 100 ether); 568 | assertEq(conduit.withdraw(ILK, address(token), type(uint256).max), 100 ether); 569 | 570 | _assertTokenState({ 571 | bufferBalance: 100 ether, 572 | atokenBalance: 50 ether 573 | }); 574 | 575 | _assertATokenState({ 576 | scaledBalance: 40 ether, 577 | scaledTotalSupply: 40 ether, 578 | balance: 50 ether, 579 | totalSupply: 50 ether 580 | }); 581 | 582 | assertEq(conduit.shares(address(token), ILK), 0); 583 | assertEq(conduit.shares(address(token), ILK2), 40 ether); 584 | assertEq(conduit.totalShares(address(token)), 40 ether); 585 | 586 | // This mimics a loss in the pool. Since the liquidity hasn't changed, this means that the 587 | // 40 shares that ilk2 has will not be able to withdraw the full amount of funds they 588 | // originally deposited. 589 | pool.setLiquidityIndex(80_00 * RBPS); // 100 / 80% = 125 shares for 100 asset deposit 590 | 591 | assertEq(conduit.withdraw(ILK2, address(token), type(uint256).max), 32 ether); 592 | 593 | _assertTokenState({ 594 | bufferBalance: 132 ether, 595 | atokenBalance: 18 ether 596 | }); 597 | 598 | _assertATokenState({ 599 | scaledBalance: 0, 600 | scaledTotalSupply: 0, 601 | balance: 0, 602 | totalSupply: 0 603 | }); 604 | 605 | assertEq(conduit.shares(address(token), ILK), 0); 606 | assertEq(conduit.shares(address(token), ILK2), 0); 607 | assertEq(conduit.totalShares(address(token)), 0); 608 | } 609 | 610 | } 611 | 612 | contract SparkLendConduitMaxViewFunctionTests is SparkLendConduitTestBase { 613 | 614 | function test_maxDeposit() public { 615 | assertEq(conduit.maxDeposit(ILK, address(token)), type(uint256).max); 616 | } 617 | 618 | function test_maxDeposit_unsupportedAsset() public { 619 | assertEq(conduit.maxDeposit(ILK, makeAddr("some-addr")), 0); 620 | } 621 | 622 | function test_maxWithdraw() public { 623 | assertEq(conduit.maxWithdraw(ILK, address(token)), 0); 624 | 625 | token.mint(buffer, 100 ether); 626 | conduit.deposit(ILK, address(token), 100 ether); 627 | 628 | assertEq(conduit.maxWithdraw(ILK, address(token)), 100 ether); 629 | 630 | deal(address(token), address(atoken), 40 ether); 631 | 632 | assertEq(conduit.maxWithdraw(ILK, address(token)), 40 ether); 633 | } 634 | 635 | } 636 | 637 | contract SparkLendConduitGetTotalDepositsTests is SparkLendConduitTestBase { 638 | 639 | function test_getTotalDeposits() external { 640 | token.mint(buffer, 100 ether); 641 | conduit.deposit(ILK, address(token), 100 ether); 642 | 643 | assertEq(conduit.getTotalDeposits(address(token)), 100 ether); 644 | 645 | pool.setLiquidityIndex(160_00 * RBPS); 646 | 647 | // 100 @ 1.25 = 80, 80 @ 1.6 = 128 648 | assertEq(conduit.getTotalDeposits(address(token)), 128 ether); 649 | } 650 | 651 | function testFuzz_getTotalDeposits( 652 | uint256 index1, 653 | uint256 index2, 654 | uint256 depositAmount 655 | ) 656 | external 657 | { 658 | index1 = bound(index1, 1 * RBPS, 500_00 * RBPS); 659 | index2 = bound(index2, 1 * RBPS, 500_00 * RBPS); 660 | depositAmount = bound(depositAmount, 0, 1e32); 661 | 662 | pool.setLiquidityIndex(index1); 663 | 664 | token.mint(buffer, depositAmount); 665 | conduit.deposit(ILK, address(token), depositAmount); 666 | 667 | assertApproxEqAbs(conduit.getTotalDeposits(address(token)), depositAmount, 10); 668 | 669 | pool.setLiquidityIndex(index2); 670 | 671 | uint256 expectedDeposit = depositAmount * 1e27 / index1 * index2 / 1e27; 672 | 673 | assertApproxEqAbs(conduit.getTotalDeposits(address(token)), expectedDeposit, 10); 674 | } 675 | 676 | } 677 | 678 | contract SparkLendConduitGetDepositsTests is SparkLendConduitTestBase { 679 | 680 | function test_getDeposits() external { 681 | token.mint(buffer, 100 ether); 682 | conduit.deposit(ILK, address(token), 100 ether); 683 | 684 | assertEq(conduit.getDeposits(address(token), ILK), 100 ether); 685 | 686 | pool.setLiquidityIndex(160_00 * RBPS); 687 | 688 | // 100 @ 1.25 = 80, 80 @ 1.6 = 128 689 | assertEq(conduit.getDeposits(address(token), ILK), 128 ether); 690 | } 691 | 692 | function testFuzz_getDeposits( 693 | uint256 index1, 694 | uint256 index2, 695 | uint256 depositAmount 696 | ) 697 | external 698 | { 699 | index1 = bound(index1, 1 * RBPS, 500_00 * RBPS); 700 | index2 = bound(index2, 1 * RBPS, 500_00 * RBPS); 701 | depositAmount = bound(depositAmount, 0, 1e32); 702 | 703 | pool.setLiquidityIndex(index1); 704 | 705 | token.mint(buffer, depositAmount); 706 | conduit.deposit(ILK, address(token), depositAmount); 707 | 708 | assertApproxEqAbs(conduit.getDeposits(address(token), ILK), depositAmount, 10); 709 | 710 | pool.setLiquidityIndex(index2); 711 | 712 | uint256 expectedDeposit = depositAmount * 1e27 / index1 * index2 / 1e27; 713 | 714 | assertApproxEqAbs(conduit.getDeposits(address(token), ILK), expectedDeposit, 10); 715 | } 716 | 717 | } 718 | 719 | contract SparkLendConduitGetAvailableLiquidityTests is SparkLendConduitTestBase { 720 | 721 | function test_getAvailableLiquidity() external { 722 | assertEq(conduit.getAvailableLiquidity(address(token)), 0); 723 | 724 | deal(address(token), address(atoken), 100 ether); 725 | 726 | assertEq(conduit.getAvailableLiquidity(address(token)), 100 ether); 727 | } 728 | 729 | function testFuzz_getAvailableLiquidity(uint256 dealAmount) external { 730 | assertEq(conduit.getAvailableLiquidity(address(token)), 0); 731 | 732 | deal(address(token), address(atoken), dealAmount); 733 | 734 | assertEq(conduit.getAvailableLiquidity(address(token)), dealAmount); 735 | } 736 | 737 | } 738 | 739 | contract SparkLendConduitAdminSetterTests is SparkLendConduitTestBase { 740 | 741 | address SET_ADDRESS = makeAddr("set-address"); 742 | 743 | function test_setRoles() public { 744 | assertEq(conduit.roles(), address(roles)); 745 | 746 | vm.expectEmit(); 747 | emit SetRoles(SET_ADDRESS); 748 | conduit.setRoles(SET_ADDRESS); 749 | 750 | assertEq(conduit.roles(), SET_ADDRESS); 751 | } 752 | 753 | function test_setRegistry() public { 754 | assertEq(conduit.registry(), address(registry)); 755 | 756 | vm.expectEmit(); 757 | emit SetRegistry(SET_ADDRESS); 758 | conduit.setRegistry(SET_ADDRESS); 759 | 760 | assertEq(conduit.registry(), SET_ADDRESS); 761 | } 762 | 763 | function test_setAssetEnabled() public { 764 | // Starting state 765 | conduit.setAssetEnabled(address(token), false); 766 | 767 | assertEq(conduit.enabled(address(token)), false); 768 | 769 | assertEq(token.allowance(address(conduit), address(pool)), 0); 770 | 771 | vm.expectEmit(); 772 | emit SetAssetEnabled(address(token), true); 773 | conduit.setAssetEnabled(address(token), true); 774 | 775 | assertEq(conduit.enabled(address(token)), true); 776 | 777 | assertEq(token.allowance(address(conduit), address(pool)), type(uint256).max); 778 | 779 | vm.expectEmit(); 780 | emit SetAssetEnabled(address(token), false); 781 | conduit.setAssetEnabled(address(token), false); 782 | 783 | assertEq(conduit.enabled(address(token)), false); 784 | 785 | assertEq(token.allowance(address(conduit), address(pool)), 0); 786 | } 787 | 788 | } 789 | 790 | contract SparkLendConduitHarnessDivUpTests is SparkLendConduitTestBase { 791 | 792 | SparkLendConduitHarness conduitHarness; 793 | 794 | function setUp() public override { 795 | super.setUp(); 796 | 797 | SparkLendConduitHarness impl = new SparkLendConduitHarness(address(pool)); 798 | 799 | UpgradeableProxy(address(conduit)).setImplementation(address(impl)); 800 | 801 | conduitHarness = SparkLendConduitHarness(address(conduit)); 802 | } 803 | 804 | function test_divUp() public { 805 | // Divide by zero 806 | vm.expectRevert(stdError.divisionError); 807 | conduitHarness.divUp(1, 0); 808 | 809 | // Small numbers 810 | assertEq(conduitHarness.divUp(0, 1), 0); 811 | assertEq(conduitHarness.divUp(1, 1), 1); 812 | assertEq(conduitHarness.divUp(2, 1), 2); 813 | assertEq(conduitHarness.divUp(3, 1), 3); 814 | assertEq(conduitHarness.divUp(4, 1), 4); 815 | 816 | assertEq(conduitHarness.divUp(0, 2), 0); 817 | assertEq(conduitHarness.divUp(1, 2), 1); 818 | assertEq(conduitHarness.divUp(2, 2), 1); 819 | assertEq(conduitHarness.divUp(3, 2), 2); 820 | assertEq(conduitHarness.divUp(4, 2), 2); 821 | 822 | assertEq(conduitHarness.divUp(0, 3), 0); 823 | assertEq(conduitHarness.divUp(1, 3), 1); 824 | assertEq(conduitHarness.divUp(2, 3), 1); 825 | assertEq(conduitHarness.divUp(3, 3), 1); 826 | assertEq(conduitHarness.divUp(4, 3), 2); 827 | assertEq(conduitHarness.divUp(5, 3), 2); 828 | assertEq(conduitHarness.divUp(6, 3), 2); 829 | 830 | // Large numbers 831 | assertEq(conduitHarness.divUp(0, 1e27), 0); 832 | assertEq(conduitHarness.divUp(1, 1e27), 1); 833 | 834 | assertEq(conduitHarness.divUp(1e27, 1e27 + 1), 1); 835 | assertEq(conduitHarness.divUp(1e27 + 1, 1e27 + 1), 1); 836 | assertEq(conduitHarness.divUp(1e27 + 1, 1e27), 2); 837 | } 838 | 839 | } 840 | -------------------------------------------------------------------------------- /test/harnesses/SparkLendConduitHarness.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.13; 3 | 4 | import { SparkLendConduit } from "src/SparkLendConduit.sol"; 5 | 6 | contract SparkLendConduitHarness is SparkLendConduit { 7 | constructor(address _pool) SparkLendConduit(_pool) {} 8 | 9 | function divUp(uint256 x, uint256 y) external pure returns (uint256) { 10 | return _divUp(x, y); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /test/mocks/ATokenMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity >=0.8.0; 3 | 4 | import { PoolMock } from "./Mocks.sol"; 5 | 6 | contract ATokenMock { 7 | 8 | address underlying; 9 | 10 | string public name; 11 | string public symbol; 12 | 13 | uint8 public immutable decimals; 14 | 15 | uint256 private _totalSupply; 16 | 17 | PoolMock pool; 18 | 19 | mapping(address => uint256) private _balanceOf; 20 | 21 | mapping(address => mapping(address => uint256)) public allowance; 22 | 23 | constructor( 24 | string memory name_, 25 | string memory symbol_, 26 | uint8 decimals_, 27 | address pool_ 28 | ) { 29 | name = name_; 30 | symbol = symbol_; 31 | decimals = decimals_; 32 | 33 | pool = PoolMock(pool_); 34 | } 35 | 36 | /**********************************************************************************************/ 37 | /*** External Functions ***/ 38 | /**********************************************************************************************/ 39 | 40 | function approve(address spender_, uint256 amount_) public virtual returns (bool success_) { 41 | _approve(msg.sender, spender_, amount_); 42 | return true; 43 | } 44 | 45 | function decreaseAllowance(address spender_, uint256 subtractedAmount_) 46 | public virtual returns (bool success_) 47 | { 48 | _decreaseAllowance(msg.sender, spender_, subtractedAmount_); 49 | return true; 50 | } 51 | 52 | function increaseAllowance(address spender_, uint256 addedAmount_) 53 | public virtual returns (bool success_) 54 | { 55 | _approve(msg.sender, spender_, allowance[msg.sender][spender_] + addedAmount_); 56 | return true; 57 | } 58 | function transfer(address recipient_, uint256 amount_) public virtual returns (bool success_) { 59 | _transfer(msg.sender, recipient_, amount_); 60 | return true; 61 | } 62 | 63 | function transferFrom(address owner_, address recipient_, uint256 amount_) 64 | public virtual returns (bool success_) 65 | { 66 | _decreaseAllowance(owner_, msg.sender, amount_); 67 | _transfer(owner_, recipient_, amount_); 68 | return true; 69 | } 70 | 71 | /**********************************************************************************************/ 72 | /*** View Functions ***/ 73 | /**********************************************************************************************/ 74 | 75 | function balanceOf(address user) public view returns (uint256) { 76 | return _balanceOf[user] * pool.getReserveNormalizedIncome(underlying) / 1e27; 77 | } 78 | 79 | function scaledBalanceOf(address user) public view returns (uint256) { 80 | return _balanceOf[user]; 81 | } 82 | 83 | function totalSupply() public view returns (uint256) { 84 | return _totalSupply * pool.getReserveNormalizedIncome(underlying) / 1e27; 85 | } 86 | 87 | function scaledTotalSupply() public view returns (uint256) { 88 | return _totalSupply; 89 | } 90 | 91 | /**********************************************************************************************/ 92 | /*** Mock Functions ***/ 93 | /**********************************************************************************************/ 94 | 95 | function mint(address account_, uint256 amount_) external virtual returns (bool success_) { 96 | _mint(account_, amount_); 97 | return true; 98 | } 99 | 100 | function burn(address account_, uint256 amount_) external virtual returns (bool success_) { 101 | _burn(account_, amount_); 102 | return true; 103 | } 104 | 105 | function setUnderlying(address underlying_) external { 106 | underlying = underlying_; 107 | } 108 | 109 | /**********************************************************************************************/ 110 | /*** Internal Functions ***/ 111 | /**********************************************************************************************/ 112 | 113 | function _approve(address owner_, address spender_, uint256 amount_) internal { 114 | allowance[owner_][spender_] = amount_; 115 | } 116 | 117 | function _burn(address owner_, uint256 amount_) internal { 118 | _balanceOf[owner_] -= amount_; 119 | 120 | // Cannot underflow because a user's balance will never be larger than the total supply. 121 | unchecked { _totalSupply -= amount_; } 122 | } 123 | 124 | function _decreaseAllowance(address owner_, address spender_, uint256 subtractedAmount_) internal { 125 | uint256 spenderAllowance = allowance[owner_][spender_]; // Cache to memory. 126 | 127 | if (spenderAllowance != type(uint256).max) { 128 | _approve(owner_, spender_, spenderAllowance - subtractedAmount_); 129 | } 130 | } 131 | 132 | function _mint(address recipient_, uint256 amount_) internal { 133 | _totalSupply += amount_; 134 | 135 | // Cannot overflow because totalSupply would first overflow in the statement above. 136 | unchecked { _balanceOf[recipient_] += amount_; } 137 | } 138 | 139 | function _transfer(address owner_, address recipient_, uint256 amount_) internal { 140 | _balanceOf[owner_] -= amount_; 141 | 142 | // Cannot overflow because minting prevents overflow of totalSupply, 143 | // and sum of user balances == totalSupply. 144 | unchecked { _balanceOf[recipient_] += amount_; } 145 | } 146 | 147 | } 148 | -------------------------------------------------------------------------------- /test/mocks/Mocks.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | import 'dss-test/DssTest.sol'; 5 | 6 | import { DataTypes } from 'aave-v3-core/contracts/protocol/libraries/types/DataTypes.sol'; 7 | 8 | import { MockERC20 } from 'erc20-helpers/MockERC20.sol'; 9 | 10 | import { SparkLendConduit, IERC20 } from 'src/SparkLendConduit.sol'; 11 | 12 | import { ATokenMock } from "./ATokenMock.sol"; 13 | 14 | contract DaiMock { 15 | 16 | uint256 public liquidity; 17 | 18 | function setLiquidity(uint256 _liquidity) external { 19 | liquidity += _liquidity; 20 | } 21 | 22 | function balanceOf(address) external view returns (uint256) { 23 | return liquidity; 24 | } 25 | 26 | } 27 | 28 | contract PoolMock { 29 | 30 | Vm vm; 31 | 32 | ATokenMock public atoken; 33 | 34 | uint256 public liquidityIndex = 10 ** 27; 35 | 36 | constructor(Vm vm_) { 37 | vm = vm_; 38 | atoken = new ATokenMock('aToken', 'aTKN', 18, address(this)); 39 | } 40 | 41 | function supply(address asset, uint256 amount, address, uint16) external { 42 | IERC20(asset).transferFrom(msg.sender, address(atoken), amount); 43 | atoken.mint(msg.sender, _convertToShares(amount)); 44 | } 45 | 46 | function withdraw(address asset, uint256 amount, address to) external returns (uint256) { 47 | uint256 liquidityAvailable = IERC20(asset).balanceOf(address(atoken)); 48 | if (amount > liquidityAvailable) { 49 | amount = liquidityAvailable; 50 | } 51 | vm.prank(address(atoken)); 52 | IERC20(asset).transfer(to, amount); 53 | 54 | atoken.burn(msg.sender, _convertToShares(amount)); 55 | return amount; 56 | } 57 | 58 | function getReserveData(address) external view returns (DataTypes.ReserveData memory) { 59 | return DataTypes.ReserveData({ 60 | configuration: DataTypes.ReserveConfigurationMap(0), 61 | liquidityIndex: uint128(liquidityIndex), 62 | currentLiquidityRate: 0, 63 | variableBorrowIndex: 0, 64 | currentVariableBorrowRate: 0, 65 | currentStableBorrowRate: 0, 66 | lastUpdateTimestamp: 0, 67 | id: 0, 68 | aTokenAddress: address(atoken), 69 | stableDebtTokenAddress: address(0), 70 | variableDebtTokenAddress: address(0), 71 | interestRateStrategyAddress: address(0), 72 | accruedToTreasury: 0, 73 | unbacked: 0, 74 | isolationModeTotalDebt: 0 75 | }); 76 | } 77 | 78 | function getReserveNormalizedIncome(address) external view returns (uint256) { 79 | return liquidityIndex; 80 | } 81 | 82 | function setLiquidityIndex(uint256 _liquidityIndex) external { 83 | liquidityIndex = _liquidityIndex; 84 | } 85 | 86 | function _convertToShares(uint256 amount) internal view returns (uint256) { 87 | return amount * 1e27 / liquidityIndex; 88 | } 89 | 90 | } 91 | 92 | contract RolesMock { 93 | 94 | bool public canCallSuccess = true; 95 | 96 | function canCall(bytes32, address, address, bytes4) external view returns (bool) { 97 | return canCallSuccess; 98 | } 99 | 100 | function setCanCall(bool _on) external { 101 | canCallSuccess = _on; 102 | } 103 | 104 | } 105 | 106 | contract RegistryMock { 107 | 108 | address public buffer; 109 | 110 | function buffers(bytes32) external view returns (address) { 111 | return buffer; 112 | } 113 | 114 | function setBuffer(address b) external { 115 | buffer = b; 116 | } 117 | 118 | } 119 | --------------------------------------------------------------------------------