├── .eslintrc.json ├── .gitattributes ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .prettierrc ├── .solcover.js ├── .solhint.json ├── .soliumignore ├── .soliumrc.json ├── LICENSE.md ├── README.md ├── buidler.config.js ├── contracts ├── YieldDaiBorrower.sol ├── YieldDaiLender.sol ├── YieldFYDaiLender.sol ├── YieldFlashDemo.sol ├── fyDai │ ├── Math64x64.sol │ ├── Pool.sol │ └── YieldMath.sol ├── helpers │ ├── DecimalMath.sol │ ├── Delegable.sol │ ├── ERC20Permit.sol │ ├── Orchestrated.sol │ └── SafeCast.sol └── interfaces │ ├── IDai.sol │ ├── IDelegable.sol │ ├── IERC2612.sol │ ├── IFYDai.sol │ ├── IFlashMinter.sol │ └── IPool.sol ├── deploy ├── daiBorrower.js ├── daiLender.js └── fyDaiLender.js ├── migrations └── 1_initial_migration.js ├── package.json ├── scripts ├── ganache.sh ├── mainnet-ganache.sh └── setup_mainnet_ganache.js ├── test ├── flashYield.ts └── shared │ ├── fixtures.ts │ ├── utils.spec.ts │ └── utils.ts ├── truffle-config.js ├── tsconfig.json └── yarn.lock /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "es2020": true, 4 | "node": true 5 | }, 6 | "extends": [ 7 | "airbnb-base" 8 | ], 9 | "parserOptions": { 10 | "ecmaVersion": 11, 11 | "sourceType": "module" 12 | }, 13 | "rules": { 14 | } 15 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | lint: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - uses: actions/setup-node@v1 16 | with: 17 | node-version: 12.x 18 | 19 | - id: yarn-cache 20 | run: echo "::set-output name=dir::$(yarn cache dir)" 21 | 22 | - uses: actions/cache@v1 23 | with: 24 | path: ${{ steps.yarn-cache.outputs.dir }} 25 | key: yarn-${{ hashFiles('**/yarn.lock') }} 26 | restore-keys: | 27 | yarn- 28 | - run: yarn 29 | - run: yarn lint 30 | 31 | test: 32 | runs-on: ubuntu-latest 33 | 34 | steps: 35 | - uses: actions/checkout@v1 36 | - uses: actions/setup-node@v1 37 | with: 38 | node-version: 12.x 39 | 40 | - id: yarn-cache 41 | run: echo "::set-output name=dir::$(yarn cache dir)" 42 | 43 | - uses: actions/cache@v1 44 | with: 45 | path: ${{ steps.yarn-cache.outputs.dir }} 46 | key: yarn-${{ hashFiles('**/yarn.lock') }} 47 | restore-keys: | 48 | yarn- 49 | - run: yarn 50 | - run: yarn test 51 | 52 | migrations: 53 | runs-on: ubuntu-latest 54 | 55 | steps: 56 | - uses: actions/checkout@v1 57 | - uses: actions/setup-node@v1 58 | with: 59 | node-version: 12.x 60 | 61 | - id: yarn-cache 62 | run: echo "::set-output name=dir::$(yarn cache dir)" 63 | 64 | - uses: actions/cache@v1 65 | with: 66 | path: ${{ steps.yarn-cache.outputs.dir }} 67 | key: yarn-${{ hashFiles('**/yarn.lock') }} 68 | restore-keys: | 69 | yarn- 70 | - run: yarn 71 | - run: yarn deploy:ganache 72 | - run: npx truffle exec scripts/setup_market_dev.js 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled binary addons (https://nodejs.org/api/addons.html) 2 | build/Release 3 | 4 | # Optional npm cache directory 5 | .npm 6 | 7 | # dotenv environment variables file 8 | .env 9 | .env.test 10 | 11 | # Truffle contract build files 12 | build/contracts 13 | 14 | # Temp & IDE files 15 | .vscode/ 16 | *~ 17 | *.swp 18 | *.swo 19 | 20 | # Buidler files 21 | cache 22 | artifacts 23 | node_modules/ 24 | output/ 25 | 26 | # Truffle files 27 | .infuraKey 28 | .secret 29 | keys/ 30 | build/ 31 | 32 | # Solidity-coverage 33 | coverage/ 34 | .coverage_contracts/ 35 | coverage.json 36 | 37 | # Yarn 38 | yarn-error.log 39 | 40 | # NPM 41 | package-lock.json 42 | 43 | # Crytic 44 | crytic-export/ 45 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "printWidth": 120 5 | } 6 | -------------------------------------------------------------------------------- /.solcover.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | skipFiles: [ 3 | 'Migrations.sol', 4 | 'chai', 5 | 'maker', 6 | 'mocks' 7 | ] 8 | }; -------------------------------------------------------------------------------- /.solhint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solhint:recommended", 3 | "plugins": [], 4 | "rules": { 5 | "avoid-throw": "off", 6 | "avoid-suicide": "error", 7 | "avoid-sha3": "warn", 8 | "compiler-version": "off", 9 | "no-empty-blocks": "off" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.soliumignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fifikobayashi/YieldFlashDemo/08c17d188ecbb492bea5162b9cc4634cc291ff33/.soliumignore -------------------------------------------------------------------------------- /.soliumrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solium:all", 3 | "plugins": [ 4 | "security" 5 | ], 6 | "rules": { 7 | "error-reason": "off", 8 | "indentation": [ 9 | "error", 10 | 4 11 | ], 12 | "lbrace": "off", 13 | "linebreak-style": [ 14 | "error", 15 | "unix" 16 | ], 17 | "max-len": [ 18 | "error", 19 | 119 20 | ], 21 | "no-constant": [ 22 | "error" 23 | ], 24 | "no-empty-blocks": "off", 25 | "quotes": [ 26 | "error", 27 | "double" 28 | ], 29 | "uppercase": "off", 30 | "visibility-first": "error", 31 | "security/enforce-explicit-visibility": [ 32 | "error" 33 | ], 34 | "security/no-block-members": [ 35 | "warning" 36 | ], 37 | "security/no-inline-assembly": [ 38 | "warning" 39 | ], 40 | "imports-on-top": "warning", 41 | "variable-declarations": "warning", 42 | "array-declarations": "warning", 43 | "operator-whitespace": "warning", 44 | "function-whitespace": "warning", 45 | "semicolon-whitespace": "warning", 46 | "comma-whitespace": "warning", 47 | "conditionals-whitespace": "warning", 48 | "arg-overflow": "off" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 [Free Software Foundation, Inc.](http://fsf.org/) 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this license 7 | document, but changing it is not allowed. 8 | 9 | ## Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for software and 12 | other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed to take 15 | away your freedom to share and change the works. By contrast, the GNU General 16 | Public License is intended to guarantee your freedom to share and change all 17 | versions of a program--to make sure it remains free software for all its users. 18 | We, the Free Software Foundation, use the GNU General Public License for most 19 | of our software; it applies also to any other work released this way by its 20 | authors. You can apply it to your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not price. Our 23 | General Public Licenses are designed to make sure that you have the freedom to 24 | distribute copies of free software (and charge for them if you wish), that you 25 | receive source code or can get it if you want it, that you can change the 26 | software or use pieces of it in new free programs, and that you know you can do 27 | these things. 28 | 29 | To protect your rights, we need to prevent others from denying you these rights 30 | or asking you to surrender the rights. Therefore, you have certain 31 | responsibilities if you distribute copies of the software, or if you modify it: 32 | responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for 35 | a fee, you must pass on to the recipients the same freedoms that you received. 36 | You must make sure that they, too, receive or can get the source code. And you 37 | must show them these terms so they know their rights. 38 | 39 | Developers that use the GNU GPL protect your rights with two steps: 40 | 41 | 1. assert copyright on the software, and 42 | 2. offer you this License giving you legal permission to copy, distribute 43 | and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains that 46 | there is no warranty for this free software. For both users' and authors' sake, 47 | the GPL requires that modified versions be marked as changed, so that their 48 | problems will not be attributed erroneously to authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run modified 51 | versions of the software inside them, although the manufacturer can do so. This 52 | is fundamentally incompatible with the aim of protecting users' freedom to 53 | change the software. The systematic pattern of such abuse occurs in the area of 54 | products for individuals to use, which is precisely where it is most 55 | unacceptable. Therefore, we have designed this version of the GPL to prohibit 56 | the practice for those products. If such problems arise substantially in other 57 | domains, we stand ready to extend this provision to those domains in future 58 | versions of the GPL, as needed to protect the freedom of users. 59 | 60 | Finally, every program is threatened constantly by software patents. States 61 | should not allow patents to restrict development and use of software on 62 | general-purpose computers, but in those that do, we wish to avoid the special 63 | danger that patents applied to a free program could make it effectively 64 | proprietary. To prevent this, the GPL assures that patents cannot be used to 65 | render the program non-free. 66 | 67 | The precise terms and conditions for copying, distribution and modification 68 | follow. 69 | 70 | ## TERMS AND CONDITIONS 71 | 72 | ### 0. Definitions. 73 | 74 | *This License* refers to version 3 of the GNU General Public License. 75 | 76 | *Copyright* also means copyright-like laws that apply to other kinds of works, 77 | such as semiconductor masks. 78 | 79 | *The Program* refers to any copyrightable work licensed under this License. 80 | Each licensee is addressed as *you*. *Licensees* and *recipients* may be 81 | individuals or organizations. 82 | 83 | To *modify* a work means to copy from or adapt all or part of the work in a 84 | fashion requiring copyright permission, other than the making of an exact copy. 85 | The resulting work is called a *modified version* of the earlier work or a work 86 | *based on* the earlier work. 87 | 88 | A *covered work* means either the unmodified Program or a work based on the 89 | Program. 90 | 91 | To *propagate* a work means to do anything with it that, without permission, 92 | would make you directly or secondarily liable for infringement under applicable 93 | copyright law, except executing it on a computer or modifying a private copy. 94 | Propagation includes copying, distribution (with or without modification), 95 | making available to the public, and in some countries other activities as well. 96 | 97 | To *convey* a work means any kind of propagation that enables other parties to 98 | make or receive copies. Mere interaction with a user through a computer 99 | network, with no transfer of a copy, is not conveying. 100 | 101 | An interactive user interface displays *Appropriate Legal Notices* to the 102 | extent that it includes a convenient and prominently visible feature that 103 | 104 | 1. displays an appropriate copyright notice, and 105 | 2. tells the user that there is no warranty for the work (except to the 106 | extent that warranties are provided), that licensees may convey the work 107 | under this License, and how to view a copy of this License. 108 | 109 | If the interface presents a list of user commands or options, such as a menu, a 110 | prominent item in the list meets this criterion. 111 | 112 | ### 1. Source Code. 113 | 114 | The *source code* for a work means the preferred form of the work for making 115 | modifications to it. *Object code* means any non-source form of a work. 116 | 117 | A *Standard Interface* means an interface that either is an official standard 118 | defined by a recognized standards body, or, in the case of interfaces specified 119 | for a particular programming language, one that is widely used among developers 120 | working in that language. 121 | 122 | The *System Libraries* of an executable work include anything, other than the 123 | work as a whole, that (a) is included in the normal form of packaging a Major 124 | Component, but which is not part of that Major Component, and (b) serves only 125 | to enable use of the work with that Major Component, or to implement a Standard 126 | Interface for which an implementation is available to the public in source code 127 | form. A *Major Component*, in this context, means a major essential component 128 | (kernel, window system, and so on) of the specific operating system (if any) on 129 | which the executable work runs, or a compiler used to produce the work, or an 130 | object code interpreter used to run it. 131 | 132 | The *Corresponding Source* for a work in object code form means all the source 133 | code needed to generate, install, and (for an executable work) run the object 134 | code and to modify the work, including scripts to control those activities. 135 | However, it does not include the work's System Libraries, or general-purpose 136 | tools or generally available free programs which are used unmodified in 137 | performing those activities but which are not part of the work. For example, 138 | Corresponding Source includes interface definition files associated with source 139 | files for the work, and the source code for shared libraries and dynamically 140 | linked subprograms that the work is specifically designed to require, such as 141 | by intimate data communication or control flow between those subprograms and 142 | other parts of the work. 143 | 144 | The Corresponding Source need not include anything that users can regenerate 145 | automatically from other parts of the Corresponding Source. 146 | 147 | The Corresponding Source for a work in source code form is that same work. 148 | 149 | ### 2. Basic Permissions. 150 | 151 | All rights granted under this License are granted for the term of copyright on 152 | the Program, and are irrevocable provided the stated conditions are met. This 153 | License explicitly affirms your unlimited permission to run the unmodified 154 | Program. The output from running a covered work is covered by this License only 155 | if the output, given its content, constitutes a covered work. This License 156 | acknowledges your rights of fair use or other equivalent, as provided by 157 | copyright law. 158 | 159 | You may make, run and propagate covered works that you do not convey, without 160 | conditions so long as your license otherwise remains in force. You may convey 161 | covered works to others for the sole purpose of having them make modifications 162 | exclusively for you, or provide you with facilities for running those works, 163 | provided that you comply with the terms of this License in conveying all 164 | material for which you do not control copyright. Those thus making or running 165 | the covered works for you must do so exclusively on your behalf, under your 166 | direction and control, on terms that prohibit them from making any copies of 167 | your copyrighted material outside their relationship with you. 168 | 169 | Conveying under any other circumstances is permitted solely under the 170 | conditions stated below. Sublicensing is not allowed; section 10 makes it 171 | unnecessary. 172 | 173 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 174 | 175 | No covered work shall be deemed part of an effective technological measure 176 | under any applicable law fulfilling obligations under article 11 of the WIPO 177 | copyright treaty adopted on 20 December 1996, or similar laws prohibiting or 178 | restricting circumvention of such measures. 179 | 180 | When you convey a covered work, you waive any legal power to forbid 181 | circumvention of technological measures to the extent such circumvention is 182 | effected by exercising rights under this License with respect to the covered 183 | work, and you disclaim any intention to limit operation or modification of the 184 | work as a means of enforcing, against the work's users, your or third parties' 185 | legal rights to forbid circumvention of technological measures. 186 | 187 | ### 4. Conveying Verbatim Copies. 188 | 189 | You may convey verbatim copies of the Program's source code as you receive it, 190 | in any medium, provided that you conspicuously and appropriately publish on 191 | each copy an appropriate copyright notice; keep intact all notices stating that 192 | this License and any non-permissive terms added in accord with section 7 apply 193 | to the code; keep intact all notices of the absence of any warranty; and give 194 | all recipients a copy of this License along with the Program. 195 | 196 | You may charge any price or no price for each copy that you convey, and you may 197 | offer support or warranty protection for a fee. 198 | 199 | ### 5. Conveying Modified Source Versions. 200 | 201 | You may convey a work based on the Program, or the modifications to produce it 202 | from the Program, in the form of source code under the terms of section 4, 203 | provided that you also meet all of these conditions: 204 | 205 | - a) The work must carry prominent notices stating that you modified it, and 206 | giving a relevant date. 207 | - b) The work must carry prominent notices stating that it is released under 208 | this License and any conditions added under section 7. This requirement 209 | modifies the requirement in section 4 to *keep intact all notices*. 210 | - c) You must license the entire work, as a whole, under this License to 211 | anyone who comes into possession of a copy. This License will therefore 212 | apply, along with any applicable section 7 additional terms, to the whole 213 | of the work, and all its parts, regardless of how they are packaged. This 214 | License gives no permission to license the work in any other way, but it 215 | does not invalidate such permission if you have separately received it. 216 | - d) If the work has interactive user interfaces, each must display 217 | Appropriate Legal Notices; however, if the Program has interactive 218 | interfaces that do not display Appropriate Legal Notices, your work need 219 | not make them do so. 220 | 221 | A compilation of a covered work with other separate and independent works, 222 | which are not by their nature extensions of the covered work, and which are not 223 | combined with it such as to form a larger program, in or on a volume of a 224 | storage or distribution medium, is called an *aggregate* if the compilation and 225 | its resulting copyright are not used to limit the access or legal rights of the 226 | compilation's users beyond what the individual works permit. Inclusion of a 227 | covered work in an aggregate does not cause this License to apply to the other 228 | parts of the aggregate. 229 | 230 | ### 6. Conveying Non-Source Forms. 231 | 232 | You may convey a covered work in object code form under the terms of sections 4 233 | and 5, provided that you also convey the machine-readable Corresponding Source 234 | under the terms of this License, in one of these ways: 235 | 236 | - a) Convey the object code in, or embodied in, a physical product (including 237 | a physical distribution medium), accompanied by the Corresponding Source 238 | fixed on a durable physical medium customarily used for software 239 | interchange. 240 | - b) Convey the object code in, or embodied in, a physical product (including 241 | a physical distribution medium), accompanied by a written offer, valid for 242 | at least three years and valid for as long as you offer spare parts or 243 | customer support for that product model, to give anyone who possesses the 244 | object code either 245 | 1. a copy of the Corresponding Source for all the software in the product 246 | that is covered by this License, on a durable physical medium 247 | customarily used for software interchange, for a price no more than your 248 | reasonable cost of physically performing this conveying of source, or 249 | 2. access to copy the Corresponding Source from a network server at no 250 | charge. 251 | - c) Convey individual copies of the object code with a copy of the written 252 | offer to provide the Corresponding Source. This alternative is allowed only 253 | occasionally and noncommercially, and only if you received the object code 254 | with such an offer, in accord with subsection 6b. 255 | - d) Convey the object code by offering access from a designated place 256 | (gratis or for a charge), and offer equivalent access to the Corresponding 257 | Source in the same way through the same place at no further charge. You 258 | need not require recipients to copy the Corresponding Source along with the 259 | object code. If the place to copy the object code is a network server, the 260 | Corresponding Source may be on a different server operated by you or a 261 | third party) that supports equivalent copying facilities, provided you 262 | maintain clear directions next to the object code saying where to find the 263 | Corresponding Source. Regardless of what server hosts the Corresponding 264 | Source, you remain obligated to ensure that it is available for as long as 265 | needed to satisfy these requirements. 266 | - e) Convey the object code using peer-to-peer transmission, provided you 267 | inform other peers where the object code and Corresponding Source of the 268 | work are being offered to the general public at no charge under subsection 269 | 6d. 270 | 271 | A separable portion of the object code, whose source code is excluded from the 272 | Corresponding Source as a System Library, need not be included in conveying the 273 | object code work. 274 | 275 | A *User Product* is either 276 | 277 | 1. a *consumer product*, which means any tangible personal property which is 278 | normally used for personal, family, or household purposes, or 279 | 2. anything designed or sold for incorporation into a dwelling. 280 | 281 | In determining whether a product is a consumer product, doubtful cases shall be 282 | resolved in favor of coverage. For a particular product received by a 283 | particular user, *normally used* refers to a typical or common use of that 284 | class of product, regardless of the status of the particular user or of the way 285 | in which the particular user actually uses, or expects or is expected to use, 286 | the product. A product is a consumer product regardless of whether the product 287 | has substantial commercial, industrial or non-consumer uses, unless such uses 288 | represent the only significant mode of use of the product. 289 | 290 | *Installation Information* for a User Product means any methods, procedures, 291 | authorization keys, or other information required to install and execute 292 | modified versions of a covered work in that User Product from a modified 293 | version of its Corresponding Source. The information must suffice to ensure 294 | that the continued functioning of the modified object code is in no case 295 | prevented or interfered with solely because modification has been made. 296 | 297 | If you convey an object code work under this section in, or with, or 298 | specifically for use in, a User Product, and the conveying occurs as part of a 299 | transaction in which the right of possession and use of the User Product is 300 | transferred to the recipient in perpetuity or for a fixed term (regardless of 301 | how the transaction is characterized), the Corresponding Source conveyed under 302 | this section must be accompanied by the Installation Information. But this 303 | requirement does not apply if neither you nor any third party retains the 304 | ability to install modified object code on the User Product (for example, the 305 | work has been installed in ROM). 306 | 307 | The requirement to provide Installation Information does not include a 308 | requirement to continue to provide support service, warranty, or updates for a 309 | work that has been modified or installed by the recipient, or for the User 310 | Product in which it has been modified or installed. Access to a network may be 311 | denied when the modification itself materially and adversely affects the 312 | operation of the network or violates the rules and protocols for communication 313 | across the network. 314 | 315 | Corresponding Source conveyed, and Installation Information provided, in accord 316 | with this section must be in a format that is publicly documented (and with an 317 | implementation available to the public in source code form), and must require 318 | no special password or key for unpacking, reading or copying. 319 | 320 | ### 7. Additional Terms. 321 | 322 | *Additional permissions* are terms that supplement the terms of this License by 323 | making exceptions from one or more of its conditions. Additional permissions 324 | that are applicable to the entire Program shall be treated as though they were 325 | included in this License, to the extent that they are valid under applicable 326 | law. If additional permissions apply only to part of the Program, that part may 327 | be used separately under those permissions, but the entire Program remains 328 | governed by this License without regard to the additional permissions. 329 | 330 | When you convey a copy of a covered work, you may at your option remove any 331 | additional permissions from that copy, or from any part of it. (Additional 332 | permissions may be written to require their own removal in certain cases when 333 | you modify the work.) You may place additional permissions on material, added 334 | by you to a covered work, for which you have or can give appropriate copyright 335 | permission. 336 | 337 | Notwithstanding any other provision of this License, for material you add to a 338 | covered work, you may (if authorized by the copyright holders of that material) 339 | supplement the terms of this License with terms: 340 | 341 | - a) Disclaiming warranty or limiting liability differently from the terms of 342 | sections 15 and 16 of this License; or 343 | - b) Requiring preservation of specified reasonable legal notices or author 344 | attributions in that material or in the Appropriate Legal Notices displayed 345 | by works containing it; or 346 | - c) Prohibiting misrepresentation of the origin of that material, or 347 | requiring that modified versions of such material be marked in reasonable 348 | ways as different from the original version; or 349 | - d) Limiting the use for publicity purposes of names of licensors or authors 350 | of the material; or 351 | - e) Declining to grant rights under trademark law for use of some trade 352 | names, trademarks, or service marks; or 353 | - f) Requiring indemnification of licensors and authors of that material by 354 | anyone who conveys the material (or modified versions of it) with 355 | contractual assumptions of liability to the recipient, for any liability 356 | that these contractual assumptions directly impose on those licensors and 357 | authors. 358 | 359 | All other non-permissive additional terms are considered *further restrictions* 360 | within the meaning of section 10. If the Program as you received it, or any 361 | part of it, contains a notice stating that it is governed by this License along 362 | with a term that is a further restriction, you may remove that term. If a 363 | license document contains a further restriction but permits relicensing or 364 | conveying under this License, you may add to a covered work material governed 365 | by the terms of that license document, provided that the further restriction 366 | does not survive such relicensing or conveying. 367 | 368 | If you add terms to a covered work in accord with this section, you must place, 369 | in the relevant source files, a statement of the additional terms that apply to 370 | those files, or a notice indicating where to find the applicable terms. 371 | 372 | Additional terms, permissive or non-permissive, may be stated in the form of a 373 | separately written license, or stated as exceptions; the above requirements 374 | apply either way. 375 | 376 | ### 8. Termination. 377 | 378 | You may not propagate or modify a covered work except as expressly provided 379 | under this License. Any attempt otherwise to propagate or modify it is void, 380 | and will automatically terminate your rights under this License (including any 381 | patent licenses granted under the third paragraph of section 11). 382 | 383 | However, if you cease all violation of this License, then your license from a 384 | particular copyright holder is reinstated 385 | 386 | - a) provisionally, unless and until the copyright holder explicitly and 387 | finally terminates your license, and 388 | - b) permanently, if the copyright holder fails to notify you of the 389 | violation by some reasonable means prior to 60 days after the cessation. 390 | 391 | Moreover, your license from a particular copyright holder is reinstated 392 | permanently if the copyright holder notifies you of the violation by some 393 | reasonable means, this is the first time you have received notice of violation 394 | of this License (for any work) from that copyright holder, and you cure the 395 | violation prior to 30 days after your receipt of the notice. 396 | 397 | Termination of your rights under this section does not terminate the licenses 398 | of parties who have received copies or rights from you under this License. If 399 | your rights have been terminated and not permanently reinstated, you do not 400 | qualify to receive new licenses for the same material under section 10. 401 | 402 | ### 9. Acceptance Not Required for Having Copies. 403 | 404 | You are not required to accept this License in order to receive or run a copy 405 | of the Program. Ancillary propagation of a covered work occurring solely as a 406 | consequence of using peer-to-peer transmission to receive a copy likewise does 407 | not require acceptance. However, nothing other than this License grants you 408 | permission to propagate or modify any covered work. These actions infringe 409 | copyright if you do not accept this License. Therefore, by modifying or 410 | propagating a covered work, you indicate your acceptance of this License to do 411 | so. 412 | 413 | ### 10. Automatic Licensing of Downstream Recipients. 414 | 415 | Each time you convey a covered work, the recipient automatically receives a 416 | license from the original licensors, to run, modify and propagate that work, 417 | subject to this License. You are not responsible for enforcing compliance by 418 | third parties with this License. 419 | 420 | An *entity transaction* is a transaction transferring control of an 421 | organization, or substantially all assets of one, or subdividing an 422 | organization, or merging organizations. If propagation of a covered work 423 | results from an entity transaction, each party to that transaction who receives 424 | a copy of the work also receives whatever licenses to the work the party's 425 | predecessor in interest had or could give under the previous paragraph, plus a 426 | right to possession of the Corresponding Source of the work from the 427 | predecessor in interest, if the predecessor has it or can get it with 428 | reasonable efforts. 429 | 430 | You may not impose any further restrictions on the exercise of the rights 431 | granted or affirmed under this License. For example, you may not impose a 432 | license fee, royalty, or other charge for exercise of rights granted under this 433 | License, and you may not initiate litigation (including a cross-claim or 434 | counterclaim in a lawsuit) alleging that any patent claim is infringed by 435 | making, using, selling, offering for sale, or importing the Program or any 436 | portion of it. 437 | 438 | ### 11. Patents. 439 | 440 | A *contributor* is a copyright holder who authorizes use under this License of 441 | the Program or a work on which the Program is based. The work thus licensed is 442 | called the contributor's *contributor version*. 443 | 444 | A contributor's *essential patent claims* are all patent claims owned or 445 | controlled by the contributor, whether already acquired or hereafter acquired, 446 | that would be infringed by some manner, permitted by this License, of making, 447 | using, or selling its contributor version, but do not include claims that would 448 | be infringed only as a consequence of further modification of the contributor 449 | version. For purposes of this definition, *control* includes the right to grant 450 | patent sublicenses in a manner consistent with the requirements of this 451 | License. 452 | 453 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent 454 | license under the contributor's essential patent claims, to make, use, sell, 455 | offer for sale, import and otherwise run, modify and propagate the contents of 456 | its contributor version. 457 | 458 | In the following three paragraphs, a *patent license* is any express agreement 459 | or commitment, however denominated, not to enforce a patent (such as an express 460 | permission to practice a patent or covenant not to sue for patent 461 | infringement). To *grant* such a patent license to a party means to make such 462 | an agreement or commitment not to enforce a patent against the party. 463 | 464 | If you convey a covered work, knowingly relying on a patent license, and the 465 | Corresponding Source of the work is not available for anyone to copy, free of 466 | charge and under the terms of this License, through a publicly available 467 | network server or other readily accessible means, then you must either 468 | 469 | 1. cause the Corresponding Source to be so available, or 470 | 2. arrange to deprive yourself of the benefit of the patent license for this 471 | particular work, or 472 | 3. arrange, in a manner consistent with the requirements of this License, to 473 | extend the patent license to downstream recipients. 474 | 475 | *Knowingly relying* means you have actual knowledge that, but for the patent 476 | license, your conveying the covered work in a country, or your recipient's use 477 | of the covered work in a country, would infringe one or more identifiable 478 | patents in that country that you have reason to believe are valid. 479 | 480 | If, pursuant to or in connection with a single transaction or arrangement, you 481 | convey, or propagate by procuring conveyance of, a covered work, and grant a 482 | patent license to some of the parties receiving the covered work authorizing 483 | them to use, propagate, modify or convey a specific copy of the covered work, 484 | then the patent license you grant is automatically extended to all recipients 485 | of the covered work and works based on it. 486 | 487 | A patent license is *discriminatory* if it does not include within the scope of 488 | its coverage, prohibits the exercise of, or is conditioned on the non-exercise 489 | of one or more of the rights that are specifically granted under this License. 490 | You may not convey a covered work if you are a party to an arrangement with a 491 | third party that is in the business of distributing software, under which you 492 | make payment to the third party based on the extent of your activity of 493 | conveying the work, and under which the third party grants, to any of the 494 | parties who would receive the covered work from you, a discriminatory patent 495 | license 496 | 497 | - a) in connection with copies of the covered work conveyed by you (or copies 498 | made from those copies), or 499 | - b) primarily for and in connection with specific products or compilations 500 | that contain the covered work, unless you entered into that arrangement, or 501 | that patent license was granted, prior to 28 March 2007. 502 | 503 | Nothing in this License shall be construed as excluding or limiting any implied 504 | license or other defenses to infringement that may otherwise be available to 505 | you under applicable patent law. 506 | 507 | ### 12. No Surrender of Others' Freedom. 508 | 509 | If conditions are imposed on you (whether by court order, agreement or 510 | otherwise) that contradict the conditions of this License, they do not excuse 511 | you from the conditions of this License. If you cannot convey a covered work so 512 | as to satisfy simultaneously your obligations under this License and any other 513 | pertinent obligations, then as a consequence you may not convey it at all. For 514 | example, if you agree to terms that obligate you to collect a royalty for 515 | further conveying from those to whom you convey the Program, the only way you 516 | could satisfy both those terms and this License would be to refrain entirely 517 | from conveying the Program. 518 | 519 | ### 13. Use with the GNU Affero General Public License. 520 | 521 | Notwithstanding any other provision of this License, you have permission to 522 | link or combine any covered work with a work licensed under version 3 of the 523 | GNU Affero General Public License into a single combined work, and to convey 524 | the resulting work. The terms of this License will continue to apply to the 525 | part which is the covered work, but the special requirements of the GNU Affero 526 | General Public License, section 13, concerning interaction through a network 527 | will apply to the combination as such. 528 | 529 | ### 14. Revised Versions of this License. 530 | 531 | The Free Software Foundation may publish revised and/or new versions of the GNU 532 | General Public License from time to time. Such new versions will be similar in 533 | spirit to the present version, but may differ in detail to address new problems 534 | or concerns. 535 | 536 | Each version is given a distinguishing version number. If the Program specifies 537 | that a certain numbered version of the GNU General Public License *or any later 538 | version* applies to it, you have the option of following the terms and 539 | conditions either of that numbered version or of any later version published by 540 | the Free Software Foundation. If the Program does not specify a version number 541 | of the GNU General Public License, you may choose any version ever published by 542 | the Free Software Foundation. 543 | 544 | If the Program specifies that a proxy can decide which future versions of the 545 | GNU General Public License can be used, that proxy's public statement of 546 | acceptance of a version permanently authorizes you to choose that version for 547 | the Program. 548 | 549 | Later license versions may give you additional or different permissions. 550 | However, no additional obligations are imposed on any author or copyright 551 | holder as a result of your choosing to follow a later version. 552 | 553 | ### 15. Disclaimer of Warranty. 554 | 555 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE 556 | LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER 557 | PARTIES PROVIDE THE PROGRAM *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER 558 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 559 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 560 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 561 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 562 | CORRECTION. 563 | 564 | ### 16. Limitation of Liability. 565 | 566 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 567 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 568 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 569 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE 570 | THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED 571 | INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE 572 | PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY 573 | HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 574 | 575 | ### 17. Interpretation of Sections 15 and 16. 576 | 577 | If the disclaimer of warranty and limitation of liability provided above cannot 578 | be given local legal effect according to their terms, reviewing courts shall 579 | apply local law that most closely approximates an absolute waiver of all civil 580 | liability in connection with the Program, unless a warranty or assumption of 581 | liability accompanies a copy of the Program in return for a fee. 582 | 583 | ## END OF TERMS AND CONDITIONS ### 584 | 585 | ### How to Apply These Terms to Your New Programs 586 | 587 | If you develop a new program, and you want it to be of the greatest possible 588 | use to the public, the best way to achieve this is to make it free software 589 | which everyone can redistribute and change under these terms. 590 | 591 | To do so, attach the following notices to the program. It is safest to attach 592 | them to the start of each source file to most effectively state the exclusion 593 | of warranty; and each file should have at least the *copyright* line and a 594 | pointer to where the full notice is found. 595 | 596 | 597 | Copyright (C) 598 | 599 | This program is free software: you can redistribute it and/or modify 600 | it under the terms of the GNU General Public License as published by 601 | the Free Software Foundation, either version 3 of the License, or 602 | (at your option) any later version. 603 | 604 | This program is distributed in the hope that it will be useful, 605 | but WITHOUT ANY WARRANTY; without even the implied warranty of 606 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 607 | GNU General Public License for more details. 608 | 609 | You should have received a copy of the GNU General Public License 610 | along with this program. If not, see . 611 | 612 | Also add information on how to contact you by electronic and paper mail. 613 | 614 | If the program does terminal interaction, make it output a short notice like 615 | this when it starts in an interactive mode: 616 | 617 | Copyright (C) 618 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 619 | This is free software, and you are welcome to redistribute it 620 | under certain conditions; type `show c' for details. 621 | 622 | The hypothetical commands `show w` and `show c` should show the appropriate 623 | parts of the General Public License. Of course, your program's commands might 624 | be different; for a GUI interface, you would use an *about box*. 625 | 626 | You should also get your employer (if you work as a programmer) or school, if 627 | any, to sign a *copyright disclaimer* for the program, if necessary. For more 628 | information on this, and how to apply and follow the GNU GPL, see 629 | [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/). 630 | 631 | The GNU General Public License does not permit incorporating your program into 632 | proprietary programs. If your program is a subroutine library, you may consider 633 | it more useful to permit linking proprietary applications with the library. If 634 | this is what you want to do, use the GNU Lesser General Public License instead 635 | of this License. But first, please read 636 | [http://www.gnu.org/philosophy/why-not-lgpl.html](http://www.gnu.org/philosophy/why-not-lgpl.html). -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Yield Flash-Mint-Powered Flash Loan 2 | 3 | I recently tried out [Alberto Cuesta Canada](https://twitter.com/acuestacanada)'s Flash Mint powered Flash Loan offering from the Yield Protocol, so here's a template contract you can play and customise. 4 | 5 | This flash loan basically flash mints fyDAI and then swaps it into DAI for your contract's use via YieldSpace pools. 6 | 7 | Some key attributes I've noticed include: 8 | - the use of ERC-3156 wrappers to provide a standardized fyDai and Dai flash lending interfaces to fyDai and Pool contracts. 9 | - the YieldDaiBorrower contract which you inherit from, flash mints fyDAI and then uses it to borrow Dai from YieldSpace pools, which is like a normal AMM but the invariant takes a time to maturity parameter. 10 | - the swapping logic of the flash minted fyDAI into DAI is abstracted away for the end developer. 11 | - the flash fee is roughly 2.5 bps, but can change subject to time-to-maturity and loan-to-reserves ratio. 12 | 13 | ## Experienced Devs 14 | If you're an experienced dev simply head to https://docs.yield.is and should be pretty easy for you to work things out. Just make your contract inherit YieldDaiBorrower and then override the receiveLoan() function with your mid flash logic. 15 | 16 | ## Junior Devs 17 | If you're not as experienced with all this flashiness, but would still like to try this out, detailed instructions below: 18 | 19 | ### Setup and Deployment 20 | 1. git clone this repo 21 | ``` 22 | git clone https://github.com/fifikobayashi/YieldFlashDemo 23 | cd YieldFlashDemo 24 | ``` 25 | 2. setup dependencies 26 | ``` 27 | npm install @openzeppelin/contracts 28 | npm install dotenv 29 | npm install --save truffle-hdwallet-provider 30 | ``` 31 | 3. sort out your .gitignore and .env 32 | 4. update the first argument in truffle migration script to reflect which DAI you want to use (see [docs.yield.is](https://docs.yield.is)) e.g. for kovan DAI 33 | ``` 34 | module.exports = function (deployer) { 35 | deployer.deploy(YieldFlashDemo, "0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa"); 36 | }; 37 | ``` 38 | 5. By default, it simply flash mints fyDAI then swaps it for DAI from YieldSpace pools before repaying the amount+fee. If you want to do some fancy arbitrage with the temporarily acquired DAI, then you need to add that to the receiveLoan() function within the YieldFlashDemo contract, before the repayFlashLoan() function is called. 39 | ``` 40 | /// @dev Override this function with your own logic. Make sure the contract holds `loanAmount` + `fee` Dai 41 | // and that `repayFlashLoan` is called. 42 | function receiveLoan(address sender_, uint256 loanAmount_, uint256 fee_) internal override { 43 | sender = sender_; 44 | loanAmount = loanAmount_; 45 | fee = fee_; 46 | balance = dai.balanceOf(address(this)); 47 | 48 | /** 49 | * Insert your mid flash logic here 50 | * e.g. arbitrage, collateral swap, self liquidation, refinancing, exploit research 51 | **/ 52 | 53 | repayFlashLoan(loanAmount_, fee_); 54 | } 55 | } 56 | ``` 57 | 6. Now let's deploy this contract 58 | ``` 59 | truffle migrate --network kovan --reset --skipDryRun 60 | ``` 61 | 62 | ### Execution 63 | 7. Note the deployed contract address and send some DAI to it to cover the approx. 2.5 bps flash fee. 64 | 8. Let's jump onto truffle console 65 | ``` 66 | truffle console --network kovan 67 | ``` 68 | 9. Set the YieldSpace pool e.g. for fyDaiLP20Dec21 on Kovan it is 69 | ``` 70 | YieldFlashDemo.deployed().then(function(instance){return instance.setPool('0x2b004AF29102Ab5f1ca977a45AF24A26eaa683Ca')}); 71 | ``` 72 | 10. Now based on that pool let's check the available flash liquidity so we can ensure we don't try to flash more than this 73 | ``` 74 | YieldFlashDemo.deployed().then(function(instance){return instance.flashSupply()}); 75 | ``` 76 | 11. Then based on how much you want to flash, let's get an estimate of the fee e.g. for 1500 DAI 77 | ``` 78 | YieldFlashDemo.deployed().then(function(instance){return instance.flashFee('1500000000000000000000')}); 79 | ``` 80 | 12. Finally, with all the information known, we execute this flash mint powered flash loan for 1500 DAI 81 | ``` 82 | YieldFlashDemo.deployed().then(function(instance){return instance.flashBorrow('1500000000000000000000')}); 83 | ``` 84 | 13. If all went well, it should look like this on [kovan testnet](https://kovan.etherscan.io/tx/0x406d396044b5cda6cb33f6c6bb891c96a5fe3a4a4b0a982425bc2e78f980b6d5) 85 | 86 | ### It didn't work, why? 87 | Could be anything, but check whether: 88 | - you forgot to set the YieldSpace Pool prior to flashing or used the wrong address 89 | - you tried to flash more than the available liquidity on testnet 90 | - you forgot to fund the contract with enough DAI to cover the flash fee 91 | - ask [Alberto](https://twitter.com/acuestacanada) 92 | 93 | 94 | That's it! Have fun with it! 95 | 96 | Thanks, 97 | fifikobayashi 98 | -------------------------------------------------------------------------------- /buidler.config.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const path = require('path') 3 | usePlugin('@nomiclabs/buidler-truffle5') 4 | usePlugin('solidity-coverage') 5 | usePlugin('buidler-gas-reporter') 6 | usePlugin('buidler-deploy') 7 | 8 | 9 | // REQUIRED TO ENSURE METADATA IS SAVED IN DEPLOYMENTS (because solidity-coverage disable it otherwise) 10 | const { 11 | TASK_COMPILE_GET_COMPILER_INPUT 12 | } = require("@nomiclabs/buidler/builtin-tasks/task-names"); 13 | task(TASK_COMPILE_GET_COMPILER_INPUT).setAction(async (_, bre, runSuper) => { 14 | const input = await runSuper(); 15 | input.settings.metadata.useLiteralContent = bre.network.name !== "coverage"; 16 | return input; 17 | }) 18 | 19 | 20 | function nodeUrl(network) { 21 | let infuraKey 22 | try { 23 | infuraKey = fs.readFileSync(path.resolve(__dirname, '.infuraKey')).toString().trim() 24 | } catch(e) { 25 | infuraKey = '' 26 | } 27 | return `https://${network}.infura.io/v3/${infuraKey}` 28 | } 29 | 30 | let mnemonic = process.env.MNEMONIC; 31 | if (!mnemonic) { 32 | try { 33 | mnemonic = fs.readFileSync(path.resolve(__dirname, '.secret')).toString().trim() 34 | } catch(e){} 35 | } 36 | const accounts = mnemonic ? { 37 | mnemonic, 38 | }: undefined; 39 | 40 | module.exports = { 41 | defaultNetwork: 'buidlerevm', 42 | networks: { 43 | kovan: { 44 | accounts, 45 | url: nodeUrl('kovan'), 46 | timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) 47 | gasPrice: 10000000000, // 10 gwei 48 | skipDryRun: false // Skip dry run before migrations? (default: false for public nets ) 49 | }, 50 | goerli: { 51 | accounts, 52 | url: nodeUrl('goerli'), 53 | }, 54 | rinkeby: { 55 | accounts, 56 | url: nodeUrl('rinkeby') 57 | }, 58 | ropsten: { 59 | accounts, 60 | url: nodeUrl('ropsten') 61 | }, 62 | mainnet: { 63 | accounts, 64 | url: nodeUrl('mainnet'), 65 | timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) 66 | gasPrice: 50000000000, // 50 gwei 67 | skipDryRun: false // Skip dry run before migrations? (default: false for public nets ) 68 | }, 69 | coverage: { 70 | url: 'http://127.0.0.1:8555', 71 | }, 72 | }, 73 | solc: { 74 | version: '0.6.10', 75 | optimizer: { 76 | enabled: true, 77 | runs: 20000, 78 | }, 79 | }, 80 | gasReporter: { 81 | enabled: true, 82 | }, 83 | paths: { 84 | sources: './contracts', 85 | tests: './test', 86 | cache: './cache', 87 | coverage: './coverage', 88 | coverageJson: './coverage.json', 89 | artifacts: './artifacts', 90 | }, 91 | namedAccounts: { 92 | deployer: 0 93 | } 94 | } -------------------------------------------------------------------------------- /contracts/YieldDaiBorrower.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | import "@openzeppelin/contracts/math/SafeMath.sol"; 5 | import "./fyDai/YieldMath.sol"; 6 | import "./helpers/SafeCast.sol"; 7 | import "./interfaces/IPool.sol"; 8 | import "./interfaces/IFYDai.sol"; 9 | 10 | 11 | /** 12 | * YieldDaiBorrower allows Dai flash loans out of a YieldSpace pool, by flash minting fyDai and selling it to the pool. 13 | */ 14 | abstract contract YieldDaiBorrower { 15 | using SafeCast for uint256; 16 | using SafeMath for uint256; 17 | 18 | IPool public pool; 19 | 20 | /// @dev Choose a lending pool. 21 | function setPool(IPool pool_) public { 22 | pool = pool_; 23 | 24 | // Allow pool to take dai and fyDai for trading 25 | if (pool.dai().allowance(address(this), address(pool)) < type(uint256).max) 26 | pool.dai().approve(address(pool), type(uint256).max); 27 | if (pool.fyDai().allowance(address(this), address(pool)) < type(uint112).max) 28 | pool.fyDai().approve(address(pool), type(uint256).max); 29 | 30 | } 31 | 32 | /// @dev Fee charged on top of a Dai flash loan. 33 | function flashFee(uint256 daiBorrowed) public view returns (uint256) { 34 | uint128 fyDaiAmount = pool.buyDaiPreview(daiBorrowed.toUint128()); 35 | 36 | // To obtain the result of a trade on hypothetical reserves we need to call the YieldMath library 37 | uint256 daiRepaid = YieldMath.daiInForFYDaiOut( 38 | (uint256(pool.getDaiReserves()).sub(daiBorrowed)).toUint128(), // Dai reserves minus Dai we just bought 39 | (uint256(pool.getFYDaiReserves()).add(fyDaiAmount)).toUint128(), // fyDai reserves plus fyDai we just sold 40 | fyDaiAmount, // fyDai flash mint we have to repay 41 | (pool.fyDai().maturity() - now).toUint128(), // This can't be called after maturity 42 | int128(uint256((1 << 64)) / 126144000), // 1 / Seconds in 4 years, in 64.64 43 | int128(uint256((950 << 64)) / 1000) // Fees applied when selling Dai to the pool, in 64.64 44 | ); 45 | 46 | return daiRepaid.sub(daiBorrowed); 47 | } 48 | 49 | /// @dev Maximum Dai flash loan available. 50 | function flashSupply() public view returns (uint256) { 51 | return pool.getDaiReserves(); 52 | } 53 | 54 | /// @dev Borrow `daiAmount` as a flash loan. 55 | function flashBorrow(uint256 daiAmount) public returns (uint256) { 56 | bytes memory data = abi.encode(msg.sender, daiAmount); 57 | uint256 fyDaiAmount = pool.buyDaiPreview(daiAmount.toUint128()); 58 | pool.fyDai().flashMint(fyDaiAmount, data); 59 | } 60 | 61 | /// @dev FYDai `flashMint` callback. 62 | function executeOnFlashMint(uint256 fyDaiAmount, bytes memory data) public { 63 | require(msg.sender == address(pool.fyDai()), "Callbacks only allowed from fyDai contract"); 64 | 65 | (address sender, uint256 daiAmount) = abi.decode(data, (address, uint256)); 66 | 67 | uint256 paidFYDai = pool.buyDai(address(this), address(this), daiAmount.toUint128()); 68 | 69 | uint256 fee = uint256(pool.buyFYDaiPreview(fyDaiAmount.toUint128())).sub(daiAmount); 70 | receiveLoan(sender, daiAmount, fee); 71 | } 72 | 73 | /// @dev Override this function with your own logic. Make sure the contract holds `loanAmount` + `fee` Dai 74 | // and that `repayFlashLoan` is called. 75 | function receiveLoan(address sender, uint256 loanAmount, uint256 fee) internal virtual { 76 | repayFlashLoan(loanAmount, fee); 77 | } 78 | 79 | /// @dev Before the end of the transaction, `receiver` must `transfer` the `loanAmount` plus the `fee` 80 | /// to this contract and call `repayFlashLoan` to do the conversions that repay the loan. 81 | function repayFlashLoan(uint256 loanAmount, uint256 fee) public { 82 | pool.sellDai(address(this), address(this), loanAmount.add(fee).toUint128()); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /contracts/YieldDaiLender.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | import "@openzeppelin/contracts/math/SafeMath.sol"; 5 | import "./fyDai/YieldMath.sol"; 6 | import "./helpers/SafeCast.sol"; 7 | import "./interfaces/IPool.sol"; 8 | import "./interfaces/IFYDai.sol"; 9 | 10 | 11 | /** 12 | * ILoanReceiver receives flash loans, and is expected to repay them plus a fee. 13 | * Implements ERC-3156: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3156.md 14 | * `receiver` should verify that the `onFlashLoan` caller is in a whitelist of trusted lenders. 15 | */ 16 | interface ILoanReceiver { 17 | function onFlashLoan(address sender, uint256 loanAmount, uint256 fee, bytes memory data) external; 18 | } 19 | 20 | /** 21 | * YieldDaiLender allows ERC-3156 Dai flash loans out of a YieldSpace pool, by flash minting fyDai and selling it to the pool. 22 | */ 23 | contract YieldDaiLender { 24 | using SafeCast for uint256; 25 | using SafeMath for uint256; 26 | 27 | IPool public pool; 28 | 29 | constructor (IPool pool_) public { 30 | pool = pool_; 31 | 32 | // Allow pool to take dai and fyDai for trading 33 | if (pool.dai().allowance(address(this), address(pool)) < type(uint256).max) 34 | pool.dai().approve(address(pool), type(uint256).max); 35 | if (pool.fyDai().allowance(address(this), address(pool)) < type(uint112).max) 36 | pool.fyDai().approve(address(pool), type(uint256).max); 37 | } 38 | 39 | /// @dev Fee charged on top of a Dai flash loan. 40 | function flashFee(uint256 daiBorrowed) public view returns (uint256) { 41 | uint128 fyDaiAmount = pool.buyDaiPreview(daiBorrowed.toUint128()); 42 | 43 | // To obtain the result of a trade on hypothetical reserves we need to call the YieldMath library 44 | uint256 daiRepaid = YieldMath.daiInForFYDaiOut( 45 | (uint256(pool.getDaiReserves()).sub(daiBorrowed)).toUint128(), // Dai reserves minus Dai we just bought 46 | (uint256(pool.getFYDaiReserves()).add(fyDaiAmount)).toUint128(), // fyDai reserves plus fyDai we just sold 47 | fyDaiAmount, // fyDai flash mint we have to repay 48 | (pool.fyDai().maturity() - now).toUint128(), // This can't be called after maturity 49 | int128(uint256((1 << 64)) / 126144000), // 1 / Seconds in 4 years, in 64.64 50 | int128(uint256((950 << 64)) / 1000) // Fees applied when selling Dai to the pool, in 64.64 51 | ); 52 | 53 | return daiRepaid.sub(daiBorrowed); 54 | } 55 | 56 | /// @dev Maximum Dai flash loan available. 57 | function flashSupply() public view returns (uint256) { 58 | return pool.getDaiReserves(); 59 | } 60 | 61 | /// @dev Borrow `daiAmount` as a flash loan. 62 | function flashLoan(address receiver, uint256 daiAmount, bytes memory data) public returns (uint256) { 63 | bytes memory wrappedData = abi.encode(data, msg.sender, receiver, daiAmount); 64 | uint256 fyDaiAmount = pool.buyDaiPreview(daiAmount.toUint128()); 65 | pool.fyDai().flashMint(fyDaiAmount, wrappedData); 66 | } 67 | 68 | /// @dev FYDai `flashMint` callback. 69 | function executeOnFlashMint(uint256 fyDaiAmount, bytes memory wrappedData) public { 70 | require(msg.sender == address(pool.fyDai()), "Callbacks only allowed from fyDai contract"); 71 | 72 | (bytes memory data, address sender, address receiver, uint256 daiAmount) = abi.decode(wrappedData, (bytes, address, address, uint256)); 73 | 74 | uint256 paidFYDai = pool.buyDai(address(this), address(this), daiAmount.toUint128()); 75 | 76 | uint256 fee = uint256(pool.buyFYDaiPreview(fyDaiAmount.toUint128())).sub(daiAmount); 77 | ILoanReceiver(receiver).onFlashLoan(sender, daiAmount, fee, data); 78 | } 79 | 80 | /// @dev Before the end of the transaction, `receiver` must `transfer` the `loanAmount` plus the `fee` 81 | /// to this contract and call `repayFlashLoan` to do the conversions that repay the loan. 82 | function repayFlashLoan(uint256 loanAmount, uint256 fee) public { 83 | pool.sellDai(address(this), address(this), loanAmount.add(fee).toUint128()); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /contracts/YieldFYDaiLender.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | import "./interfaces/IFYDai.sol"; 5 | 6 | /** 7 | * ILoanReceiver receives flash loans, and is expected to repay them plus a fee. 8 | * Implements ERC-3156: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3156.md 9 | * `receiver` should verify that the `onFlashLoan` caller is in a whitelist of trusted lenders. 10 | */ 11 | interface ILoanReceiver { 12 | function onFlashLoan(address sender, uint256 loanAmount, uint256 fee, bytes memory data) external; 13 | } 14 | 15 | /** 16 | * YieldFYDaiLender allows flash loans of fyDai compliant with ERC-3156: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3156.md 17 | */ 18 | contract YieldFYDaiLender { 19 | IFYDai public fyDai; 20 | 21 | constructor (IFYDai fyDai_) public { 22 | fyDai = fyDai_; 23 | } 24 | 25 | /// @dev Fee charged on top of a fyDai flash loan. 26 | function flashFee(uint256) public view returns (uint256) { 27 | return 0; 28 | } 29 | 30 | /// @dev Maximum fyDai flash loan available. 31 | function flashSupply() public view returns (uint256) { 32 | return type(uint112).max - fyDai.totalSupply(); // Can't overflow 33 | } 34 | 35 | /// @dev ERC-3156 entry point to send `fyDaiAmount` fyDai to `receiver` as a flash loan. 36 | function flashLoan(address receiver, uint256 fyDaiAmount, bytes memory data) public returns (uint256) { 37 | bytes memory wrappedData = abi.encode(data, msg.sender, receiver); 38 | fyDai.flashMint(fyDaiAmount, wrappedData); 39 | } 40 | 41 | /// @dev FYDai `flashMint` callback, which bridges to the ERC-3156 `onFlashLoan` callback. 42 | function executeOnFlashMint(uint256 fyDaiAmount, bytes memory wrappedData) public { 43 | require(msg.sender == address(fyDai), "Callbacks only allowed from fyDai contract"); 44 | (bytes memory data, address sender, address receiver) = abi.decode(wrappedData, (bytes, address, address)); 45 | ILoanReceiver(receiver).onFlashLoan(sender, fyDaiAmount, 0, data); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /contracts/YieldFlashDemo.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 5 | import "./YieldDaiBorrower.sol"; 6 | 7 | 8 | contract YieldFlashDemo is YieldDaiBorrower { 9 | IERC20 public immutable dai; 10 | 11 | address public sender; 12 | uint256 public loanAmount; 13 | uint256 public fee; 14 | uint256 public balance; 15 | 16 | constructor (IERC20 dai_) public { 17 | dai = dai_; 18 | } 19 | 20 | /// @dev Override this function with your own logic. Make sure the contract holds `loanAmount` + `fee` Dai 21 | // and that `repayFlashLoan` is called. 22 | function receiveLoan(address sender_, uint256 loanAmount_, uint256 fee_) internal override { 23 | sender = sender_; 24 | loanAmount = loanAmount_; 25 | fee = fee_; 26 | balance = dai.balanceOf(address(this)); 27 | 28 | /** 29 | * Insert your mid flash logic here 30 | * e.g. arbitrage, collateral swap, self liquidation, refinancing, exploit research 31 | **/ 32 | 33 | repayFlashLoan(loanAmount_, fee_); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /contracts/fyDai/Math64x64.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | /* 3 | * Math 64.64 Smart Contract Library. Copyright © 2019 by Consulting. 4 | * Author: Mikhail Vladimirov 5 | */ 6 | pragma solidity ^0.6.0; 7 | 8 | /** 9 | * Smart contract library of mathematical functions operating with signed 10 | * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is 11 | * basically a simple fraction whose numerator is signed 128-bit integer and 12 | * denominator is 2^64. As long as denominator is always the same, there is no 13 | * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are 14 | * represented by int128 type holding only the numerator. 15 | */ 16 | library Math64x64 { 17 | /** 18 | * @dev Minimum value signed 64.64-bit fixed point number may have. 19 | */ 20 | int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; 21 | 22 | /** 23 | * @dev Maximum value signed 64.64-bit fixed point number may have. 24 | */ 25 | int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; 26 | 27 | /** 28 | * @dev Convert signed 256-bit integer number into signed 64.64-bit fixed point 29 | * number. Revert on overflow. 30 | * 31 | * @param x signed 256-bit integer number 32 | * @return signed 64.64-bit fixed point number 33 | */ 34 | function fromInt (int256 x) internal pure returns (int128) { 35 | require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); 36 | return int128 (x << 64); 37 | } 38 | 39 | /** 40 | * @dev Convert signed 64.64 fixed point number into signed 64-bit integer number 41 | * rounding down. 42 | * 43 | * @param x signed 64.64-bit fixed point number 44 | * @return signed 64-bit integer number 45 | */ 46 | function toInt (int128 x) internal pure returns (int64) { 47 | return int64 (x >> 64); 48 | } 49 | 50 | /** 51 | * @dev Convert unsigned 256-bit integer number into signed 64.64-bit fixed point 52 | * number. Revert on overflow. 53 | * 54 | * @param x unsigned 256-bit integer number 55 | * @return signed 64.64-bit fixed point number 56 | */ 57 | function fromUInt (uint256 x) internal pure returns (int128) { 58 | require (x <= 0x7FFFFFFFFFFFFFFF); 59 | return int128 (x << 64); 60 | } 61 | 62 | /** 63 | * @dev Convert signed 64.64 fixed point number into unsigned 64-bit integer 64 | * number rounding down. Revert on underflow. 65 | * 66 | * @param x signed 64.64-bit fixed point number 67 | * @return unsigned 64-bit integer number 68 | */ 69 | function toUInt (int128 x) internal pure returns (uint64) { 70 | require (x >= 0); 71 | return uint64 (x >> 64); 72 | } 73 | 74 | /** 75 | * @dev Convert signed 128.128 fixed point number into signed 64.64-bit fixed point 76 | * number rounding down. Revert on overflow. 77 | * 78 | * @param x signed 128.128-bin fixed point number 79 | * @return signed 64.64-bit fixed point number 80 | */ 81 | function from128x128 (int256 x) internal pure returns (int128) { 82 | int256 result = x >> 64; 83 | require (result >= MIN_64x64 && result <= MAX_64x64); 84 | return int128 (result); 85 | } 86 | 87 | /** 88 | * @dev Convert signed 64.64 fixed point number into signed 128.128 fixed point 89 | * number. 90 | * 91 | * @param x signed 64.64-bit fixed point number 92 | * @return signed 128.128 fixed point number 93 | */ 94 | function to128x128 (int128 x) internal pure returns (int256) { 95 | return int256 (x) << 64; 96 | } 97 | 98 | /** 99 | * @dev Calculate x + y. Revert on overflow. 100 | * 101 | * @param x signed 64.64-bit fixed point number 102 | * @param y signed 64.64-bit fixed point number 103 | * @return signed 64.64-bit fixed point number 104 | */ 105 | function add (int128 x, int128 y) internal pure returns (int128) { 106 | int256 result = int256(x) + y; 107 | require (result >= MIN_64x64 && result <= MAX_64x64); 108 | return int128 (result); 109 | } 110 | 111 | /** 112 | * @dev Calculate x - y. Revert on overflow. 113 | * 114 | * @param x signed 64.64-bit fixed point number 115 | * @param y signed 64.64-bit fixed point number 116 | * @return signed 64.64-bit fixed point number 117 | */ 118 | function sub (int128 x, int128 y) internal pure returns (int128) { 119 | int256 result = int256(x) - y; 120 | require (result >= MIN_64x64 && result <= MAX_64x64); 121 | return int128 (result); 122 | } 123 | 124 | /** 125 | * @dev Calculate x * y rounding down. Revert on overflow. 126 | * 127 | * @param x signed 64.64-bit fixed point number 128 | * @param y signed 64.64-bit fixed point number 129 | * @return signed 64.64-bit fixed point number 130 | */ 131 | function mul (int128 x, int128 y) internal pure returns (int128) { 132 | int256 result = int256(x) * y >> 64; 133 | require (result >= MIN_64x64 && result <= MAX_64x64); 134 | return int128 (result); 135 | } 136 | 137 | /** 138 | * @dev Calculate x * y rounding towards zero, where x is signed 64.64 fixed point 139 | * number and y is signed 256-bit integer number. Revert on overflow. 140 | * 141 | * @param x signed 64.64 fixed point number 142 | * @param y signed 256-bit integer number 143 | * @return signed 256-bit integer number 144 | */ 145 | function muli (int128 x, int256 y) internal pure returns (int256) { 146 | if (x == MIN_64x64) { 147 | require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && 148 | y <= 0x1000000000000000000000000000000000000000000000000); 149 | return -y << 63; 150 | } else { 151 | bool negativeResult = false; 152 | if (x < 0) { 153 | x = -x; 154 | negativeResult = true; 155 | } 156 | if (y < 0) { 157 | y = -y; // We rely on overflow behavior here 158 | negativeResult = !negativeResult; 159 | } 160 | uint256 absoluteResult = mulu (x, uint256 (y)); 161 | if (negativeResult) { 162 | require (absoluteResult <= 163 | 0x8000000000000000000000000000000000000000000000000000000000000000); 164 | return -int256 (absoluteResult); // We rely on overflow behavior here 165 | } else { 166 | require (absoluteResult <= 167 | 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); 168 | return int256 (absoluteResult); 169 | } 170 | } 171 | } 172 | 173 | /** 174 | * @dev Calculate x * y rounding down, where x is signed 64.64 fixed point number 175 | * and y is unsigned 256-bit integer number. Revert on overflow. 176 | * 177 | * @param x signed 64.64 fixed point number 178 | * @param y unsigned 256-bit integer number 179 | * @return unsigned 256-bit integer number 180 | */ 181 | function mulu (int128 x, uint256 y) internal pure returns (uint256) { 182 | if (y == 0) return 0; 183 | 184 | require (x >= 0); 185 | 186 | uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; 187 | uint256 hi = uint256 (x) * (y >> 128); 188 | 189 | require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); 190 | hi <<= 64; 191 | 192 | require (hi <= 193 | 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); 194 | return hi + lo; 195 | } 196 | 197 | /** 198 | * @dev Calculate x / y rounding towards zero. Revert on overflow or when y is 199 | * zero. 200 | * 201 | * @param x signed 64.64-bit fixed point number 202 | * @param y signed 64.64-bit fixed point number 203 | * @return signed 64.64-bit fixed point number 204 | */ 205 | function div (int128 x, int128 y) internal pure returns (int128) { 206 | require (y != 0); 207 | int256 result = (int256 (x) << 64) / y; 208 | require (result >= MIN_64x64 && result <= MAX_64x64); 209 | return int128 (result); 210 | } 211 | 212 | /** 213 | * @dev Calculate x / y rounding towards zero, where x and y are signed 256-bit 214 | * integer numbers. Revert on overflow or when y is zero. 215 | * 216 | * @param x signed 256-bit integer number 217 | * @param y signed 256-bit integer number 218 | * @return signed 64.64-bit fixed point number 219 | */ 220 | function divi (int256 x, int256 y) internal pure returns (int128) { 221 | require (y != 0); 222 | 223 | bool negativeResult = false; 224 | if (x < 0) { 225 | x = -x; // We rely on overflow behavior here 226 | negativeResult = true; 227 | } 228 | if (y < 0) { 229 | y = -y; // We rely on overflow behavior here 230 | negativeResult = !negativeResult; 231 | } 232 | uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); 233 | if (negativeResult) { 234 | require (absoluteResult <= 0x80000000000000000000000000000000); 235 | return -int128 (absoluteResult); // We rely on overflow behavior here 236 | } else { 237 | require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); 238 | return int128 (absoluteResult); // We rely on overflow behavior here 239 | } 240 | } 241 | 242 | /** 243 | * @dev Calculate x / y rounding towards zero, where x and y are unsigned 256-bit 244 | * integer numbers. Revert on overflow or when y is zero. 245 | * 246 | * @param x unsigned 256-bit integer number 247 | * @param y unsigned 256-bit integer number 248 | * @return signed 64.64-bit fixed point number 249 | */ 250 | function divu (uint256 x, uint256 y) internal pure returns (int128) { 251 | require (y != 0); 252 | uint128 result = divuu (x, y); 253 | require (result <= uint128 (MAX_64x64)); 254 | return int128 (result); 255 | } 256 | 257 | /** 258 | * @dev Calculate -x. Revert on overflow. 259 | * 260 | * @param x signed 64.64-bit fixed point number 261 | * @return signed 64.64-bit fixed point number 262 | */ 263 | function neg (int128 x) internal pure returns (int128) { 264 | require (x != MIN_64x64); 265 | return -x; 266 | } 267 | 268 | /** 269 | * @dev Calculate |x|. Revert on overflow. 270 | * 271 | * @param x signed 64.64-bit fixed point number 272 | * @return signed 64.64-bit fixed point number 273 | */ 274 | function abs (int128 x) internal pure returns (int128) { 275 | require (x != MIN_64x64); 276 | return x < 0 ? -x : x; 277 | } 278 | 279 | /** 280 | * @dev Calculate 1 / x rounding towards zero. Revert on overflow or when x is 281 | * zero. 282 | * 283 | * @param x signed 64.64-bit fixed point number 284 | * @return signed 64.64-bit fixed point number 285 | */ 286 | function inv (int128 x) internal pure returns (int128) { 287 | require (x != 0); 288 | int256 result = int256 (0x100000000000000000000000000000000) / x; 289 | require (result >= MIN_64x64 && result <= MAX_64x64); 290 | return int128 (result); 291 | } 292 | 293 | /** 294 | * @dev Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. 295 | * 296 | * @param x signed 64.64-bit fixed point number 297 | * @param y signed 64.64-bit fixed point number 298 | * @return signed 64.64-bit fixed point number 299 | */ 300 | function avg (int128 x, int128 y) internal pure returns (int128) { 301 | return int128 ((int256 (x) + int256 (y)) >> 1); 302 | } 303 | 304 | /** 305 | * @dev Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. 306 | * Revert on overflow or in case x * y is negative. 307 | * 308 | * @param x signed 64.64-bit fixed point number 309 | * @param y signed 64.64-bit fixed point number 310 | * @return signed 64.64-bit fixed point number 311 | */ 312 | function gavg (int128 x, int128 y) internal pure returns (int128) { 313 | int256 m = int256 (x) * int256 (y); 314 | require (m >= 0); 315 | require (m < 316 | 0x4000000000000000000000000000000000000000000000000000000000000000); 317 | return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1)); 318 | } 319 | 320 | /** 321 | * @dev Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number 322 | * and y is unsigned 256-bit integer number. Revert on overflow. 323 | * 324 | * @param x signed 64.64-bit fixed point number 325 | * @param y uint256 value 326 | * @return signed 64.64-bit fixed point number 327 | */ 328 | function pow (int128 x, uint256 y) internal pure returns (int128) { 329 | uint256 absoluteResult; 330 | bool negativeResult = false; 331 | if (x >= 0) { 332 | absoluteResult = powu (uint256 (x) << 63, y); 333 | } else { 334 | // We rely on overflow behavior here 335 | absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); 336 | negativeResult = y & 1 > 0; 337 | } 338 | 339 | absoluteResult >>= 63; 340 | 341 | if (negativeResult) { 342 | require (absoluteResult <= 0x80000000000000000000000000000000); 343 | return -int128 (absoluteResult); // We rely on overflow behavior here 344 | } else { 345 | require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); 346 | return int128 (absoluteResult); // We rely on overflow behavior here 347 | } 348 | } 349 | 350 | /** 351 | * @dev Calculate sqrt (x) rounding down. Revert if x < 0. 352 | * 353 | * @param x signed 64.64-bit fixed point number 354 | * @return signed 64.64-bit fixed point number 355 | */ 356 | function sqrt (int128 x) internal pure returns (int128) { 357 | require (x >= 0); 358 | return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); 359 | } 360 | 361 | /** 362 | * @dev Calculate binary logarithm of x. Revert if x <= 0. 363 | * 364 | * @param x signed 64.64-bit fixed point number 365 | * @return signed 64.64-bit fixed point number 366 | */ 367 | function log_2 (int128 x) internal pure returns (int128) { 368 | require (x > 0); 369 | 370 | int256 msb = 0; 371 | int256 xc = x; 372 | if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } 373 | if (xc >= 0x100000000) { xc >>= 32; msb += 32; } 374 | if (xc >= 0x10000) { xc >>= 16; msb += 16; } 375 | if (xc >= 0x100) { xc >>= 8; msb += 8; } 376 | if (xc >= 0x10) { xc >>= 4; msb += 4; } 377 | if (xc >= 0x4) { xc >>= 2; msb += 2; } 378 | if (xc >= 0x2) msb += 1; // No need to shift xc anymore 379 | 380 | int256 result = msb - 64 << 64; 381 | uint256 ux = uint256 (x) << 127 - msb; 382 | for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { 383 | ux *= ux; 384 | uint256 b = ux >> 255; 385 | ux >>= 127 + b; 386 | result += bit * int256 (b); 387 | } 388 | 389 | return int128 (result); 390 | } 391 | 392 | /** 393 | * @dev Calculate natural logarithm of x. Revert if x <= 0. 394 | * 395 | * @param x signed 64.64-bit fixed point number 396 | * @return signed 64.64-bit fixed point number 397 | */ 398 | function ln (int128 x) internal pure returns (int128) { 399 | require (x > 0); 400 | 401 | return int128 ( 402 | uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); 403 | } 404 | 405 | /** 406 | * @dev Calculate binary exponent of x. Revert on overflow. 407 | * 408 | * @param x signed 64.64-bit fixed point number 409 | * @return signed 64.64-bit fixed point number 410 | */ 411 | function exp_2 (int128 x) internal pure returns (int128) { 412 | require (x < 0x400000000000000000); // Overflow 413 | 414 | if (x < -0x400000000000000000) return 0; // Underflow 415 | 416 | uint256 result = 0x80000000000000000000000000000000; 417 | 418 | if (x & 0x8000000000000000 > 0) 419 | result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; 420 | if (x & 0x4000000000000000 > 0) 421 | result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; 422 | if (x & 0x2000000000000000 > 0) 423 | result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; 424 | if (x & 0x1000000000000000 > 0) 425 | result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; 426 | if (x & 0x800000000000000 > 0) 427 | result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; 428 | if (x & 0x400000000000000 > 0) 429 | result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; 430 | if (x & 0x200000000000000 > 0) 431 | result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; 432 | if (x & 0x100000000000000 > 0) 433 | result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; 434 | if (x & 0x80000000000000 > 0) 435 | result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; 436 | if (x & 0x40000000000000 > 0) 437 | result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; 438 | if (x & 0x20000000000000 > 0) 439 | result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; 440 | if (x & 0x10000000000000 > 0) 441 | result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; 442 | if (x & 0x8000000000000 > 0) 443 | result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; 444 | if (x & 0x4000000000000 > 0) 445 | result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; 446 | if (x & 0x2000000000000 > 0) 447 | result = result * 0x1000162E525EE054754457D5995292026 >> 128; 448 | if (x & 0x1000000000000 > 0) 449 | result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; 450 | if (x & 0x800000000000 > 0) 451 | result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; 452 | if (x & 0x400000000000 > 0) 453 | result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; 454 | if (x & 0x200000000000 > 0) 455 | result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; 456 | if (x & 0x100000000000 > 0) 457 | result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; 458 | if (x & 0x80000000000 > 0) 459 | result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; 460 | if (x & 0x40000000000 > 0) 461 | result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; 462 | if (x & 0x20000000000 > 0) 463 | result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; 464 | if (x & 0x10000000000 > 0) 465 | result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; 466 | if (x & 0x8000000000 > 0) 467 | result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; 468 | if (x & 0x4000000000 > 0) 469 | result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; 470 | if (x & 0x2000000000 > 0) 471 | result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; 472 | if (x & 0x1000000000 > 0) 473 | result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; 474 | if (x & 0x800000000 > 0) 475 | result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; 476 | if (x & 0x400000000 > 0) 477 | result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; 478 | if (x & 0x200000000 > 0) 479 | result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; 480 | if (x & 0x100000000 > 0) 481 | result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; 482 | if (x & 0x80000000 > 0) 483 | result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; 484 | if (x & 0x40000000 > 0) 485 | result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; 486 | if (x & 0x20000000 > 0) 487 | result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; 488 | if (x & 0x10000000 > 0) 489 | result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; 490 | if (x & 0x8000000 > 0) 491 | result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; 492 | if (x & 0x4000000 > 0) 493 | result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; 494 | if (x & 0x2000000 > 0) 495 | result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; 496 | if (x & 0x1000000 > 0) 497 | result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; 498 | if (x & 0x800000 > 0) 499 | result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; 500 | if (x & 0x400000 > 0) 501 | result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; 502 | if (x & 0x200000 > 0) 503 | result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; 504 | if (x & 0x100000 > 0) 505 | result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; 506 | if (x & 0x80000 > 0) 507 | result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; 508 | if (x & 0x40000 > 0) 509 | result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; 510 | if (x & 0x20000 > 0) 511 | result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; 512 | if (x & 0x10000 > 0) 513 | result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; 514 | if (x & 0x8000 > 0) 515 | result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; 516 | if (x & 0x4000 > 0) 517 | result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; 518 | if (x & 0x2000 > 0) 519 | result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; 520 | if (x & 0x1000 > 0) 521 | result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; 522 | if (x & 0x800 > 0) 523 | result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; 524 | if (x & 0x400 > 0) 525 | result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; 526 | if (x & 0x200 > 0) 527 | result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; 528 | if (x & 0x100 > 0) 529 | result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; 530 | if (x & 0x80 > 0) 531 | result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; 532 | if (x & 0x40 > 0) 533 | result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; 534 | if (x & 0x20 > 0) 535 | result = result * 0x100000000000000162E42FEFA39EF366F >> 128; 536 | if (x & 0x10 > 0) 537 | result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; 538 | if (x & 0x8 > 0) 539 | result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; 540 | if (x & 0x4 > 0) 541 | result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; 542 | if (x & 0x2 > 0) 543 | result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; 544 | if (x & 0x1 > 0) 545 | result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; 546 | 547 | result >>= 63 - (x >> 64); 548 | require (result <= uint256 (MAX_64x64)); 549 | 550 | return int128 (result); 551 | } 552 | 553 | /** 554 | * @dev Calculate natural exponent of x. Revert on overflow. 555 | * 556 | * @param x signed 64.64-bit fixed point number 557 | * @return signed 64.64-bit fixed point number 558 | */ 559 | function exp (int128 x) internal pure returns (int128) { 560 | require (x < 0x400000000000000000); // Overflow 561 | 562 | if (x < -0x400000000000000000) return 0; // Underflow 563 | 564 | return exp_2 ( 565 | int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); 566 | } 567 | 568 | /** 569 | * @dev Calculate x / y rounding towards zero, where x and y are unsigned 256-bit 570 | * integer numbers. Revert on overflow or when y is zero. 571 | * 572 | * @param x unsigned 256-bit integer number 573 | * @param y unsigned 256-bit integer number 574 | * @return unsigned 64.64-bit fixed point number 575 | */ 576 | function divuu (uint256 x, uint256 y) private pure returns (uint128) { 577 | require (y != 0); 578 | 579 | uint256 result; 580 | 581 | if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) 582 | result = (x << 64) / y; 583 | else { 584 | uint256 msb = 192; 585 | uint256 xc = x >> 192; 586 | if (xc >= 0x100000000) { xc >>= 32; msb += 32; } 587 | if (xc >= 0x10000) { xc >>= 16; msb += 16; } 588 | if (xc >= 0x100) { xc >>= 8; msb += 8; } 589 | if (xc >= 0x10) { xc >>= 4; msb += 4; } 590 | if (xc >= 0x4) { xc >>= 2; msb += 2; } 591 | if (xc >= 0x2) msb += 1; // No need to shift xc anymore 592 | 593 | result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); 594 | require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); 595 | 596 | uint256 hi = result * (y >> 128); 597 | uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); 598 | 599 | uint256 xh = x >> 192; 600 | uint256 xl = x << 64; 601 | 602 | if (xl < lo) xh -= 1; 603 | xl -= lo; // We rely on overflow behavior here 604 | lo = hi << 128; 605 | if (xl < lo) xh -= 1; 606 | xl -= lo; // We rely on overflow behavior here 607 | 608 | assert (xh == hi >> 128); 609 | 610 | result += xl / y; 611 | } 612 | 613 | require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); 614 | return uint128 (result); 615 | } 616 | 617 | /** 618 | * @dev Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point 619 | * number and y is unsigned 256-bit integer number. Revert on overflow. 620 | * 621 | * @param x unsigned 129.127-bit fixed point number 622 | * @param y uint256 value 623 | * @return unsigned 129.127-bit fixed point number 624 | */ 625 | function powu (uint256 x, uint256 y) private pure returns (uint256) { 626 | if (y == 0) return 0x80000000000000000000000000000000; 627 | else if (x == 0) return 0; 628 | else { 629 | int256 msb = 0; 630 | uint256 xc = x; 631 | if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } 632 | if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } 633 | if (xc >= 0x100000000) { xc >>= 32; msb += 32; } 634 | if (xc >= 0x10000) { xc >>= 16; msb += 16; } 635 | if (xc >= 0x100) { xc >>= 8; msb += 8; } 636 | if (xc >= 0x10) { xc >>= 4; msb += 4; } 637 | if (xc >= 0x4) { xc >>= 2; msb += 2; } 638 | if (xc >= 0x2) msb += 1; // No need to shift xc anymore 639 | 640 | int256 xe = msb - 127; 641 | if (xe > 0) x >>= xe; 642 | else x <<= -xe; 643 | 644 | uint256 result = 0x80000000000000000000000000000000; 645 | int256 re = 0; 646 | 647 | while (y > 0) { 648 | if (y & 1 > 0) { 649 | result = result * x; 650 | y -= 1; 651 | re += xe; 652 | if (result >= 653 | 0x8000000000000000000000000000000000000000000000000000000000000000) { 654 | result >>= 128; 655 | re += 1; 656 | } else result >>= 127; 657 | if (re < -127) return 0; // Underflow 658 | require (re < 128); // Overflow 659 | } else { 660 | x = x * x; 661 | y >>= 1; 662 | xe <<= 1; 663 | if (x >= 664 | 0x8000000000000000000000000000000000000000000000000000000000000000) { 665 | x >>= 128; 666 | xe += 1; 667 | } else x >>= 127; 668 | if (xe < -127) return 0; // Underflow 669 | require (xe < 128); // Overflow 670 | } 671 | } 672 | 673 | if (re > 0) result <<= re; 674 | else if (re < 0) result >>= -re; 675 | 676 | return result; 677 | } 678 | } 679 | 680 | /** 681 | * @dev Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer 682 | * number. 683 | * 684 | * @param x unsigned 256-bit integer number 685 | * @return unsigned 128-bit integer number 686 | */ 687 | function sqrtu (uint256 x, uint256 r) private pure returns (uint128) { 688 | if (x == 0) return 0; 689 | else { 690 | require (r > 0); 691 | while (true) { 692 | uint256 rr = x / r; 693 | if (r == rr || r + 1 == rr) return uint128 (r); 694 | else if (r == rr + 1) return uint128 (rr); 695 | r = r + rr + 1 >> 1; 696 | } 697 | } 698 | } 699 | } 700 | -------------------------------------------------------------------------------- /contracts/fyDai/Pool.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 5 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 6 | import "./YieldMath.sol"; 7 | import "../helpers/Delegable.sol"; 8 | import "../helpers/ERC20Permit.sol"; 9 | import "../interfaces/IFYDai.sol"; 10 | import "../interfaces/IPool.sol"; 11 | 12 | 13 | /// @dev The Pool contract exchanges Dai for fyDai at a price defined by a specific formula. 14 | contract Pool is IPool, Delegable(), ERC20Permit { 15 | 16 | event Trade(uint256 maturity, address indexed from, address indexed to, int256 daiTokens, int256 fyDaiTokens); 17 | event Liquidity(uint256 maturity, address indexed from, address indexed to, int256 daiTokens, int256 fyDaiTokens, int256 poolTokens); 18 | 19 | int128 constant public k = int128(uint256((1 << 64)) / 126144000); // 1 / Seconds in 4 years, in 64.64 20 | int128 constant public g1 = int128(uint256((950 << 64)) / 1000); // To be used when selling Dai to the pool. All constants are `ufixed`, to divide them they must be converted to uint256 21 | int128 constant public g2 = int128(uint256((1000 << 64)) / 950); // To be used when selling fyDai to the pool. All constants are `ufixed`, to divide them they must be converted to uint256 22 | uint128 immutable public maturity; 23 | 24 | IERC20 public override dai; 25 | IFYDai public override fyDai; 26 | 27 | constructor(address dai_, address fyDai_, string memory name_, string memory symbol_) 28 | public 29 | ERC20Permit(name_, symbol_) 30 | { 31 | dai = IERC20(dai_); 32 | fyDai = IFYDai(fyDai_); 33 | 34 | maturity = toUint128(fyDai.maturity()); 35 | } 36 | 37 | /// @dev Trading can only be done before maturity 38 | modifier beforeMaturity() { 39 | require( 40 | now < maturity, 41 | "Pool: Too late" 42 | ); 43 | _; 44 | } 45 | 46 | /// @dev Overflow-protected addition, from OpenZeppelin 47 | function add(uint128 a, uint128 b) 48 | internal pure returns (uint128) 49 | { 50 | uint128 c = a + b; 51 | require(c >= a, "Pool: Dai reserves too high"); 52 | 53 | return c; 54 | } 55 | 56 | /// @dev Overflow-protected substraction, from OpenZeppelin 57 | function sub(uint128 a, uint128 b) internal pure returns (uint128) { 58 | require(b <= a, "Pool: fyDai reserves too low"); 59 | uint128 c = a - b; 60 | 61 | return c; 62 | } 63 | 64 | /// @dev Safe casting from uint256 to uint128 65 | function toUint128(uint256 x) internal pure returns(uint128) { 66 | require( 67 | x <= type(uint128).max, 68 | "Pool: Cast overflow" 69 | ); 70 | return uint128(x); 71 | } 72 | 73 | /// @dev Safe casting from uint256 to int256 74 | function toInt256(uint256 x) internal pure returns(int256) { 75 | require( 76 | x <= uint256(type(int256).max), 77 | "Pool: Cast overflow" 78 | ); 79 | return int256(x); 80 | } 81 | 82 | /// @dev Mint initial liquidity tokens. 83 | /// The liquidity provider needs to have called `dai.approve` 84 | /// @param daiIn The initial Dai liquidity to provide. 85 | function init(uint256 daiIn) 86 | internal 87 | beforeMaturity 88 | returns (uint256) 89 | { 90 | require( 91 | totalSupply() == 0, 92 | "Pool: Already initialized" 93 | ); 94 | // no fyDai transferred, because initial fyDai deposit is entirely virtual 95 | dai.transferFrom(msg.sender, address(this), daiIn); 96 | _mint(msg.sender, daiIn); 97 | emit Liquidity(maturity, msg.sender, msg.sender, -toInt256(daiIn), 0, toInt256(daiIn)); 98 | 99 | return daiIn; 100 | } 101 | 102 | /// @dev Mint liquidity tokens in exchange for adding dai and fyDai 103 | /// The liquidity provider needs to have called `dai.approve` and `fyDai.approve`. 104 | /// @param from Wallet providing the dai and fyDai. Must have approved the operator with `pool.addDelegate(operator)`. 105 | /// @param to Wallet receiving the minted liquidity tokens. 106 | /// @param daiOffered Amount of `dai` being invested, an appropriate amount of `fyDai` to be invested alongside will be calculated and taken by this function from the caller. 107 | /// @return The amount of liquidity tokens minted. 108 | function mint(address from, address to, uint256 daiOffered) 109 | external override 110 | onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate") 111 | returns (uint256) 112 | { 113 | uint256 supply = totalSupply(); 114 | if (supply == 0) return init(daiOffered); 115 | 116 | uint256 daiReserves = dai.balanceOf(address(this)); 117 | // use the actual reserves rather than the virtual reserves 118 | uint256 fyDaiReserves = fyDai.balanceOf(address(this)); 119 | uint256 tokensMinted = supply.mul(daiOffered).div(daiReserves); 120 | uint256 fyDaiRequired = fyDaiReserves.mul(tokensMinted).div(supply); 121 | 122 | require(daiReserves.add(daiOffered) <= type(uint128).max); // daiReserves can't go over type(uint128).max 123 | require(supply.add(fyDaiReserves.add(fyDaiRequired)) <= type(uint128).max); // fyDaiReserves can't go over type(uint128).max 124 | 125 | require(dai.transferFrom(from, address(this), daiOffered)); 126 | require(fyDai.transferFrom(from, address(this), fyDaiRequired)); 127 | _mint(to, tokensMinted); 128 | emit Liquidity(maturity, from, to, -toInt256(daiOffered), -toInt256(fyDaiRequired), toInt256(tokensMinted)); 129 | 130 | return tokensMinted; 131 | } 132 | 133 | /// @dev Burn liquidity tokens in exchange for dai and fyDai. 134 | /// The liquidity provider needs to have called `pool.approve`. 135 | /// @param from Wallet providing the liquidity tokens. Must have approved the operator with `pool.addDelegate(operator)`. 136 | /// @param to Wallet receiving the dai and fyDai. 137 | /// @param tokensBurned Amount of liquidity tokens being burned. 138 | /// @return The amount of reserve tokens returned (daiTokens, fyDaiTokens). 139 | function burn(address from, address to, uint256 tokensBurned) 140 | external override 141 | onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate") 142 | returns (uint256, uint256) 143 | { 144 | uint256 supply = totalSupply(); 145 | uint256 daiReserves = dai.balanceOf(address(this)); 146 | // use the actual reserves rather than the virtual reserves 147 | uint256 daiReturned; 148 | uint256 fyDaiReturned; 149 | { // avoiding stack too deep 150 | uint256 fyDaiReserves = fyDai.balanceOf(address(this)); 151 | daiReturned = tokensBurned.mul(daiReserves).div(supply); 152 | fyDaiReturned = tokensBurned.mul(fyDaiReserves).div(supply); 153 | } 154 | 155 | _burn(from, tokensBurned); 156 | dai.transfer(to, daiReturned); 157 | fyDai.transfer(to, fyDaiReturned); 158 | emit Liquidity(maturity, from, to, toInt256(daiReturned), toInt256(fyDaiReturned), -toInt256(tokensBurned)); 159 | 160 | return (daiReturned, fyDaiReturned); 161 | } 162 | 163 | /// @dev Sell Dai for fyDai 164 | /// The trader needs to have called `dai.approve` 165 | /// @param from Wallet providing the dai being sold. Must have approved the operator with `pool.addDelegate(operator)`. 166 | /// @param to Wallet receiving the fyDai being bought 167 | /// @param daiIn Amount of dai being sold that will be taken from the user's wallet 168 | /// @return Amount of fyDai that will be deposited on `to` wallet 169 | function sellDai(address from, address to, uint128 daiIn) 170 | external override 171 | onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate") 172 | returns(uint128) 173 | { 174 | uint128 fyDaiOut = sellDaiPreview(daiIn); 175 | 176 | dai.transferFrom(from, address(this), daiIn); 177 | fyDai.transfer(to, fyDaiOut); 178 | emit Trade(maturity, from, to, -toInt256(daiIn), toInt256(fyDaiOut)); 179 | 180 | return fyDaiOut; 181 | } 182 | 183 | /// @dev Returns how much fyDai would be obtained by selling `daiIn` dai 184 | /// @param daiIn Amount of dai hypothetically sold. 185 | /// @return Amount of fyDai hypothetically bought. 186 | function sellDaiPreview(uint128 daiIn) 187 | public view override 188 | beforeMaturity 189 | returns(uint128) 190 | { 191 | uint128 daiReserves = getDaiReserves(); 192 | uint128 fyDaiReserves = getFYDaiReserves(); 193 | 194 | uint128 fyDaiOut = YieldMath.fyDaiOutForDaiIn( 195 | daiReserves, 196 | fyDaiReserves, 197 | daiIn, 198 | toUint128(maturity - now), // This can't be called after maturity 199 | k, 200 | g1 201 | ); 202 | 203 | require( 204 | sub(fyDaiReserves, fyDaiOut) >= add(daiReserves, daiIn), 205 | "Pool: fyDai reserves too low" 206 | ); 207 | 208 | return fyDaiOut; 209 | } 210 | 211 | /// @dev Buy Dai for fyDai 212 | /// The trader needs to have called `fyDai.approve` 213 | /// @param from Wallet providing the fyDai being sold. Must have approved the operator with `pool.addDelegate(operator)`. 214 | /// @param to Wallet receiving the dai being bought 215 | /// @param daiOut Amount of dai being bought that will be deposited in `to` wallet 216 | /// @return Amount of fyDai that will be taken from `from` wallet 217 | function buyDai(address from, address to, uint128 daiOut) 218 | external override 219 | onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate") 220 | returns(uint128) 221 | { 222 | uint128 fyDaiIn = buyDaiPreview(daiOut); 223 | 224 | fyDai.transferFrom(from, address(this), fyDaiIn); 225 | dai.transfer(to, daiOut); 226 | emit Trade(maturity, from, to, toInt256(daiOut), -toInt256(fyDaiIn)); 227 | 228 | return fyDaiIn; 229 | } 230 | 231 | /// @dev Returns how much fyDai would be required to buy `daiOut` dai. 232 | /// @param daiOut Amount of dai hypothetically desired. 233 | /// @return Amount of fyDai hypothetically required. 234 | function buyDaiPreview(uint128 daiOut) 235 | public view override 236 | beforeMaturity 237 | returns(uint128) 238 | { 239 | return YieldMath.fyDaiInForDaiOut( 240 | getDaiReserves(), 241 | getFYDaiReserves(), 242 | daiOut, 243 | toUint128(maturity - now), // This can't be called after maturity 244 | k, 245 | g2 246 | ); 247 | } 248 | 249 | /// @dev Sell fyDai for Dai 250 | /// The trader needs to have called `fyDai.approve` 251 | /// @param from Wallet providing the fyDai being sold. Must have approved the operator with `pool.addDelegate(operator)`. 252 | /// @param to Wallet receiving the dai being bought 253 | /// @param fyDaiIn Amount of fyDai being sold that will be taken from the user's wallet 254 | /// @return Amount of dai that will be deposited on `to` wallet 255 | function sellFYDai(address from, address to, uint128 fyDaiIn) 256 | external override 257 | onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate") 258 | returns(uint128) 259 | { 260 | uint128 daiOut = sellFYDaiPreview(fyDaiIn); 261 | 262 | fyDai.transferFrom(from, address(this), fyDaiIn); 263 | dai.transfer(to, daiOut); 264 | emit Trade(maturity, from, to, toInt256(daiOut), -toInt256(fyDaiIn)); 265 | 266 | return daiOut; 267 | } 268 | 269 | /// @dev Returns how much dai would be obtained by selling `fyDaiIn` fyDai. 270 | /// @param fyDaiIn Amount of fyDai hypothetically sold. 271 | /// @return Amount of Dai hypothetically bought. 272 | function sellFYDaiPreview(uint128 fyDaiIn) 273 | public view override 274 | beforeMaturity 275 | returns(uint128) 276 | { 277 | return YieldMath.daiOutForFYDaiIn( 278 | getDaiReserves(), 279 | getFYDaiReserves(), 280 | fyDaiIn, 281 | toUint128(maturity - now), // This can't be called after maturity 282 | k, 283 | g2 284 | ); 285 | } 286 | 287 | /// @dev Buy fyDai for dai 288 | /// The trader needs to have called `dai.approve` 289 | /// @param from Wallet providing the dai being sold. Must have approved the operator with `pool.addDelegate(operator)`. 290 | /// @param to Wallet receiving the fyDai being bought 291 | /// @param fyDaiOut Amount of fyDai being bought that will be deposited in `to` wallet 292 | /// @return Amount of dai that will be taken from `from` wallet 293 | function buyFYDai(address from, address to, uint128 fyDaiOut) 294 | external override 295 | onlyHolderOrDelegate(from, "Pool: Only Holder Or Delegate") 296 | returns(uint128) 297 | { 298 | uint128 daiIn = buyFYDaiPreview(fyDaiOut); 299 | 300 | dai.transferFrom(from, address(this), daiIn); 301 | fyDai.transfer(to, fyDaiOut); 302 | emit Trade(maturity, from, to, -toInt256(daiIn), toInt256(fyDaiOut)); 303 | 304 | return daiIn; 305 | } 306 | 307 | 308 | /// @dev Returns how much dai would be required to buy `fyDaiOut` fyDai. 309 | /// @param fyDaiOut Amount of fyDai hypothetically desired. 310 | /// @return Amount of Dai hypothetically required. 311 | function buyFYDaiPreview(uint128 fyDaiOut) 312 | public view override 313 | beforeMaturity 314 | returns(uint128) 315 | { 316 | uint128 daiReserves = getDaiReserves(); 317 | uint128 fyDaiReserves = getFYDaiReserves(); 318 | 319 | uint128 daiIn = YieldMath.daiInForFYDaiOut( 320 | daiReserves, 321 | fyDaiReserves, 322 | fyDaiOut, 323 | toUint128(maturity - now), // This can't be called after maturity 324 | k, 325 | g1 326 | ); 327 | 328 | require( 329 | sub(fyDaiReserves, fyDaiOut) >= add(daiReserves, daiIn), 330 | "Pool: fyDai reserves too low" 331 | ); 332 | 333 | return daiIn; 334 | } 335 | 336 | /// @dev Returns the "virtual" fyDai reserves 337 | function getFYDaiReserves() 338 | public view override 339 | returns(uint128) 340 | { 341 | return toUint128(fyDai.balanceOf(address(this)).add(totalSupply())); 342 | } 343 | 344 | /// @dev Returns the Dai reserves 345 | function getDaiReserves() 346 | public view override 347 | returns(uint128) 348 | { 349 | return toUint128(dai.balanceOf(address(this))); 350 | } 351 | } 352 | -------------------------------------------------------------------------------- /contracts/fyDai/YieldMath.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.0; 3 | 4 | import "./Math64x64.sol"; 5 | 6 | /** 7 | * Ethereum smart contract library implementing Yield Math model. 8 | */ 9 | library YieldMath { 10 | /** 11 | * Calculate the amount of fyDai a user would get for given amount of Dai. 12 | * 13 | * @param daiReserves Dai reserves amount 14 | * @param fyDaiReserves fyDai reserves amount 15 | * @param daiAmount Dai amount to be traded 16 | * @param timeTillMaturity time till maturity in seconds 17 | * @param k time till maturity coefficient, multiplied by 2^64 18 | * @param g fee coefficient, multiplied by 2^64 19 | * @return the amount of fyDai a user would get for given amount of Dai 20 | */ 21 | function fyDaiOutForDaiIn ( 22 | uint128 daiReserves, uint128 fyDaiReserves, uint128 daiAmount, 23 | uint128 timeTillMaturity, int128 k, int128 g) 24 | internal pure returns (uint128) { 25 | // t = k * timeTillMaturity 26 | int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity)); 27 | 28 | // a = (1 - gt) 29 | int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t)); 30 | require (a > 0, "YieldMath: Too far from maturity"); 31 | 32 | // xdx = daiReserves + daiAmount 33 | uint256 xdx = uint256 (daiReserves) + uint256 (daiAmount); 34 | require (xdx < 0x100000000000000000000000000000000, "YieldMath: Too much Dai in"); 35 | 36 | uint256 sum = 37 | pow (daiReserves, uint128 (a), 0x10000000000000000) + 38 | pow (fyDaiReserves, uint128 (a), 0x10000000000000000) - 39 | pow (uint128(xdx), uint128 (a), 0x10000000000000000); 40 | require (sum < 0x100000000000000000000000000000000, "YieldMath: Insufficient fyDai reserves"); 41 | 42 | uint256 result = fyDaiReserves - pow (uint128 (sum), 0x10000000000000000, uint128 (a)); 43 | require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error"); 44 | result = result > 1e12 ? result - 1e12 : 0; // Substract error guard, flooring the result at zero 45 | 46 | return uint128 (result); 47 | } 48 | 49 | /** 50 | * Calculate the amount of Dai a user would get for certain amount of fyDai. 51 | * 52 | * @param daiReserves Dai reserves amount 53 | * @param fyDaiReserves fyDai reserves amount 54 | * @param fyDaiAmount fyDai amount to be traded 55 | * @param timeTillMaturity time till maturity in seconds 56 | * @param k time till maturity coefficient, multiplied by 2^64 57 | * @param g fee coefficient, multiplied by 2^64 58 | * @return the amount of Dai a user would get for given amount of fyDai 59 | */ 60 | function daiOutForFYDaiIn ( 61 | uint128 daiReserves, uint128 fyDaiReserves, uint128 fyDaiAmount, 62 | uint128 timeTillMaturity, int128 k, int128 g) 63 | internal pure returns (uint128) { 64 | // t = k * timeTillMaturity 65 | int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity)); 66 | 67 | // a = (1 - gt) 68 | int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t)); 69 | require (a > 0, "YieldMath: Too far from maturity"); 70 | 71 | // ydy = fyDaiReserves + fyDaiAmount; 72 | uint256 ydy = uint256 (fyDaiReserves) + uint256 (fyDaiAmount); 73 | require (ydy < 0x100000000000000000000000000000000, "YieldMath: Too much fyDai in"); 74 | 75 | uint256 sum = 76 | pow (uint128 (daiReserves), uint128 (a), 0x10000000000000000) - 77 | pow (uint128 (ydy), uint128 (a), 0x10000000000000000) + 78 | pow (fyDaiReserves, uint128 (a), 0x10000000000000000); 79 | require (sum < 0x100000000000000000000000000000000, "YieldMath: Insufficient Dai reserves"); 80 | 81 | uint256 result = 82 | daiReserves - 83 | pow (uint128 (sum), 0x10000000000000000, uint128 (a)); 84 | require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error"); 85 | result = result > 1e12 ? result - 1e12 : 0; // Substract error guard, flooring the result at zero 86 | 87 | return uint128 (result); 88 | } 89 | 90 | /** 91 | * Calculate the amount of fyDai a user could sell for given amount of Dai. 92 | * 93 | * @param daiReserves Dai reserves amount 94 | * @param fyDaiReserves fyDai reserves amount 95 | * @param daiAmount Dai amount to be traded 96 | * @param timeTillMaturity time till maturity in seconds 97 | * @param k time till maturity coefficient, multiplied by 2^64 98 | * @param g fee coefficient, multiplied by 2^64 99 | * @return the amount of fyDai a user could sell for given amount of Dai 100 | */ 101 | function fyDaiInForDaiOut ( 102 | uint128 daiReserves, uint128 fyDaiReserves, uint128 daiAmount, 103 | uint128 timeTillMaturity, int128 k, int128 g) 104 | internal pure returns (uint128) { 105 | // t = k * timeTillMaturity 106 | int128 t = Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity)); 107 | 108 | // a = (1 - gt) 109 | int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, t)); 110 | require (a > 0, "YieldMath: Too far from maturity"); 111 | 112 | // xdx = daiReserves - daiAmount 113 | uint256 xdx = uint256 (daiReserves) - uint256 (daiAmount); 114 | require (xdx < 0x100000000000000000000000000000000, "YieldMath: Too much Dai out"); 115 | 116 | uint256 sum = 117 | pow (uint128 (daiReserves), uint128 (a), 0x10000000000000000) + 118 | pow (fyDaiReserves, uint128 (a), 0x10000000000000000) - 119 | pow (uint128 (xdx), uint128 (a), 0x10000000000000000); 120 | require (sum < 0x100000000000000000000000000000000, "YieldMath: Resulting fyDai reserves too high"); 121 | 122 | uint256 result = pow (uint128 (sum), 0x10000000000000000, uint128 (a)) - fyDaiReserves; 123 | require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error"); 124 | result = result < type(uint128).max - 1e12 ? result + 1e12 : type(uint128).max; // Add error guard, ceiling the result at max 125 | 126 | return uint128 (result); 127 | } 128 | 129 | /** 130 | * Calculate the amount of Dai a user would have to pay for certain amount of 131 | * fyDai. 132 | * 133 | * @param daiReserves Dai reserves amount 134 | * @param fyDaiReserves fyDai reserves amount 135 | * @param fyDaiAmount fyDai amount to be traded 136 | * @param timeTillMaturity time till maturity in seconds 137 | * @param k time till maturity coefficient, multiplied by 2^64 138 | * @param g fee coefficient, multiplied by 2^64 139 | * @return the amount of Dai a user would have to pay for given amount of 140 | * fyDai 141 | */ 142 | function daiInForFYDaiOut ( 143 | uint128 daiReserves, uint128 fyDaiReserves, uint128 fyDaiAmount, 144 | uint128 timeTillMaturity, int128 k, int128 g) 145 | internal pure returns (uint128) { 146 | // a = (1 - g * k * timeTillMaturity) 147 | int128 a = Math64x64.sub (0x10000000000000000, Math64x64.mul (g, Math64x64.mul (k, Math64x64.fromUInt (timeTillMaturity)))); 148 | require (a > 0, "YieldMath: Too far from maturity"); 149 | 150 | // ydy = fyDaiReserves - fyDaiAmount; 151 | uint256 ydy = uint256 (fyDaiReserves) - uint256 (fyDaiAmount); 152 | require (ydy < 0x100000000000000000000000000000000, "YieldMath: Too much fyDai out"); 153 | 154 | uint256 sum = 155 | pow (daiReserves, uint128 (a), 0x10000000000000000) + 156 | pow (fyDaiReserves, uint128 (a), 0x10000000000000000) - 157 | pow (uint128 (ydy), uint128 (a), 0x10000000000000000); 158 | require (sum < 0x100000000000000000000000000000000, "YieldMath: Resulting Dai reserves too high"); 159 | 160 | uint256 result = 161 | pow (uint128 (sum), 0x10000000000000000, uint128 (a)) - 162 | daiReserves; 163 | require (result < 0x100000000000000000000000000000000, "YieldMath: Rounding induced error"); 164 | result = result < type(uint128).max - 1e12 ? result + 1e12 : type(uint128).max; // Add error guard, ceiling the result at max 165 | 166 | return uint128 (result); 167 | } 168 | 169 | /** 170 | * Raise given number x into power specified as a simple fraction y/z and then 171 | * multiply the result by the normalization factor 2^(128 * (1 - y/z)). 172 | * Revert if z is zero, or if both x and y are zeros. 173 | * 174 | * @param x number to raise into given power y/z 175 | * @param y numerator of the power to raise x into 176 | * @param z denominator of the power to raise x into 177 | * @return x raised into power y/z and then multiplied by 2^(128 * (1 - y/z)) 178 | */ 179 | function pow (uint128 x, uint128 y, uint128 z) 180 | internal pure returns (uint256) { 181 | require (z != 0); 182 | 183 | if (x == 0) { 184 | require (y != 0); 185 | return 0; 186 | } else { 187 | uint256 l = 188 | uint256 (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - log_2 (x)) * y / z; 189 | if (l > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return 0; 190 | else return uint256 (pow_2 (uint128 (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - l))); 191 | } 192 | } 193 | 194 | /** 195 | * Calculate base 2 logarithm of an unsigned 128-bit integer number. Revert 196 | * in case x is zero. 197 | * 198 | * @param x number to calculate base 2 logarithm of 199 | * @return base 2 logarithm of x, multiplied by 2^121 200 | */ 201 | function log_2 (uint128 x) 202 | internal pure returns (uint128) { 203 | require (x != 0); 204 | 205 | uint b = x; 206 | 207 | uint l = 0xFE000000000000000000000000000000; 208 | 209 | if (b < 0x10000000000000000) {l -= 0x80000000000000000000000000000000; b <<= 64;} 210 | if (b < 0x1000000000000000000000000) {l -= 0x40000000000000000000000000000000; b <<= 32;} 211 | if (b < 0x10000000000000000000000000000) {l -= 0x20000000000000000000000000000000; b <<= 16;} 212 | if (b < 0x1000000000000000000000000000000) {l -= 0x10000000000000000000000000000000; b <<= 8;} 213 | if (b < 0x10000000000000000000000000000000) {l -= 0x8000000000000000000000000000000; b <<= 4;} 214 | if (b < 0x40000000000000000000000000000000) {l -= 0x4000000000000000000000000000000; b <<= 2;} 215 | if (b < 0x80000000000000000000000000000000) {l -= 0x2000000000000000000000000000000; b <<= 1;} 216 | 217 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000000;} 218 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000000;} 219 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000000;} 220 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000000;} 221 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000000;} 222 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000000;} 223 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000000;} 224 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000000;} 225 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000000;} 226 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000000;} 227 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000000;} 228 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000000;} 229 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000;} 230 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000;} 231 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000;} 232 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000;} 233 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000;} 234 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000;} 235 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000;} 236 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000;} 237 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000;} 238 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000;} 239 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000;} 240 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000;} 241 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000;} 242 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000;} 243 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000;} 244 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000;} 245 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000;} 246 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000;} 247 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000;} 248 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000;} 249 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000;} 250 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000;} 251 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000;} 252 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000;} 253 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000;} 254 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000;} 255 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000;} 256 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000;} 257 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000;} 258 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000;} 259 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000;} 260 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000;} 261 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000;} 262 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000;} 263 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000;} 264 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000;} 265 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000;} 266 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000;} 267 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000;} 268 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000;} 269 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000;} 270 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000;} 271 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000;} 272 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000;} 273 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000;} 274 | /* Precision reduced to 64 bits 275 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000;} 276 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000;} 277 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000;} 278 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000;} 279 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000;} 280 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000;} 281 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000;} 282 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000;} 283 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000;} 284 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000;} 285 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000;} 286 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000;} 287 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000;} 288 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000;} 289 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000;} 290 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000;} 291 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000;} 292 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000;} 293 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000;} 294 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000;} 295 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000;} 296 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000;} 297 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000;} 298 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000;} 299 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000;} 300 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000;} 301 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000;} 302 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000;} 303 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000;} 304 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000;} 305 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000;} 306 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000;} 307 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000;} 308 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000;} 309 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000;} 310 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000;} 311 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000;} 312 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000;} 313 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000;} 314 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000;} 315 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000;} 316 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000;} 317 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000;} 318 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000;} 319 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000;} 320 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000;} 321 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000;} 322 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000;} 323 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000;} 324 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000;} 325 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000;} 326 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000;} 327 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800;} 328 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400;} 329 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200;} 330 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100;} 331 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80;} 332 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40;} 333 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20;} 334 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10;} 335 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8;} 336 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4;} 337 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2;} 338 | b = b * b >> 127; if (b >= 0x100000000000000000000000000000000) l |= 0x1; 339 | */ 340 | 341 | return uint128 (l); 342 | } 343 | 344 | /** 345 | * Calculate 2 raised into given power. 346 | * 347 | * @param x power to raise 2 into, multiplied by 2^121 348 | * @return 2 raised into given power 349 | */ 350 | function pow_2 (uint128 x) 351 | internal pure returns (uint128) { 352 | uint r = 0x80000000000000000000000000000000; 353 | if (x & 0x1000000000000000000000000000000 > 0) r = r * 0xb504f333f9de6484597d89b3754abe9f >> 127; 354 | if (x & 0x800000000000000000000000000000 > 0) r = r * 0x9837f0518db8a96f46ad23182e42f6f6 >> 127; 355 | if (x & 0x400000000000000000000000000000 > 0) r = r * 0x8b95c1e3ea8bd6e6fbe4628758a53c90 >> 127; 356 | if (x & 0x200000000000000000000000000000 > 0) r = r * 0x85aac367cc487b14c5c95b8c2154c1b2 >> 127; 357 | if (x & 0x100000000000000000000000000000 > 0) r = r * 0x82cd8698ac2ba1d73e2a475b46520bff >> 127; 358 | if (x & 0x80000000000000000000000000000 > 0) r = r * 0x8164d1f3bc0307737be56527bd14def4 >> 127; 359 | if (x & 0x40000000000000000000000000000 > 0) r = r * 0x80b1ed4fd999ab6c25335719b6e6fd20 >> 127; 360 | if (x & 0x20000000000000000000000000000 > 0) r = r * 0x8058d7d2d5e5f6b094d589f608ee4aa2 >> 127; 361 | if (x & 0x10000000000000000000000000000 > 0) r = r * 0x802c6436d0e04f50ff8ce94a6797b3ce >> 127; 362 | if (x & 0x8000000000000000000000000000 > 0) r = r * 0x8016302f174676283690dfe44d11d008 >> 127; 363 | if (x & 0x4000000000000000000000000000 > 0) r = r * 0x800b179c82028fd0945e54e2ae18f2f0 >> 127; 364 | if (x & 0x2000000000000000000000000000 > 0) r = r * 0x80058baf7fee3b5d1c718b38e549cb93 >> 127; 365 | if (x & 0x1000000000000000000000000000 > 0) r = r * 0x8002c5d00fdcfcb6b6566a58c048be1f >> 127; 366 | if (x & 0x800000000000000000000000000 > 0) r = r * 0x800162e61bed4a48e84c2e1a463473d9 >> 127; 367 | if (x & 0x400000000000000000000000000 > 0) r = r * 0x8000b17292f702a3aa22beacca949013 >> 127; 368 | if (x & 0x200000000000000000000000000 > 0) r = r * 0x800058b92abbae02030c5fa5256f41fe >> 127; 369 | if (x & 0x100000000000000000000000000 > 0) r = r * 0x80002c5c8dade4d71776c0f4dbea67d6 >> 127; 370 | if (x & 0x80000000000000000000000000 > 0) r = r * 0x8000162e44eaf636526be456600bdbe4 >> 127; 371 | if (x & 0x40000000000000000000000000 > 0) r = r * 0x80000b1721fa7c188307016c1cd4e8b6 >> 127; 372 | if (x & 0x20000000000000000000000000 > 0) r = r * 0x8000058b90de7e4cecfc487503488bb1 >> 127; 373 | if (x & 0x10000000000000000000000000 > 0) r = r * 0x800002c5c8678f36cbfce50a6de60b14 >> 127; 374 | if (x & 0x8000000000000000000000000 > 0) r = r * 0x80000162e431db9f80b2347b5d62e516 >> 127; 375 | if (x & 0x4000000000000000000000000 > 0) r = r * 0x800000b1721872d0c7b08cf1e0114152 >> 127; 376 | if (x & 0x2000000000000000000000000 > 0) r = r * 0x80000058b90c1aa8a5c3736cb77e8dff >> 127; 377 | if (x & 0x1000000000000000000000000 > 0) r = r * 0x8000002c5c8605a4635f2efc2362d978 >> 127; 378 | if (x & 0x800000000000000000000000 > 0) r = r * 0x800000162e4300e635cf4a109e3939bd >> 127; 379 | if (x & 0x400000000000000000000000 > 0) r = r * 0x8000000b17217ff81bef9c551590cf83 >> 127; 380 | if (x & 0x200000000000000000000000 > 0) r = r * 0x800000058b90bfdd4e39cd52c0cfa27c >> 127; 381 | if (x & 0x100000000000000000000000 > 0) r = r * 0x80000002c5c85fe6f72d669e0e76e411 >> 127; 382 | if (x & 0x80000000000000000000000 > 0) r = r * 0x8000000162e42ff18f9ad35186d0df28 >> 127; 383 | if (x & 0x40000000000000000000000 > 0) r = r * 0x80000000b17217f84cce71aa0dcfffe7 >> 127; 384 | if (x & 0x20000000000000000000000 > 0) r = r * 0x8000000058b90bfc07a77ad56ed22aaa >> 127; 385 | if (x & 0x10000000000000000000000 > 0) r = r * 0x800000002c5c85fdfc23cdead40da8d6 >> 127; 386 | if (x & 0x8000000000000000000000 > 0) r = r * 0x80000000162e42fefc25eb1571853a66 >> 127; 387 | if (x & 0x4000000000000000000000 > 0) r = r * 0x800000000b17217f7d97f692baacded5 >> 127; 388 | if (x & 0x2000000000000000000000 > 0) r = r * 0x80000000058b90bfbead3b8b5dd254d7 >> 127; 389 | if (x & 0x1000000000000000000000 > 0) r = r * 0x8000000002c5c85fdf4eedd62f084e67 >> 127; 390 | if (x & 0x800000000000000000000 > 0) r = r * 0x800000000162e42fefa58aef378bf586 >> 127; 391 | if (x & 0x400000000000000000000 > 0) r = r * 0x8000000000b17217f7d24a78a3c7ef02 >> 127; 392 | if (x & 0x200000000000000000000 > 0) r = r * 0x800000000058b90bfbe9067c93e474a6 >> 127; 393 | if (x & 0x100000000000000000000 > 0) r = r * 0x80000000002c5c85fdf47b8e5a72599f >> 127; 394 | if (x & 0x80000000000000000000 > 0) r = r * 0x8000000000162e42fefa3bdb315934a2 >> 127; 395 | if (x & 0x40000000000000000000 > 0) r = r * 0x80000000000b17217f7d1d7299b49c46 >> 127; 396 | if (x & 0x20000000000000000000 > 0) r = r * 0x8000000000058b90bfbe8e9a8d1c4ea0 >> 127; 397 | if (x & 0x10000000000000000000 > 0) r = r * 0x800000000002c5c85fdf4745969ea76f >> 127; 398 | if (x & 0x8000000000000000000 > 0) r = r * 0x80000000000162e42fefa3a0df5373bf >> 127; 399 | if (x & 0x4000000000000000000 > 0) r = r * 0x800000000000b17217f7d1cff4aac1e1 >> 127; 400 | if (x & 0x2000000000000000000 > 0) r = r * 0x80000000000058b90bfbe8e7db95a2f1 >> 127; 401 | if (x & 0x1000000000000000000 > 0) r = r * 0x8000000000002c5c85fdf473e61ae1f8 >> 127; 402 | if (x & 0x800000000000000000 > 0) r = r * 0x800000000000162e42fefa39f121751c >> 127; 403 | if (x & 0x400000000000000000 > 0) r = r * 0x8000000000000b17217f7d1cf815bb96 >> 127; 404 | if (x & 0x200000000000000000 > 0) r = r * 0x800000000000058b90bfbe8e7bec1e0d >> 127; 405 | if (x & 0x100000000000000000 > 0) r = r * 0x80000000000002c5c85fdf473dee5f17 >> 127; 406 | if (x & 0x80000000000000000 > 0) r = r * 0x8000000000000162e42fefa39ef5438f >> 127; 407 | if (x & 0x40000000000000000 > 0) r = r * 0x80000000000000b17217f7d1cf7a26c8 >> 127; 408 | if (x & 0x20000000000000000 > 0) r = r * 0x8000000000000058b90bfbe8e7bcf4a4 >> 127; 409 | if (x & 0x10000000000000000 > 0) r = r * 0x800000000000002c5c85fdf473de72a2 >> 127; 410 | /* Precision reduced to 64 bits 411 | if (x & 0x8000000000000000 > 0) r = r * 0x80000000000000162e42fefa39ef3765 >> 127; 412 | if (x & 0x4000000000000000 > 0) r = r * 0x800000000000000b17217f7d1cf79b37 >> 127; 413 | if (x & 0x2000000000000000 > 0) r = r * 0x80000000000000058b90bfbe8e7bcd7d >> 127; 414 | if (x & 0x1000000000000000 > 0) r = r * 0x8000000000000002c5c85fdf473de6b6 >> 127; 415 | if (x & 0x800000000000000 > 0) r = r * 0x800000000000000162e42fefa39ef359 >> 127; 416 | if (x & 0x400000000000000 > 0) r = r * 0x8000000000000000b17217f7d1cf79ac >> 127; 417 | if (x & 0x200000000000000 > 0) r = r * 0x800000000000000058b90bfbe8e7bcd6 >> 127; 418 | if (x & 0x100000000000000 > 0) r = r * 0x80000000000000002c5c85fdf473de6a >> 127; 419 | if (x & 0x80000000000000 > 0) r = r * 0x8000000000000000162e42fefa39ef35 >> 127; 420 | if (x & 0x40000000000000 > 0) r = r * 0x80000000000000000b17217f7d1cf79a >> 127; 421 | if (x & 0x20000000000000 > 0) r = r * 0x8000000000000000058b90bfbe8e7bcd >> 127; 422 | if (x & 0x10000000000000 > 0) r = r * 0x800000000000000002c5c85fdf473de6 >> 127; 423 | if (x & 0x8000000000000 > 0) r = r * 0x80000000000000000162e42fefa39ef3 >> 127; 424 | if (x & 0x4000000000000 > 0) r = r * 0x800000000000000000b17217f7d1cf79 >> 127; 425 | if (x & 0x2000000000000 > 0) r = r * 0x80000000000000000058b90bfbe8e7bc >> 127; 426 | if (x & 0x1000000000000 > 0) r = r * 0x8000000000000000002c5c85fdf473de >> 127; 427 | if (x & 0x800000000000 > 0) r = r * 0x800000000000000000162e42fefa39ef >> 127; 428 | if (x & 0x400000000000 > 0) r = r * 0x8000000000000000000b17217f7d1cf7 >> 127; 429 | if (x & 0x200000000000 > 0) r = r * 0x800000000000000000058b90bfbe8e7b >> 127; 430 | if (x & 0x100000000000 > 0) r = r * 0x80000000000000000002c5c85fdf473d >> 127; 431 | if (x & 0x80000000000 > 0) r = r * 0x8000000000000000000162e42fefa39e >> 127; 432 | if (x & 0x40000000000 > 0) r = r * 0x80000000000000000000b17217f7d1cf >> 127; 433 | if (x & 0x20000000000 > 0) r = r * 0x8000000000000000000058b90bfbe8e7 >> 127; 434 | if (x & 0x10000000000 > 0) r = r * 0x800000000000000000002c5c85fdf473 >> 127; 435 | if (x & 0x8000000000 > 0) r = r * 0x80000000000000000000162e42fefa39 >> 127; 436 | if (x & 0x4000000000 > 0) r = r * 0x800000000000000000000b17217f7d1c >> 127; 437 | if (x & 0x2000000000 > 0) r = r * 0x80000000000000000000058b90bfbe8e >> 127; 438 | if (x & 0x1000000000 > 0) r = r * 0x8000000000000000000002c5c85fdf47 >> 127; 439 | if (x & 0x800000000 > 0) r = r * 0x800000000000000000000162e42fefa3 >> 127; 440 | if (x & 0x400000000 > 0) r = r * 0x8000000000000000000000b17217f7d1 >> 127; 441 | if (x & 0x200000000 > 0) r = r * 0x800000000000000000000058b90bfbe8 >> 127; 442 | if (x & 0x100000000 > 0) r = r * 0x80000000000000000000002c5c85fdf4 >> 127; 443 | if (x & 0x80000000 > 0) r = r * 0x8000000000000000000000162e42fefa >> 127; 444 | if (x & 0x40000000 > 0) r = r * 0x80000000000000000000000b17217f7d >> 127; 445 | if (x & 0x20000000 > 0) r = r * 0x8000000000000000000000058b90bfbe >> 127; 446 | if (x & 0x10000000 > 0) r = r * 0x800000000000000000000002c5c85fdf >> 127; 447 | if (x & 0x8000000 > 0) r = r * 0x80000000000000000000000162e42fef >> 127; 448 | if (x & 0x4000000 > 0) r = r * 0x800000000000000000000000b17217f7 >> 127; 449 | if (x & 0x2000000 > 0) r = r * 0x80000000000000000000000058b90bfb >> 127; 450 | if (x & 0x1000000 > 0) r = r * 0x8000000000000000000000002c5c85fd >> 127; 451 | if (x & 0x800000 > 0) r = r * 0x800000000000000000000000162e42fe >> 127; 452 | if (x & 0x400000 > 0) r = r * 0x8000000000000000000000000b17217f >> 127; 453 | if (x & 0x200000 > 0) r = r * 0x800000000000000000000000058b90bf >> 127; 454 | if (x & 0x100000 > 0) r = r * 0x80000000000000000000000002c5c85f >> 127; 455 | if (x & 0x80000 > 0) r = r * 0x8000000000000000000000000162e42f >> 127; 456 | if (x & 0x40000 > 0) r = r * 0x80000000000000000000000000b17217 >> 127; 457 | if (x & 0x20000 > 0) r = r * 0x8000000000000000000000000058b90b >> 127; 458 | if (x & 0x10000 > 0) r = r * 0x800000000000000000000000002c5c85 >> 127; 459 | if (x & 0x8000 > 0) r = r * 0x80000000000000000000000000162e42 >> 127; 460 | if (x & 0x4000 > 0) r = r * 0x800000000000000000000000000b1721 >> 127; 461 | if (x & 0x2000 > 0) r = r * 0x80000000000000000000000000058b90 >> 127; 462 | if (x & 0x1000 > 0) r = r * 0x8000000000000000000000000002c5c8 >> 127; 463 | if (x & 0x800 > 0) r = r * 0x800000000000000000000000000162e4 >> 127; 464 | if (x & 0x400 > 0) r = r * 0x8000000000000000000000000000b172 >> 127; 465 | if (x & 0x200 > 0) r = r * 0x800000000000000000000000000058b9 >> 127; 466 | if (x & 0x100 > 0) r = r * 0x80000000000000000000000000002c5c >> 127; 467 | if (x & 0x80 > 0) r = r * 0x8000000000000000000000000000162e >> 127; 468 | if (x & 0x40 > 0) r = r * 0x80000000000000000000000000000b17 >> 127; 469 | if (x & 0x20 > 0) r = r * 0x8000000000000000000000000000058b >> 127; 470 | if (x & 0x10 > 0) r = r * 0x800000000000000000000000000002c5 >> 127; 471 | if (x & 0x8 > 0) r = r * 0x80000000000000000000000000000162 >> 127; 472 | if (x & 0x4 > 0) r = r * 0x800000000000000000000000000000b1 >> 127; 473 | if (x & 0x2 > 0) r = r * 0x80000000000000000000000000000058 >> 127; 474 | if (x & 0x1 > 0) r = r * 0x8000000000000000000000000000002c >> 127; 475 | */ 476 | 477 | r >>= 127 - (x >> 121); 478 | 479 | return uint128 (r); 480 | } 481 | } -------------------------------------------------------------------------------- /contracts/helpers/DecimalMath.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | import "@openzeppelin/contracts/math/SafeMath.sol"; 4 | 5 | 6 | /// @dev Implements simple fixed point math mul and div operations for 27 decimals. 7 | contract DecimalMath { 8 | using SafeMath for uint256; 9 | 10 | uint256 constant public UNIT = 1e27; 11 | 12 | /// @dev Multiplies x and y, assuming they are both fixed point with 27 digits. 13 | function muld(uint256 x, uint256 y) internal pure returns (uint256) { 14 | return x.mul(y).div(UNIT); 15 | } 16 | 17 | /// @dev Divides x between y, assuming they are both fixed point with 27 digits. 18 | function divd(uint256 x, uint256 y) internal pure returns (uint256) { 19 | return x.mul(UNIT).div(y); 20 | } 21 | 22 | /// @dev Multiplies x and y, rounding up to the closest representable number. 23 | /// Assumes x and y are both fixed point with `decimals` digits. 24 | function muldrup(uint256 x, uint256 y) internal pure returns (uint256) 25 | { 26 | uint256 z = x.mul(y); 27 | return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1); 28 | } 29 | 30 | /// @dev Divides x between y, rounding up to the closest representable number. 31 | /// Assumes x and y are both fixed point with `decimals` digits. 32 | function divdrup(uint256 x, uint256 y) internal pure returns (uint256) 33 | { 34 | uint256 z = x.mul(UNIT); 35 | return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /contracts/helpers/Delegable.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | import "../interfaces/IDelegable.sol"; 5 | 6 | 7 | /// @dev Delegable enables users to delegate their account management to other users. 8 | /// Delegable implements addDelegateBySignature, to add delegates using a signature instead of a separate transaction. 9 | contract Delegable is IDelegable { 10 | event Delegate(address indexed user, address indexed delegate, bool enabled); 11 | 12 | // keccak256("Signature(address user,address delegate,uint256 nonce,uint256 deadline)"); 13 | bytes32 public immutable SIGNATURE_TYPEHASH = 0x0d077601844dd17f704bafff948229d27f33b57445915754dfe3d095fda2beb7; 14 | bytes32 public immutable DELEGABLE_DOMAIN; 15 | mapping(address => uint) public signatureCount; 16 | 17 | mapping(address => mapping(address => bool)) public override delegated; 18 | 19 | constructor () public { 20 | uint256 chainId; 21 | assembly { 22 | chainId := chainid() 23 | } 24 | 25 | DELEGABLE_DOMAIN = keccak256( 26 | abi.encode( 27 | keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), 28 | keccak256(bytes('Yield')), 29 | keccak256(bytes('1')), 30 | chainId, 31 | address(this) 32 | ) 33 | ); 34 | } 35 | 36 | /// @dev Require that msg.sender is the account holder or a delegate 37 | modifier onlyHolderOrDelegate(address holder, string memory errorMessage) { 38 | require( 39 | msg.sender == holder || delegated[holder][msg.sender], 40 | errorMessage 41 | ); 42 | _; 43 | } 44 | 45 | /// @dev Enable a delegate to act on the behalf of caller 46 | function addDelegate(address delegate) public override { 47 | _addDelegate(msg.sender, delegate); 48 | } 49 | 50 | /// @dev Stop a delegate from acting on the behalf of caller 51 | function revokeDelegate(address delegate) public { 52 | _revokeDelegate(msg.sender, delegate); 53 | } 54 | 55 | /// @dev Add a delegate through an encoded signature 56 | function addDelegateBySignature(address user, address delegate, uint deadline, uint8 v, bytes32 r, bytes32 s) public override { 57 | require(deadline >= block.timestamp, 'Delegable: Signature expired'); 58 | 59 | bytes32 hashStruct = keccak256( 60 | abi.encode( 61 | SIGNATURE_TYPEHASH, 62 | user, 63 | delegate, 64 | signatureCount[user]++, 65 | deadline 66 | ) 67 | ); 68 | 69 | bytes32 digest = keccak256( 70 | abi.encodePacked( 71 | '\x19\x01', 72 | DELEGABLE_DOMAIN, 73 | hashStruct 74 | ) 75 | ); 76 | address signer = ecrecover(digest, v, r, s); 77 | require( 78 | signer != address(0) && signer == user, 79 | 'Delegable: Invalid signature' 80 | ); 81 | 82 | _addDelegate(user, delegate); 83 | } 84 | 85 | /// @dev Enable a delegate to act on the behalf of an user 86 | function _addDelegate(address user, address delegate) internal { 87 | require(!delegated[user][delegate], "Delegable: Already delegated"); 88 | delegated[user][delegate] = true; 89 | emit Delegate(user, delegate, true); 90 | } 91 | 92 | /// @dev Stop a delegate from acting on the behalf of an user 93 | function _revokeDelegate(address user, address delegate) internal { 94 | require(delegated[user][delegate], "Delegable: Already undelegated"); 95 | delegated[user][delegate] = false; 96 | emit Delegate(user, delegate, false); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /contracts/helpers/ERC20Permit.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | // Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol 3 | pragma solidity ^0.6.0; 4 | 5 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 6 | import "../interfaces/IERC2612.sol"; 7 | 8 | /** 9 | * @dev Extension of {ERC20} that allows token holders to use their tokens 10 | * without sending any transactions by setting {IERC20-allowance} with a 11 | * signature using the {permit} method, and then spend them via 12 | * {IERC20-transferFrom}. 13 | * 14 | * The {permit} signature mechanism conforms to the {IERC2612} interface. 15 | */ 16 | abstract contract ERC20Permit is ERC20, IERC2612 { 17 | mapping (address => uint256) public override nonces; 18 | 19 | bytes32 public immutable PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); 20 | bytes32 public immutable DOMAIN_SEPARATOR; 21 | 22 | constructor(string memory name_, string memory symbol_) internal ERC20(name_, symbol_) { 23 | uint256 chainId; 24 | assembly { 25 | chainId := chainid() 26 | } 27 | 28 | DOMAIN_SEPARATOR = keccak256( 29 | abi.encode( 30 | keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), 31 | keccak256(bytes(name_)), 32 | keccak256(bytes("1")), 33 | chainId, 34 | address(this) 35 | ) 36 | ); 37 | } 38 | 39 | /** 40 | * @dev See {IERC2612-permit}. 41 | * 42 | * In cases where the free option is not a concern, deadline can simply be 43 | * set to uint(-1), so it should be seen as an optional parameter 44 | */ 45 | function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { 46 | require(deadline >= block.timestamp, "ERC20Permit: expired deadline"); 47 | 48 | bytes32 hashStruct = keccak256( 49 | abi.encode( 50 | PERMIT_TYPEHASH, 51 | owner, 52 | spender, 53 | amount, 54 | nonces[owner]++, 55 | deadline 56 | ) 57 | ); 58 | 59 | bytes32 hash = keccak256( 60 | abi.encodePacked( 61 | '\x19\x01', 62 | DOMAIN_SEPARATOR, 63 | hashStruct 64 | ) 65 | ); 66 | 67 | address signer = ecrecover(hash, v, r, s); 68 | require( 69 | signer != address(0) && signer == owner, 70 | "ERC20Permit: invalid signature" 71 | ); 72 | 73 | _approve(owner, spender, amount); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /contracts/helpers/Orchestrated.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | import "@openzeppelin/contracts/access/Ownable.sol"; 4 | 5 | 6 | /** 7 | * @dev Orchestrated allows to define static access control between multiple contracts. 8 | * This contract would be used as a parent contract of any contract that needs to restrict access to some methods, 9 | * which would be marked with the `onlyOrchestrated` modifier. 10 | * During deployment, the contract deployer (`owner`) can register any contracts that have privileged access by calling `orchestrate`. 11 | * Once deployment is completed, `owner` should call `transferOwnership(address(0))` to avoid any more contracts ever gaining privileged access. 12 | */ 13 | 14 | contract Orchestrated is Ownable { 15 | event GrantedAccess(address access, bytes4 signature); 16 | 17 | mapping(address => mapping (bytes4 => bool)) public orchestration; 18 | 19 | constructor () public Ownable() {} 20 | 21 | /// @dev Restrict usage to authorized users 22 | /// @param err The error to display if the validation fails 23 | modifier onlyOrchestrated(string memory err) { 24 | require(orchestration[msg.sender][msg.sig], err); 25 | _; 26 | } 27 | 28 | /// @dev Add orchestration 29 | /// @param user Address of user or contract having access to this contract. 30 | /// @param signature bytes4 signature of the function we are giving orchestrated access to. 31 | /// It seems to me a bad idea to give access to humans, and would use this only for predictable smart contracts. 32 | function orchestrate(address user, bytes4 signature) public onlyOwner { 33 | orchestration[user][signature] = true; 34 | emit GrantedAccess(user, signature); 35 | } 36 | 37 | /// @dev Adds orchestration for the provided function signatures 38 | function batchOrchestrate(address user, bytes4[] memory signatures) public onlyOwner { 39 | for (uint256 i = 0; i < signatures.length; i++) { 40 | orchestrate(user, signatures[i]); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /contracts/helpers/SafeCast.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | 5 | library SafeCast { 6 | /// @dev Safe casting from uint256 to uint128 7 | function toUint128(uint256 x) internal pure returns(uint128) { 8 | require( 9 | x <= type(uint128).max, 10 | "SafeCast: Cast overflow" 11 | ); 12 | return uint128(x); 13 | } 14 | 15 | /// @dev Safe casting from uint256 to int256 16 | function toInt256(uint256 x) internal pure returns(int256) { 17 | require( 18 | x <= uint256(type(int256).max), 19 | "SafeCast: Cast overflow" 20 | ); 21 | return int256(x); 22 | } 23 | } -------------------------------------------------------------------------------- /contracts/interfaces/IDai.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 4 | 5 | interface IDai is IERC20 { // Doesn't conform to IERC2612 6 | function nonces(address user) external view returns (uint256); 7 | function permit(address holder, address spender, uint256 nonce, uint256 expiry, 8 | bool allowed, uint8 v, bytes32 r, bytes32 s) external; 9 | } 10 | -------------------------------------------------------------------------------- /contracts/interfaces/IDelegable.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | 5 | interface IDelegable { 6 | function addDelegate(address) external; 7 | function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external; 8 | function delegated(address, address) external view returns (bool); 9 | } 10 | -------------------------------------------------------------------------------- /contracts/interfaces/IERC2612.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ 3 | pragma solidity ^0.6.0; 4 | 5 | /** 6 | * @dev Interface of the ERC2612 standard as defined in the EIP. 7 | * 8 | * Adds the {permit} method, which can be used to change one's 9 | * {IERC20-allowance} without having to send a transaction, by signing a 10 | * message. This allows users to spend tokens without having to hold Ether. 11 | * 12 | * See https://eips.ethereum.org/EIPS/eip-2612. 13 | */ 14 | interface IERC2612 { 15 | /** 16 | * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, 17 | * given `owner`'s signed approval. 18 | * 19 | * IMPORTANT: The same issues {IERC20-approve} has related to transaction 20 | * ordering also apply here. 21 | * 22 | * Emits an {Approval} event. 23 | * 24 | * Requirements: 25 | * 26 | * - `owner` cannot be the zero address. 27 | * - `spender` cannot be the zero address. 28 | * - `deadline` must be a timestamp in the future. 29 | * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` 30 | * over the EIP712-formatted function arguments. 31 | * - the signature must use ``owner``'s current nonce (see {nonces}). 32 | * 33 | * For more information on the signature format, see the 34 | * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP 35 | * section]. 36 | */ 37 | function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; 38 | 39 | /** 40 | * @dev Returns the current ERC2612 nonce for `owner`. This value must be 41 | * included whenever a signature is generated for {permit}. 42 | * 43 | * Every successful call to {permit} increases ``owner``'s nonce by one. This 44 | * prevents a signature from being used multiple times. 45 | */ 46 | function nonces(address owner) external view returns (uint256); 47 | } 48 | -------------------------------------------------------------------------------- /contracts/interfaces/IFYDai.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 5 | import "./IERC2612.sol"; 6 | 7 | interface IFYDai is IERC20, IERC2612 { 8 | function isMature() external view returns(bool); 9 | function maturity() external view returns(uint); 10 | function chi0() external view returns(uint); 11 | function rate0() external view returns(uint); 12 | function chiGrowth() external view returns(uint); 13 | function rateGrowth() external view returns(uint); 14 | function mature() external; 15 | function unlocked() external view returns (uint); 16 | function mint(address, uint) external; 17 | function burn(address, uint) external; 18 | function flashMint(uint, bytes calldata) external; 19 | function redeem(address, address, uint256) external returns (uint256); 20 | // function transfer(address, uint) external returns (bool); 21 | // function transferFrom(address, address, uint) external returns (bool); 22 | // function approve(address, uint) external returns (bool); 23 | } 24 | -------------------------------------------------------------------------------- /contracts/interfaces/IFlashMinter.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | 5 | interface IFlashMinter { 6 | function executeOnFlashMint(uint256 fyDaiAmount, bytes calldata data) external; 7 | } 8 | -------------------------------------------------------------------------------- /contracts/interfaces/IPool.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity ^0.6.10; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 5 | import "./IDelegable.sol"; 6 | import "./IERC2612.sol"; 7 | import "./IFYDai.sol"; 8 | 9 | interface IPool is IDelegable, IERC20, IERC2612 { 10 | function dai() external view returns(IERC20); 11 | function fyDai() external view returns(IFYDai); 12 | function getDaiReserves() external view returns(uint128); 13 | function getFYDaiReserves() external view returns(uint128); 14 | function sellDai(address from, address to, uint128 daiIn) external returns(uint128); 15 | function buyDai(address from, address to, uint128 daiOut) external returns(uint128); 16 | function sellFYDai(address from, address to, uint128 fyDaiIn) external returns(uint128); 17 | function buyFYDai(address from, address to, uint128 fyDaiOut) external returns(uint128); 18 | function sellDaiPreview(uint128 daiIn) external view returns(uint128); 19 | function buyDaiPreview(uint128 daiOut) external view returns(uint128); 20 | function sellFYDaiPreview(uint128 fyDaiIn) external view returns(uint128); 21 | function buyFYDaiPreview(uint128 fyDaiOut) external view returns(uint128); 22 | function mint(address from, address to, uint256 daiOffered) external returns (uint256); 23 | function burn(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); 24 | } -------------------------------------------------------------------------------- /deploy/daiBorrower.js: -------------------------------------------------------------------------------- 1 | const dai = { 2 | '42' : '0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa' 3 | } 4 | 5 | const func = async function ({ deployments, getNamedAccounts, getChainId }) { 6 | const { deploy, read, execute } = deployments; 7 | const { deployer } = await getNamedAccounts(); 8 | const chainId = await getChainId() 9 | 10 | if (chainId === '31337') { // buidlerevm's chainId 11 | console.log('Local deployments not implemented') 12 | return 13 | } else { 14 | const borrower = await deploy('YieldDaiBorrowerMock', { 15 | from: deployer, 16 | deterministicDeployment: true, 17 | args: [dai[chainId]], 18 | }) 19 | console.log(`Deployed YieldDaiBorrower to ${borrower.address}`); 20 | } 21 | }; 22 | 23 | module.exports = func; 24 | module.exports.tags = ["YieldDaiBorrower"]; 25 | -------------------------------------------------------------------------------- /deploy/daiLender.js: -------------------------------------------------------------------------------- 1 | const pools = { 2 | '' : { 3 | '1' : '', 4 | '42' : '' 5 | }, 6 | '' : { 7 | '1' : '', 8 | '42' : '' 9 | }, 10 | '' : { 11 | '1' : '', 12 | '42' : '' 13 | }, 14 | '' : { 15 | '1' : '', 16 | '42' : '' 17 | }, 18 | '' : { 19 | '1' : '', 20 | '42' : '' 21 | }, 22 | } 23 | 24 | const func = async function ({ deployments, getNamedAccounts, getChainId }) { 25 | const { deploy, read, execute } = deployments; 26 | const { deployer } = await getNamedAccounts(); 27 | const chainId = await getChainId() 28 | 29 | /* if (chainId === '31337') { // buidlerevm's chainId 30 | console.log('Local deployments not implemented') 31 | return 32 | } else { 33 | lender = await deploy('YieldDaiLender-' + name, { 34 | from: deployer, 35 | deterministicDeployment: true, 36 | args: [pools[name][chainId]], 37 | }) 38 | console.log(`Deployed YieldDaiLender to ${lender.address}`); 39 | } */ 40 | }; 41 | 42 | module.exports = func; 43 | module.exports.tags = ["YieldDaiLender"]; 44 | -------------------------------------------------------------------------------- /deploy/fyDaiLender.js: -------------------------------------------------------------------------------- 1 | const fyDai = { 2 | '' : { 3 | '1' : '', 4 | '42' : '' 5 | }, 6 | '' : { 7 | '1' : '', 8 | '42' : '' 9 | }, 10 | '' : { 11 | '1' : '', 12 | '42' : '' 13 | }, 14 | '' : { 15 | '1' : '', 16 | '42' : '' 17 | }, 18 | '' : { 19 | '1' : '', 20 | '42' : '' 21 | }, 22 | } 23 | 24 | const func = async function ({ deployments, getNamedAccounts, getChainId }) { 25 | const { deploy, read, execute } = deployments; 26 | const { deployer } = await getNamedAccounts(); 27 | const chainId = await getChainId() 28 | 29 | /* if (chainId === '31337') { // buidlerevm's chainId 30 | console.log('Local deployments not implemented') 31 | return 32 | } else { 33 | lender = await deploy('YieldFYDaiLender-' + name, { 34 | from: deployer, 35 | deterministicDeployment: true, 36 | args: [fyDai[name][chainId]], 37 | }) 38 | console.log(`Deployed YieldFYDaiLender to ${lender.address}`); 39 | } */ 40 | }; 41 | 42 | module.exports = func; 43 | module.exports.tags = ["YieldFYDaiLender"]; 44 | -------------------------------------------------------------------------------- /migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | const YieldFlashDemo = artifacts.require("YieldFlashDemo"); 2 | 3 | module.exports = function (deployer) { 4 | deployer.deploy(YieldFlashDemo, "0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa"); 5 | }; 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fydai-flash", 3 | "version": "0.1.1", 4 | "description": "Dai Flash Loans from YieldSpace pools", 5 | "main": "index.js", 6 | "author": "Alberto Cuesta Cañada", 7 | "license": "GPL-3.0-or-later", 8 | "engines": { 9 | "node": ">= 14.0.0", 10 | "npm": ">= 6.4.0", 11 | "yarn": ">= 1.10.0" 12 | }, 13 | "files": [ 14 | "/contracts/YieldDaiBorrower.sol" 15 | ], 16 | "keywords": [ 17 | "solidity", 18 | "ethereum", 19 | "smart", 20 | "contracts" 21 | ], 22 | "repository": { 23 | "type": "git", 24 | "url": "git+https://github.com/yieldprotocol/fyDai-flash.git" 25 | }, 26 | "bugs": { 27 | "url": "https://github.com/yieldprotocol/fyDai-flash/issues" 28 | }, 29 | "homepage": "https://github.com/yieldprotocol/fyDai-flash", 30 | "scripts": { 31 | "build": "buidler compile", 32 | "test": "buidler test test/*.ts", 33 | "ganache": "./scripts/ganache.sh", 34 | "deploy:ganache": "yarn ganache && truffle migrate", 35 | "mainnet-ganache": "./scripts/mainnet-ganache.sh", 36 | "coverage": "buidler coverage --network coverage --temp build --testfiles 'test/*.ts'", 37 | "lint": "prettier ./test/**/*.ts --check", 38 | "lint:ts": "prettier ./test/**/*.ts --write", 39 | "lint:sol": "solhint -f table contracts/**/*.sol" 40 | }, 41 | "devDependencies": { 42 | "@nomiclabs/buidler": "^1.3.8", 43 | "@nomiclabs/buidler-truffle5": "^1.3.4", 44 | "@nomiclabs/buidler-web3": "^1.3.4", 45 | "@openzeppelin/contracts": "^3.3.0", 46 | "@openzeppelin/test-helpers": "^0.5.6", 47 | "@truffle/hdwallet-provider": "^1.0.40", 48 | "@types/mocha": "^8.0.0", 49 | "buidler-deploy": "^0.6.0-beta.37", 50 | "buidler-gas-reporter": "0.1.4-beta.4", 51 | "chai": "4.2.0", 52 | "ethereumjs-util": "^7.0.3", 53 | "ethers": "^5.0.7", 54 | "ganache-time-traveler": "^1.0.14", 55 | "mocha": "^7.1.0", 56 | "prettier": "^2.0.5", 57 | "solhint": "^3.2.0", 58 | "solidity-coverage": "^0.7.9", 59 | "truffle": "^5.1.39", 60 | "truffle-flattener": "^1.5.0", 61 | "truffle-typings": "^1.0.8", 62 | "ts-node": "^8.10.2", 63 | "typescript": "^3.9.7" 64 | }, 65 | "dependencies": { 66 | "dotenv": "^8.2.0", 67 | "truffle-hdwallet-provider": "^1.0.17" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /scripts/ganache.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # move to subfolder 4 | # cd scripts 5 | 6 | # create db directory 7 | # [ ! -d "./db_ganache" ] && mkdir db_ganache 8 | 9 | # start ganache 10 | npx ganache-cli \ 11 | --mnemonic "all your mnemonic are belong to us seed me up scotty over" \ 12 | --defaultBalanceEther 1000000 \ 13 | --gasLimit 0xfffffffffff \ 14 | --gasPrice 0 \ 15 | --port 8545 \ 16 | --networkId 5777 \ 17 | --host 0.0.0.0 & 18 | -------------------------------------------------------------------------------- /scripts/mainnet-ganache.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # move to subfolder 4 | # cd scripts 5 | 6 | # create db directory 7 | # [ ! -d "./db_ganache" ] && mkdir db_ganache 8 | 9 | # start ganache 10 | npx ganache-cli \ 11 | --mnemonic "how are you gentlemen all your mnemonic are belong to us" \ 12 | --defaultBalanceEther 1000000 \ 13 | --gasLimit 0xfffffffffff \ 14 | --gasPrice 0 \ 15 | --port 8545 \ 16 | --networkId 1 \ 17 | --host 0.0.0.0 \ 18 | --fork https://mainnet.infura.io/v3/`cat .infuraKey` & 19 | -------------------------------------------------------------------------------- /scripts/setup_mainnet_ganache.js: -------------------------------------------------------------------------------- 1 | const Migrations = artifacts.require('Migrations') 2 | const Chai = artifacts.require('Chai') 3 | const Controller = artifacts.require('Controller') 4 | const Dai = artifacts.require('Dai') 5 | const DaiJoin = artifacts.require('DaiJoin') 6 | const FYDai = artifacts.require('FYDai') 7 | const Treasury = artifacts.require('Treasury') 8 | const Vat = artifacts.require('Vat') 9 | const WETH9 = artifacts.require('WETH9') 10 | const GemJoin = artifacts.require('GemJoin') 11 | const Pool = artifacts.require('Pool') 12 | const Pot = artifacts.require('Pot') 13 | const YieldProxy = artifacts.require('YieldProxy') 14 | 15 | const ethers = require('ethers') 16 | 17 | // Logs all addresses of contracts 18 | module.exports = async (callback) => { 19 | try { 20 | migrations = await Migrations.deployed() 21 | 22 | chai = await Chai.at(await migrations.contracts(ethers.utils.formatBytes32String('Chai'))) 23 | controller = await Controller.at(await migrations.contracts(ethers.utils.formatBytes32String('Controller'))) 24 | dai = await Dai.at(await migrations.contracts(ethers.utils.formatBytes32String('Dai'))) 25 | daiJoin = await DaiJoin.at(await migrations.contracts(ethers.utils.formatBytes32String('DaiJoin'))) 26 | fyDai0 = await FYDai.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDai20Sep'))) 27 | fyDai1 = await FYDai.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDai20Oct'))) 28 | fyDai2 = await FYDai.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDai21Jan'))) 29 | fyDai3 = await FYDai.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDai21Apr'))) 30 | fyDai4 = await FYDai.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDai21Jul'))) 31 | treasury = await Treasury.at(await migrations.contracts(ethers.utils.formatBytes32String('Treasury'))) 32 | vat = await Vat.at(await migrations.contracts(ethers.utils.formatBytes32String('Vat'))) 33 | weth = await WETH9.at(await migrations.contracts(ethers.utils.formatBytes32String('Weth'))) 34 | wethJoin = await GemJoin.at(await migrations.contracts(ethers.utils.formatBytes32String('WethJoin'))) 35 | pool0 = await Pool.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDaiLP20Sep'))) 36 | pool1 = await Pool.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDaiLP20Oct'))) 37 | pool2 = await Pool.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDaiLP21Jan'))) 38 | pool3 = await Pool.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDaiLP21Apr'))) 39 | pool4 = await Pool.at(await migrations.contracts(ethers.utils.formatBytes32String('fyDaiLP21Jul'))) 40 | pot = await Pot.at(await migrations.contracts(ethers.utils.formatBytes32String('Pot'))) 41 | yieldProxy = await YieldProxy.at(await migrations.contracts(ethers.utils.formatBytes32String('YieldProxy'))) 42 | console.log('Contracts loaded') 43 | 44 | me = (await web3.eth.getAccounts())[0] 45 | 46 | WAD = '000000000000000000' 47 | THOUSAND = '000' 48 | MILLION = '000000' 49 | 50 | MAX = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' 51 | Line = web3.utils.fromAscii('Line') 52 | line = web3.utils.fromAscii('line') 53 | spot = web3.utils.fromAscii('spot') 54 | ETH_A = web3.utils.fromAscii('ETH-A') 55 | 56 | maturity0 = await fyDai0.maturity() 57 | maturity1 = await fyDai1.maturity() 58 | maturity2 = await fyDai2.maturity() 59 | maturity3 = await fyDai3.maturity() 60 | maturity4 = await fyDai4.maturity() 61 | 62 | await vat.hope(daiJoin.address) 63 | await weth.approve(treasury.address, MAX) 64 | await weth.approve(wethJoin.address, MAX) 65 | await dai.approve(pool0.address, MAX) 66 | await dai.approve(pool1.address, MAX) 67 | await dai.approve(pool2.address, MAX) 68 | await dai.approve(pool3.address, MAX) 69 | await dai.approve(pool4.address, MAX) 70 | await dai.approve(yieldProxy.address, MAX) 71 | await fyDai0.approve(pool0.address, MAX) 72 | await fyDai1.approve(pool1.address, MAX) 73 | await fyDai2.approve(pool2.address, MAX) 74 | await fyDai3.approve(pool3.address, MAX) 75 | await fyDai4.approve(pool4.address, MAX) 76 | console.log('Approvals granted') 77 | 78 | if (!(await controller.delegated(me, yieldProxy.address))) { 79 | await controller.addDelegate(yieldProxy.address) 80 | await pool0.addDelegate(yieldProxy.address) 81 | await pool1.addDelegate(yieldProxy.address) 82 | await pool2.addDelegate(yieldProxy.address) 83 | await pool3.addDelegate(yieldProxy.address) 84 | await pool4.addDelegate(yieldProxy.address) 85 | console.log('Delegates granted') 86 | } 87 | 88 | await weth.deposit({ value: '70' + THOUSAND + WAD }) 89 | console.log('Weth obtained') 90 | 91 | await wethJoin.join(me, '10' + THOUSAND + WAD) 92 | await vat.frob(ETH_A, me, me, me, '10' + THOUSAND + WAD, '2' + MILLION + WAD) 93 | await daiJoin.exit(me, '2' + MILLION + WAD) 94 | console.log('Dai obtained') 95 | 96 | await controller.post(ETH_A, me, me, '50' + THOUSAND + WAD) 97 | 98 | await controller.borrow(ETH_A, maturity0, me, me, '100' + THOUSAND + WAD) 99 | await controller.borrow(ETH_A, maturity1, me, me, '100' + THOUSAND + WAD) 100 | await controller.borrow(ETH_A, maturity2, me, me, '100' + THOUSAND + WAD) 101 | await controller.borrow(ETH_A, maturity3, me, me, '100' + THOUSAND + WAD) 102 | await controller.borrow(ETH_A, maturity4, me, me, '100' + THOUSAND + WAD) 103 | console.log('fyDai obtained') 104 | 105 | await pool0.mint(me, me, '100' + THOUSAND + WAD) 106 | await pool1.mint(me, me, '100' + THOUSAND + WAD) 107 | await pool2.mint(me, me, '100' + THOUSAND + WAD) 108 | await pool3.mint(me, me, '100' + THOUSAND + WAD) 109 | await pool4.mint(me, me, '100' + THOUSAND + WAD) 110 | console.log('Pools initialized') 111 | 112 | await yieldProxy.addLiquidity(pool0.address, '100' + THOUSAND + WAD, MAX) 113 | await yieldProxy.addLiquidity(pool1.address, '100' + THOUSAND + WAD, MAX) 114 | await yieldProxy.addLiquidity(pool2.address, '100' + THOUSAND + WAD, MAX) 115 | await yieldProxy.addLiquidity(pool3.address, '100' + THOUSAND + WAD, MAX) 116 | await yieldProxy.addLiquidity(pool4.address, '100' + THOUSAND + WAD, MAX) 117 | console.log('Liquidity added') 118 | 119 | await yieldProxy.sellFYDai(pool0.address, me, '25' + THOUSAND + WAD, 0) 120 | await yieldProxy.sellFYDai(pool1.address, me, '25' + THOUSAND + WAD, 0) 121 | await yieldProxy.sellFYDai(pool2.address, me, '25' + THOUSAND + WAD, 0) 122 | await yieldProxy.sellFYDai(pool3.address, me, '25' + THOUSAND + WAD, 0) 123 | await yieldProxy.sellFYDai(pool4.address, me, '25' + THOUSAND + WAD, 0) 124 | console.log('fyDai sold') 125 | 126 | callback() 127 | } catch (e) { 128 | console.log(e) 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /test/flashYield.ts: -------------------------------------------------------------------------------- 1 | const Pool = artifacts.require('Pool') 2 | const FYDaiMock = artifacts.require('FYDaiMock') 3 | const DaiMock = artifacts.require('DaiMock') 4 | const FlashBorrower = artifacts.require('YieldDaiBorrowerMock') 5 | 6 | import { keccak256, toUtf8Bytes } from 'ethers/lib/utils' 7 | // @ts-ignore 8 | import helper from 'ganache-time-traveler' 9 | import { rate1, daiTokens1, toWad, almostEqual } from './shared/utils' 10 | import { Contract } from './shared/fixtures' 11 | // @ts-ignore 12 | import { BN, expectRevert } from '@openzeppelin/test-helpers' 13 | import { assert } from 'chai' 14 | 15 | contract('YieldDaiBorrower', async (accounts) => { 16 | let [owner, user1] = accounts 17 | 18 | const initialDai = daiTokens1 19 | 20 | let snapshot: any 21 | let snapshotId: string 22 | 23 | let dai: Contract 24 | let pool: Contract 25 | let fyDai: Contract 26 | let borrower: Contract 27 | 28 | let maturity0: number 29 | 30 | beforeEach(async () => { 31 | snapshot = await helper.takeSnapshot() 32 | snapshotId = snapshot['result'] 33 | 34 | // Setup fyDai 35 | const block = await web3.eth.getBlockNumber() 36 | maturity0 = (await web3.eth.getBlock(block)).timestamp + 15778476 // Six months 37 | 38 | dai = await DaiMock.new("Test", "TST") 39 | fyDai = await FYDaiMock.new("Test", "TST", maturity0) 40 | 41 | // Setup Pools 42 | pool = await Pool.new(dai.address, fyDai.address, 'Name', 'Symbol', { from: owner }) 43 | 44 | // Initialize pools 45 | const additionalFYDaiReserves = toWad(34.4) 46 | 47 | await dai.mint(user1, initialDai, { from: user1 }) 48 | await dai.approve(pool.address, initialDai, { from: user1 }) 49 | await pool.mint(user1, user1, initialDai, { from: user1 }) 50 | await fyDai.mint(owner, additionalFYDaiReserves, { from: owner }) 51 | await fyDai.approve(pool.address, additionalFYDaiReserves, { from: owner }) 52 | await pool.sellFYDai(owner, owner, additionalFYDaiReserves, { from: owner }) 53 | 54 | // Set up the FlashBorrower 55 | borrower = await FlashBorrower.new(dai.address, { from: owner }) 56 | await borrower.setPool(pool.address, { from: owner }) 57 | }) 58 | 59 | it('should do a simple flash loan from an EOA', async () => { 60 | const ONE = new BN(toWad(1).toString()) 61 | const loan = ONE 62 | 63 | const expectedFee = await borrower.flashFee(loan) 64 | 65 | await dai.mint(user1, ONE, { from: user1 }) 66 | await dai.transfer(borrower.address, ONE, { from: user1 }) 67 | 68 | const balanceBefore = await dai.balanceOf(borrower.address) 69 | await borrower.flashBorrow(loan, { from: user1 }) 70 | 71 | assert.equal(await borrower.sender(), user1) 72 | 73 | assert.equal((await borrower.loanAmount()).toString(), loan.toString()) 74 | 75 | assert.equal((await borrower.balance()).toString(), balanceBefore.add(loan).toString()) 76 | 77 | const fee = await borrower.fee() 78 | assert.equal((await dai.balanceOf(borrower.address)).toString(), balanceBefore.sub(fee).toString()) 79 | almostEqual(fee.toString(), expectedFee.toString(), fee.div(new BN('100000')).toString()) // Accurate to 0.00001 % 80 | }) 81 | }) 82 | -------------------------------------------------------------------------------- /test/shared/fixtures.ts: -------------------------------------------------------------------------------- 1 | export type Contract = any 2 | -------------------------------------------------------------------------------- /test/shared/utils.spec.ts: -------------------------------------------------------------------------------- 1 | // Ignoring it because it conflicts with the globally declared `chai` smart contract 2 | // @ts-ignore 3 | import { assert } from 'chai' 4 | import { toRay, toRad } from './utils' 5 | 6 | describe('Utils', () => { 7 | const spot = '1500000000000000000000000000' 8 | const rate = '1250000000000000000000000000' 9 | const price = '1200000000000000000000000000' // spot / rate 10 | const limits = '1000000000000000000000000000000000000000000000' 11 | const frac = '1500000000000000000000000000000000000000000000' 12 | 13 | describe('toRay', async () => { 14 | it('runs toRay', async () => { 15 | assert(toRay(5).toString() == '5000000000000000000000000000', 'toRay not working') 16 | }) 17 | 18 | it('handles decimals', async () => { 19 | assert(toRay(1.5).toString() == spot, 'toRay failing with decimals') 20 | assert(toRay('1.5').toString() == spot, 'toRay failing with decimals') 21 | assert(toRay('1.25').toString() == rate, 'toRay failing with decimals') 22 | assert(toRay('1.2').toString() == price, 'toRay failing with decimals') 23 | }) 24 | }) 25 | 26 | describe('toRad', async () => { 27 | it('runs toRad', async () => { 28 | assert(toRad(1).toString() == limits, 'toRad not working') 29 | }) 30 | 31 | it('handles decimals', async () => { 32 | assert(toRad('1.5').toString() == frac, 'toRad failing with decimals') 33 | assert(toRad(1.5).toString() == frac, 'toRad failing with decimals') 34 | }) 35 | }) 36 | }) 37 | -------------------------------------------------------------------------------- /test/shared/utils.ts: -------------------------------------------------------------------------------- 1 | // @ts-ignore 2 | import { BN } from '@openzeppelin/test-helpers' 3 | import { BigNumber, BigNumberish } from 'ethers' 4 | import { expect } from 'chai' 5 | 6 | export const ZERO = new BN('0').toString() 7 | export const chainId = 31337 // buidlerevm chain id 8 | export const name = 'Yield' 9 | 10 | /// @dev Converts a bignumberish to a BigNumber (this is useful for compatibility between BN and BigNumber) 11 | export const bnify = (num: BigNumberish) => BigNumber.from(num.toString()) 12 | 13 | /// @dev 2^256 -1 14 | export const MAX = bnify('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff') 15 | 16 | /// @dev Converts a BigNumberish to WAD precision, for BigNumberish up to 10 decimal places 17 | export function toWad(value: BigNumberish): BigNumber { 18 | let exponent = BigNumber.from(10).pow(BigNumber.from(8)) 19 | return BigNumber.from((value as any) * 10 ** 10).mul(exponent) 20 | } 21 | 22 | /// @dev Converts a BigNumberish to RAY precision, for BigNumberish up to 10 decimal places 23 | export function toRay(value: BigNumberish): BigNumber { 24 | let exponent = BigNumber.from(10).pow(BigNumber.from(17)) 25 | return BigNumber.from((value as any) * 10 ** 10).mul(exponent) 26 | } 27 | 28 | /// @dev Converts a BigNumberish to RAD precision, for BigNumberish up to 10 decimal places 29 | export function toRad(value: BigNumberish): BigNumber { 30 | let exponent = BigNumber.from(10).pow(BigNumber.from(35)) 31 | return BigNumber.from((value as any) * 10 ** 10).mul(exponent) 32 | } 33 | 34 | /// @dev Adds two BigNumberishs 35 | /// I.e. addBN(ray(x), ray(y)) = ray(x - y) 36 | export function addBN(x: BigNumberish, y: BigNumberish): BigNumber { 37 | return BigNumber.from(x).add(BigNumber.from(y)) 38 | } 39 | 40 | /// @dev Substracts a BigNumberish from another 41 | /// I.e. subBN(ray(x), ray(y)) = ray(x - y) 42 | export function subBN(x: BigNumberish, y: BigNumberish): BigNumber { 43 | return BigNumber.from(x).sub(BigNumber.from(y)) 44 | } 45 | 46 | /// @dev Multiplies a BigNumberish in any precision by a BigNumberish in RAY precision, with the output in the first parameter's precision. 47 | /// I.e. mulRay(wad(x), ray(y)) = wad(x*y) 48 | export function mulRay(x: BigNumberish, ray: BigNumberish): BigNumber { 49 | return BigNumber.from(x).mul(BigNumber.from(ray)).div(UNIT) 50 | } 51 | 52 | /// @dev Divides x by y, rounding up 53 | export function divrup(x: BigNumber, y: BigNumber): BigNumber { 54 | const z = BigNumber.from(x).mul(10).div(BigNumber.from(y)) 55 | if (z.mod(10).gt(0)) return z.div(10).add(1) 56 | return z.div(10) 57 | } 58 | 59 | // Checks if 2 bignumberish are almost-equal with up to `precision` room for wiggle which by default is 1 60 | export function almostEqual(x: BigNumberish, y: BigNumberish, precision: BigNumberish = 1) { 61 | x = bnify(x) 62 | y = bnify(y) 63 | 64 | if (x.gt(y)) { 65 | expect(x.sub(y).lte(precision)).to.be.true 66 | } else { 67 | expect(y.sub(x).lte(precision)).to.be.true 68 | } 69 | } 70 | 71 | /// @dev Divides a BigNumberish in any precision by a BigNumberish in RAY precision, with the output in the first parameter's precision. 72 | /// I.e. divRay(wad(x), ray(y)) = wad(x/y) 73 | export function divRay(x: BigNumberish, ray: BigNumberish): BigNumber { 74 | return UNIT.mul(BigNumber.from(x)).div(BigNumber.from(ray)) 75 | } 76 | 77 | /// @dev Divides a BigNumberish in any precision by a BigNumberish in RAY precision, with the output in the first parameter's precision. 78 | /// Rounds up, careful if using negative numbers. 79 | /// I.e. divRay(wad(x), ray(y)) = wad(x/y) 80 | export function divrupRay(x: BigNumberish, ray: BigNumberish): BigNumber { 81 | const z = UNIT.mul(BigNumber.from(x)).div(BigNumber.from(ray)) 82 | if (z.mul(ray).div(UNIT) < x) return z.add('1') 83 | return z 84 | } 85 | 86 | const UNIT: BigNumber = BigNumber.from(10).pow(BigNumber.from(27)) 87 | 88 | export const precision = 10 // Loss in wei that is tolerated with each operation -------------------------------------------------------------------------------- /truffle-config.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | var HDWalletProvider = require("truffle-hdwallet-provider"); 3 | module.exports = { 4 | networks: { 5 | development: { 6 | host: "127.0.0.1", 7 | port: 7545, 8 | network_id: "7775" 9 | }, 10 | kovan: { 11 | provider: function() { 12 | return new HDWalletProvider(process.env.KOVAN_PRTK, process.env.KOVAN_PROVIDER) 13 | }, 14 | network_id: "42", 15 | gas: 4000000 //make sure this gas allocation isn't over 4M, which is the max 16 | } 17 | }, 18 | compilers: { 19 | solc: { 20 | version: "0.6.10" // ex: "0.4.20". (Default: Truffle's installed solc) 21 | } 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2015", 4 | "module": "commonjs", 5 | "strict": true, 6 | "esModuleInterop": true, 7 | "resolveJsonModule": true 8 | }, 9 | "files": [ 10 | "./buidler.config.ts", 11 | "./node_modules/@nomiclabs/buidler-ethers/src/type-extensions.d.ts", 12 | "./node_modules/@nomiclabs/buidler-waffle/src/type-extensions.d.ts", 13 | "./node_modules/truffle-typings/index.d.ts", 14 | "./@types/types.d.ts" 15 | ] 16 | } 17 | --------------------------------------------------------------------------------