├── .gitattributes
├── .gitignore
├── .solcover.js
├── .solhint.json
├── .soliumignore
├── .soliumrc.json
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── audits
├── jorge-signature.md
└── jorge.md
├── contracts
├── Exchange.sol
├── ExchangeInterface.sol
├── HookSubscriber.sol
├── Interfaces
│ └── ERC820.sol
├── Libraries
│ ├── OrderLibrary.sol
│ ├── SafeMath.sol
│ └── SignatureValidator.sol
├── Migrations.sol
├── Ownership
│ └── Ownable.sol
├── Tokens
│ ├── ERC20.sol
│ └── ERC777.sol
└── Vault
│ ├── Vault.sol
│ └── VaultInterface.sol
├── migrations
├── 1_initial_migration.js
└── 2_deploy_contracts.js
├── package.json
├── scripts
└── coverage.sh
├── test
├── TestExchange.js
├── TestVault.js
├── helpers
│ └── Utils.js
└── mocks
│ ├── HookSubscriberMock.sol
│ ├── SelfDestructor.sol
│ └── Token.sol
└── truffle.js
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.sol linguist-language=Solidity
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | build/*
2 | node_modules
3 | coverage/
4 | coverageEnv/
5 | coverage.json
6 | scTopics
7 | functions.csv
8 | artifacts/
9 | allFiredEvents
--------------------------------------------------------------------------------
/.solcover.js:
--------------------------------------------------------------------------------
1 | const tokens = require('glob').sync('contracts/Tokens/*.sol').map(n => n.replace('contracts/', ''));
2 | const interfaces = [
3 | 'Ownership/Ownable.sol',
4 | 'Vault/VaultInterface.sol',
5 | 'ExchangeInterface.sol',
6 | 'Migrations.sol',
7 | 'Libraries/SafeMath.sol'
8 | ];
9 |
10 | module.exports = {
11 | norpc: true,
12 | skipFiles: tokens.concat(interfaces),
13 | copyNodeModules: false,
14 | };
15 |
--------------------------------------------------------------------------------
/.solhint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "default",
3 | "rules": {
4 | "indent": ["warn", 4],
5 | "two-lines-top-level-separator": false,
6 | "compiler-fixed": false
7 | }
8 | }
--------------------------------------------------------------------------------
/.soliumignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/.soliumrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "solium:all",
3 | "rules": {
4 | "indentation": ["error", 4],
5 | "quotes": ["error", "double"],
6 | "arg-overflow": "off",
7 | "blank-lines": "off"
8 | }
9 | }
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: required
2 |
3 | dist: trusty
4 |
5 | language: node_js
6 |
7 | node_js:
8 | - "8"
9 | env:
10 | - TASK=test
11 | - TASK=lint
12 | matrix:
13 | fast_finish: true
14 | allow_failures:
15 | - env: TASK=lint
16 | script:
17 | - npm run $TASK
18 |
19 | notifications:
20 | email: false
21 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file.
4 |
5 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
6 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
7 |
8 | ## [2.1.0] - 2018-04-26
9 |
10 | ### Changed
11 | - Minor cleanup to trade function.
12 | - Deduplicated withdraw handling.
13 |
14 | ### Added
15 | - Traded Hook to subscribe to trade events.
16 |
17 | ### Fixed
18 | - Fixes ERC777 implementation
19 |
20 | ## [2.0.0] - 2018-04-18
21 |
22 | ### Changed
23 | - Vault can have multiple spenders.
24 | - Rearrange parameter ordering for trade function.
25 | - Using eth constant in exchange
26 | - Removed user from ```fills```
27 | - Renamed give / get to maker / taker.
28 |
29 | ### Fixed
30 | - Checks for rounding errors
31 | - Invariant with small denominations that may end with 0 value transfers.
32 |
33 | ## [1.0.0] - 2018-04-03
34 |
35 | ### Added
36 | - Truffle configuration files
37 | - package.json
38 | - Solium files
39 | - Travis configuration
40 | - Base exchange contracts
41 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DEXY
2 |
3 | [](https://travis-ci.com/DexyProject/contracts) [](LICENSE)
4 |
5 | Smart Contracts for the DEXY exchange project.
6 |
7 | ## Getting Started
8 |
9 | These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
10 |
11 | ### Installing
12 |
13 | DEXY uses npm to manage dependencies, therefore the installation process is kept simple:
14 |
15 | ```
16 | npm install
17 | ```
18 |
19 | ### Running tests
20 |
21 | DEXY uses truffle for its ethereum development environment. All tests can be run using truffle:
22 |
23 | ```
24 | truffle test
25 | ```
26 |
27 | To run linting, use solium:
28 |
29 | ```
30 | solium --dir ./contracts
31 | ```
32 |
33 | ### Deployed Addresses
34 |
35 | #### Mainnet
36 | - Exchange: [0x1d150cfcd9bfa01e754e034442341ba85b85f1bb](https://etherscan.io/address/0x1d150cfcd9bfa01e754e034442341ba85b85f1bb)
37 | - Vault: [0x3956925d7d5199a6db1f42347fedbcd35312ae82](https://etherscan.io/address/0x3956925d7d5199a6db1f42347fedbcd35312ae82)
38 |
39 | #### Ropsten
40 | - Exchange: [0xeea40bf84bd146ec53063b6aacfec250e23e200b](https://ropsten.etherscan.io/address/0xeea40bf84bd146ec53063b6aacfec250e23e200b)
41 | - Vault: [0xbac2d30ecf6e22080ad8d11c892456c569a2f4dd](https://ropsten.etherscan.io/address/0xbac2d30ecf6e22080ad8d11c892456c569a2f4dd)
42 |
43 | #### Kovan
44 | - Exchange: [0x0fc2843d2bb414a896cbbba613c75e1d05e2eee4](https://kovan.etherscan.io/address/0x0fc2843d2bb414a896cbbba613c75e1d05e2eee4)
45 | - Vault: [0xf7d3db5afbee4e0a4f0935133fb71f57633f51a5](https://kovan.etherscan.io/address/0xf7d3db5afbee4e0a4f0935133fb71f57633f51a5)
46 |
47 | ## Built With
48 | * [Truffle](https://github.com/trufflesuite/truffle) - Ethereum development environment
49 |
50 | ## Authors
51 |
52 | * **Dean Eigenmann** - [decanus](https://github.com/decanus)
53 | * **Matthew Di Ferrante** - [mattdf](https://github.com/mattdf)
54 |
55 | See also the list of [contributors](https://github.com/DexyProject/contracts/contributors) who participated in this project.
56 |
57 | ## Versioning
58 |
59 | We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/DexyProject/contracts/tags).
60 |
61 | ## License
62 |
63 | This project is licensed under the GNU General Public License v3.0 - see the [LICENSE](LICENSE) file for details
64 |
--------------------------------------------------------------------------------
/audits/jorge-signature.md:
--------------------------------------------------------------------------------
1 | - SHA256 checksum: `7077d69aa80628107ae909d96a5750542349cd6361a4e110d106922d3333f611`
2 | - Compute: `shasum -a 256 audits/jorge.md`
3 | - Signed by: `0x4838eab6f43841e0d233db4cea47bd64f614f0c5`
4 | - Transaction: [0x793bf07f45cb0fa87dcb1ffa4a34f0c0137220775b3aee41a3cf6dc3a97533f0](https://etherscan.io/tx/0x793bf07f45cb0fa87dcb1ffa4a34f0c0137220775b3aee41a3cf6dc3a97533f0)
5 |
--------------------------------------------------------------------------------
/audits/jorge.md:
--------------------------------------------------------------------------------
1 | # Dexy contracts code review – Jorge Izquierdo
2 |
3 | ## Introduction
4 |
5 | - I reviewed the code at the following commit hash [ 4a0197fe327a002b45b3081241aaac86f1abcbff](https://github.com/DexyProject/contracts/tree/4a0197fe327a002b45b3081241aaac86f1abcbff).
6 | - I received no compensation for the following review nor I'm financially
7 | involved with Dexy in any capacity.
8 | - I did this review as an individual, there is no formal relationship between
9 | Aragon and Dexy.
10 | - This is not a comprehensive review, just a check to see if I could put my own
11 | money for trading in Dexy.
12 | - I'm not a professional code auditor and I employed less than three hours in
13 | total to review, communicate with the team about it and produce this report.
14 | Don't take it too seriously.
15 | - No guarantees and all the legal boring stuff. If something breaks and people lose money, they should go tweet [Dean](https://twitter.com/DeanEigenmann).
16 | - A SHA256 checksum of this file will be sent in the transaction data of a 0 value
17 | transfer to the 0th account made with my verified account
18 | `0x4838eab6f43841e0d233db4cea47bd64f614f0c5`
19 | [Proof](https://etherscan.io/tx/0x5aaeb2d0361dbdf3b4ecadad1b49c239eb1b3b5e1cf973f6a4597ad56edc47b9). For obvious inception reasons the transaction hash of that
20 | cannot be pasted here, but will be provided in parallel.
21 |
22 | ## TLDR
23 |
24 | - I did not find any issues that could lead to losing or stealing funds under normal operation and the main exchange logic seems to check out.
25 | - I feel safe about trading with my own money in the exchange.
26 | - There is a high severity issue that would allow the exchange operator to steal
27 | the entire token amount a taker thinks she's getting. On fixing, this is a
28 | completely trustless exchange.
29 | - Because of its design Dexy will provide the best UX in the (DEX) game.
30 | - Please increase test coverage.
31 |
32 | ## Fixes
33 |
34 | - After handing in this report, one high severity issue, one medium and one low
35 | have been fixed and the exchange will be deployed with those.
36 | - There is still one low severity issue not solved that is mostly related to
37 | documentation.
38 |
39 | ## Review
40 |
41 | ### Smart contract code
42 |
43 | #### Critical severity
44 |
45 | No critical issues were found.
46 |
47 | #### High severity
48 |
49 | ##### (FIXED) Exchange operator can steal from taker by frontrunning a trade transaction with a `Exchange.setFees(...)` transaction
50 | - https://github.com/DexyProject/contracts/blob/4a0197fe327a002b45b3081241aaac86f1abcbff/contracts/Exchange.sol#L201
51 | - Because fees are not part of the orders themselves but just taken from a
52 | storage value set by the operator, the operator can change the fee to a very
53 | big amount right before a trade is mined, effectively allowing them to get the
54 | entire amount they are taking.
55 | - I suggest allowing the trader to pass the `takerFee` they are willing
56 | to pay to `trade(...)` or adding a hardcoded max fee to the exchange code (say
57 | 5%).
58 | - FIX: https://github.com/DexyProject/contracts/commit/a2edcea876ea12fbc10ec66f225cf934897966e7#diff-a5e6c43f03b96911facdf9d4e9b82b9cR118
59 |
60 | #### Medium severity
61 |
62 | ##### (FIXED) Fee math bug requires taker to have an extra balance to pay for fees
63 | - https://github.com/DexyProject/contracts/blob/development/contracts/Exchange.sol#L206
64 |
65 | - I recommend just changing `give` for `give.sub(tradeTakerFee)`
66 | - FIX: https://github.com/DexyProject/contracts/commit/a2edcea876ea12fbc10ec66f225cf934897966e7#diff-a5e6c43f03b96911facdf9d4e9b82b9cR208
67 |
68 |
69 | #### Low severity
70 |
71 | ##### Vault balance check for transfers is too implicit
72 | - At the moment, a trade will fail if the maker or taker don't have enough
73 | balance because of the implicit underflow check in SafeMath.
74 | - Even though I cannot think of any way to exploit this, it would be more future
75 | proof to at least add a comment or assertion on this.
76 |
77 | ##### (FIXED) `withdrawOverflow(...)` does not support `ERC777.send(...)`
78 | - Potentially low risk as the transfer method is backwards compatible.
79 | - If the operator is a contract by adding this, the contract could get a callback
80 | when an overflow is withdrawn.
81 | - FIX: https://github.com/DexyProject/contracts/commit/a2edcea876ea12fbc10ec66f225cf934897966e7#diff-1087dd2047aa77a42d016220179d02d5R105
82 |
83 | #### Comments
84 |
85 | ##### `setERC777(...)` can be replaced by a standard interface check
86 | - Rather than having an in-contract mapping of whether a token is ERC777 or not,
87 | that fact can be checked by asserting whether a given token address has been
88 | registered as ERC777 (From EIP: `The token-contract MUST register the ERC777Token interface via EIP-820.`)
89 | - As far as I know, ERC777 is going to start using ERC780 rather than ERC820 for
90 | this purpose so it might be a good idea to wait.
91 | - After the first check to the token, it can safely be assumed the token won't
92 | change its nature, and that value can be cached, saving 1 call in every
93 | interaction.
94 | - It is already done when receiving a callback from the token, so this might
95 | be innecessary.
96 |
97 | ##### Upgrading to new Exchange version requires explicit transaction to Vault
98 | - It should be possible for users to provide a message signing their approval
99 | to migrate to the new version executing a trade.
100 | - Anyone, including the Exchange, could then provide the signed message to the
101 | Vault effectively approving a new version.
102 | - This would allow to upgrade and start trading in just one transaction.
103 |
104 | ##### Wash trading 'protection' can give false security to users
105 | - https://github.com/DexyProject/contracts/blob/4a0197fe327a002b45b3081241aaac86f1abcbff/contracts/Exchange.sol#L73
106 |
107 | - It checks whether a user is not trading with themselves.
108 | - Given that there is no sybil protection a user can create another account and
109 | trade with themselves that way, which is impossible to detect.
110 | - I suggest removing the check.
111 |
112 | ##### Cancels can be made much cheaper by scoping them by account
113 | - https://github.com/DexyProject/contracts/blob/4a0197fe327a002b45b3081241aaac86f1abcbff/contracts/Exchange.sol#L112
114 |
115 | - If rather than `mapping (bytes32 => bool) cancelled` the cancels mapping is
116 | made `mapping (address => mapping (bytes32 => bool)) cancelled` no checks are
117 | required to cancel an order, because a user can cancel order hashes in their
118 | account even if they haven't signed the order to begin with.
119 | - I consider this extremely important because there is a big incentive to
120 | frontrun order cancels, so they should be as cheap as possible so the sender can
121 | pay a higher gas price if needed.
122 |
123 | ##### Smart contracts cannot order make
124 | - Order making requires an ECDSA signature which contracts cannot do.
125 | - I recommend adding something similar like
126 | [this](https://github.com/0xProject/ZEIPs/issues/7#issuecomment-355280219) but
127 | with ERC780.
128 |
129 |
130 | ##### Fallback function is redundant
131 | - https://github.com/DexyProject/contracts/blob/development/contracts/Exchange.sol#L51
132 | - Solidity already generates code to revert if no function signature matches.
133 | - If it is there to make the code more explicit it could be commented out.
134 |
135 | ##### Deposit and `trade(...)` could be made in just one transaction
136 | - If the taker doesn't have enough balance in the Vault to make a trade, it
137 | should try to deposit the required token amount into the user account and then
138 | execute the trade.
139 | - This could also be used as an implicit approval of the current exchange
140 | instance.
141 |
142 | #### Praise
143 | - Great use of [ERC712 `eth_signTypedData`](https://github.com/ethereum/EIPs/pull/712) 🔏
144 | - [ERC777 token](https://github.com/ethereum/EIPs/issues/777) support for deposits 🤩
145 | - Great balance between convenience and security in the upgradeabily approach to
146 | such a critical contract. 🕵️♀️
147 | - Clean ETH handling to avoid the indirection of using a wrapped ether token,
148 | improved UX as a result. 🏋️♀️
149 | - Contract is completely trustless and stealing funds would require the exchange
150 | operator to set a rogue exchange and then convince users to send a transaction
151 | approving that exchange to use their funds. 🙅♀️
152 | - Low deployment risk: deployment is so simple it is hard to make a mistake on
153 | deployment. This makes it easy too for users to trustlessly verify the code of
154 | the exchange they are interacting with. 🚀
155 | - Math is safe 📓
156 | - Hardware wallet signature support 🙏👍
157 | - Because there is no 'utility token' this exchange could be designed maximizing
158 | UX, and IMO they achieved the best DEX UX I have seen. 🥅⚽️
159 |
160 | ### Testing suite
161 |
162 | #### Critical severity
163 |
164 | ##### No comprehensive trading tests
165 | - At the moment I reviewed trading logic wasn't thoroughly tested.
166 | - I have been told those were a WIP at the time
167 |
168 | #### High severity
169 |
170 | ##### General low coverage
171 | - No automated coverage metric as part of the CI process
172 | - I recommend a 100% test coverage at least on `Exchange.sol` and `Vault.sol`
173 |
174 | ##### Tests not run against real nodes
175 | - Even though ganache-core is a full EVM implementation, there have been instances in which
176 | ganache doesn't behave 100% like a real node EVM implementation.
177 | - I recommend running the tests against Geth and/or Parity as part of the CI pipeline.
178 |
179 | #### Praise
180 | - Tests are descriptive and easy to follow ✅
181 | - Tests passed at the first try by doing `npm i && npm t` 👍
182 |
--------------------------------------------------------------------------------
/contracts/Exchange.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | import "./ExchangeInterface.sol";
4 | import "./Libraries/SafeMath.sol";
5 | import "./Libraries/SignatureValidator.sol";
6 | import "./Libraries/OrderLibrary.sol";
7 | import "./Ownership/Ownable.sol";
8 | import "./Tokens/ERC20.sol";
9 | import "./HookSubscriber.sol";
10 |
11 | contract Exchange is Ownable, ExchangeInterface {
12 |
13 | using SafeMath for *;
14 | using OrderLibrary for OrderLibrary.Order;
15 |
16 | address constant public ETH = 0x0;
17 |
18 | uint256 constant public MAX_FEE = 5000000000000000; // 0.5% ((0.5 / 100) * 10**18)
19 | uint256 constant private MAX_ROUNDING_PERCENTAGE = 1000; // 0.1%
20 |
21 | uint256 constant private MAX_HOOK_GAS = 40000; // enough for a storage write and some accounting logic
22 |
23 | VaultInterface public vault;
24 |
25 | uint public takerFee = 0;
26 | address public feeAccount;
27 |
28 | mapping (address => mapping (bytes32 => bool)) private orders;
29 | mapping (bytes32 => uint) private fills;
30 | mapping (bytes32 => bool) private cancelled;
31 | mapping (address => bool) private subscribed;
32 |
33 | function Exchange(uint _takerFee, address _feeAccount, VaultInterface _vault) public {
34 | require(address(_vault) != 0x0);
35 | setFees(_takerFee);
36 | setFeeAccount(_feeAccount);
37 | vault = _vault;
38 | }
39 |
40 | /// @dev Withdraws tokens accidentally sent to this contract.
41 | /// @param token Address of the token to withdraw.
42 | /// @param amount Amount of tokens to withdraw.
43 | function withdraw(address token, uint amount) external onlyOwner {
44 | if (token == ETH) {
45 | msg.sender.transfer(amount);
46 | return;
47 | }
48 |
49 | ERC20(token).transfer(msg.sender, amount);
50 | }
51 |
52 | /// @dev Subscribes user to trade hooks.
53 | function subscribe() external {
54 | require(!subscribed[msg.sender]);
55 | subscribed[msg.sender] = true;
56 | emit Subscribed(msg.sender);
57 | }
58 |
59 | /// @dev Unsubscribes user from trade hooks.
60 | function unsubscribe() external {
61 | require(subscribed[msg.sender]);
62 | subscribed[msg.sender] = false;
63 | emit Unsubscribed(msg.sender);
64 | }
65 |
66 | /// @dev Takes an order.
67 | /// @param addresses Array of trade's maker, makerToken and takerToken.
68 | /// @param values Array of trade's makerTokenAmount, takerTokenAmount, expires and nonce.
69 | /// @param signature Signed order along with signature mode.
70 | /// @param maxFillAmount Maximum amount of the order to be filled.
71 | function trade(address[3] addresses, uint[4] values, bytes signature, uint maxFillAmount) external {
72 | trade(OrderLibrary.createOrder(addresses, values), msg.sender, signature, maxFillAmount);
73 | }
74 |
75 | /// @dev Cancels an order.
76 | /// @param addresses Array of trade's maker, makerToken and takerToken.
77 | /// @param values Array of trade's makerTokenAmount, takerTokenAmount, expires and nonce.
78 | function cancel(address[3] addresses, uint[4] values) external {
79 | OrderLibrary.Order memory order = OrderLibrary.createOrder(addresses, values);
80 |
81 | require(msg.sender == order.maker);
82 | require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0);
83 |
84 | bytes32 hash = order.hash();
85 | require(fills[hash] < order.takerTokenAmount);
86 | require(!cancelled[hash]);
87 |
88 | cancelled[hash] = true;
89 | emit Cancelled(hash);
90 | }
91 |
92 | /// @dev Creates an order which is then indexed in the orderbook.
93 | /// @param addresses Array of trade's makerToken and takerToken.
94 | /// @param values Array of trade's makerTokenAmount, takerTokenAmount, expires and nonce.
95 | function order(address[2] addresses, uint[4] values) external {
96 | OrderLibrary.Order memory order = OrderLibrary.createOrder(
97 | [msg.sender, addresses[0], addresses[1]],
98 | values
99 | );
100 |
101 | require(vault.isApproved(order.maker, this));
102 | require(vault.balanceOf(order.makerToken, order.maker) >= order.makerTokenAmount);
103 | require(order.makerToken != order.takerToken);
104 | require(order.makerTokenAmount > 0);
105 | require(order.takerTokenAmount > 0);
106 |
107 | bytes32 hash = order.hash();
108 |
109 | require(!orders[msg.sender][hash]);
110 | orders[msg.sender][hash] = true;
111 |
112 | emit Ordered(
113 | order.maker,
114 | order.makerToken,
115 | order.takerToken,
116 | order.makerTokenAmount,
117 | order.takerTokenAmount,
118 | order.expires,
119 | order.nonce
120 | );
121 | }
122 |
123 | /// @dev Checks if a order can be traded.
124 | /// @param addresses Array of trade's maker, makerToken and takerToken.
125 | /// @param values Array of trade's makerTokenAmount, takerTokenAmount, expires and nonce.
126 | /// @param signature Signed order along with signature mode.
127 | /// @return Boolean if order can be traded
128 | function canTrade(address[3] addresses, uint[4] values, bytes signature)
129 | external
130 | view
131 | returns (bool)
132 | {
133 | OrderLibrary.Order memory order = OrderLibrary.createOrder(addresses, values);
134 |
135 | bytes32 hash = order.hash();
136 |
137 | return canTrade(order, signature, hash);
138 | }
139 |
140 | /// @dev Returns if user has subscribed to trade hooks.
141 | /// @param subscriber Address of the subscriber.
142 | /// @return Boolean if user is subscribed.
143 | function isSubscribed(address subscriber) external view returns (bool) {
144 | return subscribed[subscriber];
145 | }
146 |
147 | /// @dev Checks how much of an order can be filled.
148 | /// @param addresses Array of trade's maker, makerToken and takerToken.
149 | /// @param values Array of trade's makerTokenAmount, takerTokenAmount, expires and nonce.
150 | /// @return Amount of the order which can be filled.
151 | function availableAmount(address[3] addresses, uint[4] values) external view returns (uint) {
152 | OrderLibrary.Order memory order = OrderLibrary.createOrder(addresses, values);
153 | return availableAmount(order, order.hash());
154 | }
155 |
156 | /// @dev Returns how much of an order was filled.
157 | /// @param hash Hash of the order.
158 | /// @return Amount which was filled.
159 | function filled(bytes32 hash) external view returns (uint) {
160 | return fills[hash];
161 | }
162 |
163 | /// @dev Sets the taker fee.
164 | /// @param _takerFee New taker fee.
165 | function setFees(uint _takerFee) public onlyOwner {
166 | require(_takerFee <= MAX_FEE);
167 | takerFee = _takerFee;
168 | }
169 |
170 | /// @dev Sets the account where fees will be transferred to.
171 | /// @param _feeAccount Address for the account.
172 | function setFeeAccount(address _feeAccount) public onlyOwner {
173 | require(_feeAccount != 0x0);
174 | feeAccount = _feeAccount;
175 | }
176 |
177 | function vault() public view returns (VaultInterface) {
178 | return vault;
179 | }
180 |
181 | /// @dev Checks if an order was created on chain.
182 | /// @param user User who created the order.
183 | /// @param hash Hash of the order.
184 | /// @return Boolean if the order was created on chain.
185 | function isOrdered(address user, bytes32 hash) public view returns (bool) {
186 | return orders[user][hash];
187 | }
188 |
189 | /// @dev Executes the actual trade by transferring balances.
190 | /// @param order Order to be traded.
191 | /// @param taker Address of the taker.
192 | /// @param signature Signed order along with signature mode.
193 | /// @param maxFillAmount Maximum amount of the order to be filled.
194 | function trade(OrderLibrary.Order memory order, address taker, bytes signature, uint maxFillAmount) internal {
195 | require(taker != order.maker);
196 | bytes32 hash = order.hash();
197 |
198 | require(order.makerToken != order.takerToken);
199 | require(canTrade(order, signature, hash));
200 |
201 | uint fillAmount = SafeMath.min256(maxFillAmount, availableAmount(order, hash));
202 |
203 | require(roundingPercent(fillAmount, order.takerTokenAmount, order.makerTokenAmount) <= MAX_ROUNDING_PERCENTAGE);
204 | require(vault.balanceOf(order.takerToken, taker) >= fillAmount);
205 |
206 | uint makeAmount = order.makerTokenAmount.mul(fillAmount).div(order.takerTokenAmount);
207 | uint tradeTakerFee = makeAmount.mul(takerFee).div(1 ether);
208 |
209 | if (tradeTakerFee > 0) {
210 | vault.transfer(order.makerToken, order.maker, feeAccount, tradeTakerFee);
211 | }
212 |
213 | vault.transfer(order.takerToken, taker, order.maker, fillAmount);
214 | vault.transfer(order.makerToken, order.maker, taker, makeAmount.sub(tradeTakerFee));
215 |
216 | fills[hash] = fills[hash].add(fillAmount);
217 | assert(fills[hash] <= order.takerTokenAmount);
218 |
219 | if (subscribed[order.maker]) {
220 | order.maker.call.gas(MAX_HOOK_GAS)(HookSubscriber(order.maker).tradeExecuted.selector, order.takerToken, fillAmount);
221 | }
222 |
223 | emit Traded(
224 | hash,
225 | order.makerToken,
226 | makeAmount,
227 | order.takerToken,
228 | fillAmount,
229 | order.maker,
230 | taker
231 | );
232 | }
233 |
234 | /// @dev Indicates whether or not an certain amount of an order can be traded.
235 | /// @param order Order to be traded.
236 | /// @param signature Signed order along with signature mode.
237 | /// @param hash Hash of the order.
238 | /// @return Boolean if order can be traded
239 | function canTrade(OrderLibrary.Order memory order, bytes signature, bytes32 hash)
240 | internal
241 | view
242 | returns (bool)
243 | {
244 | // if the order has never been traded against, we need to check the sig.
245 | if (fills[hash] == 0) {
246 | // ensures order was either created on chain, or signature is valid
247 | if (!isOrdered(order.maker, hash) && !SignatureValidator.isValidSignature(hash, order.maker, signature)) {
248 | return false;
249 | }
250 | }
251 |
252 | if (cancelled[hash]) {
253 | return false;
254 | }
255 |
256 | if (!vault.isApproved(order.maker, this)) {
257 | return false;
258 | }
259 |
260 | if (order.takerTokenAmount == 0) {
261 | return false;
262 | }
263 |
264 | if (order.makerTokenAmount == 0) {
265 | return false;
266 | }
267 |
268 | // ensures that the order still has an available amount to be filled.
269 | if (availableAmount(order, hash) == 0) {
270 | return false;
271 | }
272 |
273 | return order.expires > now;
274 | }
275 |
276 | /// @dev Returns the maximum available amount that can be taken of an order.
277 | /// @param order Order to check.
278 | /// @param hash Hash of the order.
279 | /// @return Amount of the order that can be filled.
280 | function availableAmount(OrderLibrary.Order memory order, bytes32 hash) internal view returns (uint) {
281 | return SafeMath.min256(
282 | order.takerTokenAmount.sub(fills[hash]),
283 | vault.balanceOf(order.makerToken, order.maker).mul(order.takerTokenAmount).div(order.makerTokenAmount)
284 | );
285 | }
286 |
287 | /// @dev Returns the percentage which was rounded when dividing.
288 | /// @param numerator Numerator.
289 | /// @param denominator Denominator.
290 | /// @param target Value to multiply with.
291 | /// @return Percentage rounded.
292 | function roundingPercent(uint numerator, uint denominator, uint target) internal pure returns (uint) {
293 | // Inspired by https://github.com/0xProject/contracts/blob/1.0.0/contracts/Exchange.sol#L472-L490
294 | uint remainder = mulmod(target, numerator, denominator);
295 | if (remainder == 0) {
296 | return 0;
297 | }
298 |
299 | return remainder.mul(1000000).div(numerator.mul(target));
300 | }
301 | }
302 |
--------------------------------------------------------------------------------
/contracts/ExchangeInterface.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | import "./Vault/VaultInterface.sol";
4 |
5 | interface ExchangeInterface {
6 |
7 | event Subscribed(address indexed user);
8 | event Unsubscribed(address indexed user);
9 |
10 | event Cancelled(bytes32 indexed hash);
11 |
12 | event Traded(
13 | bytes32 indexed hash,
14 | address makerToken,
15 | uint makerTokenAmount,
16 | address takerToken,
17 | uint takerTokenAmount,
18 | address maker,
19 | address taker
20 | );
21 |
22 | event Ordered(
23 | address maker,
24 | address makerToken,
25 | address takerToken,
26 | uint makerTokenAmount,
27 | uint takerTokenAmount,
28 | uint expires,
29 | uint nonce
30 | );
31 |
32 | function subscribe() external;
33 | function unsubscribe() external;
34 |
35 | function trade(address[3] addresses, uint[4] values, bytes signature, uint maxFillAmount) external;
36 | function cancel(address[3] addresses, uint[4] values) external;
37 | function order(address[2] addresses, uint[4] values) external;
38 |
39 | function canTrade(address[3] addresses, uint[4] values, bytes signature)
40 | external
41 | view
42 | returns (bool);
43 |
44 | function isSubscribed(address subscriber) external view returns (bool);
45 | function availableAmount(address[3] addresses, uint[4] values) external view returns (uint);
46 | function filled(bytes32 hash) external view returns (uint);
47 | function isOrdered(address user, bytes32 hash) public view returns (bool);
48 | function vault() public view returns (VaultInterface);
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/contracts/HookSubscriber.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | interface HookSubscriber {
4 |
5 | function tradeExecuted(address token, uint amount) external;
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/contracts/Interfaces/ERC820.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | interface ERC820 {
4 |
5 | function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public;
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/contracts/Libraries/OrderLibrary.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | library OrderLibrary {
4 |
5 | bytes32 constant public HASH_SCHEME = keccak256(
6 | "address Taker Token",
7 | "uint Taker Token Amount",
8 | "address Maker Token",
9 | "uint Maker Token Amount",
10 | "uint Expires",
11 | "uint Nonce",
12 | "address Maker",
13 | "address Exchange"
14 | );
15 |
16 | struct Order {
17 | address maker;
18 | address makerToken;
19 | address takerToken;
20 | uint makerTokenAmount;
21 | uint takerTokenAmount;
22 | uint expires;
23 | uint nonce;
24 | }
25 |
26 | /// @dev Hashes the order.
27 | /// @param order Order to be hashed.
28 | /// @return hash result
29 | function hash(Order memory order) internal view returns (bytes32) {
30 | return keccak256(
31 | HASH_SCHEME,
32 | keccak256(
33 | order.takerToken,
34 | order.takerTokenAmount,
35 | order.makerToken,
36 | order.makerTokenAmount,
37 | order.expires,
38 | order.nonce,
39 | order.maker,
40 | this
41 | )
42 | );
43 | }
44 |
45 | /// @dev Creates order struct from value arrays.
46 | /// @param addresses Array of trade's maker, makerToken and takerToken.
47 | /// @param values Array of trade's makerTokenAmount, takerTokenAmount, expires and nonce.
48 | /// @return Order struct
49 | function createOrder(address[3] addresses, uint[4] values) internal pure returns (Order memory) {
50 | return Order({
51 | maker: addresses[0],
52 | makerToken: addresses[1],
53 | takerToken: addresses[2],
54 | makerTokenAmount: values[0],
55 | takerTokenAmount: values[1],
56 | expires: values[2],
57 | nonce: values[3]
58 | });
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/contracts/Libraries/SafeMath.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | library SafeMath {
4 |
5 | function mul(uint a, uint b) internal pure returns (uint) {
6 | uint c = a * b;
7 | assert(a == 0 || c / a == b);
8 | return c;
9 | }
10 |
11 | function div(uint a, uint b) internal pure returns (uint) {
12 | assert(b > 0);
13 | uint c = a / b;
14 | assert(a == b * c + a % b);
15 | return c;
16 | }
17 |
18 | function sub(uint a, uint b) internal pure returns (uint) {
19 | assert(b <= a);
20 | return a - b;
21 | }
22 |
23 | function add(uint a, uint b) internal pure returns (uint) {
24 | uint c = a + b;
25 | assert(c >= a);
26 | return c;
27 | }
28 |
29 | function max64(uint64 a, uint64 b) internal pure returns (uint64) {
30 | return a >= b ? a : b;
31 | }
32 |
33 | function min64(uint64 a, uint64 b) internal pure returns (uint64) {
34 | return a < b ? a : b;
35 | }
36 |
37 | function max256(uint a, uint b) internal pure returns (uint) {
38 | return a >= b ? a : b;
39 | }
40 |
41 | function min256(uint a, uint b) internal pure returns (uint) {
42 | return a < b ? a : b;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/contracts/Libraries/SignatureValidator.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | library SignatureValidator {
4 |
5 | enum SignatureMode {
6 | EIP712,
7 | GETH,
8 | TREZOR
9 | }
10 |
11 | /// @dev Validates that a hash was signed by a specified signer.
12 | /// @param hash Hash which was signed.
13 | /// @param signer Address of the signer.
14 | /// @param signature ECDSA signature along with the mode (0 = EIP712, 1 = Geth, 2 = Trezor) {mode}{v}{r}{s}.
15 | /// @return Returns whether signature is from a specified user.
16 | function isValidSignature(bytes32 hash, address signer, bytes signature) internal pure returns (bool) {
17 | require(signature.length == 66);
18 | SignatureMode mode = SignatureMode(uint8(signature[0]));
19 |
20 | uint8 v = uint8(signature[1]);
21 | bytes32 r;
22 | bytes32 s;
23 | assembly {
24 | r := mload(add(signature, 34))
25 | s := mload(add(signature, 66))
26 | }
27 |
28 | if (mode == SignatureMode.GETH) {
29 | hash = keccak256("\x19Ethereum Signed Message:\n32", hash);
30 | } else if (mode == SignatureMode.TREZOR) {
31 | hash = keccak256("\x19Ethereum Signed Message:\n\x20", hash);
32 | }
33 |
34 | return ecrecover(hash, v, r, s) == signer;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.17;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner)
9 | _;
10 | }
11 |
12 | function Migrations() public {
13 | owner = msg.sender;
14 | }
15 |
16 | function setCompleted(uint completed) public restricted {
17 | last_completed_migration = completed;
18 | }
19 |
20 | function upgrade(address newAddress) public restricted {
21 | Migrations upgraded = Migrations(newAddress);
22 | upgraded.setCompleted(last_completed_migration);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/contracts/Ownership/Ownable.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | contract Ownable {
4 |
5 | address public owner;
6 |
7 | modifier onlyOwner {
8 | require(isOwner(msg.sender));
9 | _;
10 | }
11 |
12 | function Ownable() public {
13 | owner = msg.sender;
14 | }
15 |
16 | function transferOwnership(address _newOwner) public onlyOwner {
17 | owner = _newOwner;
18 | }
19 |
20 | function isOwner(address _address) public view returns (bool) {
21 | return owner == _address;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/contracts/Tokens/ERC20.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | interface ERC20 {
4 |
5 | function totalSupply() public view returns (uint);
6 | function balanceOf(address owner) public view returns (uint);
7 | function allowance(address owner, address spender) public view returns (uint);
8 | function transfer(address to, uint value) public returns (bool);
9 | function transferFrom(address from, address to, uint value) public returns (bool);
10 | function approve(address spender, uint value) public returns (bool);
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/contracts/Tokens/ERC777.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | interface ERC777 {
4 | function name() public constant returns (string);
5 | function symbol() public constant returns (string);
6 | function totalSupply() public constant returns (uint256);
7 | function granularity() public constant returns (uint256);
8 | function balanceOf(address owner) public constant returns (uint256);
9 |
10 | function send(address to, uint256 amount) public;
11 | function send(address to, uint256 amount, bytes userData) public;
12 |
13 | function authorizeOperator(address operator) public;
14 | function revokeOperator(address operator) public;
15 | function isOperatorFor(address operator, address tokenHolder) public constant returns (bool);
16 | function operatorSend(address from, address to, uint256 amount, bytes userData, bytes operatorData) public;
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/contracts/Vault/Vault.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | import "./VaultInterface.sol";
4 | import "../Interfaces/ERC820.sol";
5 | import "../Libraries/SafeMath.sol";
6 | import "../Ownership/Ownable.sol";
7 | import "../Tokens/ERC20.sol";
8 | import "../Tokens/ERC777.sol";
9 |
10 | contract Vault is Ownable, VaultInterface {
11 |
12 | using SafeMath for *;
13 |
14 | address constant public ETH = 0x0;
15 |
16 | mapping (address => bool) public isERC777;
17 |
18 | // user => spender => approved
19 | mapping (address => mapping (address => bool)) private approved;
20 | mapping (address => mapping (address => uint)) private balances;
21 | mapping (address => uint) private accounted;
22 | mapping (address => bool) private spenders;
23 |
24 | address private latest;
25 |
26 | modifier onlySpender {
27 | require(spenders[msg.sender]);
28 | _;
29 | }
30 |
31 | modifier onlyApproved(address user) {
32 | require(approved[user][msg.sender]);
33 | _;
34 | }
35 |
36 | function Vault(ERC820 registry) public {
37 | // required by ERC777 standard.
38 | registry.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
39 | }
40 |
41 | /// @dev Deposits a specific token.
42 | /// @param token Address of the token to deposit.
43 | /// @param amount Amount of tokens to deposit.
44 | function deposit(address token, uint amount) external payable {
45 | require(token == ETH || msg.value == 0);
46 |
47 | uint value = amount;
48 | if (token == ETH) {
49 | value = msg.value;
50 | } else {
51 | require(ERC20(token).transferFrom(msg.sender, address(this), value));
52 | }
53 |
54 | depositFor(msg.sender, token, value);
55 | }
56 |
57 | /// @dev Withdraws a specific token.
58 | /// @param token Address of the token to withdraw.
59 | /// @param amount Amount of tokens to withdraw.
60 | function withdraw(address token, uint amount) external {
61 | require(balanceOf(token, msg.sender) >= amount);
62 |
63 | balances[token][msg.sender] = balances[token][msg.sender].sub(amount);
64 | accounted[token] = accounted[token].sub(amount);
65 |
66 | withdrawTo(msg.sender, token, amount);
67 |
68 | emit Withdrawn(msg.sender, token, amount);
69 | }
70 |
71 | /// @dev Approves an spender to trade balances of the sender.
72 | /// @param spender Address of the spender to approve.
73 | function approve(address spender) external {
74 | require(spenders[spender]);
75 | approved[msg.sender][spender] = true;
76 | emit Approved(msg.sender, spender);
77 | }
78 |
79 | /// @dev Unapproves an spender to trade balances of the sender.
80 | /// @param spender Address of the spender to unapprove.
81 | function unapprove(address spender) external {
82 | approved[msg.sender][spender] = false;
83 | emit Unapproved(msg.sender, spender);
84 | }
85 |
86 | /// @dev Adds a spender.
87 | /// @param spender Address of the spender.
88 | function addSpender(address spender) external onlyOwner {
89 | require(spender != 0x0);
90 | spenders[spender] = true;
91 | latest = spender;
92 | emit AddedSpender(spender);
93 | }
94 |
95 | /// @dev Removes a spender.
96 | /// @param spender Address of the spender.
97 | function removeSpender(address spender) external onlyOwner {
98 | spenders[spender] = false;
99 | emit RemovedSpender(spender);
100 | }
101 |
102 | /// @dev Transfers balances of a token between users.
103 | /// @param token Address of the token to transfer.
104 | /// @param from Address of the user to transfer tokens from.
105 | /// @param to Address of the user to transfer tokens to.
106 | /// @param amount Amount of tokens to transfer.
107 | function transfer(address token, address from, address to, uint amount) external onlySpender onlyApproved(from) {
108 | // We do not check the balance here, as SafeMath will revert if sub / add fail. Due to over/underflows.
109 | require(amount > 0);
110 | balances[token][from] = balances[token][from].sub(amount);
111 | balances[token][to] = balances[token][to].add(amount);
112 | }
113 |
114 | /// @dev Returns if an spender has been approved by a user.
115 | /// @param user Address of the user.
116 | /// @param spender Address of the spender.
117 | /// @return Boolean whether spender has been approved.
118 | function isApproved(address user, address spender) external view returns (bool) {
119 | return approved[user][spender];
120 | }
121 |
122 | /// @dev Returns if an address has been approved as a spender.
123 | /// @param spender Address of the spender.
124 | /// @return Boolean whether spender has been approved.
125 | function isSpender(address spender) external view returns (bool) {
126 | return spenders[spender];
127 | }
128 |
129 | function latestSpender() external view returns (address) {
130 | return latest;
131 | }
132 |
133 | function tokenFallback(address from, uint value, bytes) public {
134 | depositFor(from, msg.sender, value);
135 | }
136 |
137 | function tokensReceived(address, address from, address, uint amount, bytes, bytes) public {
138 | if (!isERC777[msg.sender]) {
139 | isERC777[msg.sender] = true;
140 | }
141 |
142 | depositFor(from, msg.sender, amount);
143 | }
144 |
145 | /// @dev Marks a token as an ERC777 token.
146 | /// @param token Address of the token.
147 | function setERC777(address token) public onlyOwner {
148 | isERC777[token] = true;
149 | }
150 |
151 | /// @dev Unmarks a token as an ERC777 token.
152 | /// @param token Address of the token.
153 | function unsetERC777(address token) public onlyOwner {
154 | isERC777[token] = false;
155 | }
156 |
157 | /// @dev Allows owner to withdraw tokens accidentally sent to the contract.
158 | /// @param token Address of the token to withdraw.
159 | function withdrawOverflow(address token) public onlyOwner {
160 | withdrawTo(msg.sender, token, overflow(token));
161 | }
162 |
163 | /// @dev Returns the balance of a user for a specified token.
164 | /// @param token Address of the token.
165 | /// @param user Address of the user.
166 | /// @return Balance for the user.
167 | function balanceOf(address token, address user) public view returns (uint) {
168 | return balances[token][user];
169 | }
170 |
171 | /// @dev Calculates how many tokens were accidentally sent to the contract.
172 | /// @param token Address of the token to calculate for.
173 | /// @return Amount of tokens not accounted for.
174 | function overflow(address token) internal view returns (uint) {
175 | if (token == ETH) {
176 | return address(this).balance.sub(accounted[token]);
177 | }
178 |
179 | return ERC20(token).balanceOf(this).sub(accounted[token]);
180 | }
181 |
182 | /// @dev Accounts for token deposits.
183 | /// @param user Address of the user who deposited.
184 | /// @param token Address of the token deposited.
185 | /// @param amount Amount of tokens deposited.
186 | function depositFor(address user, address token, uint amount) private {
187 | balances[token][user] = balances[token][user].add(amount);
188 | accounted[token] = accounted[token].add(amount);
189 | emit Deposited(user, token, amount);
190 | }
191 |
192 | /// @dev Withdraws tokens to user.
193 | /// @param user Address of the target user.
194 | /// @param token Address of the token.
195 | /// @param amount Amount of tokens.
196 | function withdrawTo(address user, address token, uint amount) private {
197 | if (token == ETH) {
198 | user.transfer(amount);
199 | return;
200 | }
201 |
202 | if (isERC777[token]) {
203 | ERC777(token).send(user, amount);
204 | return;
205 | }
206 |
207 | require(ERC20(token).transfer(user, amount));
208 | }
209 | }
210 |
--------------------------------------------------------------------------------
/contracts/Vault/VaultInterface.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | interface VaultInterface {
4 |
5 | event Deposited(address indexed user, address token, uint amount);
6 | event Withdrawn(address indexed user, address token, uint amount);
7 |
8 | event Approved(address indexed user, address indexed spender);
9 | event Unapproved(address indexed user, address indexed spender);
10 |
11 | event AddedSpender(address indexed spender);
12 | event RemovedSpender(address indexed spender);
13 |
14 | function deposit(address token, uint amount) external payable;
15 | function withdraw(address token, uint amount) external;
16 | function transfer(address token, address from, address to, uint amount) external;
17 | function approve(address spender) external;
18 | function unapprove(address spender) external;
19 | function isApproved(address user, address spender) external view returns (bool);
20 | function addSpender(address spender) external;
21 | function removeSpender(address spender) external;
22 | function latestSpender() external view returns (address);
23 | function isSpender(address spender) external view returns (bool);
24 | function tokenFallback(address from, uint value, bytes data) public;
25 | function balanceOf(address token, address user) public view returns (uint);
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/migrations/1_initial_migration.js:
--------------------------------------------------------------------------------
1 | var Migrations = artifacts.require("./Migrations.sol");
2 |
3 | module.exports = function(deployer) {
4 | deployer.deploy(Migrations);
5 | };
6 |
--------------------------------------------------------------------------------
/migrations/2_deploy_contracts.js:
--------------------------------------------------------------------------------
1 | module.exports = async (deployer) => { };
2 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "contracts",
3 | "version": "2.1.0",
4 | "description": "Decentralized exchange contracts for DEXY",
5 | "author": "DEXY",
6 | "contributors": [
7 | "Dean Eigenmann "
8 | ],
9 | "license": "GPL-3.0",
10 | "scripts": {
11 | "test": "truffle test",
12 | "lint": "solium --dir ./contracts",
13 | "coverage": "sh scripts/coverage.sh"
14 | },
15 | "files": [
16 | "contracts/",
17 | "truffle.js"
18 | ],
19 | "repository": {
20 | "type": "git",
21 | "url": "git+https://github.com/DEXY/contracts.git"
22 | },
23 | "devDependencies": {
24 | "solidity-coverage": "^0.3.5",
25 | "solium": "^1.1.6",
26 | "truffle": "^4.1.7"
27 | },
28 | "keywords": [
29 | "solidity",
30 | "ethereum",
31 | "smart",
32 | "contracts"
33 | ],
34 | "dependencies": {
35 | "ethereumjs-util": "^5.1.5",
36 | "ganache-cli": "^6.1.0",
37 | "testrpc": "0.0.1",
38 | "web3-utils": "^1.0.0-beta.34",
39 | "web3": "^1.0.0-beta.34",
40 | "eip820": "^0.0.20"
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/scripts/coverage.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Exit script as soon as a command fails.
4 | set -o errexit
5 |
6 | # Executes cleanup function at script exit.
7 | trap cleanup EXIT
8 |
9 | cleanup() {
10 | # Kill the testrpc instance that we started (if we started one and if it's still running).
11 | if [ -n "$testrpc_pid" ] && ps -p $testrpc_pid > /dev/null; then
12 | kill -9 $testrpc_pid
13 | fi
14 | }
15 |
16 | node_modules/.bin/testrpc-sc --gasLimit 0xfffffffffff --port "8555" > /dev/null &
17 | testrpc_pid=$!
18 |
19 | node_modules/.bin/solidity-coverage
--------------------------------------------------------------------------------
/test/TestExchange.js:
--------------------------------------------------------------------------------
1 | const Vault = artifacts.require('vault/Vault.sol');
2 | const Exchange = artifacts.require('Exchange.sol');
3 | const MockToken = artifacts.require('./mocks/Token.sol');
4 | const HookSubscriber = artifacts.require('./mocks/HookSubscriberMock.sol');
5 | const SelfDestructor = artifacts.require('./mocks/SelfDestructor.sol');
6 | const utils = require('./helpers/Utils.js');
7 | const web3Utils = require('web3-utils');
8 | const ethutil = require('ethereumjs-util');
9 | const EIP820Registry = require('eip820');
10 | const Web3 = require('web3');
11 | let web3;
12 |
13 | const schema_hash = '0xb9caf644225739cd2bda9073346357ae4a0c3d71809876978bd81cc702b7fdc7';
14 |
15 | contract('Exchange', function (accounts) {
16 |
17 | let vault, exchange, erc820Registry;
18 | let feeAccount;
19 |
20 | beforeEach(async () => {
21 | feeAccount = accounts[4];
22 |
23 | erc820Registry = await EIP820Registry.deploy(
24 | new Web3(new Web3.providers.WebsocketProvider("ws://localhost:7545/")),
25 | accounts[0]
26 | );
27 |
28 | web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545/"));
29 |
30 | vault = await Vault.new(erc820Registry.$address);
31 | exchange = await Exchange.new(2500000000000000, feeAccount, vault.address);
32 | await vault.addSpender(exchange.address)
33 | });
34 |
35 | it('should revert when depositing ether', async () => {
36 | try {
37 | await exchange.sendTransaction({from: accounts[0], value: 1});
38 | } catch (error) {
39 | return utils.ensureException(error);
40 | }
41 |
42 | assert.fail('depositing ether did not fail');
43 | });
44 |
45 | describe('cancel', async () => {
46 |
47 | let order, addresses, values;
48 |
49 | beforeEach(async () => {
50 | order = {
51 | takerToken: '0xc5427f201fcbc3f7ee175c22e0096078c6f584c4',
52 | takerTokenAmount: '10',
53 | makerToken: '0x0000000000000000000000000000000000000000',
54 | makerTokenAmount: '100',
55 | expires: Math.floor((Date.now() / 1000) + 5000),
56 | nonce: 10,
57 | maker: accounts[0],
58 | exchange: exchange.address
59 | };
60 |
61 | addresses = [order.maker, order.makerToken, order.takerToken];
62 | values = [order.makerTokenAmount, order.takerTokenAmount, order.expires, order.nonce];
63 | });
64 |
65 |
66 | it('should allow maker to cancel own order', async () => {
67 | let result = await exchange.cancel(addresses, values);
68 | assert.equal(result['logs'][0]['event'], 'Cancelled');
69 | });
70 |
71 | it('should prevent maker to cancel other users order', async () => {
72 | try {
73 | await exchange.cancel(addresses, values, {from: accounts[1]});
74 | } catch (error) {
75 | return utils.ensureException(error);
76 | }
77 |
78 | assert.fail('cancelling did not fail');
79 | });
80 | });
81 |
82 | describe('trade', async () => {
83 |
84 | let order;
85 | let data;
86 | let token;
87 |
88 | beforeEach(async () => {
89 |
90 | token = await MockToken.new();
91 |
92 | order = {
93 | takerToken: token.address,
94 | takerTokenAmount: '10000000000000000000000',
95 | makerToken: '0x0000000000000000000000000000000000000000',
96 | makerTokenAmount: '1000000000000000000',
97 | expires: Math.floor((Date.now() / 1000) + 5000),
98 | nonce: 10,
99 | maker: accounts[0],
100 | exchange: exchange.address
101 | };
102 |
103 | data = await signOrder(order);
104 | });
105 |
106 | it('should not allow maker to trade own order', async () => {
107 | try {
108 | await exchange.trade(data.addresses, data.values, data.sig, 10, {from: accounts[0]});
109 | } catch (error) {
110 | return utils.ensureException(error);
111 | }
112 |
113 | assert.fail('trade did not fail');
114 | });
115 |
116 | it('should not allow maker to trade order without enough balance', async () => {
117 | await vault.deposit(0x0, order.makerTokenAmount, {from: accounts[0], value: order.makerTokenAmount});
118 | await vault.approve(exchange.address);
119 |
120 | try {
121 | await exchange.trade(data.addresses, data.values, data.sig, 10, {from: accounts[1]});
122 | } catch (error) {
123 | return utils.ensureException(error);
124 | }
125 |
126 | assert.fail('trade did not fail');
127 | });
128 |
129 | it('should transfer fees correctly on trade', async () => {
130 | await vault.deposit(0x0, order.makerTokenAmount, {from: accounts[0], value: order.makerTokenAmount});
131 | await vault.approve(exchange.address);
132 |
133 | await token.mint(accounts[1], order.takerTokenAmount);
134 | await vault.deposit(token.address, order.takerTokenAmount, {from: accounts[1]});
135 | await vault.approve(exchange.address, {from: accounts[1]});
136 |
137 | await exchange.trade(data.addresses, data.values, data.sig, order.takerTokenAmount, {from: accounts[1]});
138 |
139 | assert.equal((await vault.balanceOf(0x0, feeAccount)).toString(10), '2500000000000000');
140 | assert.equal((await exchange.filled.call(data.hash)).toString(10), '10000000000000000000000')
141 | });
142 |
143 | it('should transfer correctly when trade exceeds available amount on trade', async () => {
144 | await vault.deposit(0x0, order.makerTokenAmount, {from: accounts[0], value: order.makerTokenAmount});
145 | await vault.approve(exchange.address);
146 |
147 | await token.mint(accounts[1], order.takerTokenAmount);
148 | await vault.deposit(token.address, order.takerTokenAmount, {from: accounts[1]});
149 | await vault.approve(exchange.address, {from: accounts[1]});
150 |
151 | await token.mint(accounts[2], order.takerTokenAmount);
152 | await vault.approve(exchange.address, {from: accounts[2]});
153 | await vault.deposit(token.address, order.takerTokenAmount, {from: accounts[2]});
154 |
155 | await exchange.trade(data.addresses, data.values, data.sig, order.takerTokenAmount / 2, {from: accounts[1]});
156 |
157 | assert.equal((await vault.balanceOf(0x0, feeAccount)).toString(), '1250000000000000');
158 | assert.equal((await exchange.filled.call(data.hash)).toString(10), order.takerTokenAmount / 2);
159 |
160 | await exchange.trade(data.addresses, data.values, data.sig, order.takerTokenAmount, {from: accounts[2]});
161 |
162 | assert.equal((await vault.balanceOf(0x0, feeAccount)).toString(), '2500000000000000');
163 | assert.equal((await exchange.filled.call(data.hash)).toString(10), order.takerTokenAmount);
164 | assert.equal(
165 | (await vault.balanceOf(order.makerToken, accounts[2])).toString(),
166 | (order.makerTokenAmount / 2) - 1250000000000000
167 | );
168 | });
169 |
170 | it('should transfer correctly when trade exceeds available balance of maker', async () => {
171 | await vault.deposit(0x0, order.makerTokenAmount, {from: accounts[0], value: order.makerTokenAmount / 2});
172 | await vault.approve(exchange.address);
173 |
174 | await token.mint(accounts[1], order.takerTokenAmount);
175 | await vault.deposit(token.address, order.takerTokenAmount, {from: accounts[1]});
176 | await vault.approve(exchange.address, {from: accounts[1]});
177 |
178 | await token.mint(accounts[2], order.takerTokenAmount);
179 | await vault.approve(exchange.address, {from: accounts[2]});
180 | await vault.deposit(token.address, order.takerTokenAmount, {from: accounts[2]});
181 |
182 | await exchange.trade(data.addresses, data.values, data.sig, order.takerTokenAmount, {from: accounts[1]});
183 |
184 | assert.equal((await vault.balanceOf(0x0, feeAccount)).toString(), '1250000000000000');
185 | assert.equal((await exchange.filled.call(data.hash)).toString(10), order.takerTokenAmount / 2);
186 | });
187 |
188 | it('should trade on chain created order correctly', async () => {
189 | await vault.deposit(0x0, order.makerTokenAmount, {from: accounts[0], value: order.makerTokenAmount});
190 | await vault.approve(exchange.address);
191 |
192 | await exchange.order([order.makerToken, order.takerToken], data.values, {from: accounts[0]});
193 |
194 | await token.mint(accounts[1], order.takerTokenAmount);
195 | await vault.deposit(token.address, order.takerTokenAmount, {from: accounts[1]});
196 | await vault.approve(exchange.address, {from: accounts[1]});
197 |
198 | await exchange.trade(data.addresses, data.values, '0x0', order.takerTokenAmount, {from: accounts[1]});
199 |
200 | assert.equal((await vault.balanceOf(0x0, feeAccount)).toString(10), order.makerTokenAmount * (0.25 / 100));
201 | assert.equal((await exchange.filled.call(data.hash)).toString(10), '10000000000000000000000')
202 | });
203 | });
204 |
205 | describe('on chain orders', async () => {
206 |
207 | let order;
208 | let token;
209 | let data;
210 |
211 | beforeEach(async () => {
212 | token = await MockToken.new();
213 |
214 | order = {
215 | takerToken: token.address,
216 | takerTokenAmount: '10',
217 | makerToken: '0x0000000000000000000000000000000000000000',
218 | makerTokenAmount: '100',
219 | expires: Math.floor((Date.now() / 1000) + 5000),
220 | nonce: 10,
221 | maker: accounts[0],
222 | exchange: exchange.address
223 | };
224 |
225 | data = {
226 | addresses: [order.makerToken, order.takerToken],
227 | values: [order.makerTokenAmount, order.takerTokenAmount, order.expires, order.nonce]
228 | }
229 | });
230 |
231 | it('should fail to order when vault has not been approved', async () => {
232 | try {
233 | await exchange.order(data.addresses, data.values, {from: accounts[0]});
234 | } catch (error) {
235 | return utils.ensureException(error);
236 | }
237 |
238 | assert.fail('ordering did not fail');
239 | });
240 |
241 | it('should fail to order when maker does not have enough balance', async () => {
242 | await vault.approve(exchange.address);
243 |
244 | try {
245 | await exchange.order(data.addresses, data.values, {from: accounts[0]});
246 | } catch (error) {
247 | return utils.ensureException(error);
248 | }
249 |
250 | assert.fail('ordering did not fail');
251 | });
252 |
253 | it('should allow ordering on chain', async () => {
254 | await vault.approve(exchange.address);
255 | await vault.deposit(0x0, order.takerTokenAmount, {from: accounts[0], value: order.makerTokenAmount});
256 |
257 | let result = await exchange.order(data.addresses, data.values, {from: accounts[0]});
258 |
259 | let log = result.logs[0].args;
260 | assert.equal(accounts[0], log.maker);
261 | assert.equal(order.makerToken, log.makerToken);
262 | assert.equal(order.takerToken, log.takerToken);
263 | assert.equal(order.takerTokenAmount, log.takerTokenAmount.toString(10));
264 | assert.equal(order.makerTokenAmount, log.makerTokenAmount.toString(10));
265 | assert.equal(order.expires, log.expires);
266 | assert.equal(order.nonce, log.nonce);
267 |
268 | let hashed = hashOrder(order);
269 | assert.equal(await exchange.isOrdered(accounts[0], hashed.hash), true);
270 | });
271 |
272 | it('should not allow duplicate orders', async () => {
273 | await vault.approve(exchange.address);
274 | await vault.deposit(0x0, order.takerTokenAmount, {from: accounts[0], value: order.makerTokenAmount});
275 |
276 | await exchange.order(data.addresses, data.values, {from: accounts[0]});
277 |
278 | try {
279 | await exchange.order(data.addresses, data.values, {from: accounts[0]});
280 | } catch (error) {
281 | return utils.ensureException(error);
282 | }
283 |
284 | assert.fail('ordering did not fail');
285 | });
286 | });
287 |
288 | describe('availableAmount', async () => {
289 | let order;
290 | let data;
291 |
292 | beforeEach(async () => {
293 |
294 | order = {
295 | takerToken: '0xdead',
296 | takerTokenAmount: '10',
297 | makerToken: '0x0000000000000000000000000000000000000000',
298 | makerTokenAmount: '100',
299 | expires: Math.floor((Date.now() / 1000) + 5000),
300 | nonce: 10,
301 | maker: accounts[0],
302 | exchange: exchange.address
303 | };
304 |
305 | data = {
306 | addresses: [order.maker, order.makerToken, order.takerToken],
307 | values: [order.makerTokenAmount, order.takerTokenAmount, order.expires, order.nonce]
308 | }
309 | });
310 |
311 | it('should return maker balance if it is smaller than order amount', async () => {
312 | await vault.deposit(0x0, order.makerTokenAmount / 2, {from: accounts[0], value: order.makerTokenAmount / 2});
313 | assert.equal((await exchange.availableAmount(data.addresses, data.values)).toString(10), order.takerTokenAmount / 2);
314 | });
315 |
316 | it('should return order balance if it is smaller than maker balance', async () => {
317 | await vault.deposit(0x0, order.makerTokenAmount * 2, {from: accounts[0], value: order.makerTokenAmount * 2});
318 | assert.equal((await exchange.availableAmount(data.addresses, data.values)).toString(10), order.takerTokenAmount);
319 | });
320 |
321 | });
322 |
323 | describe('canTrade', async () => {
324 |
325 | let token;
326 | let order;
327 | let data;
328 |
329 | beforeEach(async () => {
330 |
331 | token = await MockToken.new();
332 |
333 | order = {
334 | takerToken: token.address,
335 | takerTokenAmount: '10',
336 | makerToken: '0x0000000000000000000000000000000000000000',
337 | makerTokenAmount: '100',
338 | expires: Math.floor((Date.now() / 1000) + 5000),
339 | nonce: 10,
340 | maker: accounts[0],
341 | exchange: exchange.address
342 | };
343 |
344 | data = await signOrder(order);
345 | });
346 |
347 | it('should return false when order is signed by different maker', async () => {
348 | data.addresses[0] = accounts[1];
349 | assert.equal(await exchange.canTrade(data.addresses, data.values, data.sig), false);
350 | });
351 |
352 | it('should return false when order is cancelled', async () => {
353 | await exchange.cancel(data.addresses, data.values);
354 | assert.equal(await exchange.canTrade(data.addresses, data.values, data.sig), false);
355 | });
356 |
357 | it('should return false when vault has not been approved', async () => {
358 | await token.mint(accounts[0], order.takerTokenAmount);
359 | await vault.deposit(token.address, order.takerTokenAmount, {from: accounts[0]});
360 |
361 | assert.equal(await exchange.canTrade(data.addresses, data.values, data.sig), false);
362 | });
363 |
364 | it('should return false when order has been expired', async () => {
365 | order = {
366 | takerToken: token.address,
367 | takerTokenAmount: '10',
368 | makerToken: '0x0000000000000000000000000000000000000000',
369 | makerTokenAmount: '100',
370 | expires: Math.floor((Date.now() / 1000) - 5000),
371 | nonce: 10,
372 | maker: accounts[0],
373 | exchange: exchange.address
374 | };
375 |
376 | data = await signOrder(order);
377 |
378 | await vault.deposit(0x0, order.takerTokenAmount, {from: accounts[0], value: order.makerTokenAmount});
379 | await vault.approve(exchange.address);
380 |
381 | assert.equal(await exchange.canTrade(data.addresses, data.values, data.sig), false);
382 | });
383 |
384 | it('should return false when order has filled', async () => {
385 | order = {
386 | takerToken: token.address,
387 | takerTokenAmount: '10',
388 | makerToken: '0x0000000000000000000000000000000000000000',
389 | makerTokenAmount: '100',
390 | expires: Math.floor((Date.now() / 1000) + 5000),
391 | nonce: 10,
392 | maker: accounts[0],
393 | exchange: exchange.address
394 | };
395 |
396 | data = await signOrder(order);
397 |
398 | await vault.deposit(0x0, order.makerTokenAmount, {from: accounts[0], value: order.makerTokenAmount});
399 | await vault.approve(exchange.address);
400 |
401 | await token.mint(accounts[1], order.takerTokenAmount);
402 | await vault.deposit(token.address, order.takerTokenAmount, {from: accounts[1]});
403 | await vault.approve(exchange.address, {from: accounts[1]});
404 |
405 | await exchange.trade(data.addresses, data.values, data.sig, order.takerTokenAmount, {from: accounts[1]});
406 | assert.equal(await exchange.canTrade(data.addresses, data.values, data.sig), false);
407 | });
408 | });
409 |
410 | describe('token overflow', async () => {
411 |
412 | it('should allow withdrawing of overflow tokens', async () => {
413 |
414 | let token = await MockToken.new();
415 |
416 | let amount = 10;
417 | await token.mint(accounts[1], amount);
418 | await token.transfer(exchange.address, amount, {from: accounts[1]});
419 |
420 | await exchange.withdraw(token.address, amount / 2, {from: accounts[0]});
421 | assert.equal((await token.balanceOf(accounts[0])).toString(10), amount / 2);
422 | });
423 |
424 | it('should allow withdrawing of overflow eth', async () => {
425 | let selfdestruct = await SelfDestructor.new();
426 |
427 | let amount = 10;
428 | await selfdestruct.sendTransaction({from: accounts[0], value: amount});
429 | await selfdestruct.destroy(exchange.address);
430 |
431 | assert.equal(await web3.eth.getBalance(exchange.address), amount);
432 | await exchange.withdraw(0x0, amount, {from: accounts[0]});
433 | assert.equal((await web3.eth.getBalance(exchange.address)).toString(10), 0);
434 | });
435 | });
436 |
437 | it('should notify subscriber of trade', async () => {
438 | let subscriber = await HookSubscriber.new();
439 | let amount = 10;
440 | let token = await MockToken.new();
441 |
442 | await token.mint(subscriber.address, amount);
443 |
444 | let order = {
445 | takerToken: '0x0000000000000000000000000000000000000000',
446 | takerTokenAmount: '10',
447 | makerToken: token.address,
448 | makerTokenAmount: amount,
449 | expires: Math.floor((Date.now() / 1000) + 5000),
450 | nonce: 10,
451 | exchange: exchange.address
452 | };
453 |
454 | let data = {
455 | addresses: [order.makerToken, order.takerToken],
456 | values: [order.makerTokenAmount, order.takerTokenAmount, order.expires, order.nonce]
457 | };
458 |
459 | await subscriber.createOrder(data.addresses, data.values, exchange.address);
460 |
461 | await vault.deposit(0x0, order.takerTokenAmount, {from: accounts[1], value: order.takerTokenAmount});
462 | await vault.approve(exchange.address, {from: accounts[1]});
463 |
464 | assert.equal(0, (await subscriber.tokens.call(order.takerToken)).toString(10));
465 |
466 | await exchange.trade(
467 | [subscriber.address, order.makerToken, order.takerToken],
468 | data.values, '0x0', order.takerTokenAmount, {from: accounts[1]}
469 | );
470 |
471 | assert.equal(amount, (await subscriber.tokens.call(order.takerToken)).toString(10));
472 |
473 | });
474 | });
475 |
476 | async function signOrder(order) {
477 | let hashed = hashOrder(order);
478 |
479 | let sig = (await web3.eth.sign(hashed.hash, order.maker)).slice(2);
480 |
481 | let r = ethutil.toBuffer('0x' + sig.substring(0, 64));
482 | let s = ethutil.toBuffer('0x' + sig.substring(64, 128));
483 | let v = ethutil.toBuffer(parseInt(sig.substring(128, 130), 16) + 27);
484 | let mode = ethutil.toBuffer(1);
485 |
486 | let signature = '0x' + Buffer.concat([mode, v, r, s]).toString('hex');
487 |
488 | return {addresses: hashed.addresses, values: hashed.values, sig: signature, hash: hashed.hash};
489 | }
490 |
491 | function hashOrder(order) {
492 | let addresses = [order.maker, order.makerToken, order.takerToken];
493 | let values = [order.makerTokenAmount, order.takerTokenAmount, order.expires, order.nonce];
494 |
495 | let valuesHash = web3Utils.soliditySha3.apply(null, Object.entries(order).map(function (x) {
496 | return x[1]
497 | }));
498 |
499 | let hash = web3Utils.soliditySha3(schema_hash, valuesHash);
500 |
501 | return {hash: hash, addresses: addresses, values: values}
502 | }
503 |
--------------------------------------------------------------------------------
/test/TestVault.js:
--------------------------------------------------------------------------------
1 | const Vault = artifacts.require('vault/Vault.sol');
2 | const MockToken = artifacts.require('./mocks/Token.sol');
3 | const SelfDestructor = artifacts.require('./mocks/SelfDestructor.sol');
4 | const EIP820Registry = require('eip820');
5 | const utils = require('./helpers/Utils.js');
6 | const Web3 = require('web3');
7 |
8 | contract('Vault', function (accounts) {
9 |
10 | let vault, token, erc820Registry;
11 | let web3;
12 |
13 | beforeEach(async () => {
14 | erc820Registry = await EIP820Registry.deploy(
15 | new Web3(new Web3.providers.WebsocketProvider("ws://localhost:7545/")),
16 | accounts[0]
17 | );
18 |
19 | web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545/"));
20 |
21 | token = await MockToken.new();
22 | vault = await Vault.new(erc820Registry.$address);
23 | });
24 |
25 | describe('funds', async () => {
26 |
27 | it('should revert when directly depositing ether', async () => {
28 | try {
29 | await vault.sendTransaction({from: accounts[0], value: 1});
30 | } catch (error) {
31 | return utils.ensureException(error);
32 | }
33 |
34 | assert.fail('depositing ether did not fail');
35 | });
36 |
37 | it('should allow depositing of token', async () => {
38 | let total = 30;
39 | let using = total / 2;
40 |
41 | await token.mint(accounts[0], total);
42 | await vault.deposit(token.address, using, {from: accounts[0]});
43 | assert.equal(await vault.balanceOf.call(token.address, accounts[0]), using);
44 | });
45 |
46 | it('should allow depositing of ether', async () => {
47 | await vault.deposit(0x0, 0, {from: accounts[0], value: 10});
48 | assert.equal(await vault.balanceOf.call(0x0, accounts[0]), 10);
49 | });
50 |
51 | it('should allow withdrawing of tokens', async () => {
52 | let total = 30;
53 | let using = total / 2;
54 |
55 | await token.mint(accounts[0], total);
56 | await vault.deposit(token.address, using, {from: accounts[0]});
57 | assert.equal(await vault.balanceOf.call(token.address, accounts[0]), using);
58 |
59 | await vault.withdraw(token.address, using, {from: accounts[0]});
60 | assert.equal(await vault.balanceOf.call(token.address, accounts[0]), 0);
61 | assert.equal(await token.balanceOf.call(accounts[0]), total);
62 | });
63 |
64 | it('should allow withdrawing of ether', async () => {
65 | let using = 15;
66 |
67 | await vault.deposit(0x0, using, {from: accounts[0], value: using});
68 | assert.equal(await vault.balanceOf.call(0x0, accounts[0]), using);
69 |
70 | await vault.withdraw(0x0, using, {from: accounts[0]});
71 | assert.equal(await vault.balanceOf.call(0x0, accounts[0]), 0);
72 | });
73 | });
74 |
75 | describe('overflow', async () => {
76 |
77 | it('should allow withdrawing of overflow tokens', async () => {
78 | await vault.deposit(token.address, 10, {from: accounts[0]});
79 | await token.transfer(vault.address, 10, {from: accounts[0]});
80 |
81 | let previousBalance = await token.balanceOf(accounts[0]);
82 |
83 | assert.equal(await token.balanceOf(vault.address), 20);
84 | await vault.withdrawOverflow(token.address, {from: accounts[0]});
85 | assert.equal(await token.balanceOf(vault.address), 10);
86 |
87 | let balance = await token.balanceOf(accounts[0]);
88 | assert.equal(balance.toString(18), previousBalance.plus(10).toString(18));
89 | });
90 |
91 | it('should allow withdrawing of overflow eth', async () => {
92 | let selfdestruct = await SelfDestructor.new();
93 | await selfdestruct.sendTransaction({from: accounts[0], value: 10});
94 | await selfdestruct.destroy(vault.address);
95 | await vault.deposit(0x0, 10, {from: accounts[0], value: 10});
96 |
97 | assert.equal(await web3.eth.getBalance(vault.address), 20);
98 | await vault.withdrawOverflow(0x0, {from: accounts[0]});
99 | assert.equal(await web3.eth.getBalance(vault.address), 10);
100 | });
101 | });
102 |
103 | it('should allow setting and unsetting of ERC777 token', async () => {
104 | await vault.setERC777(token.address, {from: accounts[0]});
105 | assert.equal(await vault.isERC777(token.address), true);
106 |
107 | await vault.unsetERC777(token.address, {from: accounts[0]});
108 | assert.equal(await vault.isERC777(token.address), false);
109 | });
110 |
111 | it('should allow a maker to approve and unapprove an exchange', async () => {
112 | await vault.addSpender(accounts[1]);
113 |
114 | assert.equal(await vault.isApproved(accounts[0], accounts[1]), false);
115 |
116 | await vault.approve(accounts[1], {from: accounts[0]});
117 | assert.equal(await vault.isApproved(accounts[0], accounts[1]), true);
118 |
119 | await vault.unapprove(accounts[1], {from: accounts[0]});
120 | assert.equal(await vault.isApproved(accounts[0], accounts[1]), false);
121 | });
122 |
123 | it('should allow funds to be transferred', async () => {
124 | let exchange = accounts[2];
125 |
126 | await vault.addSpender(exchange);
127 | await vault.approve(exchange, {from: accounts[0]});
128 |
129 | let sum = 30;
130 |
131 | await token.mint(accounts[0], sum);
132 | await vault.deposit(token.address, sum, {from: accounts[0]});
133 | assert.equal(await vault.balanceOf.call(token.address, accounts[0]), sum);
134 |
135 | await vault.transfer(token.address, accounts[0], accounts[1], sum, {from: exchange});
136 | assert.equal(await vault.balanceOf.call(token.address, accounts[1]), sum);
137 | });
138 |
139 | it('should allow adding and removing spender', async () => {
140 | let exchange = accounts[2];
141 |
142 | await vault.addSpender(exchange);
143 | assert.equal(true, await vault.isSpender(exchange));
144 | assert.equal(exchange, await vault.latestSpender());
145 |
146 | await vault.removeSpender(exchange);
147 | assert.equal(false, await vault.isSpender(exchange));
148 | });
149 | });
150 |
--------------------------------------------------------------------------------
/test/helpers/Utils.js:
--------------------------------------------------------------------------------
1 | function isException(error) {
2 | let strError = error.toString();
3 | return strError.includes('invalid opcode') || strError.includes('invalid JUMP') || strError.includes('revert');
4 | }
5 |
6 | function ensureException(error) {
7 | assert(isException(error), error.toString());
8 | }
9 |
10 | function assertJump(error) {
11 | assert.isAbove(error.message.search('invalid JUMP'), -1, 'Invalid JUMP error must be returned');
12 | }
13 |
14 | module.exports = {
15 | zeroAddress: '0x0000000000000000000000000000000000000000',
16 | isException: isException,
17 | ensureException: ensureException,
18 | assertJump: assertJump
19 | };
--------------------------------------------------------------------------------
/test/mocks/HookSubscriberMock.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | import "./../../contracts/ExchangeInterface.sol";
4 |
5 | contract HookSubscriberMock {
6 |
7 | mapping (address => uint) public tokens;
8 |
9 | function tradeExecuted(address token, uint amount) external {
10 | tokens[token] += amount;
11 | }
12 |
13 | function createOrder(address[2] addresses, uint[4] values, ExchangeInterface exchange) external {
14 | exchange.subscribe();
15 | exchange.vault().approve(exchange);
16 | exchange.vault().deposit(addresses[0], values[0]);
17 | exchange.order(addresses, values);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/test/mocks/SelfDestructor.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | contract SelfDestructor {
4 |
5 | function () public payable { }
6 |
7 | function destroy(address vault) public {
8 | selfdestruct(vault);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/test/mocks/Token.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | contract Token {
4 |
5 | mapping (address => uint) balances;
6 |
7 | function balanceOf(address owner) public view returns (uint) {
8 | return balances[owner];
9 | }
10 |
11 | function transfer(address to, uint value) public returns (bool) {
12 | balances[msg.sender] = balances[msg.sender] - value;
13 | balances[to] = balances[to] + value;
14 | return true;
15 | }
16 |
17 | function transferFrom(address from, address to, uint value) public returns (bool) {
18 | balances[from] = balances[from] - value;
19 | balances[to] = balances[to] + value;
20 | return true;
21 | }
22 |
23 | function mint(address to, uint _amount) public {
24 | balances[to] = balances[to] + _amount;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/truffle.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | networks: {
3 | coverage: {
4 | host: "localhost",
5 | network_id: "*",
6 | port: 8555,
7 | gas: 0xffffffffff,
8 | gasPrice: 0x01
9 | },
10 | }
11 | };
--------------------------------------------------------------------------------