├── .github
└── workflows
│ ├── pull-request.yml
│ ├── push-to-main.yml
│ └── slither.yaml
├── .gitignore
├── .gitmodules
├── .vscode
└── settings.json
├── LICENSE
├── Makefile
├── README.md
├── build.sh
├── contracts
├── interfaces
│ └── IxMPL.sol
├── test
│ ├── ERC20.t.sol
│ ├── Invariants.t.sol
│ ├── RDT.t.sol
│ ├── accounts
│ │ └── Owner.sol
│ ├── mocks
│ │ ├── MockERC20.xMPL.sol
│ │ ├── Mocks.sol
│ │ └── xMPLMutable.sol
│ └── xMPL.t.sol
└── xMPL.sol
├── dapp-build.sh
├── dapp-config.json
├── deploy.sh
├── flattened
└── xMPL.sol
├── foundry.toml
├── invariant-test.sh
├── package.yaml
├── release.sh
└── test.sh
/.github/workflows/pull-request.yml:
--------------------------------------------------------------------------------
1 | name: Basic PR Tests
2 |
3 | on: [pull_request]
4 |
5 | jobs:
6 | run-ci:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v2
10 |
11 | - name: Install Foundry
12 | uses: onbjerg/foundry-toolchain@v1
13 | with:
14 | version: nightly
15 |
16 | - name: Install submodules
17 | run: |
18 | git config --global url."https://github.com/".insteadOf "git@github.com:"
19 | git submodule update --init --recursive
20 | - name: Run forge tests
21 | run: ./test.sh -p deep
22 |
--------------------------------------------------------------------------------
/.github/workflows/push-to-main.yml:
--------------------------------------------------------------------------------
1 | name: 50k fuzz run test on push to main
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 |
8 | jobs:
9 | run-ci:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v2
13 |
14 | - name: Install Foundry
15 | uses: onbjerg/foundry-toolchain@v1
16 | with:
17 | version: nightly
18 |
19 | - name: Install submodules
20 | run: |
21 | git config --global url."https://github.com/".insteadOf "git@github.com:"
22 | git submodule update --init --recursive
23 | - name: Run forge tests
24 | run: ./test.sh -p super_deep
25 |
--------------------------------------------------------------------------------
/.github/workflows/slither.yaml:
--------------------------------------------------------------------------------
1 | name: Static Analysis
2 | on:
3 | push:
4 | branches: "*"
5 |
6 | jobs:
7 | build:
8 | runs-on: ubuntu-latest
9 |
10 | steps:
11 | - uses: actions/checkout@v2
12 |
13 | - name: Set up Python ${{ matrix.python-version }}
14 | uses: actions/setup-python@v2
15 | with:
16 | python-version: 3.8
17 |
18 | - name: Install dependencies
19 | run: |
20 | sudo snap install solc
21 | python -m pip install --upgrade pip
22 | pip install slither-analyzer==0.8.2 solc-select==0.2.1
23 | solc-select install 0.8.7
24 | solc-select use 0.8.7
25 |
26 | - name: Checkout mpl-migration submodule
27 | env:
28 | SSH_KEY_MPL_MIGRATION: ${{secrets.SSH_KEY_MPL_MIGRATION}}
29 | shell: bash
30 | run: |
31 | mkdir $HOME/.ssh
32 | echo "$SSH_KEY_MPL_MIGRATION" > $HOME/.ssh/id_rsa
33 | chmod 600 $HOME/.ssh/id_rsa
34 | git submodule update --init --recursive modules/mpl-migration
35 |
36 | - name: Checkout revenue-distribution-token submodule
37 | env:
38 | SSH_KEY_RDT: ${{secrets.SSH_KEY_RDT}}
39 | shell: bash
40 | run: |
41 | rm -rf $HOME/.ssh/id_rsa
42 | echo "$SSH_KEY_RDT" > $HOME/.ssh/id_rsa
43 | chmod 600 $HOME/.ssh/id_rsa
44 | git submodule update --init --recursive modules/revenue-distribution-token
45 |
46 | - name: Summary of static analysis
47 | run: |
48 | slither contracts --print human-summary
49 |
50 | - name: Contract summary of static analysis
51 | run: |
52 | slither contracts --print contract-summary
53 |
54 | - name: Function summary
55 | run: |
56 | slither contracts --print function-summary
57 |
58 | - name: Inheritance
59 | run: |
60 | slither contracts --print inheritance
61 |
62 | - name: Data dependency
63 | run: |
64 | slither contracts --print data-dependency
65 |
66 | - name: Static Analysis
67 | run: |
68 | slither contracts
69 | continue-on-error: true
70 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /out
2 | /cache
3 | /package
4 | artifacts/
5 | docs/
6 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "modules/revenue-distribution-token"]
2 | path = modules/revenue-distribution-token
3 | url = git@github.com:maple-labs/revenue-distribution-token.git
4 | [submodule "modules/mpl-migration"]
5 | path = modules/mpl-migration
6 | url = git@github.com:maple-labs/mpl-migration.git
7 | [submodule "modules/contract-test-utils"]
8 | path = modules/contract-test-utils
9 | url = git@github.com:maple-labs/contract-test-utils.git
10 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "solidity.compileUsingRemoteVersion": "v0.8.7+commit.e28d00a7"
3 | }
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | invariant :; ./invariant-test.sh -t invariant
2 | test :; ./test.sh -p local
3 | deep-test :; ./test.sh -p deep
4 | test-all :; ./test.sh && ./invariant-test.sh -t invariant
5 | release :; ./release.sh
6 | dapp-build :; ./dapp-build.sh
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # xMPL
2 |
3 |  [](https://www.gnu.org/licenses/agpl-3.0)
4 |
5 | This repo contains a set of contracts to facilitate on-chain distribution of protocol revenues denominated in MPL tokens. MPL distributions are made using RevenueDistributionToken (RDT) vesting schedule functionaltiy. This allows for multiple deposits to be made to the same contract on a recurring basis with custom vesting parameters.
6 |
7 | ## Capabilities
8 |
9 | xMPL inherits the core functionality from Maple's [Revenue Distribution Token](https://github.com/maple-labs/revenue-distribution-token), which allows users to lock assets to earn rewards distributions based on a vesting schedule, with the increased functionality to perform a one time asset migration for the underlying token. This migration will interact with the contracts defined in [mpl-migration](https://github.com/maple-labs/mpl-migration).
10 |
11 | This mechanism is present in case an MPL migration is ever needed, which would require approval of the Maple DAO. The transaction that perform the migration has a time delay, which allows any parties to withdraw before the changes take effect.
12 |
13 | 
14 |
15 | ### One-Time xMPL Migration
16 |
17 | This allows a seamless and safe migration for all users that have staked their MPL into the xMPL contract.
18 |
19 | 1. The first step to trigger a migration is for the contract governor to call `scheduleMigration`, which sets a execution to occur at least 10 days from the transaction time. In the meantime, all functionality in the xMPL contract remain operational.
20 |
21 | 2. During this period, any party that disagrees with the scheduled migration can withdraw their funds from the contract.
22 |
23 | 3. After the time delay, anyone can call `performMigration`, which executes the migration with the parameters set 10 days prior.
24 |
25 | 4. During this migration,the xMPL contract deposits its entire balance of MPL to the migrator contract, which includes non vested and vested funds.
26 |
27 | 5. The migrator contract takes the MPL amount and returns the exact same amount of MPLv2, with a 1:1 ratio. The MPL tokens will remain locked in the migrator contract so they cannot be migrated twice.
28 |
29 | 6. In the last step, the address defined as `asset` in xMPL contract is switched from MPLv1 to the newly migrated MPLv2 address. From that point on, all subsequent operations will be in relation to the new migrated token.
30 |
31 | Holders of the xMPL token do not need to perform any action in order to migrate their tokens, however holders that do not interact with the xMPL contract would need to perform a migration by themselves.
32 |
33 | ## Testing and Development
34 | #### Setup
35 | ```sh
36 | git clone git@github.com:maple-labs/xMPL.git
37 | cd xMPL
38 | forge update
39 | ```
40 | #### Running Tests
41 | - To run all unit/fuzz tests: `make test` (runs `./test.sh`)
42 | - To run all invariant tests: `make invariant` (runs `./invariant.sh`)
43 | - To run all tests (unit/fuzz and invariant tests): `make test-all`
44 | - To run specific unit tests: `./test.sh -t ` (e.g., `./test.sh -t test_scheduleMigration`)
45 | - To run specific invariant tests: `./invariant-test.sh -t ` (e.g., `./invariant-test.sh -t invariant_totalSupply`)
46 | - To run specific fuzz tests with a specified number of fuzz runs: `./test.sh -r ` (e.g., `./test.sh -t testFuzz_performMigration -r 10000`)
47 |
48 | This project was built using [Foundry](https://github.com/gakonst/Foundry).
49 |
50 | ## Audit Reports
51 | | Auditor | Report link |
52 | |---|---|
53 | | Trail of Bits | [ToB Report - April 12, 2022](https://docs.google.com/viewer?url=https://github.com/maple-labs/maple-core/files/8507237/Maple.Finance.-.Final.Report.-.Fixes.pdf) |
54 | | Code 4rena | [C4 Report - April 20, 2022](https://code4rena.com/reports/2022-03-maple/) |
55 |
56 | ## Bug Bounty
57 |
58 | For all information related to the ongoing bug bounty for these contracts run by [Immunefi](https://immunefi.com/), please visit this [site](https://immunefi.com/bounty/maple/).
59 |
60 | | Severity of Finding | Payout |
61 | |---|---|
62 | | Critical | $50,000 |
63 | | High | $25,000 |
64 | | Medium | $1,000 |
65 |
66 | ## About Maple
67 | [Maple Finance](https://maple.finance) is a decentralized corporate credit market. Maple provides capital to institutional borrowers through globally accessible fixed-income yield opportunities.
68 |
69 | For all technical documentation related to the currently deployed Maple protocol, please refer to the maple-core GitHub [wiki](https://github.com/maple-labs/maple-core/wiki).
70 |
71 | ---
72 |
73 |
74 |
75 |
76 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -e
3 |
4 | while getopts p: flag
5 | do
6 | case "${flag}" in
7 | p) profile=${OPTARG};;
8 | esac
9 | done
10 |
11 | export FOUNDRY_PROFILE=$profile
12 | echo Using profile: $FOUNDRY_PROFILE
13 |
14 | forge build
15 |
--------------------------------------------------------------------------------
/contracts/interfaces/IxMPL.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 | pragma solidity 0.8.7;
3 |
4 | import { IRevenueDistributionToken } from "../../modules/revenue-distribution-token/contracts/interfaces/IRevenueDistributionToken.sol";
5 |
6 | interface IxMPL is IRevenueDistributionToken {
7 |
8 | /**************/
9 | /*** Events ***/
10 | /**************/
11 |
12 | /**
13 | * @dev Notifies that a scheduled migration was cancelled.
14 | */
15 | event MigrationCancelled();
16 |
17 | /**
18 | * @dev Notifies that a scheduled migration was executed.
19 | * @param fromAsset_ The address of the old asset.
20 | * @param toAsset_ The address of new asset migrated to.
21 | * @param amount_ The amount of tokens migrated.
22 | */
23 | event MigrationPerformed(address indexed fromAsset_, address indexed toAsset_, uint256 amount_);
24 |
25 | /**
26 | * @dev Notifies that migration was scheduled.
27 | * @param fromAsset_ The current asset address.
28 | * @param toAsset_ The address of the asset to be migrated to.
29 | * @param migrator_ The address of the migrator contract.
30 | * @param migrationTime_ The earliest time the migration is scheduled for.
31 | */
32 | event MigrationScheduled(address indexed fromAsset_, address indexed toAsset_, address indexed migrator_, uint256 migrationTime_);
33 |
34 | /********************************/
35 | /*** Administrative Functions ***/
36 | /********************************/
37 |
38 | /**
39 | * @dev Cancel the scheduled migration
40 | */
41 | function cancelMigration() external;
42 |
43 | /**
44 | * @dev Perform a migration of the asset.
45 | */
46 | function performMigration() external;
47 |
48 | /**
49 | * @dev Schedule a migration to be executed after a delay.
50 | * @param migrator_ The address of the migrator contract.
51 | * @param newAsset_ The address of the new asset token.
52 | */
53 | function scheduleMigration(address migrator_, address newAsset_) external;
54 |
55 | /**********************/
56 | /*** View Functions ***/
57 | /**********************/
58 |
59 | /**
60 | * @dev Get the minimum delay that a scheduled transaction needs in order to be executed.
61 | * @return minimumMigrationDelay_ The delay in seconds.
62 | */
63 | function MINIMUM_MIGRATION_DELAY() external pure returns (uint256 minimumMigrationDelay_);
64 |
65 | /**
66 | * @dev Get the timestamp that a migration is scheduled for.
67 | * @return scheduledMigrationTimestamp_ The timestamp of the migration.
68 | */
69 | function scheduledMigrationTimestamp() external view returns (uint256 scheduledMigrationTimestamp_);
70 |
71 | /**
72 | * @dev The address of the migrator contract to be used during the scheduled migration.
73 | * @return scheduledMigrator_ The address of the migrator.
74 | */
75 | function scheduledMigrator() external view returns (address scheduledMigrator_);
76 |
77 | /**
78 | * @dev The address of the new asset token to be migrated to during the scheduled migration.
79 | * @return scheduledNewAsset_ The address of the new asset token.
80 | */
81 | function scheduledNewAsset() external view returns (address scheduledNewAsset_);
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/contracts/test/ERC20.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 | pragma solidity 0.8.7;
3 |
4 | import { ERC20User } from "../../modules/revenue-distribution-token/modules/erc20/contracts/test/accounts/ERC20User.sol";
5 | import { ERC20BaseTest, ERC20PermitTest } from "../../modules/revenue-distribution-token/modules/erc20/contracts/test/ERC20.t.sol";
6 | import { MockERC20 } from "../../modules/revenue-distribution-token/modules/erc20/contracts/test/mocks/MockERC20.sol";
7 |
8 | import { xMPL } from "../xMPL.sol";
9 |
10 | import { MockERC20_xMPL } from "./mocks/MockERC20.xMPL.sol"; // Required for mint/burn tests
11 |
12 | contract xMPL_ERC20Test is ERC20BaseTest {
13 |
14 | function setUp() override public {
15 | address asset = address(new MockERC20("MockToken", "MT", 18));
16 | _token = MockERC20(address(new MockERC20_xMPL("Token", "TKN", address(this), asset, 1e30)));
17 | }
18 |
19 | }
20 |
21 | contract xMPL_ERC20PermitTest is ERC20PermitTest {
22 |
23 | function setUp() override public {
24 | super.setUp();
25 | address asset = address(new MockERC20("MockToken", "MT", 18));
26 | _token = MockERC20(address(new xMPL("Token", "TKN", address(this), asset, 1e30)));
27 | }
28 |
29 | function test_domainSeparator() public override {
30 | assertEq(_token.DOMAIN_SEPARATOR(), 0x0365f9ff9ad9eb5882a196869a0b88aa974d4bec7b6d908aa145e4973fe7315a);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/contracts/test/Invariants.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-only
2 | pragma solidity ^0.8.7;
3 |
4 | import { TestUtils, InvariantTest } from "../../modules/contract-test-utils/contracts/test.sol";
5 | import { Migrator } from "../../modules/mpl-migration/contracts/Migrator.sol";
6 | import { InvariantERC20User } from "../../modules/revenue-distribution-token/contracts/test/accounts/ERC20User.sol";
7 | import { InvariantStakerManager } from "../../modules/revenue-distribution-token/contracts/test/accounts/Staker.sol";
8 | import { Warper } from "../../modules/revenue-distribution-token/contracts/test/accounts/Warper.sol";
9 | import { RDTInvariants, MutableRDT } from "../../modules/revenue-distribution-token/contracts/test/Invariants.t.sol";
10 | import { MockERC20 } from "../../modules/revenue-distribution-token/modules/erc20/contracts/test/mocks/MockERC20.sol";
11 |
12 | import { xMPLInvariantOwner } from "./accounts/Owner.sol";
13 |
14 | import { MutableXMPL } from "./mocks/Mocks.sol";
15 |
16 | contract xMPLInvariants is RDTInvariants {
17 |
18 | InvariantERC20User internal _newErc20User;
19 | Migrator internal _migrator;
20 | MockERC20 internal _newUnderlying;
21 | xMPLInvariantOwner internal _invariantOwner; // Different from inherited _owner
22 |
23 | bool migrated;
24 |
25 | function setUp() public override {
26 | _underlying = new MockERC20("MockToken", "MT", 18);
27 | _newUnderlying = new MockERC20("NewMockToken", "NMT", 18);
28 | _migrator = new Migrator(address(_underlying), address(_newUnderlying));
29 |
30 | _rdToken = MutableRDT(address(new MutableXMPL("Revenue Distribution Token", "RDT", address(this), address(_underlying), 1e30)));
31 |
32 | _erc20User = new InvariantERC20User(address(_rdToken), address(_underlying));
33 | _newErc20User = new InvariantERC20User(address(_rdToken), address(_underlying));
34 | _stakerManager = new InvariantStakerManager(address(_rdToken), address(_underlying));
35 | _invariantOwner = new xMPLInvariantOwner(address(_rdToken), address(_underlying), address(_migrator), address(_newUnderlying));
36 | _warper = new Warper();
37 |
38 | // Required to prevent `acceptOwner` from being a target function
39 | _rdToken.setOwner(address(_invariantOwner));
40 |
41 | // Performs random transfers of underlying into contract
42 | addTargetContract(address(_erc20User));
43 | addTargetContract(address(_newErc20User));
44 |
45 | // Performs random transfers of underlying into contract
46 | // Performs random updateVestingSchedule calls
47 | addTargetContract(address(_invariantOwner));
48 |
49 | // Performs random instantiations of new staker users
50 | // Performs random deposit calls from a random instantiated staker
51 | // Performs random withdraw calls from a random instantiated staker
52 | // Performs random redeem calls from a random instantiated staker
53 | addTargetContract(address(_stakerManager));
54 |
55 | // Peforms random warps forward in time
56 | addTargetContract(address(_warper));
57 |
58 | // Create one staker to prevent underflows on index calculations
59 | _stakerManager.createStaker();
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/contracts/test/RDT.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 | pragma solidity 0.8.7;
3 |
4 | import { RevenueDistributionToken as RDT } from "../../modules/revenue-distribution-token/contracts/RevenueDistributionToken.sol";
5 | import { Staker } from "../../modules/revenue-distribution-token/contracts/test/accounts/Staker.sol";
6 | import { MockERC20 } from "../../modules/revenue-distribution-token/modules/erc20/contracts/test/mocks/MockERC20.sol";
7 |
8 | import {
9 | AuthTests,
10 | ConstructorTest,
11 | DepositFailureTests,
12 | DepositTests,
13 | DepositWithPermitFailureTests,
14 | DepositWithPermitTests,
15 | EndToEndRevenueStreamingTests,
16 | MintFailureTests,
17 | MintTests,
18 | MintWithPermitFailureTests,
19 | MintWithPermitTests,
20 | RedeemCallerNotOwnerTests,
21 | RedeemFailureTests,
22 | RedeemRevertOnTransfers,
23 | RedeemTests,
24 | UpdateVestingScheduleFailureTests,
25 | UpdateVestingScheduleTests,
26 | WithdrawCallerNotOwnerTests,
27 | WithdrawFailureTests,
28 | WithdrawRevertOnTransfers,
29 | WithdrawTests
30 | } from "../../modules/revenue-distribution-token/contracts/test/RevenueDistributionToken.t.sol";
31 |
32 | import { xMPL } from "../xMPL.sol";
33 |
34 | contract xMPL_RDT_AuthTests is AuthTests {
35 |
36 | function setUp() override public {
37 | super.setUp();
38 | rdToken = RDT(address(new xMPL("Token", "TKN", address(owner), address(asset), 1e30)));
39 | }
40 |
41 | }
42 |
43 | contract xMPL_RDT_ConstructorTest is ConstructorTest { }
44 |
45 | contract xMPL_RDT_DepositFailureTests is DepositFailureTests {
46 |
47 | function setUp() override public {
48 | super.setUp();
49 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
50 | }
51 |
52 | }
53 |
54 | contract xMPL_RDT_DepositTests is DepositTests {
55 |
56 | function setUp() override public {
57 | super.setUp();
58 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
59 | }
60 |
61 | }
62 |
63 | contract xMPL_RDT_DepositWithPermitFailureTests is DepositWithPermitFailureTests {
64 |
65 | function setUp() override public {
66 | super.setUp();
67 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
68 | }
69 |
70 | }
71 |
72 | contract xMPL_RDT_DepositWithPermitTests is DepositWithPermitTests {
73 |
74 | function setUp() override public {
75 | super.setUp();
76 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
77 | }
78 |
79 | }
80 |
81 | contract xMPL_RDT_EndToEndRevenueStreamingTests is EndToEndRevenueStreamingTests {
82 |
83 | function setUp() override public {
84 | super.setUp();
85 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
86 | }
87 |
88 | }
89 |
90 | contract xMPL_RDT_MintFailureTests is MintFailureTests {
91 |
92 | function setUp() override public {
93 | super.setUp();
94 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
95 | }
96 |
97 | }
98 |
99 | contract xMPL_RDT_MintTests is MintTests {
100 |
101 | function setUp() override public {
102 | super.setUp();
103 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
104 | }
105 |
106 | }
107 |
108 | contract xMPL_RDT_MintWithPermitFailureTests is MintWithPermitFailureTests {
109 |
110 | function setUp() override public {
111 | super.setUp();
112 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
113 | }
114 |
115 | }
116 |
117 | contract xMPL_RDT_MintWithPermitTests is MintWithPermitTests {
118 |
119 | function setUp() override public {
120 | super.setUp();
121 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
122 | }
123 |
124 | }
125 |
126 | contract xMPL_RDT_RedeemCallerNotOwnerTests is RedeemCallerNotOwnerTests {
127 |
128 | function setUp() override public {
129 | super.setUp();
130 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
131 | }
132 |
133 | }
134 |
135 | contract xMPL_RDT_RedeemFailureTests is RedeemFailureTests {
136 |
137 | function setUp() override public {
138 | super.setUp();
139 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
140 | }
141 |
142 | }
143 |
144 | contract xMPL_RDT_RedeemRevertOnTransfers is RedeemRevertOnTransfers {
145 |
146 | function setUp() override public {
147 | super.setUp();
148 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(revertingAsset), 1e30)));
149 | }
150 |
151 | }
152 |
153 | contract xMPL_RDT_RedeemTests is RedeemTests {
154 |
155 | function setUp() override public {
156 | super.setUp();
157 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
158 | }
159 |
160 | }
161 |
162 | contract xMPL_RDT_UpdateVestingScheduleFailureTests is UpdateVestingScheduleFailureTests {
163 |
164 | function setUp() override public {
165 | super.setUp();
166 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
167 | }
168 |
169 | }
170 |
171 | contract xMPL_RDT_UpdateVestingScheduleTests is UpdateVestingScheduleTests {
172 |
173 | function setUp() override public {
174 | super.setUp();
175 |
176 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
177 |
178 | // Deposit the minimum amount of the asset to allow the vesting schedule updates to occur.
179 | asset.mint(address(firstStaker), startingAssets);
180 |
181 | firstStaker.erc20_approve(address(asset), address(rdToken), startingAssets);
182 | firstStaker.rdToken_deposit(address(rdToken), startingAssets);
183 | }
184 |
185 | }
186 |
187 | contract xMPL_RDT_WithdrawCallerNotOwnerTests is WithdrawCallerNotOwnerTests {
188 |
189 | function setUp() override public {
190 | super.setUp();
191 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
192 | }
193 |
194 | }
195 |
196 | contract xMPL_RDT_WithdrawFailureTests is WithdrawFailureTests {
197 |
198 | function setUp() override public {
199 | super.setUp();
200 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
201 | }
202 |
203 | }
204 |
205 | contract xMPL_RDT_WithdrawRevertOnTransfers is WithdrawRevertOnTransfers {
206 |
207 | function setUp() override public {
208 | super.setUp();
209 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(revertingAsset), 1e30)));
210 | }
211 |
212 | }
213 |
214 | contract xMPL_RDT_WithdrawTests is WithdrawTests {
215 |
216 | function setUp() override public {
217 | super.setUp();
218 | rdToken = RDT(address(new xMPL("Token", "TKN", address(this), address(asset), 1e30)));
219 | }
220 |
221 | }
222 |
--------------------------------------------------------------------------------
/contracts/test/accounts/Owner.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 | pragma solidity 0.8.7;
3 |
4 | import { Owner, InvariantOwner, MockERC20 } from "../../../modules/revenue-distribution-token/contracts/test/accounts/Owner.sol";
5 |
6 | import { IxMPL } from "../../interfaces/IxMPL.sol";
7 |
8 | contract xMPLOwner is Owner {
9 |
10 | function xMPL_cancelMigration(address xmpl_) external {
11 | IxMPL(xmpl_).cancelMigration();
12 | }
13 |
14 | function xMPL_performMigration(address xmpl_) external {
15 | IxMPL(xmpl_).performMigration();
16 | }
17 |
18 | function xMPL_scheduleMigration(address xmpl_, address migrator_, address newAsset_) external {
19 | IxMPL(xmpl_).scheduleMigration(migrator_, newAsset_);
20 | }
21 |
22 | }
23 |
24 | contract xMPLInvariantOwner is InvariantOwner {
25 |
26 | address _migrator;
27 | address newUnderlying;
28 |
29 | IxMPL xmpl = IxMPL(address(_rdToken));
30 |
31 | constructor(address rdToken_, address underlying_, address migrator_, address newUnderlying_) InvariantOwner(rdToken_, underlying_) {
32 | _migrator = migrator_;
33 | newUnderlying = newUnderlying_;
34 | }
35 |
36 | function rdToken_scheduleAndPerformMigration() external {
37 | xmpl.scheduleMigration(_migrator, newUnderlying);
38 |
39 | vm.warp(block.timestamp + 10 days + 1);
40 |
41 | xmpl.performMigration();
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/contracts/test/mocks/MockERC20.xMPL.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-only
2 | pragma solidity 0.8.7;
3 |
4 | import { xMPL } from "../../xMPL.sol";
5 |
6 | contract MockERC20_xMPL is xMPL {
7 |
8 | constructor(string memory name_, string memory symbol_, address owner_, address asset_, uint256 precision_)
9 | xMPL(name_, symbol_, owner_, asset_, precision_) { }
10 |
11 | function mint(address recipient_, uint256 amount_) external {
12 | _mint(recipient_, amount_);
13 | }
14 |
15 | function burn(address owner_, uint256 amount_) external {
16 | _burn(owner_, amount_);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/contracts/test/mocks/Mocks.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 | pragma solidity 0.8.7;
3 |
4 | import "../../xMPL.sol";
5 |
6 | contract CompromisedMigrator {
7 |
8 | address public immutable newToken;
9 | address public immutable oldToken;
10 |
11 | constructor(address oldToken_, address newToken_) {
12 | oldToken = oldToken_;
13 | newToken = newToken_;
14 | }
15 |
16 | function migrate(uint256 amount_) external {
17 | // do nothing
18 | }
19 |
20 | }
21 |
22 | contract MutableXMPL is xMPL {
23 |
24 | constructor(string memory name_, string memory symbol_, address owner_, address underlying_, uint256 precision_)
25 | xMPL(name_, symbol_, owner_, underlying_, precision_) { }
26 |
27 | function setOwner(address owner_) external {
28 | owner = owner_;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/contracts/test/mocks/xMPLMutable.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-only
2 | pragma solidity 0.8.7;
3 |
4 | import { xMPL } from "../../xMPL.sol";
5 |
6 | contract xMPLMutable is xMPL {
7 |
8 | constructor(string memory name_, string memory symbol_, address owner_, address underlying_, uint256 precision_)
9 | xMPL(name_, symbol_, owner_, underlying_, precision_) { }
10 |
11 | function setOwner(address owner_) external {
12 | owner = owner_;
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/contracts/test/xMPL.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 | pragma solidity 0.8.7;
3 |
4 | import { CompromisedMigrator } from "./mocks/Mocks.sol";
5 |
6 | import { TestUtils } from "../../modules/contract-test-utils/contracts/test.sol";
7 | import { Migrator } from "../../modules/mpl-migration/contracts/Migrator.sol";
8 | import { MockERC20 } from "../../modules/mpl-migration/modules/erc20/contracts/test/mocks/MockERC20.sol";
9 | import { Staker } from "../../modules/revenue-distribution-token/contracts/test/accounts/Staker.sol";
10 |
11 | import { xMPL } from "../xMPL.sol";
12 |
13 | import { xMPLOwner } from "./accounts/Owner.sol";
14 |
15 | contract xMPLTest is TestUtils {
16 |
17 | uint256 internal constant SAMPLE_AMOUNT = 1e18;
18 | uint256 internal constant START = 52 weeks;
19 | uint256 internal constant OLD_SUPPLY = 10_000_000e18;
20 |
21 | Migrator migrator;
22 | MockERC20 newAsset;
23 | MockERC20 oldAsset;
24 | Staker staker;
25 | xMPLOwner owner;
26 | xMPLOwner notOwner;
27 | xMPL xmpl;
28 |
29 | function setUp() public {
30 | vm.warp(START);
31 |
32 | oldAsset = new MockERC20("Old Token", "OT", 18);
33 | newAsset = new MockERC20("New Token", "NT", 18);
34 |
35 | migrator = new Migrator(address(oldAsset), address(newAsset));
36 |
37 | owner = new xMPLOwner();
38 | notOwner = new xMPLOwner();
39 | staker = new Staker();
40 |
41 | newAsset.mint(address(migrator), OLD_SUPPLY);
42 | oldAsset.mint(address(staker), SAMPLE_AMOUNT);
43 |
44 | xmpl = new xMPL("xMPL", "xMPL", address(owner), address(oldAsset), 1e30);
45 |
46 | staker.erc20_approve(address(oldAsset), address(xmpl), SAMPLE_AMOUNT);
47 | staker.rdToken_deposit(address(xmpl), SAMPLE_AMOUNT);
48 | }
49 |
50 | function test_cancelMigration_notOwner() public {
51 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
52 |
53 | vm.expectRevert("xMPL:NOT_OWNER");
54 | notOwner.xMPL_cancelMigration(address(xmpl));
55 |
56 | owner.xMPL_cancelMigration(address(xmpl));
57 | }
58 |
59 | function test_cancelMigration_notScheduled() public {
60 | vm.expectRevert("xMPL:CM:NOT_SCHEDULED");
61 | owner.xMPL_cancelMigration(address(xmpl));
62 |
63 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
64 | owner.xMPL_cancelMigration(address(xmpl));
65 | }
66 |
67 | function test_cancelMigration_success() public {
68 | assertEq(xmpl.scheduledMigrator(), address(0));
69 | assertEq(xmpl.scheduledNewAsset(), address(0));
70 | assertEq(xmpl.scheduledMigrationTimestamp(), 0);
71 |
72 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
73 |
74 | assertEq(xmpl.scheduledMigrator(), address(migrator));
75 | assertEq(xmpl.scheduledNewAsset(), address(newAsset));
76 | assertEq(xmpl.scheduledMigrationTimestamp(), START + xmpl.MINIMUM_MIGRATION_DELAY());
77 |
78 | owner.xMPL_cancelMigration(address(xmpl));
79 |
80 | assertEq(xmpl.scheduledMigrator(), address(0));
81 | assertEq(xmpl.scheduledNewAsset(), address(0));
82 | assertEq(xmpl.scheduledMigrationTimestamp(), 0);
83 | }
84 |
85 | function test_performMigration_notOwner() public {
86 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
87 |
88 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY());
89 |
90 | vm.expectRevert("xMPL:NOT_OWNER");
91 | notOwner.xMPL_performMigration(address(xmpl));
92 |
93 | owner.xMPL_performMigration(address(xmpl));
94 | }
95 |
96 | function test_performMigration_notScheduled() public {
97 | vm.expectRevert("xMPL:PM:NOT_SCHEDULED");
98 | owner.xMPL_performMigration(address(xmpl));
99 |
100 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
101 |
102 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY());
103 |
104 | owner.xMPL_performMigration(address(xmpl));
105 | }
106 |
107 | function test_performMigration_tooEarly() public {
108 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
109 |
110 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY() - 1);
111 |
112 | vm.expectRevert("xMPL:PM:TOO_EARLY");
113 | owner.xMPL_performMigration(address(xmpl));
114 |
115 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY());
116 |
117 | owner.xMPL_performMigration(address(xmpl));
118 | }
119 |
120 | function test_performMigration_wrongAmount() public {
121 | CompromisedMigrator badMigrator = new CompromisedMigrator(address(oldAsset), address(newAsset));
122 |
123 | owner.xMPL_scheduleMigration(address(xmpl), address(badMigrator), address(newAsset));
124 |
125 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY());
126 |
127 | vm.expectRevert("xMPL:PM:WRONG_AMOUNT");
128 | owner.xMPL_performMigration(address(xmpl));
129 |
130 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
131 |
132 | vm.warp(START + 2 * xmpl.MINIMUM_MIGRATION_DELAY());
133 |
134 | owner.xMPL_performMigration(address(xmpl));
135 | }
136 |
137 | function testFuzz_performMigration_migrationPostVesting(uint256 amount_, uint vestingPeriod_) public {
138 | amount_ = constrictToRange(amount_, 1, OLD_SUPPLY - SAMPLE_AMOUNT);
139 | vestingPeriod_ = constrictToRange(vestingPeriod_, 10 seconds, 100_000 days);
140 |
141 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
142 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY());
143 |
144 | oldAsset.mint(address(xmpl), amount_);
145 | owner.rdToken_updateVestingSchedule(address(xmpl), vestingPeriod_);
146 |
147 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY() + xmpl.vestingPeriodFinish());
148 |
149 | uint256 expectedRate = amount_ * 1e30 / vestingPeriod_;
150 | uint256 expectedTotalAssets = SAMPLE_AMOUNT + expectedRate * vestingPeriod_ / 1e30;
151 |
152 | assertEq(oldAsset.balanceOf(address(xmpl)), amount_ + SAMPLE_AMOUNT);
153 | assertEq(newAsset.balanceOf(address(xmpl)), 0);
154 |
155 | assertEq(xmpl.asset(), address(oldAsset));
156 | assertEq(xmpl.totalAssets(), expectedTotalAssets);
157 | assertEq(xmpl.convertToAssets(SAMPLE_AMOUNT), SAMPLE_AMOUNT * expectedTotalAssets / SAMPLE_AMOUNT);
158 | assertEq(xmpl.convertToShares(SAMPLE_AMOUNT), SAMPLE_AMOUNT * SAMPLE_AMOUNT / expectedTotalAssets);
159 | assertEq(xmpl.scheduledMigrator(), address(migrator));
160 | assertEq(xmpl.scheduledNewAsset(), address(newAsset));
161 | assertEq(xmpl.scheduledMigrationTimestamp(), START + xmpl.MINIMUM_MIGRATION_DELAY());
162 |
163 | assertWithinDiff(xmpl.balanceOfAssets(address(staker)), SAMPLE_AMOUNT + amount_, 1);
164 | assertWithinDiff(xmpl.totalAssets(), SAMPLE_AMOUNT + amount_, 1);
165 |
166 | owner.xMPL_performMigration(address(xmpl));
167 |
168 | assertEq(oldAsset.balanceOf(address(xmpl)), 0);
169 | assertEq(newAsset.balanceOf(address(xmpl)), amount_ + SAMPLE_AMOUNT);
170 |
171 | assertEq(xmpl.asset(), address(newAsset));
172 | assertEq(xmpl.totalAssets(), expectedTotalAssets);
173 | assertEq(xmpl.convertToAssets(SAMPLE_AMOUNT), SAMPLE_AMOUNT * expectedTotalAssets / SAMPLE_AMOUNT);
174 | assertEq(xmpl.convertToShares(SAMPLE_AMOUNT), SAMPLE_AMOUNT * SAMPLE_AMOUNT / expectedTotalAssets);
175 | assertEq(xmpl.scheduledMigrator(), address(0));
176 | assertEq(xmpl.scheduledNewAsset(), address(0));
177 | assertEq(xmpl.scheduledMigrationTimestamp(), 0);
178 |
179 | assertWithinDiff(xmpl.balanceOfAssets(address(staker)), SAMPLE_AMOUNT + amount_, 1);
180 | assertWithinDiff(xmpl.totalAssets(), SAMPLE_AMOUNT + amount_, 1);
181 | }
182 |
183 | function testFuzz_performMigration_migrationBeforeVestingEnds(uint256 amount_, uint256 vestingPeriod_, uint256 warpAmount_) public {
184 | amount_ = constrictToRange(amount_, 1, OLD_SUPPLY - SAMPLE_AMOUNT);
185 | vestingPeriod_ = constrictToRange(vestingPeriod_, 10 seconds, 100_000 days);
186 | warpAmount_ = constrictToRange(warpAmount_, 1, vestingPeriod_);
187 |
188 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
189 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY());
190 |
191 | oldAsset.mint(address(xmpl), amount_);
192 | owner.rdToken_updateVestingSchedule(address(xmpl), vestingPeriod_);
193 |
194 | vm.warp(START + xmpl.MINIMUM_MIGRATION_DELAY() + warpAmount_);
195 |
196 | uint256 expectedRate = amount_ * 1e30 / vestingPeriod_;
197 | uint256 expectedTotalAssets = SAMPLE_AMOUNT + expectedRate * warpAmount_ / 1e30;
198 |
199 | assertEq(oldAsset.balanceOf(address(xmpl)), amount_ + SAMPLE_AMOUNT);
200 | assertEq(newAsset.balanceOf(address(xmpl)), 0);
201 |
202 | assertEq(xmpl.asset(), address(oldAsset));
203 | assertEq(xmpl.totalAssets(), expectedTotalAssets);
204 | assertEq(xmpl.convertToAssets(SAMPLE_AMOUNT), SAMPLE_AMOUNT * expectedTotalAssets / SAMPLE_AMOUNT);
205 | assertEq(xmpl.convertToShares(SAMPLE_AMOUNT), SAMPLE_AMOUNT * SAMPLE_AMOUNT / expectedTotalAssets);
206 | assertEq(xmpl.scheduledMigrator(), address(migrator));
207 | assertEq(xmpl.scheduledNewAsset(), address(newAsset));
208 | assertEq(xmpl.scheduledMigrationTimestamp(), START + xmpl.MINIMUM_MIGRATION_DELAY());
209 |
210 | assertWithinDiff(xmpl.balanceOfAssets(address(staker)), expectedTotalAssets, 1);
211 |
212 | owner.xMPL_performMigration(address(xmpl));
213 |
214 | assertEq(oldAsset.balanceOf(address(xmpl)), 0);
215 | assertEq(newAsset.balanceOf(address(xmpl)), amount_ + SAMPLE_AMOUNT);
216 |
217 | assertEq(xmpl.asset(), address(newAsset));
218 | assertEq(xmpl.totalAssets(), expectedTotalAssets);
219 | assertEq(xmpl.convertToAssets(SAMPLE_AMOUNT), SAMPLE_AMOUNT * expectedTotalAssets / SAMPLE_AMOUNT);
220 | assertEq(xmpl.convertToShares(SAMPLE_AMOUNT), SAMPLE_AMOUNT * SAMPLE_AMOUNT / expectedTotalAssets);
221 | assertEq(xmpl.scheduledMigrator(), address(0));
222 | assertEq(xmpl.scheduledNewAsset(), address(0));
223 | assertEq(xmpl.scheduledMigrationTimestamp(), 0);
224 |
225 | assertWithinDiff(xmpl.balanceOfAssets(address(staker)), expectedTotalAssets, 1);
226 | }
227 |
228 | function test_scheduleMigration_notOwner() public {
229 | vm.expectRevert("xMPL:NOT_OWNER");
230 | notOwner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
231 |
232 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
233 | }
234 |
235 | function test_scheduleMigration_zeroMigrator() public {
236 | vm.expectRevert("xMPL:SM:INVALID_MIGRATOR");
237 | owner.xMPL_scheduleMigration(address(xmpl), address(0), address(newAsset));
238 | }
239 |
240 | function test_scheduleMigration_zeroNewAsset() public {
241 | vm.expectRevert("xMPL:SM:INVALID_NEW_ASSET");
242 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(0));
243 | }
244 |
245 | function test_scheduleMigration_once() public {
246 | assertEq(xmpl.scheduledMigrator(), address(0));
247 | assertEq(xmpl.scheduledNewAsset(), address(0));
248 | assertEq(xmpl.scheduledMigrationTimestamp(), 0);
249 |
250 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
251 |
252 | assertEq(xmpl.scheduledMigrator(), address(migrator));
253 | assertEq(xmpl.scheduledNewAsset(), address(newAsset));
254 | assertEq(xmpl.scheduledMigrationTimestamp(), START + xmpl.MINIMUM_MIGRATION_DELAY());
255 | }
256 |
257 | function test_scheduleMigration_withCorrection() public {
258 | assertEq(xmpl.scheduledMigrator(), address(0));
259 | assertEq(xmpl.scheduledNewAsset(), address(0));
260 | assertEq(xmpl.scheduledMigrationTimestamp(), 0);
261 |
262 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(oldAsset));
263 |
264 | assertEq(xmpl.scheduledMigrator(), address(migrator));
265 | assertEq(xmpl.scheduledNewAsset(), address(oldAsset));
266 | assertEq(xmpl.scheduledMigrationTimestamp(), START + xmpl.MINIMUM_MIGRATION_DELAY());
267 |
268 | vm.warp(START + 1);
269 | owner.xMPL_scheduleMigration(address(xmpl), address(migrator), address(newAsset));
270 |
271 | assertEq(xmpl.scheduledMigrator(), address(migrator));
272 | assertEq(xmpl.scheduledNewAsset(), address(newAsset));
273 | assertEq(xmpl.scheduledMigrationTimestamp(), START + 1 + xmpl.MINIMUM_MIGRATION_DELAY());
274 | }
275 |
276 | }
277 |
278 | ///@dev Copied from modules/revenue-distribution-token/src/test/RevenueDistributionToken.sol
279 | contract FullMigrationTest is TestUtils {
280 |
281 | Migrator migrator;
282 | MockERC20 asset;
283 | MockERC20 newAsset;
284 | xMPL rdToken;
285 |
286 | bytes constant ARITHMETIC_ERROR = abi.encodeWithSignature("Panic(uint256)", 0x11);
287 |
288 | uint256 start;
289 |
290 | function setUp() public virtual {
291 | // Use non-zero timestamp
292 | start = 10_000_000;
293 | vm.warp(start);
294 |
295 | asset = new MockERC20("Old Token", "OT", 18);
296 | newAsset = new MockERC20("New Token", "NT", 18);
297 | migrator = new Migrator(address(asset), address(newAsset));
298 | rdToken = new xMPL("Revenue Distribution Token", "RDT", address(this), address(asset), 1e30);
299 | }
300 |
301 | function testFuzz_fullMigrationStory(uint256 depositAmount_, uint256 vestingAmount_, uint256 vestingPeriod_) public {
302 | depositAmount_ = constrictToRange(depositAmount_, 1e6, 1e30); // 1 trillion at WAD precision
303 | vestingAmount_ = constrictToRange(vestingAmount_, 1e6, 1e30); // 1 trillion at WAD precision
304 | vestingPeriod_ = constrictToRange(vestingPeriod_, 10 seconds, 100_000 days) / 10 * 10; // Must be divisible by 10 for for loop 10% increment calculations
305 |
306 | Staker staker = new Staker();
307 |
308 | asset.mint(address(staker), depositAmount_);
309 |
310 | staker.erc20_approve(address(asset), address(rdToken), depositAmount_);
311 | staker.rdToken_deposit(address(rdToken), depositAmount_);
312 |
313 | assertEq(rdToken.freeAssets(), depositAmount_);
314 | assertEq(rdToken.totalAssets(), depositAmount_);
315 | assertEq(rdToken.convertToAssets(1e30), 1e30);
316 | assertEq(rdToken.issuanceRate(), 0);
317 | assertEq(rdToken.lastUpdated(), start);
318 | assertEq(rdToken.vestingPeriodFinish(), 0);
319 |
320 | vm.warp(start + 1 days);
321 |
322 | assertEq(rdToken.totalAssets(), depositAmount_); // No change
323 |
324 | vm.warp(start); // Warp back after demonstrating totalHoldings is not time-dependent before vesting starts
325 |
326 | _depositAndUpdateVesting(vestingAmount_, vestingPeriod_);
327 |
328 | uint256 expectedRate = vestingAmount_ * 1e30 / vestingPeriod_;
329 |
330 | assertEq(rdToken.freeAssets(), depositAmount_);
331 | assertEq(rdToken.totalAssets(), depositAmount_);
332 | assertEq(rdToken.convertToAssets(1e30), 1e30);
333 | assertEq(rdToken.issuanceRate(), expectedRate);
334 | assertEq(rdToken.lastUpdated(), start);
335 | assertEq(rdToken.vestingPeriodFinish(), start + vestingPeriod_);
336 |
337 | // Warp and assert vesting in 10% increments
338 | for (uint256 i = 1; i < 10; ++i) {
339 | vm.warp(start + vestingPeriod_ * i / 10); // 10% intervals of vesting schedule
340 |
341 | uint256 expectedTotalHoldings = depositAmount_ + expectedRate * (block.timestamp - start) / 1e30;
342 |
343 | assertWithinDiff(rdToken.balanceOfAssets(address(staker)), expectedTotalHoldings, 1);
344 |
345 | // Do the migration
346 | if (i == 5) {
347 | newAsset.mint(address(migrator), asset.balanceOf(address(rdToken)));
348 |
349 | // go back in time to schedule a migration
350 | uint256 currentTimestamp = block.timestamp;
351 | vm.warp(block.timestamp - 10 days - 1);
352 | rdToken.scheduleMigration(address(migrator), address(newAsset));
353 |
354 | vm.warp(currentTimestamp);
355 | rdToken.performMigration();
356 | }
357 |
358 | assertEq(rdToken.totalAssets(), expectedTotalHoldings);
359 | assertEq(rdToken.convertToAssets(1e30), expectedTotalHoldings * 1e30 / depositAmount_);
360 | }
361 |
362 | vm.warp(start + vestingPeriod_);
363 |
364 | uint256 expectedFinalTotal = depositAmount_ + vestingAmount_;
365 |
366 | // Assertions below will use the newAsset token
367 |
368 | assertWithinDiff(rdToken.balanceOfAssets(address(staker)), expectedFinalTotal, 2);
369 |
370 | assertWithinDiff(rdToken.totalAssets(), expectedFinalTotal, 1);
371 | assertWithinDiff(rdToken.convertToAssets(1e30), rdToken.totalAssets() * 1e30 / depositAmount_, 1); // Using totalHoldings because of rounding
372 |
373 | assertEq(newAsset.balanceOf(address(rdToken)), depositAmount_ + vestingAmount_);
374 | assertEq(asset.balanceOf(address(rdToken)), 0);
375 |
376 | assertEq(newAsset.balanceOf(address(staker)), 0);
377 | assertEq(rdToken.balanceOf(address(staker)), depositAmount_);
378 |
379 | staker.rdToken_redeem(address(rdToken), depositAmount_); // Use `redeem` so rdToken amount can be used to burn 100% of tokens
380 |
381 | assertWithinDiff(rdToken.freeAssets(), 0, 1);
382 | assertWithinDiff(rdToken.totalAssets(), 0, 1);
383 |
384 | assertEq(rdToken.convertToAssets(1e30), 1e30); // Exchange rate returns to zero when empty
385 | assertEq(rdToken.issuanceRate(), expectedRate);
386 | assertEq(rdToken.lastUpdated(), start + vestingPeriod_); // This makes issuanceRate * time zero
387 | assertEq(rdToken.vestingPeriodFinish(), start + vestingPeriod_);
388 |
389 | assertWithinDiff(newAsset.balanceOf(address(rdToken)), 0, 2);
390 |
391 | assertEq(rdToken.balanceOfAssets(address(staker)), 0);
392 |
393 | assertWithinDiff(newAsset.balanceOf(address(staker)), depositAmount_ + vestingAmount_, 2);
394 | assertWithinDiff(rdToken.balanceOf(address(staker)), 0, 1);
395 |
396 | assertEq(asset.balanceOf(address(staker)), 0);
397 | }
398 |
399 | function _depositAndUpdateVesting(uint256 vestingAmount_, uint256 vestingPeriod_) internal {
400 | asset.mint(address(this), vestingAmount_);
401 | asset.transfer(address(rdToken), vestingAmount_);
402 | rdToken.updateVestingSchedule(vestingPeriod_);
403 | }
404 |
405 | }
406 |
--------------------------------------------------------------------------------
/contracts/xMPL.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 | pragma solidity 0.8.7;
3 |
4 | import { Migrator } from "../modules/mpl-migration/contracts/Migrator.sol";
5 | import { ERC20, RevenueDistributionToken } from "../modules/revenue-distribution-token/contracts/RevenueDistributionToken.sol";
6 |
7 | import { IxMPL } from "./interfaces/IxMPL.sol";
8 |
9 | /*
10 | ██╗ ██╗███╗ ███╗██████╗ ██╗
11 | ╚██╗██╔╝████╗ ████║██╔══██╗██║
12 | ╚███╔╝ ██╔████╔██║██████╔╝██║
13 | ██╔██╗ ██║╚██╔╝██║██╔═══╝ ██║
14 | ██╔╝ ██╗██║ ╚═╝ ██║██║ ███████╗
15 | ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚══════╝
16 | */
17 |
18 | contract xMPL is IxMPL, RevenueDistributionToken {
19 |
20 | uint256 public constant override MINIMUM_MIGRATION_DELAY = 10 days;
21 |
22 | address public override scheduledMigrator;
23 | address public override scheduledNewAsset;
24 |
25 | uint256 public override scheduledMigrationTimestamp;
26 |
27 | constructor(string memory name_, string memory symbol_, address owner_, address asset_, uint256 precision_)
28 | RevenueDistributionToken(name_, symbol_, owner_, asset_, precision_) { }
29 |
30 | /*****************/
31 | /*** Modifiers ***/
32 | /*****************/
33 |
34 | modifier onlyOwner {
35 | require(msg.sender == owner, "xMPL:NOT_OWNER");
36 | _;
37 | }
38 |
39 | /********************************/
40 | /*** Administrative Functions ***/
41 | /********************************/
42 |
43 | function cancelMigration() external override onlyOwner {
44 | require(scheduledMigrationTimestamp != 0, "xMPL:CM:NOT_SCHEDULED");
45 |
46 | _cleanupMigration();
47 |
48 | emit MigrationCancelled();
49 | }
50 |
51 | function performMigration() external override onlyOwner {
52 | uint256 migrationTimestamp = scheduledMigrationTimestamp;
53 | address migrator = scheduledMigrator;
54 | address oldAsset = asset;
55 | address newAsset = scheduledNewAsset;
56 |
57 | require(migrationTimestamp != 0, "xMPL:PM:NOT_SCHEDULED");
58 | require(block.timestamp >= migrationTimestamp, "xMPL:PM:TOO_EARLY");
59 |
60 | uint256 oldAssetBalanceBeforeMigration = ERC20(oldAsset).balanceOf(address(this));
61 | uint256 newAssetBalanceBeforeMigration = ERC20(newAsset).balanceOf(address(this));
62 |
63 | require(ERC20(oldAsset).approve(migrator, oldAssetBalanceBeforeMigration), "xMPL:PM:APPROVAL_FAILED");
64 |
65 | Migrator(migrator).migrate(oldAssetBalanceBeforeMigration);
66 |
67 | require(ERC20(newAsset).balanceOf(address(this)) - newAssetBalanceBeforeMigration == oldAssetBalanceBeforeMigration, "xMPL:PM:WRONG_AMOUNT");
68 |
69 | emit MigrationPerformed(oldAsset, newAsset, oldAssetBalanceBeforeMigration);
70 |
71 | asset = newAsset;
72 |
73 | _cleanupMigration();
74 | }
75 |
76 | function scheduleMigration(address migrator_, address newAsset_) external override onlyOwner {
77 | require(migrator_ != address(0), "xMPL:SM:INVALID_MIGRATOR");
78 | require(newAsset_ != address(0), "xMPL:SM:INVALID_NEW_ASSET");
79 |
80 | scheduledMigrationTimestamp = block.timestamp + MINIMUM_MIGRATION_DELAY;
81 | scheduledMigrator = migrator_;
82 | scheduledNewAsset = newAsset_;
83 |
84 | emit MigrationScheduled(asset, newAsset_, migrator_, scheduledMigrationTimestamp);
85 | }
86 |
87 | /*************************/
88 | /*** Utility Functions ***/
89 | /*************************/
90 |
91 | function _cleanupMigration() internal {
92 | delete scheduledMigrationTimestamp;
93 | delete scheduledMigrator;
94 | delete scheduledNewAsset;
95 | }
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/dapp-build.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -e
3 |
4 | export DAPP_SOLC_VERSION=0.8.7
5 | export DAPP_SRC="contracts"
6 | export DAPP_LINK_TEST_LIBRARIES=0
7 | export DAPP_STANDARD_JSON="./dapp-config.json"
8 |
9 | dapp --use solc:0.8.7 build
10 |
--------------------------------------------------------------------------------
/dapp-config.json:
--------------------------------------------------------------------------------
1 | {
2 | "language": "Solidity",
3 | "sources": {
4 | "contracts/xMPL.sol": {
5 | "urls": ["contracts/xMPL.sol"]
6 | }
7 | },
8 | "settings": {
9 | "optimizer": {
10 | "enabled": false
11 | },
12 | "outputSelection": {
13 | "*": {
14 | "*": [
15 | "abi",
16 | "devdoc",
17 | "userdoc",
18 | "metadata"
19 | ]
20 | }
21 | },
22 | "metadata": {
23 | "bytecodeHash": "none"
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/deploy.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -e
3 |
4 | name="xMPL"
5 | MPL="0xAeECBaebEEEEF8F55cb7756019F6f8A80BAB657A" # Rinkeby
6 | contract="./contracts/xMPL.sol:xMPL"
7 | precision=1000000000000000000000000000000
8 |
9 | forge create --rpc-url $ETH_RPC_URL \
10 | --constructor-args $name $name $ETH_FROM $MPL $precision \
11 | --from $ETH_FROM \
12 | $contract
13 |
--------------------------------------------------------------------------------
/flattened/xMPL.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 | pragma solidity 0.8.7;
3 |
4 | /**
5 | * @title xMPL
6 | * @author lucas-manuel, JGCarv, deluca-mike, edag94, vbidin
7 | * @notice This contract contains functionality to facilitate on-chain distribution
8 | * of protocol revenues denominated in MPL tokens. xMPL inherits the core
9 | * functionality from Maple's Revenue Distribution Token, which allows
10 | * users to lock assets to earn rewards distributions based on a vesting
11 | * schedule, with the added functionality to perform a one time asset
12 | * migration of the underlying token.
13 | * @dev This code was deployed at commit 9604d297132503cb05d74f2998c18b07f345ecc0
14 | * (https://github.com/maple-labs/xMPL/releases/tag/v1.0.1).
15 | */
16 |
17 | /// @title Interface of the ERC20 standard as defined in the EIP, including EIP-2612 permit functionality.
18 | interface IERC20 {
19 |
20 | /**************/
21 | /*** Events ***/
22 | /**************/
23 |
24 | /**
25 | * @dev Emitted when one account has set the allowance of another account over their tokens.
26 | * @param owner_ Account that tokens are approved from.
27 | * @param spender_ Account that tokens are approved for.
28 | * @param amount_ Amount of tokens that have been approved.
29 | */
30 | event Approval(address indexed owner_, address indexed spender_, uint256 amount_);
31 |
32 | /**
33 | * @dev Emitted when tokens have moved from one account to another.
34 | * @param owner_ Account that tokens have moved from.
35 | * @param recipient_ Account that tokens have moved to.
36 | * @param amount_ Amount of tokens that have been transferred.
37 | */
38 | event Transfer(address indexed owner_, address indexed recipient_, uint256 amount_);
39 |
40 | /**************************/
41 | /*** External Functions ***/
42 | /**************************/
43 |
44 | /**
45 | * @dev Function that allows one account to set the allowance of another account over their tokens.
46 | * Emits an {Approval} event.
47 | * @param spender_ Account that tokens are approved for.
48 | * @param amount_ Amount of tokens that have been approved.
49 | * @return success_ Boolean indicating whether the operation succeeded.
50 | */
51 | function approve(address spender_, uint256 amount_) external returns (bool success_);
52 |
53 | /**
54 | * @dev Function that allows one account to decrease the allowance of another account over their tokens.
55 | * Emits an {Approval} event.
56 | * @param spender_ Account that tokens are approved for.
57 | * @param subtractedAmount_ Amount to decrease approval by.
58 | * @return success_ Boolean indicating whether the operation succeeded.
59 | */
60 | function decreaseAllowance(address spender_, uint256 subtractedAmount_) external returns (bool success_);
61 |
62 | /**
63 | * @dev Function that allows one account to increase the allowance of another account over their tokens.
64 | * Emits an {Approval} event.
65 | * @param spender_ Account that tokens are approved for.
66 | * @param addedAmount_ Amount to increase approval by.
67 | * @return success_ Boolean indicating whether the operation succeeded.
68 | */
69 | function increaseAllowance(address spender_, uint256 addedAmount_) external returns (bool success_);
70 |
71 | /**
72 | * @dev Approve by signature.
73 | * @param owner_ Owner address that signed the permit.
74 | * @param spender_ Spender of the permit.
75 | * @param amount_ Permit approval spend limit.
76 | * @param deadline_ Deadline after which the permit is invalid.
77 | * @param v_ ECDSA signature v component.
78 | * @param r_ ECDSA signature r component.
79 | * @param s_ ECDSA signature s component.
80 | */
81 | function permit(address owner_, address spender_, uint amount_, uint deadline_, uint8 v_, bytes32 r_, bytes32 s_) external;
82 |
83 | /**
84 | * @dev Moves an amount of tokens from `msg.sender` to a specified account.
85 | * Emits a {Transfer} event.
86 | * @param recipient_ Account that receives tokens.
87 | * @param amount_ Amount of tokens that are transferred.
88 | * @return success_ Boolean indicating whether the operation succeeded.
89 | */
90 | function transfer(address recipient_, uint256 amount_) external returns (bool success_);
91 |
92 | /**
93 | * @dev Moves a pre-approved amount of tokens from a sender to a specified account.
94 | * Emits a {Transfer} event.
95 | * Emits an {Approval} event.
96 | * @param owner_ Account that tokens are moving from.
97 | * @param recipient_ Account that receives tokens.
98 | * @param amount_ Amount of tokens that are transferred.
99 | * @return success_ Boolean indicating whether the operation succeeded.
100 | */
101 | function transferFrom(address owner_, address recipient_, uint256 amount_) external returns (bool success_);
102 |
103 | /**********************/
104 | /*** View Functions ***/
105 | /**********************/
106 |
107 | /**
108 | * @dev Returns the allowance that one account has given another over their tokens.
109 | * @param owner_ Account that tokens are approved from.
110 | * @param spender_ Account that tokens are approved for.
111 | * @return allowance_ Allowance that one account has given another over their tokens.
112 | */
113 | function allowance(address owner_, address spender_) external view returns (uint256 allowance_);
114 |
115 | /**
116 | * @dev Returns the amount of tokens owned by a given account.
117 | * @param account_ Account that owns the tokens.
118 | * @return balance_ Amount of tokens owned by a given account.
119 | */
120 | function balanceOf(address account_) external view returns (uint256 balance_);
121 |
122 | /**
123 | * @dev Returns the decimal precision used by the token.
124 | * @return decimals_ The decimal precision used by the token.
125 | */
126 | function decimals() external view returns (uint8 decimals_);
127 |
128 | /**
129 | * @dev Returns the signature domain separator.
130 | * @return domainSeparator_ The signature domain separator.
131 | */
132 | function DOMAIN_SEPARATOR() external view returns (bytes32 domainSeparator_);
133 |
134 | /**
135 | * @dev Returns the name of the token.
136 | * @return name_ The name of the token.
137 | */
138 | function name() external view returns (string memory name_);
139 |
140 | /**
141 | * @dev Returns the nonce for the given owner.
142 | * @param owner_ The address of the owner account.
143 | * @return nonce_ The nonce for the given owner.
144 | */
145 | function nonces(address owner_) external view returns (uint256 nonce_);
146 |
147 | /**
148 | * @dev Returns the permit type hash.
149 | * @return permitTypehash_ The permit type hash.
150 | */
151 | function PERMIT_TYPEHASH() external view returns (bytes32 permitTypehash_);
152 |
153 | /**
154 | * @dev Returns the symbol of the token.
155 | * @return symbol_ The symbol of the token.
156 | */
157 | function symbol() external view returns (string memory symbol_);
158 |
159 | /**
160 | * @dev Returns the total amount of tokens in existence.
161 | * @return totalSupply_ The total amount of tokens in existence.
162 | */
163 | function totalSupply() external view returns (uint256 totalSupply_);
164 |
165 | }
166 |
167 | /// @title Small Library to standardize ERC20 token interactions.
168 | library ERC20Helper {
169 |
170 | /**************************/
171 | /*** Internal Functions ***/
172 | /**************************/
173 |
174 | function transfer(address token_, address to_, uint256 amount_) internal returns (bool success_) {
175 | return _call(token_, abi.encodeWithSelector(IERC20.transfer.selector, to_, amount_));
176 | }
177 |
178 | function transferFrom(address token_, address from_, address to_, uint256 amount_) internal returns (bool success_) {
179 | return _call(token_, abi.encodeWithSelector(IERC20.transferFrom.selector, from_, to_, amount_));
180 | }
181 |
182 | function approve(address token_, address spender_, uint256 amount_) internal returns (bool success_) {
183 | // If setting approval to zero fails, return false.
184 | if (!_call(token_, abi.encodeWithSelector(IERC20.approve.selector, spender_, uint256(0)))) return false;
185 |
186 | // If `amount_` is zero, return true as the previous step already did this.
187 | if (amount_ == uint256(0)) return true;
188 |
189 | // Return the result of setting the approval to `amount_`.
190 | return _call(token_, abi.encodeWithSelector(IERC20.approve.selector, spender_, amount_));
191 | }
192 |
193 | function _call(address token_, bytes memory data_) private returns (bool success_) {
194 | if (token_.code.length == uint256(0)) return false;
195 |
196 | bytes memory returnData;
197 | ( success_, returnData ) = token_.call(data_);
198 |
199 | return success_ && (returnData.length == uint256(0) || abi.decode(returnData, (bool)));
200 | }
201 |
202 | }
203 |
204 | /// @title Token migrator contract to migrate MPL tokens after a timelock.
205 | contract Migrator {
206 |
207 | address public immutable newToken;
208 | address public immutable oldToken;
209 |
210 | constructor(address oldToken_, address newToken_) {
211 | require(IERC20(newToken_).decimals() == IERC20(oldToken_).decimals(), "M:C:DECIMAL_MISMATCH");
212 |
213 | oldToken = oldToken_;
214 | newToken = newToken_;
215 | }
216 |
217 | function migrate(uint256 amount_) external {
218 | migrate(msg.sender, amount_);
219 | }
220 |
221 | function migrate(address owner_, uint256 amount_) public {
222 | require(amount_ != uint256(0), "M:M:ZERO_AMOUNT");
223 | require(ERC20Helper.transferFrom(oldToken, owner_, address(this), amount_), "M:M:TRANSFER_FROM_FAILED");
224 | require(ERC20Helper.transfer(newToken, owner_, amount_), "M:M:TRANSFER_FAILED");
225 | }
226 |
227 | }
228 |
229 | /*
230 | ███████╗██████╗ ██████╗ ██████╗ ██████╗
231 | ██╔════╝██╔══██╗██╔════╝ ╚════██╗██╔═████╗
232 | █████╗ ██████╔╝██║ █████╔╝██║██╔██║
233 | ██╔══╝ ██╔══██╗██║ ██╔═══╝ ████╔╝██║
234 | ███████╗██║ ██║╚██████╗ ███████╗╚██████╔╝
235 | ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═════╝
236 | */
237 |
238 | /**
239 | * @title Modern ERC-20 implementation.
240 | * @dev Acknowledgements to Solmate, OpenZeppelin, and DSS for inspiring this code.
241 | */
242 | contract ERC20 is IERC20 {
243 |
244 | /**************/
245 | /*** ERC-20 ***/
246 | /**************/
247 |
248 | string public override name;
249 | string public override symbol;
250 |
251 | uint8 public immutable override decimals;
252 |
253 | uint256 public override totalSupply;
254 |
255 | mapping(address => uint256) public override balanceOf;
256 |
257 | mapping(address => mapping(address => uint256)) public override allowance;
258 |
259 | /****************/
260 | /*** ERC-2612 ***/
261 | /****************/
262 |
263 | // PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
264 | bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
265 |
266 | mapping(address => uint256) public override nonces;
267 |
268 | /**
269 | * @param name_ The name of the token.
270 | * @param symbol_ The symbol of the token.
271 | * @param decimals_ The decimal precision used by the token.
272 | */
273 | constructor(string memory name_, string memory symbol_, uint8 decimals_) {
274 | name = name_;
275 | symbol = symbol_;
276 | decimals = decimals_;
277 | }
278 |
279 | /**************************/
280 | /*** External Functions ***/
281 | /**************************/
282 |
283 | function approve(address spender_, uint256 amount_) external override returns (bool success_) {
284 | _approve(msg.sender, spender_, amount_);
285 | return true;
286 | }
287 |
288 | function decreaseAllowance(address spender_, uint256 subtractedAmount_) external override returns (bool success_) {
289 | _decreaseAllowance(msg.sender, spender_, subtractedAmount_);
290 | return true;
291 | }
292 |
293 | function increaseAllowance(address spender_, uint256 addedAmount_) external override returns (bool success_) {
294 | _approve(msg.sender, spender_, allowance[msg.sender][spender_] + addedAmount_);
295 | return true;
296 | }
297 |
298 | function permit(address owner_, address spender_, uint256 amount_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_) external override {
299 | require(deadline_ >= block.timestamp, "ERC20:P:EXPIRED");
300 |
301 | // Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
302 | // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}.
303 | require(
304 | uint256(s_) <= uint256(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) &&
305 | (v_ == 27 || v_ == 28),
306 | "ERC20:P:MALLEABLE"
307 | );
308 |
309 | // Nonce realistically cannot overflow.
310 | unchecked {
311 | bytes32 digest = keccak256(
312 | abi.encodePacked(
313 | "\x19\x01",
314 | DOMAIN_SEPARATOR(),
315 | keccak256(abi.encode(PERMIT_TYPEHASH, owner_, spender_, amount_, nonces[owner_]++, deadline_))
316 | )
317 | );
318 |
319 | address recoveredAddress = ecrecover(digest, v_, r_, s_);
320 |
321 | require(recoveredAddress == owner_ && owner_ != address(0), "ERC20:P:INVALID_SIGNATURE");
322 | }
323 |
324 | _approve(owner_, spender_, amount_);
325 | }
326 |
327 | function transfer(address recipient_, uint256 amount_) external override returns (bool success_) {
328 | _transfer(msg.sender, recipient_, amount_);
329 | return true;
330 | }
331 |
332 | function transferFrom(address owner_, address recipient_, uint256 amount_) external override returns (bool success_) {
333 | _decreaseAllowance(owner_, msg.sender, amount_);
334 | _transfer(owner_, recipient_, amount_);
335 | return true;
336 | }
337 |
338 | /**********************/
339 | /*** View Functions ***/
340 | /**********************/
341 |
342 | function DOMAIN_SEPARATOR() public view override returns (bytes32 domainSeparator_) {
343 | return keccak256(
344 | abi.encode(
345 | keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
346 | keccak256(bytes(name)),
347 | keccak256(bytes("1")),
348 | block.chainid,
349 | address(this)
350 | )
351 | );
352 | }
353 |
354 | /**************************/
355 | /*** Internal Functions ***/
356 | /**************************/
357 |
358 | function _approve(address owner_, address spender_, uint256 amount_) internal {
359 | emit Approval(owner_, spender_, allowance[owner_][spender_] = amount_);
360 | }
361 |
362 | function _burn(address owner_, uint256 amount_) internal {
363 | balanceOf[owner_] -= amount_;
364 |
365 | // Cannot underflow because a user's balance will never be larger than the total supply.
366 | unchecked { totalSupply -= amount_; }
367 |
368 | emit Transfer(owner_, address(0), amount_);
369 | }
370 |
371 | function _decreaseAllowance(address owner_, address spender_, uint256 subtractedAmount_) internal {
372 | uint256 spenderAllowance = allowance[owner_][spender_]; // Cache to memory.
373 |
374 | if (spenderAllowance != type(uint256).max) {
375 | _approve(owner_, spender_, spenderAllowance - subtractedAmount_);
376 | }
377 | }
378 |
379 | function _mint(address recipient_, uint256 amount_) internal {
380 | totalSupply += amount_;
381 |
382 | // Cannot overflow because totalSupply would first overflow in the statement above.
383 | unchecked { balanceOf[recipient_] += amount_; }
384 |
385 | emit Transfer(address(0), recipient_, amount_);
386 | }
387 |
388 | function _transfer(address owner_, address recipient_, uint256 amount_) internal {
389 | balanceOf[owner_] -= amount_;
390 |
391 | // Cannot overflow because minting prevents overflow of totalSupply, and sum of user balances == totalSupply.
392 | unchecked { balanceOf[recipient_] += amount_; }
393 |
394 | emit Transfer(owner_, recipient_, amount_);
395 | }
396 |
397 | }
398 |
399 | /// @title A standard for tokenized Vaults with a single underlying ERC-20 token.
400 | interface IERC4626 is IERC20 {
401 |
402 | /**************/
403 | /*** Events ***/
404 | /**************/
405 |
406 | /**
407 | * @dev `caller_` has exchanged `assets_` for `shares_` and transferred them to `owner_`.
408 | * MUST be emitted when assets are deposited via the `deposit` or `mint` methods.
409 | * @param caller_ The caller of the function that emitted the `Deposit` event.
410 | * @param owner_ The owner of the shares.
411 | * @param assets_ The amount of assets deposited.
412 | * @param shares_ The amount of shares minted.
413 | */
414 | event Deposit(address indexed caller_, address indexed owner_, uint256 assets_, uint256 shares_);
415 |
416 | /**
417 | * @dev `caller_` has exchanged `shares_`, owned by `owner_`, for `assets_`, and transferred them to `receiver_`.
418 | * MUST be emitted when assets are withdrawn via the `withdraw` or `redeem` methods.
419 | * @param caller_ The caller of the function that emitted the `Withdraw` event.
420 | * @param receiver_ The receiver of the assets.
421 | * @param owner_ The owner of the shares.
422 | * @param assets_ The amount of assets withdrawn.
423 | * @param shares_ The amount of shares burned.
424 | */
425 | event Withdraw(address indexed caller_, address indexed receiver_, address indexed owner_, uint256 assets_, uint256 shares_);
426 |
427 | /***********************/
428 | /*** State Variables ***/
429 | /***********************/
430 |
431 | /**
432 | * @dev The address of the underlying asset used by the Vault.
433 | * MUST be a contract that implements the ERC-20 standard.
434 | * MUST NOT revert.
435 | * @return asset_ The address of the underlying asset.
436 | */
437 | function asset() external view returns (address asset_);
438 |
439 | /********************************/
440 | /*** State Changing Functions ***/
441 | /********************************/
442 |
443 | /**
444 | * @dev Mints `shares_` to `receiver_` by depositing `assets_` into the Vault.
445 | * MUST emit the {Deposit} event.
446 | * MUST revert if all of the assets cannot be deposited (due to insufficient approval, deposit limits, slippage, etc).
447 | * @param assets_ The amount of assets to deposit.
448 | * @param receiver_ The receiver of the shares.
449 | * @return shares_ The amount of shares minted.
450 | */
451 | function deposit(uint256 assets_, address receiver_) external returns (uint256 shares_);
452 |
453 | /**
454 | * @dev Mints `shares_` to `receiver_` by depositing `assets_` into the Vault.
455 | * MUST emit the {Deposit} event.
456 | * MUST revert if all of shares cannot be minted (due to insufficient approval, deposit limits, slippage, etc).
457 | * @param shares_ The amount of shares to mint.
458 | * @param receiver_ The receiver of the shares.
459 | * @return assets_ The amount of assets deposited.
460 | */
461 | function mint(uint256 shares_, address receiver_) external returns (uint256 assets_);
462 |
463 | /**
464 | * @dev Burns `shares_` from `owner_` and sends `assets_` to `receiver_`.
465 | * MUST emit the {Withdraw} event.
466 | * MUST revert if all of the shares cannot be redeemed (due to insufficient shares, withdrawal limits, slippage, etc).
467 | * @param shares_ The amount of shares to redeem.
468 | * @param receiver_ The receiver of the assets.
469 | * @param owner_ The owner of the shares.
470 | * @return assets_ The amount of assets sent to the receiver.
471 | */
472 | function redeem(uint256 shares_, address receiver_, address owner_) external returns (uint256 assets_);
473 |
474 | /**
475 | * @dev Burns `shares_` from `owner_` and sends `assets_` to `receiver_`.
476 | * MUST emit the {Withdraw} event.
477 | * MUST revert if all of the assets cannot be withdrawn (due to insufficient assets, withdrawal limits, slippage, etc).
478 | * @param assets_ The amount of assets to withdraw.
479 | * @param receiver_ The receiver of the assets.
480 | * @param owner_ The owner of the assets.
481 | * @return shares_ The amount of shares burned from the owner.
482 | */
483 | function withdraw(uint256 assets_, address receiver_, address owner_) external returns (uint256 shares_);
484 |
485 | /**********************/
486 | /*** View Functions ***/
487 | /**********************/
488 |
489 | /**
490 | * @dev The amount of `assets_` the `shares_` are currently equivalent to.
491 | * MUST NOT be inclusive of any fees that are charged against assets in the Vault.
492 | * MUST NOT reflect slippage or other on-chain conditions when performing the actual exchange.
493 | * MUST NOT show any variations depending on the caller.
494 | * MUST NOT revert.
495 | * @param shares_ The amount of shares to convert.
496 | * @return assets_ The amount of equivalent assets.
497 | */
498 | function convertToAssets(uint256 shares_) external view returns (uint256 assets_);
499 |
500 | /**
501 | * @dev The amount of `shares_` the `assets_` are currently equivalent to.
502 | * MUST NOT be inclusive of any fees that are charged against assets in the Vault.
503 | * MUST NOT reflect slippage or other on-chain conditions when performing the actual exchange.
504 | * MUST NOT show any variations depending on the caller.
505 | * MUST NOT revert.
506 | * @param assets_ The amount of assets to convert.
507 | * @return shares_ The amount of equivalent shares.
508 | */
509 | function convertToShares(uint256 assets_) external view returns (uint256 shares_);
510 |
511 | /**
512 | * @dev Maximum amount of `assets_` that can be deposited on behalf of the `receiver_` through a `deposit` call.
513 | * MUST return a limited value if the receiver is subject to any limits, or the maximum value otherwise.
514 | * MUST NOT revert.
515 | * @param receiver_ The receiver of the assets.
516 | * @return assets_ The maximum amount of assets that can be deposited.
517 | */
518 | function maxDeposit(address receiver_) external view returns (uint256 assets_);
519 |
520 | /**
521 | * @dev Maximum amount of `shares_` that can be minted on behalf of the `receiver_` through a `mint` call.
522 | * MUST return a limited value if the receiver is subject to any limits, or the maximum value otherwise.
523 | * MUST NOT revert.
524 | * @param receiver_ The receiver of the shares.
525 | * @return shares_ The maximum amount of shares that can be minted.
526 | */
527 | function maxMint(address receiver_) external view returns (uint256 shares_);
528 |
529 | /**
530 | * @dev Maximum amount of `shares_` that can be redeemed from the `owner_` through a `redeem` call.
531 | * MUST return a limited value if the owner is subject to any limits, or the total amount of owned shares otherwise.
532 | * MUST NOT revert.
533 | * @param owner_ The owner of the shares.
534 | * @return shares_ The maximum amount of shares that can be redeemed.
535 | */
536 | function maxRedeem(address owner_) external view returns (uint256 shares_);
537 |
538 | /**
539 | * @dev Maximum amount of `assets_` that can be withdrawn from the `owner_` through a `withdraw` call.
540 | * MUST return a limited value if the owner is subject to any limits, or the total amount of owned assets otherwise.
541 | * MUST NOT revert.
542 | * @param owner_ The owner of the assets.
543 | * @return assets_ The maximum amount of assets that can be withdrawn.
544 | */
545 | function maxWithdraw(address owner_) external view returns (uint256 assets_);
546 |
547 | /**
548 | * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.
549 | * MUST return as close to and no more than the exact amount of shares that would be minted in a `deposit` call in the same transaction.
550 | * MUST NOT account for deposit limits like those returned from `maxDeposit` and should always act as though the deposit would be accepted.
551 | * MUST NOT revert.
552 | * @param assets_ The amount of assets to deposit.
553 | * @return shares_ The amount of shares that would be minted.
554 | */
555 | function previewDeposit(uint256 assets_) external view returns (uint256 shares_);
556 |
557 | /**
558 | * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions.
559 | * MUST return as close to and no fewer than the exact amount of assets that would be deposited in a `mint` call in the same transaction.
560 | * MUST NOT account for mint limits like those returned from `maxMint` and should always act as though the minting would be accepted.
561 | * MUST NOT revert.
562 | * @param shares_ The amount of shares to mint.
563 | * @return assets_ The amount of assets that would be deposited.
564 | */
565 | function previewMint(uint256 shares_) external view returns (uint256 assets_);
566 |
567 | /**
568 | * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block, given current on-chain conditions.
569 | * MUST return as close to and no more than the exact amount of assets that would be withdrawn in a `redeem` call in the same transaction.
570 | * MUST NOT account for redemption limits like those returned from `maxRedeem` and should always act as though the redemption would be accepted.
571 | * MUST NOT revert.
572 | * @param shares_ The amount of shares to redeem.
573 | * @return assets_ The amount of assets that would be withdrawn.
574 | */
575 | function previewRedeem(uint256 shares_) external view returns (uint256 assets_);
576 |
577 | /**
578 | * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.
579 | * MUST return as close to and no fewer than the exact amount of shares that would be burned in a `withdraw` call in the same transaction.
580 | * MUST NOT account for withdrawal limits like those returned from `maxWithdraw` and should always act as though the withdrawal would be accepted.
581 | * MUST NOT revert.
582 | * @param assets_ The amount of assets to withdraw.
583 | * @return shares_ The amount of shares that would be redeemed.
584 | */
585 | function previewWithdraw(uint256 assets_) external view returns (uint256 shares_);
586 |
587 | /**
588 | * @dev Total amount of the underlying asset that is managed by the Vault.
589 | * SHOULD include compounding that occurs from any yields.
590 | * MUST NOT revert.
591 | * @return totalAssets_ The total amount of assets the Vault manages.
592 | */
593 | function totalAssets() external view returns (uint256 totalAssets_);
594 |
595 | }
596 |
597 | /// @title A token that represents ownership of future revenues distributed linearly over time.
598 | interface IRevenueDistributionToken is IERC20, IERC4626 {
599 |
600 | /**************/
601 | /*** Events ***/
602 | /**************/
603 |
604 | /**
605 | * @dev Issuance parameters have been updated after a `_mint` or `_burn`.
606 | * @param freeAssets_ Resulting `freeAssets` (y-intercept) value after accounting update.
607 | * @param issuanceRate_ The new issuance rate of `asset` until `vestingPeriodFinish_`.
608 | */
609 | event IssuanceParamsUpdated(uint256 freeAssets_, uint256 issuanceRate_);
610 |
611 | /**
612 | * @dev `newOwner_` has accepted the transferral of RDT ownership from `previousOwner_`.
613 | * @param previousOwner_ The previous RDT owner.
614 | * @param newOwner_ The new RDT owner.
615 | */
616 | event OwnershipAccepted(address indexed previousOwner_, address indexed newOwner_);
617 |
618 | /**
619 | * @dev `owner_` has set the new pending owner of RDT to `pendingOwner_`.
620 | * @param owner_ The current RDT owner.
621 | * @param pendingOwner_ The new pending RDT owner.
622 | */
623 | event PendingOwnerSet(address indexed owner_, address indexed pendingOwner_);
624 |
625 | /**
626 | * @dev `owner_` has updated the RDT vesting schedule to end at `vestingPeriodFinish_`.
627 | * @param owner_ The current RDT owner.
628 | * @param vestingPeriodFinish_ When the unvested balance will finish vesting.
629 | */
630 | event VestingScheduleUpdated(address indexed owner_, uint256 vestingPeriodFinish_);
631 |
632 | /***********************/
633 | /*** State Variables ***/
634 | /***********************/
635 |
636 | /**
637 | * @dev The total amount of the underlying asset that is currently unlocked and is not time-dependent.
638 | * Analogous to the y-intercept in a linear function.
639 | */
640 | function freeAssets() external view returns (uint256 freeAssets_);
641 |
642 | /**
643 | * @dev The rate of issuance of the vesting schedule that is currently active.
644 | * Denominated as the amount of underlying assets vesting per second.
645 | */
646 | function issuanceRate() external view returns (uint256 issuanceRate_);
647 |
648 | /**
649 | * @dev The timestamp of when the linear function was last recalculated.
650 | * Analogous to t0 in a linear function.
651 | */
652 | function lastUpdated() external view returns (uint256 lastUpdated_);
653 |
654 | /**
655 | * @dev The address of the account that is allowed to update the vesting schedule.
656 | */
657 | function owner() external view returns (address owner_);
658 |
659 | /**
660 | * @dev The next owner, nominated by the current owner.
661 | */
662 | function pendingOwner() external view returns (address pendingOwner_);
663 |
664 | /**
665 | * @dev The precision at which the issuance rate is measured.
666 | */
667 | function precision() external view returns (uint256 precision_);
668 |
669 | /**
670 | * @dev The end of the current vesting schedule.
671 | */
672 | function vestingPeriodFinish() external view returns (uint256 vestingPeriodFinish_);
673 |
674 | /********************************/
675 | /*** Administrative Functions ***/
676 | /********************************/
677 |
678 | /**
679 | * @dev Sets the pending owner as the new owner.
680 | * Can be called only by the pending owner, and only after their nomination by the current owner.
681 | */
682 | function acceptOwnership() external;
683 |
684 | /**
685 | * @dev Sets a new address as the pending owner.
686 | * @param pendingOwner_ The address of the next potential owner.
687 | */
688 | function setPendingOwner(address pendingOwner_) external;
689 |
690 | /**
691 | * @dev Updates the current vesting formula based on the amount of total unvested funds in the contract and the new `vestingPeriod_`.
692 | * @param vestingPeriod_ The amount of time over which all currently unaccounted underlying assets will be vested over.
693 | * @return issuanceRate_ The new issuance rate.
694 | * @return freeAssets_ The new amount of underlying assets that are unlocked.
695 | */
696 | function updateVestingSchedule(uint256 vestingPeriod_) external returns (uint256 issuanceRate_, uint256 freeAssets_);
697 |
698 | /************************/
699 | /*** Staker Functions ***/
700 | /************************/
701 |
702 | /**
703 | * @dev Does a ERC4626 `deposit` with a ERC-2612 `permit`.
704 | * @param assets_ The amount of `asset` to deposit.
705 | * @param receiver_ The receiver of the shares.
706 | * @param deadline_ The timestamp after which the `permit` signature is no longer valid.
707 | * @param v_ ECDSA signature v component.
708 | * @param r_ ECDSA signature r component.
709 | * @param s_ ECDSA signature s component.
710 | * @return shares_ The amount of shares minted.
711 | */
712 | function depositWithPermit(uint256 assets_, address receiver_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_) external returns (uint256 shares_);
713 |
714 | /**
715 | * @dev Does a ERC4626 `mint` with a ERC-2612 `permit`.
716 | * @param shares_ The amount of `shares` to mint.
717 | * @param receiver_ The receiver of the shares.
718 | * @param maxAssets_ The maximum amount of assets that can be taken, as per the permit.
719 | * @param deadline_ The timestamp after which the `permit` signature is no longer valid.
720 | * @param v_ ECDSA signature v component.
721 | * @param r_ ECDSA signature r component.
722 | * @param s_ ECDSA signature s component.
723 | * @return assets_ The amount of shares deposited.
724 | */
725 | function mintWithPermit(uint256 shares_, address receiver_, uint256 maxAssets_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_) external returns (uint256 assets_);
726 |
727 | /**********************/
728 | /*** View Functions ***/
729 | /**********************/
730 |
731 | /**
732 | * @dev Returns the amount of underlying assets owned by the specified account.
733 | * @param account_ Address of the account.
734 | * @return assets_ Amount of assets owned.
735 | */
736 | function balanceOfAssets(address account_) external view returns (uint256 assets_);
737 |
738 | }
739 |
740 | /*
741 | ██████╗ ██████╗ ████████╗
742 | ██╔══██╗██╔══██╗╚══██╔══╝
743 | ██████╔╝██║ ██║ ██║
744 | ██╔══██╗██║ ██║ ██║
745 | ██║ ██║██████╔╝ ██║
746 | ╚═╝ ╚═╝╚═════╝ ╚═╝
747 | */
748 |
749 | /// @title A token that represents ownership of future revenues distributed linearly over time.
750 | contract RevenueDistributionToken is IRevenueDistributionToken, ERC20 {
751 |
752 | uint256 public immutable override precision; // Precision of rates, equals max deposit amounts before rounding errors occur
753 |
754 | address public override asset; // Underlying ERC-20 asset used by ERC-4626 functionality.
755 |
756 | address public override owner; // Current owner of the contract, able to update the vesting schedule.
757 | address public override pendingOwner; // Pending owner of the contract, able to accept ownership.
758 |
759 | uint256 public override freeAssets; // Amount of assets unlocked regardless of time passed.
760 | uint256 public override issuanceRate; // asset/second rate dependent on aggregate vesting schedule.
761 | uint256 public override lastUpdated; // Timestamp of when issuance equation was last updated.
762 | uint256 public override vestingPeriodFinish; // Timestamp when current vesting schedule ends.
763 |
764 | uint256 private locked = 1; // Used in reentrancy check.
765 |
766 | /*****************/
767 | /*** Modifiers ***/
768 | /*****************/
769 |
770 | modifier nonReentrant() {
771 | require(locked == 1, "RDT:LOCKED");
772 |
773 | locked = 2;
774 |
775 | _;
776 |
777 | locked = 1;
778 | }
779 |
780 | constructor(string memory name_, string memory symbol_, address owner_, address asset_, uint256 precision_)
781 | ERC20(name_, symbol_, ERC20(asset_).decimals())
782 | {
783 | require((owner = owner_) != address(0), "RDT:C:OWNER_ZERO_ADDRESS");
784 |
785 | asset = asset_; // Don't need to check zero address as ERC20(asset_).decimals() will fail in ERC20 constructor.
786 | precision = precision_;
787 | }
788 |
789 | /********************************/
790 | /*** Administrative Functions ***/
791 | /********************************/
792 |
793 | function acceptOwnership() external virtual override {
794 | require(msg.sender == pendingOwner, "RDT:AO:NOT_PO");
795 |
796 | emit OwnershipAccepted(owner, msg.sender);
797 |
798 | owner = msg.sender;
799 | pendingOwner = address(0);
800 | }
801 |
802 | function setPendingOwner(address pendingOwner_) external virtual override {
803 | require(msg.sender == owner, "RDT:SPO:NOT_OWNER");
804 |
805 | pendingOwner = pendingOwner_;
806 |
807 | emit PendingOwnerSet(msg.sender, pendingOwner_);
808 | }
809 |
810 | function updateVestingSchedule(uint256 vestingPeriod_) external virtual override returns (uint256 issuanceRate_, uint256 freeAssets_) {
811 | require(msg.sender == owner, "RDT:UVS:NOT_OWNER");
812 | require(totalSupply != 0, "RDT:UVS:ZERO_SUPPLY");
813 |
814 | // Update "y-intercept" to reflect current available asset.
815 | freeAssets_ = freeAssets = totalAssets();
816 |
817 | // Calculate slope.
818 | issuanceRate_ = issuanceRate = ((ERC20(asset).balanceOf(address(this)) - freeAssets_) * precision) / vestingPeriod_;
819 |
820 | // Update timestamp and period finish.
821 | vestingPeriodFinish = (lastUpdated = block.timestamp) + vestingPeriod_;
822 |
823 | emit IssuanceParamsUpdated(freeAssets_, issuanceRate_);
824 | emit VestingScheduleUpdated(msg.sender, vestingPeriodFinish);
825 | }
826 |
827 | /************************/
828 | /*** Staker Functions ***/
829 | /************************/
830 |
831 | function deposit(uint256 assets_, address receiver_) external virtual override nonReentrant returns (uint256 shares_) {
832 | _mint(shares_ = previewDeposit(assets_), assets_, receiver_, msg.sender);
833 | }
834 |
835 | function depositWithPermit(
836 | uint256 assets_,
837 | address receiver_,
838 | uint256 deadline_,
839 | uint8 v_,
840 | bytes32 r_,
841 | bytes32 s_
842 | )
843 | external virtual override nonReentrant returns (uint256 shares_)
844 | {
845 | ERC20(asset).permit(msg.sender, address(this), assets_, deadline_, v_, r_, s_);
846 | _mint(shares_ = previewDeposit(assets_), assets_, receiver_, msg.sender);
847 | }
848 |
849 | function mint(uint256 shares_, address receiver_) external virtual override nonReentrant returns (uint256 assets_) {
850 | _mint(shares_, assets_ = previewMint(shares_), receiver_, msg.sender);
851 | }
852 |
853 | function mintWithPermit(
854 | uint256 shares_,
855 | address receiver_,
856 | uint256 maxAssets_,
857 | uint256 deadline_,
858 | uint8 v_,
859 | bytes32 r_,
860 | bytes32 s_
861 | )
862 | external virtual override nonReentrant returns (uint256 assets_)
863 | {
864 | require((assets_ = previewMint(shares_)) <= maxAssets_, "RDT:MWP:INSUFFICIENT_PERMIT");
865 |
866 | ERC20(asset).permit(msg.sender, address(this), maxAssets_, deadline_, v_, r_, s_);
867 | _mint(shares_, assets_, receiver_, msg.sender);
868 | }
869 |
870 | function redeem(uint256 shares_, address receiver_, address owner_) external virtual override nonReentrant returns (uint256 assets_) {
871 | _burn(shares_, assets_ = previewRedeem(shares_), receiver_, owner_, msg.sender);
872 | }
873 |
874 | function withdraw(uint256 assets_, address receiver_, address owner_) external virtual override nonReentrant returns (uint256 shares_) {
875 | _burn(shares_ = previewWithdraw(assets_), assets_, receiver_, owner_, msg.sender);
876 | }
877 |
878 | /**************************/
879 | /*** Internal Functions ***/
880 | /**************************/
881 |
882 | function _mint(uint256 shares_, uint256 assets_, address receiver_, address caller_) internal {
883 | require(receiver_ != address(0), "RDT:M:ZERO_RECEIVER");
884 | require(shares_ != uint256(0), "RDT:M:ZERO_SHARES");
885 | require(assets_ != uint256(0), "RDT:M:ZERO_ASSETS");
886 |
887 | _mint(receiver_, shares_);
888 |
889 | uint256 freeAssetsCache = freeAssets = totalAssets() + assets_;
890 |
891 | uint256 issuanceRate_ = _updateIssuanceParams();
892 |
893 | emit Deposit(caller_, receiver_, assets_, shares_);
894 | emit IssuanceParamsUpdated(freeAssetsCache, issuanceRate_);
895 |
896 | require(ERC20Helper.transferFrom(asset, caller_, address(this), assets_), "RDT:M:TRANSFER_FROM");
897 | }
898 |
899 | function _burn(uint256 shares_, uint256 assets_, address receiver_, address owner_, address caller_) internal {
900 | require(receiver_ != address(0), "RDT:B:ZERO_RECEIVER");
901 | require(shares_ != uint256(0), "RDT:B:ZERO_SHARES");
902 | require(assets_ != uint256(0), "RDT:B:ZERO_ASSETS");
903 |
904 | if (caller_ != owner_) {
905 | _decreaseAllowance(owner_, caller_, shares_);
906 | }
907 |
908 | _burn(owner_, shares_);
909 |
910 | uint256 freeAssetsCache = freeAssets = totalAssets() - assets_;
911 |
912 | uint256 issuanceRate_ = _updateIssuanceParams();
913 |
914 | emit Withdraw(caller_, receiver_, owner_, assets_, shares_);
915 | emit IssuanceParamsUpdated(freeAssetsCache, issuanceRate_);
916 |
917 | require(ERC20Helper.transfer(asset, receiver_, assets_), "RDT:B:TRANSFER");
918 | }
919 |
920 | function _updateIssuanceParams() internal returns (uint256 issuanceRate_) {
921 | return issuanceRate = (lastUpdated = block.timestamp) > vestingPeriodFinish ? 0 : issuanceRate;
922 | }
923 |
924 | /**********************/
925 | /*** View Functions ***/
926 | /**********************/
927 |
928 | function balanceOfAssets(address account_) public view virtual override returns (uint256 balanceOfAssets_) {
929 | return convertToAssets(balanceOf[account_]);
930 | }
931 |
932 | function convertToAssets(uint256 shares_) public view virtual override returns (uint256 assets_) {
933 | uint256 supply = totalSupply; // Cache to stack.
934 |
935 | assets_ = supply == 0 ? shares_ : (shares_ * totalAssets()) / supply;
936 | }
937 |
938 | function convertToShares(uint256 assets_) public view virtual override returns (uint256 shares_) {
939 | uint256 supply = totalSupply; // Cache to stack.
940 |
941 | shares_ = supply == 0 ? assets_ : (assets_ * supply) / totalAssets();
942 | }
943 |
944 | function maxDeposit(address receiver_) external pure virtual override returns (uint256 maxAssets_) {
945 | receiver_; // Silence warning
946 | maxAssets_ = type(uint256).max;
947 | }
948 |
949 | function maxMint(address receiver_) external pure virtual override returns (uint256 maxShares_) {
950 | receiver_; // Silence warning
951 | maxShares_ = type(uint256).max;
952 | }
953 |
954 | function maxRedeem(address owner_) external view virtual override returns (uint256 maxShares_) {
955 | maxShares_ = balanceOf[owner_];
956 | }
957 |
958 | function maxWithdraw(address owner_) external view virtual override returns (uint256 maxAssets_) {
959 | maxAssets_ = balanceOfAssets(owner_);
960 | }
961 |
962 | function previewDeposit(uint256 assets_) public view virtual override returns (uint256 shares_) {
963 | // As per https://eips.ethereum.org/EIPS/eip-4626#security-considerations,
964 | // it should round DOWN if it’s calculating the amount of shares to issue to a user, given an amount of assets provided.
965 | shares_ = convertToShares(assets_);
966 | }
967 |
968 | function previewMint(uint256 shares_) public view virtual override returns (uint256 assets_) {
969 | uint256 supply = totalSupply; // Cache to stack.
970 |
971 | // As per https://eips.ethereum.org/EIPS/eip-4626#security-considerations,
972 | // it should round UP if it’s calculating the amount of assets a user must provide, to be issued a given amount of shares.
973 | assets_ = supply == 0 ? shares_ : _divRoundUp(shares_ * totalAssets(), supply);
974 | }
975 |
976 | function previewRedeem(uint256 shares_) public view virtual override returns (uint256 assets_) {
977 | // As per https://eips.ethereum.org/EIPS/eip-4626#security-considerations,
978 | // it should round DOWN if it’s calculating the amount of assets to send to a user, given amount of shares returned.
979 | assets_ = convertToAssets(shares_);
980 | }
981 |
982 | function previewWithdraw(uint256 assets_) public view virtual override returns (uint256 shares_) {
983 | uint256 supply = totalSupply; // Cache to stack.
984 |
985 | // As per https://eips.ethereum.org/EIPS/eip-4626#security-considerations,
986 | // it should round UP if it’s calculating the amount of shares a user must return, to be sent a given amount of assets.
987 | shares_ = supply == 0 ? assets_ : _divRoundUp(assets_ * supply, totalAssets());
988 | }
989 |
990 | function totalAssets() public view virtual override returns (uint256 totalManagedAssets_) {
991 | uint256 issuanceRate_ = issuanceRate;
992 |
993 | if (issuanceRate_ == 0) return freeAssets;
994 |
995 | uint256 vestingPeriodFinish_ = vestingPeriodFinish;
996 | uint256 lastUpdated_ = lastUpdated;
997 |
998 | uint256 vestingTimePassed =
999 | block.timestamp > vestingPeriodFinish_ ?
1000 | vestingPeriodFinish_ - lastUpdated_ :
1001 | block.timestamp - lastUpdated_;
1002 |
1003 | return ((issuanceRate_ * vestingTimePassed) / precision) + freeAssets;
1004 | }
1005 |
1006 | /**************************/
1007 | /*** Internal Functions ***/
1008 | /**************************/
1009 |
1010 | function _divRoundUp(uint256 numerator_, uint256 divisor_) internal pure returns (uint256 result_) {
1011 | return (numerator_ / divisor_) + (numerator_ % divisor_ > 0 ? 1 : 0);
1012 | }
1013 |
1014 | }
1015 |
1016 | /// @title A token that represents ownership of future MPL-denominated revenues distributed linearly over time.
1017 | interface IxMPL is IRevenueDistributionToken {
1018 |
1019 | /**************/
1020 | /*** Events ***/
1021 | /**************/
1022 |
1023 | /**
1024 | * @dev Notifies that a scheduled migration was cancelled.
1025 | */
1026 | event MigrationCancelled();
1027 |
1028 | /**
1029 | * @dev Notifies that a scheduled migration was executed.
1030 | * @param fromAsset_ The address of the old asset.
1031 | * @param toAsset_ The address of new asset migrated to.
1032 | * @param amount_ The amount of tokens migrated.
1033 | */
1034 | event MigrationPerformed(address indexed fromAsset_, address indexed toAsset_, uint256 amount_);
1035 |
1036 | /**
1037 | * @dev Notifies that migration was scheduled.
1038 | * @param fromAsset_ The current asset address.
1039 | * @param toAsset_ The address of the asset to be migrated to.
1040 | * @param migrator_ The address of the migrator contract.
1041 | * @param migrationTime_ The earliest time the migration is scheduled for.
1042 | */
1043 | event MigrationScheduled(address indexed fromAsset_, address indexed toAsset_, address indexed migrator_, uint256 migrationTime_);
1044 |
1045 | /********************************/
1046 | /*** Administrative Functions ***/
1047 | /********************************/
1048 |
1049 | /**
1050 | * @dev Cancel the scheduled migration
1051 | */
1052 | function cancelMigration() external;
1053 |
1054 | /**
1055 | * @dev Perform a migration of the asset.
1056 | */
1057 | function performMigration() external;
1058 |
1059 | /**
1060 | * @dev Schedule a migration to be executed after a delay.
1061 | * @param migrator_ The address of the migrator contract.
1062 | * @param newAsset_ The address of the new asset token.
1063 | */
1064 | function scheduleMigration(address migrator_, address newAsset_) external;
1065 |
1066 | /**********************/
1067 | /*** View Functions ***/
1068 | /**********************/
1069 |
1070 | /**
1071 | * @dev Get the minimum delay that a scheduled transaction needs in order to be executed.
1072 | * @return minimumMigrationDelay_ The delay in seconds.
1073 | */
1074 | function MINIMUM_MIGRATION_DELAY() external pure returns (uint256 minimumMigrationDelay_);
1075 |
1076 | /**
1077 | * @dev Get the timestamp that a migration is scheduled for.
1078 | * @return scheduledMigrationTimestamp_ The timestamp of the migration.
1079 | */
1080 | function scheduledMigrationTimestamp() external view returns (uint256 scheduledMigrationTimestamp_);
1081 |
1082 | /**
1083 | * @dev The address of the migrator contract to be used during the scheduled migration.
1084 | * @return scheduledMigrator_ The address of the migrator.
1085 | */
1086 | function scheduledMigrator() external view returns (address scheduledMigrator_);
1087 |
1088 | /**
1089 | * @dev The address of the new asset token to be migrated to during the scheduled migration.
1090 | * @return scheduledNewAsset_ The address of the new asset token.
1091 | */
1092 | function scheduledNewAsset() external view returns (address scheduledNewAsset_);
1093 |
1094 | }
1095 |
1096 | /*
1097 | ██╗ ██╗███╗ ███╗██████╗ ██╗
1098 | ╚██╗██╔╝████╗ ████║██╔══██╗██║
1099 | ╚███╔╝ ██╔████╔██║██████╔╝██║
1100 | ██╔██╗ ██║╚██╔╝██║██╔═══╝ ██║
1101 | ██╔╝ ██╗██║ ╚═╝ ██║██║ ███████╗
1102 | ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚══════╝
1103 | */
1104 |
1105 | /// @title A token that represents ownership of future MPL-denominated revenues distributed linearly over time.
1106 | contract xMPL is IxMPL, RevenueDistributionToken {
1107 |
1108 | uint256 public constant override MINIMUM_MIGRATION_DELAY = 10 days;
1109 |
1110 | address public override scheduledMigrator;
1111 | address public override scheduledNewAsset;
1112 |
1113 | uint256 public override scheduledMigrationTimestamp;
1114 |
1115 | constructor(string memory name_, string memory symbol_, address owner_, address asset_, uint256 precision_)
1116 | RevenueDistributionToken(name_, symbol_, owner_, asset_, precision_) { }
1117 |
1118 | /*****************/
1119 | /*** Modifiers ***/
1120 | /*****************/
1121 |
1122 | modifier onlyOwner {
1123 | require(msg.sender == owner, "xMPL:NOT_OWNER");
1124 | _;
1125 | }
1126 |
1127 | /********************************/
1128 | /*** Administrative Functions ***/
1129 | /********************************/
1130 |
1131 | function cancelMigration() external override onlyOwner {
1132 | require(scheduledMigrationTimestamp != 0, "xMPL:CM:NOT_SCHEDULED");
1133 |
1134 | _cleanupMigration();
1135 |
1136 | emit MigrationCancelled();
1137 | }
1138 |
1139 | function performMigration() external override onlyOwner {
1140 | uint256 migrationTimestamp = scheduledMigrationTimestamp;
1141 | address migrator = scheduledMigrator;
1142 | address oldAsset = asset;
1143 | address newAsset = scheduledNewAsset;
1144 |
1145 | require(migrationTimestamp != 0, "xMPL:PM:NOT_SCHEDULED");
1146 | require(block.timestamp >= migrationTimestamp, "xMPL:PM:TOO_EARLY");
1147 |
1148 | uint256 oldAssetBalanceBeforeMigration = ERC20(oldAsset).balanceOf(address(this));
1149 | uint256 newAssetBalanceBeforeMigration = ERC20(newAsset).balanceOf(address(this));
1150 |
1151 | require(ERC20(oldAsset).approve(migrator, oldAssetBalanceBeforeMigration), "xMPL:PM:APPROVAL_FAILED");
1152 |
1153 | Migrator(migrator).migrate(oldAssetBalanceBeforeMigration);
1154 |
1155 | require(ERC20(newAsset).balanceOf(address(this)) - newAssetBalanceBeforeMigration == oldAssetBalanceBeforeMigration, "xMPL:PM:WRONG_AMOUNT");
1156 |
1157 | emit MigrationPerformed(oldAsset, newAsset, oldAssetBalanceBeforeMigration);
1158 |
1159 | asset = newAsset;
1160 |
1161 | _cleanupMigration();
1162 | }
1163 |
1164 | function scheduleMigration(address migrator_, address newAsset_) external override onlyOwner {
1165 | require(migrator_ != address(0), "xMPL:SM:INVALID_MIGRATOR");
1166 | require(newAsset_ != address(0), "xMPL:SM:INVALID_NEW_ASSET");
1167 |
1168 | scheduledMigrationTimestamp = block.timestamp + MINIMUM_MIGRATION_DELAY;
1169 | scheduledMigrator = migrator_;
1170 | scheduledNewAsset = newAsset_;
1171 |
1172 | emit MigrationScheduled(asset, newAsset_, migrator_, scheduledMigrationTimestamp);
1173 | }
1174 |
1175 | /*************************/
1176 | /*** Utility Functions ***/
1177 | /*************************/
1178 |
1179 | function _cleanupMigration() internal {
1180 | delete scheduledMigrationTimestamp;
1181 | delete scheduledMigrator;
1182 | delete scheduledNewAsset;
1183 | }
1184 |
1185 | }
1186 |
--------------------------------------------------------------------------------
/foundry.toml:
--------------------------------------------------------------------------------
1 | [default]
2 | contracts = 'contracts' # The source directory
3 | libs = ['modules'] # A list of library directories
4 | solc_version = '0.8.7' # Override for the solc version (setting this ignores `auto_detect_solc`)
5 | offline = true # Disable downloading of missing solc version(s)
6 | optimizer = true # Enable or disable the solc optimizer
7 | optimizer_runs = 200 # The number of optimizer runs
8 | verbosity = 2 # The verbosity of tests
9 | bytecode_hash = "none" # For deterministic code
10 |
11 | [local]
12 | fuzz_runs = 100
13 |
14 | [deep]
15 | fuzz_runs = 1000
16 |
17 | [super_deep]
18 | fuzz_runs = 30000
19 |
--------------------------------------------------------------------------------
/invariant-test.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -e
3 |
4 | while getopts t:r:d flag
5 | do
6 | case "${flag}" in
7 | t) test=${OPTARG};;
8 | r) runs=${OPTARG};;
9 | d) depth=${OPTARG};;
10 | esac
11 | done
12 |
13 | runs=$([ -z "$runs" ] && echo "1" || echo "$runs")
14 | depth=$([ -z "$depth" ] && echo "200" || echo "$depth")
15 |
16 | export DAPP_SOLC_VERSION=0.8.7
17 | export DAPP_SRC="contracts"
18 | export DAPP_LIB="modules"
19 |
20 | if [ -z "$test" ]; then match="[src/test/*.t.sol]"; else match=$test; fi
21 |
22 | # Necessary until forge adds invariant testing support
23 | rm -rf out
24 |
25 | dapp test --match "$match" --fuzz-runs $runs --depth $depth --verbosity 2
26 |
--------------------------------------------------------------------------------
/package.yaml:
--------------------------------------------------------------------------------
1 | name: xmpl
2 | version: 1.0.0
3 | source: contracts
4 | packages:
5 | - path: contracts/xMPL.sol
6 | contractName: xMPL
7 | customDescription: Maple Loan Artifacts and ABIs
8 |
--------------------------------------------------------------------------------
/release.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -e
3 |
4 | version=$(cat ./package.yaml | grep "version: " | sed -r 's/.{9}//')
5 | name=$(cat ./package.yaml | grep "name: " | sed -r 's/.{6}//')
6 | customDescription=$(cat ./package.yaml | grep "customDescription: " | sed -r 's/.{19}//')
7 |
8 | ./build.sh
9 |
10 | rm -rf ./package
11 | mkdir -p package
12 |
13 | echo "{
14 | \"name\": \"@maplelabs/${name}\",
15 | \"version\": \"${version}\",
16 | \"description\": \"${customDescription}\",
17 | \"author\": \"Maple Labs\",
18 | \"license\": \"AGPLv3\",
19 | \"repository\": {
20 | \"type\": \"git\",
21 | \"url\": \"https://github.com/maple-labs/${name}.git\"
22 | },
23 | \"bugs\": {
24 | \"url\": \"https://github.com/maple-labs/${name}/issues\"
25 | },
26 | \"homepage\": \"https://github.com/maple-labs/${name}\"
27 | }" > package/package.json
28 |
29 | mkdir -p package/artifacts
30 | mkdir -p package/abis
31 |
32 | paths=($(cat ./package.yaml | grep " - path:" | sed -r 's/.{10}//'))
33 | names=($(cat ./package.yaml | grep " contractName:" | sed -r 's/.{18}//'))
34 |
35 | if [ -f "./out/dapp.sol.json" ]; then
36 | for i in "${!paths[@]}"; do
37 | cat ./out/dapp.sol.json | jq ".contracts | .\"${paths[i]}\" | .${names[i]}" > package/artifacts/${names[i]}.json
38 | cat ./out/dapp.sol.json | jq ".contracts | .\"${paths[i]}\" | .${names[i]} | .abi" > package/abis/${names[i]}.json
39 | done
40 | else
41 | for i in "${!paths[@]}"; do
42 | cat ./out/${names[i]}.sol/${names[i]}.json | jq "{ abi: .abi, evm: { bytecode: .bytecode, deployedBytecode: .deployedBytecode } }" > package/artifacts/${names[i]}.json
43 | cat ./out/${names[i]}.sol/${names[i]}.json | jq ".abi" > package/abis/${names[i]}.json
44 | done
45 | fi
46 |
47 | npm publish ./package --access public
48 |
49 | rm -rf ./package
50 |
--------------------------------------------------------------------------------
/test.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -e
3 |
4 | while getopts p:t: flag
5 | do
6 | case "${flag}" in
7 | p) profile=${OPTARG};;
8 | t) test=${OPTARG};;
9 | esac
10 | done
11 |
12 | export FOUNDRY_PROFILE=$profile
13 |
14 | echo Using profile: $FOUNDRY_PROFILE
15 |
16 | if [ -z "$test" ];
17 | then
18 | forge test --match-path "contracts/test/*";
19 | else
20 | forge test --match "$test";
21 | fi
22 |
--------------------------------------------------------------------------------