diff --git a/test/compilationTests/gnosis/Events/CategoricalEvent.sol b/test/compilationTests/gnosis/Events/CategoricalEvent.sol new file mode 100644 index 000000000..fbd1d744e --- /dev/null +++ b/test/compilationTests/gnosis/Events/CategoricalEvent.sol @@ -0,0 +1,53 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; + + +/// @title Categorical event contract - Categorical events resolve to an outcome from a set of outcomes +/// @author Stefan George - +contract CategoricalEvent is Event { + + /* + * Public functions + */ + /// @dev Contract constructor validates and sets basic event properties + /// @param _collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param _oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + function CategoricalEvent( + Token _collateralToken, + Oracle _oracle, + uint8 outcomeCount + ) + public + Event(_collateralToken, _oracle, outcomeCount) + { + + } + + /// @dev Exchanges sender's winning outcome tokens for collateral tokens + /// @return Sender's winnings + function redeemWinnings() + public + returns (uint winnings) + { + // Winning outcome has to be set + require(isOutcomeSet); + // Calculate winnings + winnings = outcomeTokens[uint(outcome)].balanceOf(msg.sender); + // Revoke tokens from winning outcome + outcomeTokens[uint(outcome)].revoke(msg.sender, winnings); + // Payout winnings + require(collateralToken.transfer(msg.sender, winnings)); + WinningsRedemption(msg.sender, winnings); + } + + /// @dev Calculates and returns event hash + /// @return Event hash + function getEventHash() + public + constant + returns (bytes32) + { + return keccak256(collateralToken, oracle, outcomeTokens.length); + } +} diff --git a/test/compilationTests/gnosis/Events/Event.sol b/test/compilationTests/gnosis/Events/Event.sol new file mode 100644 index 000000000..9aa257c46 --- /dev/null +++ b/test/compilationTests/gnosis/Events/Event.sol @@ -0,0 +1,128 @@ +pragma solidity ^0.4.11; +import "../Tokens/Token.sol"; +import "../Tokens/OutcomeToken.sol"; +import "../Oracles/Oracle.sol"; + + +/// @title Event contract - Provide basic functionality required by different event types +/// @author Stefan George - +contract Event { + + /* + * Events + */ + event OutcomeTokenCreation(OutcomeToken outcomeToken, uint8 index); + event OutcomeTokenSetIssuance(address indexed buyer, uint collateralTokenCount); + event OutcomeTokenSetRevocation(address indexed seller, uint outcomeTokenCount); + event OutcomeAssignment(int outcome); + event WinningsRedemption(address indexed receiver, uint winnings); + + /* + * Storage + */ + Token public collateralToken; + Oracle public oracle; + bool public isOutcomeSet; + int public outcome; + OutcomeToken[] public outcomeTokens; + + /* + * Public functions + */ + /// @dev Contract constructor validates and sets basic event properties + /// @param _collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param _oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + function Event(Token _collateralToken, Oracle _oracle, uint8 outcomeCount) + public + { + // Validate input + require(address(_collateralToken) != 0 && address(_oracle) != 0 && outcomeCount >= 2); + collateralToken = _collateralToken; + oracle = _oracle; + // Create an outcome token for each outcome + for (uint8 i = 0; i < outcomeCount; i++) { + OutcomeToken outcomeToken = new OutcomeToken(); + outcomeTokens.push(outcomeToken); + OutcomeTokenCreation(outcomeToken, i); + } + } + + /// @dev Buys equal number of tokens of all outcomes, exchanging collateral tokens and sets of outcome tokens 1:1 + /// @param collateralTokenCount Number of collateral tokens + function buyAllOutcomes(uint collateralTokenCount) + public + { + // Transfer collateral tokens to events contract + require(collateralToken.transferFrom(msg.sender, this, collateralTokenCount)); + // Issue new outcome tokens to sender + for (uint8 i = 0; i < outcomeTokens.length; i++) + outcomeTokens[i].issue(msg.sender, collateralTokenCount); + OutcomeTokenSetIssuance(msg.sender, collateralTokenCount); + } + + /// @dev Sells equal number of tokens of all outcomes, exchanging collateral tokens and sets of outcome tokens 1:1 + /// @param outcomeTokenCount Number of outcome tokens + function sellAllOutcomes(uint outcomeTokenCount) + public + { + // Revoke sender's outcome tokens of all outcomes + for (uint8 i = 0; i < outcomeTokens.length; i++) + outcomeTokens[i].revoke(msg.sender, outcomeTokenCount); + // Transfer collateral tokens to sender + require(collateralToken.transfer(msg.sender, outcomeTokenCount)); + OutcomeTokenSetRevocation(msg.sender, outcomeTokenCount); + } + + /// @dev Sets winning event outcome + function setOutcome() + public + { + // Winning outcome is not set yet in event contract but in oracle contract + require(!isOutcomeSet && oracle.isOutcomeSet()); + // Set winning outcome + outcome = oracle.getOutcome(); + isOutcomeSet = true; + OutcomeAssignment(outcome); + } + + /// @dev Returns outcome count + /// @return Outcome count + function getOutcomeCount() + public + constant + returns (uint8) + { + return uint8(outcomeTokens.length); + } + + /// @dev Returns outcome tokens array + /// @return Outcome tokens + function getOutcomeTokens() + public + constant + returns (OutcomeToken[]) + { + return outcomeTokens; + } + + /// @dev Returns the amount of outcome tokens held by owner + /// @return Outcome token distribution + function getOutcomeTokenDistribution(address owner) + public + constant + returns (uint[] outcomeTokenDistribution) + { + outcomeTokenDistribution = new uint[](outcomeTokens.length); + for (uint8 i = 0; i < outcomeTokenDistribution.length; i++) + outcomeTokenDistribution[i] = outcomeTokens[i].balanceOf(owner); + } + + /// @dev Calculates and returns event hash + /// @return Event hash + function getEventHash() public constant returns (bytes32); + + /// @dev Exchanges sender's winning outcome tokens for collateral tokens + /// @return Sender's winnings + function redeemWinnings() public returns (uint); +} diff --git a/test/compilationTests/gnosis/Events/EventFactory.sol b/test/compilationTests/gnosis/Events/EventFactory.sol new file mode 100644 index 000000000..dfb1a5791 --- /dev/null +++ b/test/compilationTests/gnosis/Events/EventFactory.sol @@ -0,0 +1,79 @@ +pragma solidity ^0.4.11; +import "../Events/CategoricalEvent.sol"; +import "../Events/ScalarEvent.sol"; + + +/// @title Event factory contract - Allows creation of categorical and scalar events +/// @author Stefan George - +contract EventFactory { + + /* + * Events + */ + event CategoricalEventCreation(address indexed creator, CategoricalEvent categoricalEvent, Token collateralToken, Oracle oracle, uint8 outcomeCount); + event ScalarEventCreation(address indexed creator, ScalarEvent scalarEvent, Token collateralToken, Oracle oracle, int lowerBound, int upperBound); + + /* + * Storage + */ + mapping (bytes32 => CategoricalEvent) public categoricalEvents; + mapping (bytes32 => ScalarEvent) public scalarEvents; + + /* + * Public functions + */ + /// @dev Creates a new categorical event and adds it to the event mapping + /// @param collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + /// @return Event contract + function createCategoricalEvent( + Token collateralToken, + Oracle oracle, + uint8 outcomeCount + ) + public + returns (CategoricalEvent eventContract) + { + bytes32 eventHash = keccak256(collateralToken, oracle, outcomeCount); + // Event should not exist yet + require(address(categoricalEvents[eventHash]) == 0); + // Create event + eventContract = new CategoricalEvent( + collateralToken, + oracle, + outcomeCount + ); + categoricalEvents[eventHash] = eventContract; + CategoricalEventCreation(msg.sender, eventContract, collateralToken, oracle, outcomeCount); + } + + /// @dev Creates a new scalar event and adds it to the event mapping + /// @param collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param oracle Oracle contract used to resolve the event + /// @param lowerBound Lower bound for event outcome + /// @param upperBound Lower bound for event outcome + /// @return Event contract + function createScalarEvent( + Token collateralToken, + Oracle oracle, + int lowerBound, + int upperBound + ) + public + returns (ScalarEvent eventContract) + { + bytes32 eventHash = keccak256(collateralToken, oracle, lowerBound, upperBound); + // Event should not exist yet + require(address(scalarEvents[eventHash]) == 0); + // Create event + eventContract = new ScalarEvent( + collateralToken, + oracle, + lowerBound, + upperBound + ); + scalarEvents[eventHash] = eventContract; + ScalarEventCreation(msg.sender, eventContract, collateralToken, oracle, lowerBound, upperBound); + } +} diff --git a/test/compilationTests/gnosis/Events/ScalarEvent.sol b/test/compilationTests/gnosis/Events/ScalarEvent.sol new file mode 100644 index 000000000..2e5718efe --- /dev/null +++ b/test/compilationTests/gnosis/Events/ScalarEvent.sol @@ -0,0 +1,87 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; + + +/// @title Scalar event contract - Scalar events resolve to a number within a range +/// @author Stefan George - +contract ScalarEvent is Event { + using Math for *; + + /* + * Constants + */ + uint8 public constant SHORT = 0; + uint8 public constant LONG = 1; + uint24 public constant OUTCOME_RANGE = 1000000; + + /* + * Storage + */ + int public lowerBound; + int public upperBound; + + /* + * Public functions + */ + /// @dev Contract constructor validates and sets basic event properties + /// @param _collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param _oracle Oracle contract used to resolve the event + /// @param _lowerBound Lower bound for event outcome + /// @param _upperBound Lower bound for event outcome + function ScalarEvent( + Token _collateralToken, + Oracle _oracle, + int _lowerBound, + int _upperBound + ) + public + Event(_collateralToken, _oracle, 2) + { + // Validate bounds + require(_upperBound > _lowerBound); + lowerBound = _lowerBound; + upperBound = _upperBound; + } + + /// @dev Exchanges sender's winning outcome tokens for collateral tokens + /// @return Sender's winnings + function redeemWinnings() + public + returns (uint winnings) + { + // Winning outcome has to be set + require(isOutcomeSet); + // Calculate winnings + uint24 convertedWinningOutcome; + // Outcome is lower than defined lower bound + if (outcome < lowerBound) + convertedWinningOutcome = 0; + // Outcome is higher than defined upper bound + else if (outcome > upperBound) + convertedWinningOutcome = OUTCOME_RANGE; + // Map outcome to outcome range + else + convertedWinningOutcome = uint24(OUTCOME_RANGE * (outcome - lowerBound) / (upperBound - lowerBound)); + uint factorShort = OUTCOME_RANGE - convertedWinningOutcome; + uint factorLong = OUTCOME_RANGE - factorShort; + uint shortOutcomeTokenCount = outcomeTokens[SHORT].balanceOf(msg.sender); + uint longOutcomeTokenCount = outcomeTokens[LONG].balanceOf(msg.sender); + winnings = shortOutcomeTokenCount.mul(factorShort).add(longOutcomeTokenCount.mul(factorLong)) / OUTCOME_RANGE; + // Revoke all outcome tokens + outcomeTokens[SHORT].revoke(msg.sender, shortOutcomeTokenCount); + outcomeTokens[LONG].revoke(msg.sender, longOutcomeTokenCount); + // Payout winnings to sender + require(collateralToken.transfer(msg.sender, winnings)); + WinningsRedemption(msg.sender, winnings); + } + + /// @dev Calculates and returns event hash + /// @return Event hash + function getEventHash() + public + constant + returns (bytes32) + { + return keccak256(collateralToken, oracle, lowerBound, upperBound); + } +} diff --git a/test/compilationTests/gnosis/LICENSE b/test/compilationTests/gnosis/LICENSE new file mode 100644 index 000000000..0f2001b59 --- /dev/null +++ b/test/compilationTests/gnosis/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Decentralized prediction markets and decentralized oracle system + #Copyright (C) 2015 Forecast Foundation OU, full GPL notice in LICENSE + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Decentralized prediction markets and decentralized oracle system + Copyright (C) 2015 Forecast Foundation OU + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/test/compilationTests/gnosis/MarketMakers/LMSRMarketMaker.sol b/test/compilationTests/gnosis/MarketMakers/LMSRMarketMaker.sol new file mode 100644 index 000000000..1529129dc --- /dev/null +++ b/test/compilationTests/gnosis/MarketMakers/LMSRMarketMaker.sol @@ -0,0 +1,180 @@ +pragma solidity ^0.4.11; +import "../Utils/Math.sol"; +import "../MarketMakers/MarketMaker.sol"; + + +/// @title LMSR market maker contract - Calculates share prices based on share distribution and initial funding +/// @author Alan Lu - +contract LMSRMarketMaker is MarketMaker { + using Math for *; + + /* + * Constants + */ + uint constant ONE = 0x10000000000000000; + int constant EXP_LIMIT = 2352680790717288641401; + + /* + * Public functions + */ + /// @dev Returns cost to buy given number of outcome tokens + /// @param market Market contract + /// @param outcomeTokenIndex Index of outcome to buy + /// @param outcomeTokenCount Number of outcome tokens to buy + /// @return Cost + function calcCost(Market market, uint8 outcomeTokenIndex, uint outcomeTokenCount) + public + constant + returns (uint cost) + { + require(market.eventContract().getOutcomeCount() > 1); + int[] memory netOutcomeTokensSold = getNetOutcomeTokensSold(market); + // Calculate cost level based on net outcome token balances + int logN = Math.ln(netOutcomeTokensSold.length * ONE); + uint funding = market.funding(); + int costLevelBefore = calcCostLevel(logN, netOutcomeTokensSold, funding); + // Add outcome token count to net outcome token balance + require(int(outcomeTokenCount) >= 0); + netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].add(int(outcomeTokenCount)); + // Calculate cost level after balance was updated + int costLevelAfter = calcCostLevel(logN, netOutcomeTokensSold, funding); + // Calculate cost as cost level difference + require(costLevelAfter >= costLevelBefore); + cost = uint(costLevelAfter - costLevelBefore); + // Take the ceiling to account for rounding + if (cost / ONE * ONE == cost) + cost /= ONE; + else + // Integer division by ONE ensures there is room to (+ 1) + cost = cost / ONE + 1; + // Make sure cost is not bigger than 1 per share + if (cost > outcomeTokenCount) + cost = outcomeTokenCount; + } + + /// @dev Returns profit for selling given number of outcome tokens + /// @param market Market contract + /// @param outcomeTokenIndex Index of outcome to sell + /// @param outcomeTokenCount Number of outcome tokens to sell + /// @return Profit + function calcProfit(Market market, uint8 outcomeTokenIndex, uint outcomeTokenCount) + public + constant + returns (uint profit) + { + require(market.eventContract().getOutcomeCount() > 1); + int[] memory netOutcomeTokensSold = getNetOutcomeTokensSold(market); + // Calculate cost level based on net outcome token balances + int logN = Math.ln(netOutcomeTokensSold.length * ONE); + uint funding = market.funding(); + int costLevelBefore = calcCostLevel(logN, netOutcomeTokensSold, funding); + // Subtract outcome token count from the net outcome token balance + require(int(outcomeTokenCount) >= 0); + netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].sub(int(outcomeTokenCount)); + // Calculate cost level after balance was updated + int costLevelAfter = calcCostLevel(logN, netOutcomeTokensSold, funding); + // Calculate profit as cost level difference + require(costLevelBefore >= costLevelAfter); + // Take the floor + profit = uint(costLevelBefore - costLevelAfter) / ONE; + } + + /// @dev Returns marginal price of an outcome + /// @param market Market contract + /// @param outcomeTokenIndex Index of outcome to determine marginal price of + /// @return Marginal price of an outcome as a fixed point number + function calcMarginalPrice(Market market, uint8 outcomeTokenIndex) + public + constant + returns (uint price) + { + require(market.eventContract().getOutcomeCount() > 1); + int[] memory netOutcomeTokensSold = getNetOutcomeTokensSold(market); + int logN = Math.ln(netOutcomeTokensSold.length * ONE); + uint funding = market.funding(); + // The price function is exp(quantities[i]/b) / sum(exp(q/b) for q in quantities) + // To avoid overflow, calculate with + // exp(quantities[i]/b - offset) / sum(exp(q/b - offset) for q in quantities) + var (sum, , outcomeExpTerm) = sumExpOffset(logN, netOutcomeTokensSold, funding, outcomeTokenIndex); + return outcomeExpTerm / (sum / ONE); + } + + /* + * Private functions + */ + /// @dev Calculates the result of the LMSR cost function which is used to + /// derive prices from the market state + /// @param logN Logarithm of the number of outcomes + /// @param netOutcomeTokensSold Net outcome tokens sold by market + /// @param funding Initial funding for market + /// @return Cost level + function calcCostLevel(int logN, int[] netOutcomeTokensSold, uint funding) + private + constant + returns(int costLevel) + { + // The cost function is C = b * log(sum(exp(q/b) for q in quantities)). + // To avoid overflow, we need to calc with an exponent offset: + // C = b * (offset + log(sum(exp(q/b - offset) for q in quantities))) + var (sum, offset, ) = sumExpOffset(logN, netOutcomeTokensSold, funding, 0); + costLevel = Math.ln(sum); + costLevel = costLevel.add(offset); + costLevel = (costLevel.mul(int(ONE)) / logN).mul(int(funding)); + } + + /// @dev Calculates sum(exp(q/b - offset) for q in quantities), where offset is set + /// so that the sum fits in 248-256 bits + /// @param logN Logarithm of the number of outcomes + /// @param netOutcomeTokensSold Net outcome tokens sold by market + /// @param funding Initial funding for market + /// @param outcomeIndex Index of exponential term to extract (for use by marginal price function) + /// @return A result structure composed of the sum, the offset used, and the summand associated with the supplied index + function sumExpOffset(int logN, int[] netOutcomeTokensSold, uint funding, uint8 outcomeIndex) + private + constant + returns (uint sum, int offset, uint outcomeExpTerm) + { + // Naive calculation of this causes an overflow + // since anything above a bit over 133*ONE supplied to exp will explode + // as exp(133) just about fits into 192 bits of whole number data. + + // The choice of this offset is subject to another limit: + // computing the inner sum successfully. + // Since the index is 8 bits, there has to be 8 bits of headroom for + // each summand, meaning q/b - offset <= exponential_limit, + // where that limit can be found with `mp.floor(mp.log((2**248 - 1) / ONE) * ONE)` + // That is what EXP_LIMIT is set to: it is about 127.5 + + // finally, if the distribution looks like [BIG, tiny, tiny...], using a + // BIG offset will cause the tiny quantities to go really negative + // causing the associated exponentials to vanish. + + int maxQuantity = Math.max(netOutcomeTokensSold); + require(logN >= 0 && int(funding) >= 0); + offset = maxQuantity.mul(logN) / int(funding); + offset = offset.sub(EXP_LIMIT); + uint term; + for (uint8 i = 0; i < netOutcomeTokensSold.length; i++) { + term = Math.exp((netOutcomeTokensSold[i].mul(logN) / int(funding)).sub(offset)); + if (i == outcomeIndex) + outcomeExpTerm = term; + sum = sum.add(term); + } + } + + /// @dev Gets net outcome tokens sold by market. Since all sets of outcome tokens are backed by + /// corresponding collateral tokens, the net quantity of a token sold by the market is the + /// number of collateral tokens (which is the same as the number of outcome tokens the + /// market created) subtracted by the quantity of that token held by the market. + /// @param market Market contract + /// @return Net outcome tokens sold by market + function getNetOutcomeTokensSold(Market market) + private + constant + returns (int[] quantities) + { + quantities = new int[](market.eventContract().getOutcomeCount()); + for (uint8 i = 0; i < quantities.length; i++) + quantities[i] = market.netOutcomeTokensSold(i); + } +} diff --git a/test/compilationTests/gnosis/MarketMakers/MarketMaker.sol b/test/compilationTests/gnosis/MarketMakers/MarketMaker.sol new file mode 100644 index 000000000..3162ce64e --- /dev/null +++ b/test/compilationTests/gnosis/MarketMakers/MarketMaker.sol @@ -0,0 +1,14 @@ +pragma solidity ^0.4.11; +import "../Markets/Market.sol"; + + +/// @title Abstract market maker contract - Functions to be implemented by market maker contracts +contract MarketMaker { + + /* + * Public functions + */ + function calcCost(Market market, uint8 outcomeTokenIndex, uint outcomeTokenCount) public constant returns (uint); + function calcProfit(Market market, uint8 outcomeTokenIndex, uint outcomeTokenCount) public constant returns (uint); + function calcMarginalPrice(Market market, uint8 outcomeTokenIndex) public constant returns (uint); +} diff --git a/test/compilationTests/gnosis/Markets/Campaign.sol b/test/compilationTests/gnosis/Markets/Campaign.sol new file mode 100644 index 000000000..9aee10332 --- /dev/null +++ b/test/compilationTests/gnosis/Markets/Campaign.sol @@ -0,0 +1,177 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; +import "../Markets/StandardMarketFactory.sol"; +import "../Utils/Math.sol"; + + +/// @title Campaign contract - Allows to crowdfund a market +/// @author Stefan George - +contract Campaign { + using Math for *; + + /* + * Events + */ + event CampaignFunding(address indexed sender, uint funding); + event CampaignRefund(address indexed sender, uint refund); + event MarketCreation(Market indexed market); + event MarketClosing(); + event FeeWithdrawal(address indexed receiver, uint fees); + + /* + * Constants + */ + uint24 public constant FEE_RANGE = 1000000; // 100% + + /* + * Storage + */ + Event public eventContract; + MarketFactory public marketFactory; + MarketMaker public marketMaker; + Market public market; + uint24 public fee; + uint public funding; + uint public deadline; + uint public finalBalance; + mapping (address => uint) public contributions; + Stages public stage; + + enum Stages { + AuctionStarted, + AuctionSuccessful, + AuctionFailed, + MarketCreated, + MarketClosed + } + + /* + * Modifiers + */ + modifier atStage(Stages _stage) { + // Contract has to be in given stage + require(stage == _stage); + _; + } + + modifier timedTransitions() { + if (stage == Stages.AuctionStarted && deadline < now) + stage = Stages.AuctionFailed; + _; + } + + /* + * Public functions + */ + /// @dev Constructor validates and sets campaign properties + /// @param _eventContract Event contract + /// @param _marketFactory Market factory contract + /// @param _marketMaker Market maker contract + /// @param _fee Market fee + /// @param _funding Initial funding for market + /// @param _deadline Campaign deadline + function Campaign( + Event _eventContract, + MarketFactory _marketFactory, + MarketMaker _marketMaker, + uint24 _fee, + uint _funding, + uint _deadline + ) + public + { + // Validate input + require( address(_eventContract) != 0 + && address(_marketFactory) != 0 + && address(_marketMaker) != 0 + && _fee < FEE_RANGE + && _funding > 0 + && now < _deadline); + eventContract = _eventContract; + marketFactory = _marketFactory; + marketMaker = _marketMaker; + fee = _fee; + funding = _funding; + deadline = _deadline; + } + + /// @dev Allows to contribute to required market funding + /// @param amount Amount of collateral tokens + function fund(uint amount) + public + timedTransitions + atStage(Stages.AuctionStarted) + { + uint raisedAmount = eventContract.collateralToken().balanceOf(this); + uint maxAmount = funding.sub(raisedAmount); + if (maxAmount < amount) + amount = maxAmount; + // Collect collateral tokens + require(eventContract.collateralToken().transferFrom(msg.sender, this, amount)); + contributions[msg.sender] = contributions[msg.sender].add(amount); + if (amount == maxAmount) + stage = Stages.AuctionSuccessful; + CampaignFunding(msg.sender, amount); + } + + /// @dev Withdraws refund amount + /// @return Refund amount + function refund() + public + timedTransitions + atStage(Stages.AuctionFailed) + returns (uint refundAmount) + { + refundAmount = contributions[msg.sender]; + contributions[msg.sender] = 0; + // Refund collateral tokens + require(eventContract.collateralToken().transfer(msg.sender, refundAmount)); + CampaignRefund(msg.sender, refundAmount); + } + + /// @dev Allows to create market after successful funding + /// @return Market address + function createMarket() + public + timedTransitions + atStage(Stages.AuctionSuccessful) + returns (Market) + { + market = marketFactory.createMarket(eventContract, marketMaker, fee); + require(eventContract.collateralToken().approve(market, funding)); + market.fund(funding); + stage = Stages.MarketCreated; + MarketCreation(market); + return market; + } + + /// @dev Allows to withdraw fees from market contract to campaign contract + /// @return Fee amount + function closeMarket() + public + atStage(Stages.MarketCreated) + { + // Winning outcome should be set + require(eventContract.isOutcomeSet()); + market.close(); + market.withdrawFees(); + eventContract.redeemWinnings(); + finalBalance = eventContract.collateralToken().balanceOf(this); + stage = Stages.MarketClosed; + MarketClosing(); + } + + /// @dev Allows to withdraw fees from campaign contract to contributor + /// @return Fee amount + function withdrawFees() + public + atStage(Stages.MarketClosed) + returns (uint fees) + { + fees = finalBalance.mul(contributions[msg.sender]) / funding; + contributions[msg.sender] = 0; + // Send fee share to contributor + require(eventContract.collateralToken().transfer(msg.sender, fees)); + FeeWithdrawal(msg.sender, fees); + } +} diff --git a/test/compilationTests/gnosis/Markets/CampaignFactory.sol b/test/compilationTests/gnosis/Markets/CampaignFactory.sol new file mode 100644 index 000000000..930ec2e2d --- /dev/null +++ b/test/compilationTests/gnosis/Markets/CampaignFactory.sol @@ -0,0 +1,39 @@ +pragma solidity ^0.4.11; +import "../Markets/Campaign.sol"; + + +/// @title Campaign factory contract - Allows to create campaign contracts +/// @author Stefan George - +contract CampaignFactory { + + /* + * Events + */ + event CampaignCreation(address indexed creator, Campaign campaign, Event eventContract, MarketFactory marketFactory, MarketMaker marketMaker, uint24 fee, uint funding, uint deadline); + + /* + * Public functions + */ + /// @dev Creates a new campaign contract + /// @param eventContract Event contract + /// @param marketFactory Market factory contract + /// @param marketMaker Market maker contract + /// @param fee Market fee + /// @param funding Initial funding for market + /// @param deadline Campaign deadline + /// @return Market contract + function createCampaigns( + Event eventContract, + MarketFactory marketFactory, + MarketMaker marketMaker, + uint24 fee, + uint funding, + uint deadline + ) + public + returns (Campaign campaign) + { + campaign = new Campaign(eventContract, marketFactory, marketMaker, fee, funding, deadline); + CampaignCreation(msg.sender, campaign, eventContract, marketFactory, marketMaker, fee, funding, deadline); + } +} diff --git a/test/compilationTests/gnosis/Markets/Market.sol b/test/compilationTests/gnosis/Markets/Market.sol new file mode 100644 index 000000000..635b14db5 --- /dev/null +++ b/test/compilationTests/gnosis/Markets/Market.sol @@ -0,0 +1,47 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; +import "../MarketMakers/MarketMaker.sol"; + + +/// @title Abstract market contract - Functions to be implemented by market contracts +contract Market { + + /* + * Events + */ + event MarketFunding(uint funding); + event MarketClosing(); + event FeeWithdrawal(uint fees); + event OutcomeTokenPurchase(address indexed buyer, uint8 outcomeTokenIndex, uint outcomeTokenCount, uint cost); + event OutcomeTokenSale(address indexed seller, uint8 outcomeTokenIndex, uint outcomeTokenCount, uint profit); + event OutcomeTokenShortSale(address indexed buyer, uint8 outcomeTokenIndex, uint outcomeTokenCount, uint cost); + + /* + * Storage + */ + address public creator; + uint public createdAtBlock; + Event public eventContract; + MarketMaker public marketMaker; + uint24 public fee; + uint public funding; + int[] public netOutcomeTokensSold; + Stages public stage; + + enum Stages { + MarketCreated, + MarketFunded, + MarketClosed + } + + /* + * Public functions + */ + function fund(uint _funding) public; + function close() public; + function withdrawFees() public returns (uint); + function buy(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint maxCost) public returns (uint); + function sell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) public returns (uint); + function shortSell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) public returns (uint); + function calcMarketFee(uint outcomeTokenCost) public constant returns (uint); +} diff --git a/test/compilationTests/gnosis/Markets/MarketFactory.sol b/test/compilationTests/gnosis/Markets/MarketFactory.sol new file mode 100644 index 000000000..d368e8dbd --- /dev/null +++ b/test/compilationTests/gnosis/Markets/MarketFactory.sol @@ -0,0 +1,19 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; +import "../MarketMakers/MarketMaker.sol"; +import "../Markets/Market.sol"; + + +/// @title Abstract market factory contract - Functions to be implemented by market factories +contract MarketFactory { + + /* + * Events + */ + event MarketCreation(address indexed creator, Market market, Event eventContract, MarketMaker marketMaker, uint24 fee); + + /* + * Public functions + */ + function createMarket(Event eventContract, MarketMaker marketMaker, uint24 fee) public returns (Market); +} diff --git a/test/compilationTests/gnosis/Markets/StandardMarket.sol b/test/compilationTests/gnosis/Markets/StandardMarket.sol new file mode 100644 index 000000000..b973119a1 --- /dev/null +++ b/test/compilationTests/gnosis/Markets/StandardMarket.sol @@ -0,0 +1,194 @@ +pragma solidity ^0.4.11; +import "../Markets/Market.sol"; +import "../Tokens/Token.sol"; +import "../Events/Event.sol"; +import "../MarketMakers/MarketMaker.sol"; + + +/// @title Market factory contract - Allows to create market contracts +/// @author Stefan George - +contract StandardMarket is Market { + using Math for *; + + /* + * Constants + */ + uint24 public constant FEE_RANGE = 1000000; // 100% + + /* + * Modifiers + */ + modifier isCreator () { + // Only creator is allowed to proceed + require(msg.sender == creator); + _; + } + + modifier atStage(Stages _stage) { + // Contract has to be in given stage + require(stage == _stage); + _; + } + + /* + * Public functions + */ + /// @dev Constructor validates and sets market properties + /// @param _creator Market creator + /// @param _eventContract Event contract + /// @param _marketMaker Market maker contract + /// @param _fee Market fee + function StandardMarket(address _creator, Event _eventContract, MarketMaker _marketMaker, uint24 _fee) + public + { + // Validate inputs + require(address(_eventContract) != 0 && address(_marketMaker) != 0 && _fee < FEE_RANGE); + creator = _creator; + createdAtBlock = block.number; + eventContract = _eventContract; + netOutcomeTokensSold = new int[](eventContract.getOutcomeCount()); + fee = _fee; + marketMaker = _marketMaker; + stage = Stages.MarketCreated; + } + + /// @dev Allows to fund the market with collateral tokens converting them into outcome tokens + /// @param _funding Funding amount + function fund(uint _funding) + public + isCreator + atStage(Stages.MarketCreated) + { + // Request collateral tokens and allow event contract to transfer them to buy all outcomes + require( eventContract.collateralToken().transferFrom(msg.sender, this, _funding) + && eventContract.collateralToken().approve(eventContract, _funding)); + eventContract.buyAllOutcomes(_funding); + funding = _funding; + stage = Stages.MarketFunded; + MarketFunding(funding); + } + + /// @dev Allows market creator to close the markets by transferring all remaining outcome tokens to the creator + function close() + public + isCreator + atStage(Stages.MarketFunded) + { + uint8 outcomeCount = eventContract.getOutcomeCount(); + for (uint8 i = 0; i < outcomeCount; i++) + require(eventContract.outcomeTokens(i).transfer(creator, eventContract.outcomeTokens(i).balanceOf(this))); + stage = Stages.MarketClosed; + MarketClosing(); + } + + /// @dev Allows market creator to withdraw fees generated by trades + /// @return Fee amount + function withdrawFees() + public + isCreator + returns (uint fees) + { + fees = eventContract.collateralToken().balanceOf(this); + // Transfer fees + require(eventContract.collateralToken().transfer(creator, fees)); + FeeWithdrawal(fees); + } + + /// @dev Allows to buy outcome tokens from market maker + /// @param outcomeTokenIndex Index of the outcome token to buy + /// @param outcomeTokenCount Amount of outcome tokens to buy + /// @param maxCost The maximum cost in collateral tokens to pay for outcome tokens + /// @return Cost in collateral tokens + function buy(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint maxCost) + public + atStage(Stages.MarketFunded) + returns (uint cost) + { + // Calculate cost to buy outcome tokens + uint outcomeTokenCost = marketMaker.calcCost(this, outcomeTokenIndex, outcomeTokenCount); + // Calculate fees charged by market + uint fees = calcMarketFee(outcomeTokenCost); + cost = outcomeTokenCost.add(fees); + // Check cost doesn't exceed max cost + require(cost > 0 && cost <= maxCost); + // Transfer tokens to markets contract and buy all outcomes + require( eventContract.collateralToken().transferFrom(msg.sender, this, cost) + && eventContract.collateralToken().approve(eventContract, outcomeTokenCost)); + // Buy all outcomes + eventContract.buyAllOutcomes(outcomeTokenCost); + // Transfer outcome tokens to buyer + require(eventContract.outcomeTokens(outcomeTokenIndex).transfer(msg.sender, outcomeTokenCount)); + // Add outcome token count to market maker net balance + require(int(outcomeTokenCount) >= 0); + netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].add(int(outcomeTokenCount)); + OutcomeTokenPurchase(msg.sender, outcomeTokenIndex, outcomeTokenCount, cost); + } + + /// @dev Allows to sell outcome tokens to market maker + /// @param outcomeTokenIndex Index of the outcome token to sell + /// @param outcomeTokenCount Amount of outcome tokens to sell + /// @param minProfit The minimum profit in collateral tokens to earn for outcome tokens + /// @return Profit in collateral tokens + function sell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) + public + atStage(Stages.MarketFunded) + returns (uint profit) + { + // Calculate profit for selling outcome tokens + uint outcomeTokenProfit = marketMaker.calcProfit(this, outcomeTokenIndex, outcomeTokenCount); + // Calculate fee charged by market + uint fees = calcMarketFee(outcomeTokenProfit); + profit = outcomeTokenProfit.sub(fees); + // Check profit is not too low + require(profit > 0 && profit >= minProfit); + // Transfer outcome tokens to markets contract to sell all outcomes + require(eventContract.outcomeTokens(outcomeTokenIndex).transferFrom(msg.sender, this, outcomeTokenCount)); + // Sell all outcomes + eventContract.sellAllOutcomes(outcomeTokenProfit); + // Transfer profit to seller + require(eventContract.collateralToken().transfer(msg.sender, profit)); + // Subtract outcome token count from market maker net balance + require(int(outcomeTokenCount) >= 0); + netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].sub(int(outcomeTokenCount)); + OutcomeTokenSale(msg.sender, outcomeTokenIndex, outcomeTokenCount, profit); + } + + /// @dev Buys all outcomes, then sells all shares of selected outcome which were bought, keeping + /// shares of all other outcome tokens. + /// @param outcomeTokenIndex Index of the outcome token to short sell + /// @param outcomeTokenCount Amount of outcome tokens to short sell + /// @param minProfit The minimum profit in collateral tokens to earn for short sold outcome tokens + /// @return Cost to short sell outcome in collateral tokens + function shortSell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) + public + returns (uint cost) + { + // Buy all outcomes + require( eventContract.collateralToken().transferFrom(msg.sender, this, outcomeTokenCount) + && eventContract.collateralToken().approve(eventContract, outcomeTokenCount)); + eventContract.buyAllOutcomes(outcomeTokenCount); + // Short sell selected outcome + eventContract.outcomeTokens(outcomeTokenIndex).approve(this, outcomeTokenCount); + uint profit = this.sell(outcomeTokenIndex, outcomeTokenCount, minProfit); + cost = outcomeTokenCount - profit; + // Transfer outcome tokens to buyer + uint8 outcomeCount = eventContract.getOutcomeCount(); + for (uint8 i = 0; i < outcomeCount; i++) + if (i != outcomeTokenIndex) + require(eventContract.outcomeTokens(i).transfer(msg.sender, outcomeTokenCount)); + // Send change back to buyer + require(eventContract.collateralToken().transfer(msg.sender, profit)); + OutcomeTokenShortSale(msg.sender, outcomeTokenIndex, outcomeTokenCount, cost); + } + + /// @dev Calculates fee to be paid to market maker + /// @param outcomeTokenCost Cost for buying outcome tokens + /// @return Fee for trade + function calcMarketFee(uint outcomeTokenCost) + public + constant + returns (uint) + { + return outcomeTokenCost * fee / FEE_RANGE; + } +} diff --git a/test/compilationTests/gnosis/Markets/StandardMarketFactory.sol b/test/compilationTests/gnosis/Markets/StandardMarketFactory.sol new file mode 100644 index 000000000..101c37a2a --- /dev/null +++ b/test/compilationTests/gnosis/Markets/StandardMarketFactory.sol @@ -0,0 +1,25 @@ +pragma solidity ^0.4.11; +import "../Markets/MarketFactory.sol"; +import "../Markets/StandardMarket.sol"; + + +/// @title Market factory contract - Allows to create market contracts +/// @author Stefan George - +contract StandardMarketFactory is MarketFactory { + + /* + * Public functions + */ + /// @dev Creates a new market contract + /// @param eventContract Event contract + /// @param marketMaker Market maker contract + /// @param fee Market fee + /// @return Market contract + function createMarket(Event eventContract, MarketMaker marketMaker, uint24 fee) + public + returns (Market market) + { + market = new StandardMarket(msg.sender, eventContract, marketMaker, fee); + MarketCreation(msg.sender, market, eventContract, marketMaker, fee); + } +} diff --git a/test/compilationTests/gnosis/Migrations.sol b/test/compilationTests/gnosis/Migrations.sol new file mode 100644 index 000000000..7e7fe8d47 --- /dev/null +++ b/test/compilationTests/gnosis/Migrations.sol @@ -0,0 +1,23 @@ +pragma solidity ^0.4.4; + +contract Migrations { + address public owner; + uint public last_completed_migration; + + modifier restricted() { + if (msg.sender == owner) _; + } + + function Migrations() { + owner = msg.sender; + } + + function setCompleted(uint completed) restricted { + last_completed_migration = completed; + } + + function upgrade(address new_address) restricted { + Migrations upgraded = Migrations(new_address); + upgraded.setCompleted(last_completed_migration); + } +} diff --git a/test/compilationTests/gnosis/Oracles/CentralizedOracle.sol b/test/compilationTests/gnosis/Oracles/CentralizedOracle.sol new file mode 100644 index 000000000..26acf526b --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/CentralizedOracle.sol @@ -0,0 +1,90 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; + + +/// @title Centralized oracle contract - Allows the contract owner to set an outcome +/// @author Stefan George - +contract CentralizedOracle is Oracle { + + /* + * Events + */ + event OwnerReplacement(address indexed newOwner); + event OutcomeAssignment(int outcome); + + /* + * Storage + */ + address public owner; + bytes public ipfsHash; + bool public isSet; + int public outcome; + + /* + * Modifiers + */ + modifier isOwner () { + // Only owner is allowed to proceed + require(msg.sender == owner); + _; + } + + /* + * Public functions + */ + /// @dev Constructor sets owner address and IPFS hash + /// @param _ipfsHash Hash identifying off chain event description + function CentralizedOracle(address _owner, bytes _ipfsHash) + public + { + // Description hash cannot be null + require(_ipfsHash.length == 46); + owner = _owner; + ipfsHash = _ipfsHash; + } + + /// @dev Replaces owner + /// @param newOwner New owner + function replaceOwner(address newOwner) + public + isOwner + { + // Result is not set yet + require(!isSet); + owner = newOwner; + OwnerReplacement(newOwner); + } + + /// @dev Sets event outcome + /// @param _outcome Event outcome + function setOutcome(int _outcome) + public + isOwner + { + // Result is not set yet + require(!isSet); + isSet = true; + outcome = _outcome; + OutcomeAssignment(_outcome); + } + + /// @dev Returns if winning outcome is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + return isSet; + } + + /// @dev Returns outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + return outcome; + } +} diff --git a/test/compilationTests/gnosis/Oracles/CentralizedOracleFactory.sol b/test/compilationTests/gnosis/Oracles/CentralizedOracleFactory.sol new file mode 100644 index 000000000..62a12cf45 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/CentralizedOracleFactory.sol @@ -0,0 +1,27 @@ +pragma solidity ^0.4.11; +import "../Oracles/CentralizedOracle.sol"; + + +/// @title Centralized oracle factory contract - Allows to create centralized oracle contracts +/// @author Stefan George - +contract CentralizedOracleFactory { + + /* + * Events + */ + event CentralizedOracleCreation(address indexed creator, CentralizedOracle centralizedOracle, bytes ipfsHash); + + /* + * Public functions + */ + /// @dev Creates a new centralized oracle contract + /// @param ipfsHash Hash identifying off chain event description + /// @return Oracle contract + function createCentralizedOracle(bytes ipfsHash) + public + returns (CentralizedOracle centralizedOracle) + { + centralizedOracle = new CentralizedOracle(msg.sender, ipfsHash); + CentralizedOracleCreation(msg.sender, centralizedOracle, ipfsHash); + } +} diff --git a/test/compilationTests/gnosis/Oracles/DifficultyOracle.sol b/test/compilationTests/gnosis/Oracles/DifficultyOracle.sol new file mode 100644 index 000000000..87351dfa6 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/DifficultyOracle.sol @@ -0,0 +1,63 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; + + +/// @title Difficulty oracle contract - Oracle to resolve difficulty events at given block +/// @author Stefan George - +contract DifficultyOracle is Oracle { + + /* + * Events + */ + event OutcomeAssignment(uint difficulty); + + /* + * Storage + */ + uint public blockNumber; + uint public difficulty; + + /* + * Public functions + */ + /// @dev Contract constructor validates and sets target block number + /// @param _blockNumber Target block number + function DifficultyOracle(uint _blockNumber) + public + { + // Block has to be in the future + require(_blockNumber > block.number); + blockNumber = _blockNumber; + } + + /// @dev Sets difficulty as winning outcome for specified block + function setOutcome() + public + { + // Block number was reached and outcome was not set yet + require(block.number >= blockNumber && difficulty == 0); + difficulty = block.difficulty; + OutcomeAssignment(difficulty); + } + + /// @dev Returns if difficulty is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + // Difficulty is always bigger than 0 + return difficulty > 0; + } + + /// @dev Returns difficulty + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + return int(difficulty); + } +} diff --git a/test/compilationTests/gnosis/Oracles/DifficultyOracleFactory.sol b/test/compilationTests/gnosis/Oracles/DifficultyOracleFactory.sol new file mode 100644 index 000000000..2e97362cb --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/DifficultyOracleFactory.sol @@ -0,0 +1,27 @@ +pragma solidity ^0.4.11; +import "../Oracles/DifficultyOracle.sol"; + + +/// @title Difficulty oracle factory contract - Allows to create difficulty oracle contracts +/// @author Stefan George - +contract DifficultyOracleFactory { + + /* + * Events + */ + event DifficultyOracleCreation(address indexed creator, DifficultyOracle difficultyOracle, uint blockNumber); + + /* + * Public functions + */ + /// @dev Creates a new difficulty oracle contract + /// @param blockNumber Target block number + /// @return Oracle contract + function createDifficultyOracle(uint blockNumber) + public + returns (DifficultyOracle difficultyOracle) + { + difficultyOracle = new DifficultyOracle(blockNumber); + DifficultyOracleCreation(msg.sender, difficultyOracle, blockNumber); + } +} diff --git a/test/compilationTests/gnosis/Oracles/FutarchyOracle.sol b/test/compilationTests/gnosis/Oracles/FutarchyOracle.sol new file mode 100644 index 000000000..524103d84 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/FutarchyOracle.sol @@ -0,0 +1,169 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; +import "../Events/EventFactory.sol"; +import "../Markets/MarketFactory.sol"; + + +/// @title Futarchy oracle contract - Allows to create an oracle based on market behaviour +/// @author Stefan George - +contract FutarchyOracle is Oracle { + using Math for *; + + /* + * Events + */ + event FutarchyFunding(uint funding); + event FutarchyClosing(); + event OutcomeAssignment(uint winningMarketIndex); + + /* + * Constants + */ + uint8 public constant LONG = 1; + + /* + * Storage + */ + address creator; + Market[] public markets; + CategoricalEvent public categoricalEvent; + uint public deadline; + uint public winningMarketIndex; + bool public isSet; + + /* + * Modifiers + */ + modifier isCreator () { + // Only creator is allowed to proceed + require(msg.sender == creator); + _; + } + + /* + * Public functions + */ + /// @dev Constructor creates events and markets for futarchy oracle + /// @param _creator Oracle creator + /// @param eventFactory Event factory contract + /// @param collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + /// @param lowerBound Lower bound for event outcome + /// @param upperBound Lower bound for event outcome + /// @param marketFactory Market factory contract + /// @param marketMaker Market maker contract + /// @param fee Market fee + /// @param _deadline Decision deadline + function FutarchyOracle( + address _creator, + EventFactory eventFactory, + Token collateralToken, + Oracle oracle, + uint8 outcomeCount, + int lowerBound, + int upperBound, + MarketFactory marketFactory, + MarketMaker marketMaker, + uint24 fee, + uint _deadline + ) + public + { + // Deadline is in the future + require(_deadline > now); + // Create decision event + categoricalEvent = eventFactory.createCategoricalEvent(collateralToken, this, outcomeCount); + // Create outcome events + for (uint8 i = 0; i < categoricalEvent.getOutcomeCount(); i++) { + ScalarEvent scalarEvent = eventFactory.createScalarEvent( + categoricalEvent.outcomeTokens(i), + oracle, + lowerBound, + upperBound + ); + markets.push(marketFactory.createMarket(scalarEvent, marketMaker, fee)); + } + creator = _creator; + deadline = _deadline; + } + + /// @dev Funds all markets with equal amount of funding + /// @param funding Amount of funding + function fund(uint funding) + public + isCreator + { + // Buy all outcomes + require( categoricalEvent.collateralToken().transferFrom(creator, this, funding) + && categoricalEvent.collateralToken().approve(categoricalEvent, funding)); + categoricalEvent.buyAllOutcomes(funding); + // Fund each market with outcome tokens from categorical event + for (uint8 i = 0; i < markets.length; i++) { + Market market = markets[i]; + // Approve funding for market + require(market.eventContract().collateralToken().approve(market, funding)); + market.fund(funding); + } + FutarchyFunding(funding); + } + + /// @dev Closes market for winning outcome and redeems winnings and sends all collateral tokens to creator + function close() + public + isCreator + { + // Winning outcome has to be set + Market market = markets[uint(getOutcome())]; + require(categoricalEvent.isOutcomeSet() && market.eventContract().isOutcomeSet()); + // Close market and transfer all outcome tokens from winning outcome to this contract + market.close(); + market.eventContract().redeemWinnings(); + market.withdrawFees(); + // Redeem collateral token for winning outcome tokens and transfer collateral tokens to creator + categoricalEvent.redeemWinnings(); + require(categoricalEvent.collateralToken().transfer(creator, categoricalEvent.collateralToken().balanceOf(this))); + FutarchyClosing(); + } + + /// @dev Allows to set the oracle outcome based on the market with largest long position + function setOutcome() + public + { + // Outcome is not set yet and deadline has passed + require(!isSet && deadline <= now); + // Find market with highest marginal price for long outcome tokens + uint highestMarginalPrice = markets[0].marketMaker().calcMarginalPrice(markets[0], LONG); + uint highestIndex = 0; + for (uint8 i = 1; i < markets.length; i++) { + uint marginalPrice = markets[i].marketMaker().calcMarginalPrice(markets[i], LONG); + if (marginalPrice > highestMarginalPrice) { + highestMarginalPrice = marginalPrice; + highestIndex = i; + } + } + winningMarketIndex = highestIndex; + isSet = true; + OutcomeAssignment(winningMarketIndex); + } + + /// @dev Returns if winning outcome is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + return isSet; + } + + /// @dev Returns winning outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + return int(winningMarketIndex); + } +} diff --git a/test/compilationTests/gnosis/Oracles/FutarchyOracleFactory.sol b/test/compilationTests/gnosis/Oracles/FutarchyOracleFactory.sol new file mode 100644 index 000000000..62eab4f07 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/FutarchyOracleFactory.sol @@ -0,0 +1,95 @@ +pragma solidity ^0.4.11; +import "../Oracles/FutarchyOracle.sol"; + + +/// @title Futarchy oracle factory contract - Allows to create Futarchy oracle contracts +/// @author Stefan George - +contract FutarchyOracleFactory { + + /* + * Events + */ + event FutarchyOracleCreation( + address indexed creator, + FutarchyOracle futarchyOracle, + Token collateralToken, + Oracle oracle, + uint8 outcomeCount, + int lowerBound, + int upperBound, + MarketFactory marketFactory, + MarketMaker marketMaker, + uint24 fee, + uint deadline + ); + + /* + * Storage + */ + EventFactory eventFactory; + + /* + * Public functions + */ + /// @dev Constructor sets event factory contract + /// @param _eventFactory Event factory contract + function FutarchyOracleFactory(EventFactory _eventFactory) + public + { + require(address(_eventFactory) != 0); + eventFactory = _eventFactory; + } + + /// @dev Creates a new Futarchy oracle contract + /// @param collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + /// @param lowerBound Lower bound for event outcome + /// @param upperBound Lower bound for event outcome + /// @param marketFactory Market factory contract + /// @param marketMaker Market maker contract + /// @param fee Market fee + /// @param deadline Decision deadline + /// @return Oracle contract + function createFutarchyOracle( + Token collateralToken, + Oracle oracle, + uint8 outcomeCount, + int lowerBound, + int upperBound, + MarketFactory marketFactory, + MarketMaker marketMaker, + uint24 fee, + uint deadline + ) + public + returns (FutarchyOracle futarchyOracle) + { + futarchyOracle = new FutarchyOracle( + msg.sender, + eventFactory, + collateralToken, + oracle, + outcomeCount, + lowerBound, + upperBound, + marketFactory, + marketMaker, + fee, + deadline + ); + FutarchyOracleCreation( + msg.sender, + futarchyOracle, + collateralToken, + oracle, + outcomeCount, + lowerBound, + upperBound, + marketFactory, + marketMaker, + fee, + deadline + ); + } +} diff --git a/test/compilationTests/gnosis/Oracles/MajorityOracle.sol b/test/compilationTests/gnosis/Oracles/MajorityOracle.sol new file mode 100644 index 000000000..1562ce48d --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/MajorityOracle.sol @@ -0,0 +1,89 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; + + +/// @title Majority oracle contract - Allows to resolve an event based on multiple oracles with majority vote +/// @author Stefan George - +contract MajorityOracle is Oracle { + + /* + * Storage + */ + Oracle[] public oracles; + + /* + * Public functions + */ + /// @dev Allows to create an oracle for a majority vote based on other oracles + /// @param _oracles List of oracles taking part in the majority vote + function MajorityOracle(Oracle[] _oracles) + public + { + // At least 2 oracles should be defined + require(_oracles.length > 2); + for (uint i = 0; i < _oracles.length; i++) + // Oracle address cannot be null + require(address(_oracles[i]) != 0); + oracles = _oracles; + } + + /// @dev Allows to registers oracles for a majority vote + /// @return Is outcome set? + /// @return Outcome + function getStatusAndOutcome() + public + returns (bool outcomeSet, int outcome) + { + uint i; + int[] memory outcomes = new int[](oracles.length); + uint[] memory validations = new uint[](oracles.length); + for (i = 0; i < oracles.length; i++) + if (oracles[i].isOutcomeSet()) { + int _outcome = oracles[i].getOutcome(); + for (uint j = 0; j <= i; j++) + if (_outcome == outcomes[j]) { + validations[j] += 1; + break; + } + else if (validations[j] == 0) { + outcomes[j] = _outcome; + validations[j] = 1; + break; + } + } + uint outcomeValidations = 0; + uint outcomeIndex = 0; + for (i = 0; i < oracles.length; i++) + if (validations[i] > outcomeValidations) { + outcomeValidations = validations[i]; + outcomeIndex = i; + } + // There is a majority vote + if (outcomeValidations * 2 > oracles.length) { + outcomeSet = true; + outcome = outcomes[outcomeIndex]; + } + } + + /// @dev Returns if winning outcome is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + var (outcomeSet, ) = getStatusAndOutcome(); + return outcomeSet; + } + + /// @dev Returns winning outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + var (, winningOutcome) = getStatusAndOutcome(); + return winningOutcome; + } +} diff --git a/test/compilationTests/gnosis/Oracles/MajorityOracleFactory.sol b/test/compilationTests/gnosis/Oracles/MajorityOracleFactory.sol new file mode 100644 index 000000000..0024516a9 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/MajorityOracleFactory.sol @@ -0,0 +1,27 @@ +pragma solidity ^0.4.11; +import "../Oracles/MajorityOracle.sol"; + + +/// @title Majority oracle factory contract - Allows to create majority oracle contracts +/// @author Stefan George - +contract MajorityOracleFactory { + + /* + * Events + */ + event MajorityOracleCreation(address indexed creator, MajorityOracle majorityOracle, Oracle[] oracles); + + /* + * Public functions + */ + /// @dev Creates a new majority oracle contract + /// @param oracles List of oracles taking part in the majority vote + /// @return Oracle contract + function createMajorityOracle(Oracle[] oracles) + public + returns (MajorityOracle majorityOracle) + { + majorityOracle = new MajorityOracle(oracles); + MajorityOracleCreation(msg.sender, majorityOracle, oracles); + } +} diff --git a/test/compilationTests/gnosis/Oracles/Oracle.sol b/test/compilationTests/gnosis/Oracles/Oracle.sol new file mode 100644 index 000000000..cf96eb9f9 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/Oracle.sol @@ -0,0 +1,9 @@ +pragma solidity ^0.4.11; + + +/// @title Abstract oracle contract - Functions to be implemented by oracles +contract Oracle { + + function isOutcomeSet() public constant returns (bool); + function getOutcome() public constant returns (int); +} diff --git a/test/compilationTests/gnosis/Oracles/SignedMessageOracle.sol b/test/compilationTests/gnosis/Oracles/SignedMessageOracle.sol new file mode 100644 index 000000000..d541ab463 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/SignedMessageOracle.sol @@ -0,0 +1,102 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; + + +/// @title Signed message oracle contract - Allows to set an outcome with a signed message +/// @author Stefan George - +contract SignedMessageOracle is Oracle { + + /* + * Events + */ + event SignerReplacement(address indexed newSigner); + event OutcomeAssignment(int outcome); + + /* + * Storage + */ + address public signer; + bytes32 public descriptionHash; + uint nonce; + bool public isSet; + int public outcome; + + /* + * Modifiers + */ + modifier isSigner () { + // Only signer is allowed to proceed + require(msg.sender == signer); + _; + } + + /* + * Public functions + */ + /// @dev Constructor sets signer address based on signature + /// @param _descriptionHash Hash identifying off chain event description + /// @param v Signature parameter + /// @param r Signature parameter + /// @param s Signature parameter + function SignedMessageOracle(bytes32 _descriptionHash, uint8 v, bytes32 r, bytes32 s) + public + { + signer = ecrecover(_descriptionHash, v, r, s); + descriptionHash = _descriptionHash; + } + + /// @dev Replaces signer + /// @param newSigner New signer + /// @param _nonce Unique nonce to prevent replay attacks + /// @param v Signature parameter + /// @param r Signature parameter + /// @param s Signature parameter + function replaceSigner(address newSigner, uint _nonce, uint8 v, bytes32 r, bytes32 s) + public + isSigner + { + // Result is not set yet and nonce and signer are valid + require( !isSet + && _nonce > nonce + && signer == ecrecover(keccak256(descriptionHash, newSigner, _nonce), v, r, s)); + nonce = _nonce; + signer = newSigner; + SignerReplacement(newSigner); + } + + /// @dev Sets outcome based on signed message + /// @param _outcome Signed event outcome + /// @param v Signature parameter + /// @param r Signature parameter + /// @param s Signature parameter + function setOutcome(int _outcome, uint8 v, bytes32 r, bytes32 s) + public + { + // Result is not set yet and signer is valid + require( !isSet + && signer == ecrecover(keccak256(descriptionHash, _outcome), v, r, s)); + isSet = true; + outcome = _outcome; + OutcomeAssignment(_outcome); + } + + /// @dev Returns if winning outcome + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + return isSet; + } + + /// @dev Returns winning outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + return outcome; + } +} diff --git a/test/compilationTests/gnosis/Oracles/SignedMessageOracleFactory.sol b/test/compilationTests/gnosis/Oracles/SignedMessageOracleFactory.sol new file mode 100644 index 000000000..0884d8cac --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/SignedMessageOracleFactory.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.4.11; +import "../Oracles/SignedMessageOracle.sol"; + + +/// @title Signed message oracle factory contract - Allows to create signed message oracle contracts +/// @author Stefan George - +contract SignedMessageOracleFactory { + + /* + * Events + */ + event SignedMessageOracleCreation(address indexed creator, SignedMessageOracle signedMessageOracle, address oracle); + + /* + * Public functions + */ + /// @dev Creates a new signed message oracle contract + /// @param descriptionHash Hash identifying off chain event description + /// @param v Signature parameter + /// @param r Signature parameter + /// @param s Signature parameter + /// @return Oracle contract + function createSignedMessageOracle(bytes32 descriptionHash, uint8 v, bytes32 r, bytes32 s) + public + returns (SignedMessageOracle signedMessageOracle) + { + signedMessageOracle = new SignedMessageOracle(descriptionHash, v, r, s); + address oracle = ecrecover(descriptionHash, v, r, s); + SignedMessageOracleCreation(msg.sender, signedMessageOracle, oracle); + } +} diff --git a/test/compilationTests/gnosis/Oracles/UltimateOracle.sol b/test/compilationTests/gnosis/Oracles/UltimateOracle.sol new file mode 100644 index 000000000..fe8b4ec70 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/UltimateOracle.sol @@ -0,0 +1,192 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; +import "../Tokens/Token.sol"; +import "../Utils/Math.sol"; + + +/// @title Ultimate oracle contract - Allows to swap oracle result for ultimate oracle result +/// @author Stefan George - +contract UltimateOracle is Oracle { + using Math for *; + + /* + * Events + */ + event ForwardedOracleOutcomeAssignment(int outcome); + event OutcomeChallenge(address indexed sender, int outcome); + event OutcomeVote(address indexed sender, int outcome, uint amount); + event Withdrawal(address indexed sender, uint amount); + + /* + * Storage + */ + Oracle public forwardedOracle; + Token public collateralToken; + uint8 public spreadMultiplier; + uint public challengePeriod; + uint public challengeAmount; + uint public frontRunnerPeriod; + + int public forwardedOutcome; + uint public forwardedOutcomeSetTimestamp; + int public frontRunner; + uint public frontRunnerSetTimestamp; + + uint public totalAmount; + mapping (int => uint) public totalOutcomeAmounts; + mapping (address => mapping (int => uint)) public outcomeAmounts; + + /* + * Public functions + */ + /// @dev Constructor sets ultimate oracle properties + /// @param _forwardedOracle Oracle address + /// @param _collateralToken Collateral token address + /// @param _spreadMultiplier Defines the spread as a multiple of the money bet on other outcomes + /// @param _challengePeriod Time to challenge oracle outcome + /// @param _challengeAmount Amount to challenge the outcome + /// @param _frontRunnerPeriod Time to overbid the front-runner + function UltimateOracle( + Oracle _forwardedOracle, + Token _collateralToken, + uint8 _spreadMultiplier, + uint _challengePeriod, + uint _challengeAmount, + uint _frontRunnerPeriod + ) + public + { + // Validate inputs + require( address(_forwardedOracle) != 0 + && address(_collateralToken) != 0 + && _spreadMultiplier >= 2 + && _challengePeriod > 0 + && _challengeAmount > 0 + && _frontRunnerPeriod > 0); + forwardedOracle = _forwardedOracle; + collateralToken = _collateralToken; + spreadMultiplier = _spreadMultiplier; + challengePeriod = _challengePeriod; + challengeAmount = _challengeAmount; + frontRunnerPeriod = _frontRunnerPeriod; + } + + /// @dev Allows to set oracle outcome + function setForwardedOutcome() + public + { + // There was no challenge and the outcome was not set yet in the ultimate oracle but in the forwarded oracle + require( !isChallenged() + && forwardedOutcomeSetTimestamp == 0 + && forwardedOracle.isOutcomeSet()); + forwardedOutcome = forwardedOracle.getOutcome(); + forwardedOutcomeSetTimestamp = now; + ForwardedOracleOutcomeAssignment(forwardedOutcome); + } + + /// @dev Allows to challenge the oracle outcome + /// @param _outcome Outcome to bid on + function challengeOutcome(int _outcome) + public + { + // There was no challenge yet or the challenge period expired + require( !isChallenged() + && !isChallengePeriodOver() + && collateralToken.transferFrom(msg.sender, this, challengeAmount)); + outcomeAmounts[msg.sender][_outcome] = challengeAmount; + totalOutcomeAmounts[_outcome] = challengeAmount; + totalAmount = challengeAmount; + frontRunner = _outcome; + frontRunnerSetTimestamp = now; + OutcomeChallenge(msg.sender, _outcome); + } + + /// @dev Allows to challenge the oracle outcome + /// @param _outcome Outcome to bid on + /// @param amount Amount to bid + function voteForOutcome(int _outcome, uint amount) + public + { + uint maxAmount = (totalAmount - totalOutcomeAmounts[_outcome]).mul(spreadMultiplier); + if (amount > maxAmount) + amount = maxAmount; + // Outcome is challenged and front runner period is not over yet and tokens can be transferred + require( isChallenged() + && !isFrontRunnerPeriodOver() + && collateralToken.transferFrom(msg.sender, this, amount)); + outcomeAmounts[msg.sender][_outcome] = outcomeAmounts[msg.sender][_outcome].add(amount); + totalOutcomeAmounts[_outcome] = totalOutcomeAmounts[_outcome].add(amount); + totalAmount = totalAmount.add(amount); + if (_outcome != frontRunner && totalOutcomeAmounts[_outcome] > totalOutcomeAmounts[frontRunner]) + { + frontRunner = _outcome; + frontRunnerSetTimestamp = now; + } + OutcomeVote(msg.sender, _outcome, amount); + } + + /// @dev Withdraws winnings for user + /// @return Winnings + function withdraw() + public + returns (uint amount) + { + // Outcome was challenged and ultimate outcome decided + require(isFrontRunnerPeriodOver()); + amount = totalAmount.mul(outcomeAmounts[msg.sender][frontRunner]) / totalOutcomeAmounts[frontRunner]; + outcomeAmounts[msg.sender][frontRunner] = 0; + // Transfer earnings to contributor + require(collateralToken.transfer(msg.sender, amount)); + Withdrawal(msg.sender, amount); + } + + /// @dev Checks if time to challenge the outcome is over + /// @return Is challenge period over? + function isChallengePeriodOver() + public + returns (bool) + { + return forwardedOutcomeSetTimestamp != 0 && now.sub(forwardedOutcomeSetTimestamp) > challengePeriod; + } + + /// @dev Checks if time to overbid the front runner is over + /// @return Is front runner period over? + function isFrontRunnerPeriodOver() + public + returns (bool) + { + return frontRunnerSetTimestamp != 0 && now.sub(frontRunnerSetTimestamp) > frontRunnerPeriod; + } + + /// @dev Checks if outcome was challenged + /// @return Is challenged? + function isChallenged() + public + returns (bool) + { + return frontRunnerSetTimestamp != 0; + } + + /// @dev Returns if winning outcome is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + return isChallengePeriodOver() && !isChallenged() + || isFrontRunnerPeriodOver(); + } + + /// @dev Returns winning outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + if (isFrontRunnerPeriodOver()) + return frontRunner; + return forwardedOutcome; + } +} diff --git a/test/compilationTests/gnosis/Oracles/UltimateOracleFactory.sol b/test/compilationTests/gnosis/Oracles/UltimateOracleFactory.sol new file mode 100644 index 000000000..67f8a96e9 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/UltimateOracleFactory.sol @@ -0,0 +1,64 @@ +pragma solidity ^0.4.11; +import "../Oracles/UltimateOracle.sol"; + + +/// @title Ultimate oracle factory contract - Allows to create ultimate oracle contracts +/// @author Stefan George - +contract UltimateOracleFactory { + + /* + * Events + */ + event UltimateOracleCreation( + address indexed creator, + UltimateOracle ultimateOracle, + Oracle oracle, + Token collateralToken, + uint8 spreadMultiplier, + uint challengePeriod, + uint challengeAmount, + uint frontRunnerPeriod + ); + + /* + * Public functions + */ + /// @dev Creates a new ultimate Oracle contract + /// @param oracle Oracle address + /// @param collateralToken Collateral token address + /// @param spreadMultiplier Defines the spread as a multiple of the money bet on other outcomes + /// @param challengePeriod Time to challenge oracle outcome + /// @param challengeAmount Amount to challenge the outcome + /// @param frontRunnerPeriod Time to overbid the front-runner + /// @return Oracle contract + function createUltimateOracle( + Oracle oracle, + Token collateralToken, + uint8 spreadMultiplier, + uint challengePeriod, + uint challengeAmount, + uint frontRunnerPeriod + ) + public + returns (UltimateOracle ultimateOracle) + { + ultimateOracle = new UltimateOracle( + oracle, + collateralToken, + spreadMultiplier, + challengePeriod, + challengeAmount, + frontRunnerPeriod + ); + UltimateOracleCreation( + msg.sender, + ultimateOracle, + oracle, + collateralToken, + spreadMultiplier, + challengePeriod, + challengeAmount, + frontRunnerPeriod + ); + } +} diff --git a/test/compilationTests/gnosis/README.md b/test/compilationTests/gnosis/README.md new file mode 100644 index 000000000..e939cd261 --- /dev/null +++ b/test/compilationTests/gnosis/README.md @@ -0,0 +1,3 @@ +Gnosis contracts, originally from + +https://github.com/gnosis/gnosis-contracts diff --git a/test/compilationTests/gnosis/Tokens/EtherToken.sol b/test/compilationTests/gnosis/Tokens/EtherToken.sol new file mode 100644 index 000000000..f6e73e5ac --- /dev/null +++ b/test/compilationTests/gnosis/Tokens/EtherToken.sol @@ -0,0 +1,47 @@ +pragma solidity ^0.4.11; +import "../Tokens/StandardToken.sol"; + + +/// @title Token contract - Token exchanging Ether 1:1 +/// @author Stefan George - +contract EtherToken is StandardToken { + using Math for *; + + /* + * Events + */ + event Deposit(address indexed sender, uint value); + event Withdrawal(address indexed receiver, uint value); + + /* + * Constants + */ + string public constant name = "Ether Token"; + string public constant symbol = "ETH"; + uint8 public constant decimals = 18; + + /* + * Public functions + */ + /// @dev Buys tokens with Ether, exchanging them 1:1 + function deposit() + public + payable + { + balances[msg.sender] = balances[msg.sender].add(msg.value); + totalTokens = totalTokens.add(msg.value); + Deposit(msg.sender, msg.value); + } + + /// @dev Sells tokens in exchange for Ether, exchanging them 1:1 + /// @param value Number of tokens to sell + function withdraw(uint value) + public + { + // Balance covers value + balances[msg.sender] = balances[msg.sender].sub(value); + totalTokens = totalTokens.sub(value); + msg.sender.transfer(value); + Withdrawal(msg.sender, value); + } +} diff --git a/test/compilationTests/gnosis/Tokens/OutcomeToken.sol b/test/compilationTests/gnosis/Tokens/OutcomeToken.sol new file mode 100644 index 000000000..fd1fa590a --- /dev/null +++ b/test/compilationTests/gnosis/Tokens/OutcomeToken.sol @@ -0,0 +1,63 @@ +pragma solidity ^0.4.11; +import "../Tokens/StandardToken.sol"; + + +/// @title Outcome token contract - Issuing and revoking outcome tokens +/// @author Stefan George - +contract OutcomeToken is StandardToken { + using Math for *; + + /* + * Events + */ + event Issuance(address indexed owner, uint amount); + event Revocation(address indexed owner, uint amount); + + /* + * Storage + */ + address public eventContract; + + /* + * Modifiers + */ + modifier isEventContract () { + // Only event contract is allowed to proceed + require(msg.sender == eventContract); + _; + } + + /* + * Public functions + */ + /// @dev Constructor sets events contract address + function OutcomeToken() + public + { + eventContract = msg.sender; + } + + /// @dev Events contract issues new tokens for address. Returns success + /// @param _for Address of receiver + /// @param outcomeTokenCount Number of tokens to issue + function issue(address _for, uint outcomeTokenCount) + public + isEventContract + { + balances[_for] = balances[_for].add(outcomeTokenCount); + totalTokens = totalTokens.add(outcomeTokenCount); + Issuance(_for, outcomeTokenCount); + } + + /// @dev Events contract revokes tokens for address. Returns success + /// @param _for Address of token holder + /// @param outcomeTokenCount Number of tokens to revoke + function revoke(address _for, uint outcomeTokenCount) + public + isEventContract + { + balances[_for] = balances[_for].sub(outcomeTokenCount); + totalTokens = totalTokens.sub(outcomeTokenCount); + Revocation(_for, outcomeTokenCount); + } +} diff --git a/test/compilationTests/gnosis/Tokens/StandardToken.sol b/test/compilationTests/gnosis/Tokens/StandardToken.sol new file mode 100644 index 000000000..fc899ca65 --- /dev/null +++ b/test/compilationTests/gnosis/Tokens/StandardToken.sol @@ -0,0 +1,102 @@ +pragma solidity ^0.4.11; +import "../Tokens/Token.sol"; +import "../Utils/Math.sol"; + + +/// @title Standard token contract with overflow protection +contract StandardToken is Token { + using Math for *; + + /* + * Storage + */ + mapping (address => uint) balances; + mapping (address => mapping (address => uint)) allowances; + uint totalTokens; + + /* + * Public functions + */ + /// @dev Transfers sender's tokens to a given address. Returns success + /// @param to Address of token receiver + /// @param value Number of tokens to transfer + /// @return Was transfer successful? + function transfer(address to, uint value) + public + returns (bool) + { + if ( !balances[msg.sender].safeToSub(value) + || !balances[to].safeToAdd(value)) + return false; + balances[msg.sender] -= value; + balances[to] += value; + Transfer(msg.sender, to, value); + return true; + } + + /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success + /// @param from Address from where tokens are withdrawn + /// @param to Address to where tokens are sent + /// @param value Number of tokens to transfer + /// @return Was transfer successful? + function transferFrom(address from, address to, uint value) + public + returns (bool) + { + if ( !balances[from].safeToSub(value) + || !allowances[from][msg.sender].safeToSub(value) + || !balances[to].safeToAdd(value)) + return false; + balances[from] -= value; + allowances[from][msg.sender] -= value; + balances[to] += value; + Transfer(from, to, value); + return true; + } + + /// @dev Sets approved amount of tokens for spender. Returns success + /// @param spender Address of allowed account + /// @param value Number of approved tokens + /// @return Was approval successful? + function approve(address spender, uint value) + public + returns (bool) + { + allowances[msg.sender][spender] = value; + Approval(msg.sender, spender, value); + return true; + } + + /// @dev Returns number of allowed tokens for given address + /// @param owner Address of token owner + /// @param spender Address of token spender + /// @return Remaining allowance for spender + function allowance(address owner, address spender) + public + constant + returns (uint) + { + return allowances[owner][spender]; + } + + /// @dev Returns number of tokens owned by given address + /// @param owner Address of token owner + /// @return Balance of owner + function balanceOf(address owner) + public + constant + returns (uint) + { + return balances[owner]; + } + + /// @dev Returns total supply of tokens + /// @return Total supply + function totalSupply() + public + constant + returns (uint) + { + return totalTokens; + } +} diff --git a/test/compilationTests/gnosis/Tokens/Token.sol b/test/compilationTests/gnosis/Tokens/Token.sol new file mode 100644 index 000000000..19bb618be --- /dev/null +++ b/test/compilationTests/gnosis/Tokens/Token.sol @@ -0,0 +1,23 @@ +/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 +pragma solidity ^0.4.11; + + +/// @title Abstract token contract - Functions to be implemented by token contracts +contract Token { + + /* + * Events + */ + event Transfer(address indexed from, address indexed to, uint value); + event Approval(address indexed owner, address indexed spender, uint value); + + /* + * Public functions + */ + function transfer(address to, uint value) public returns (bool); + function transferFrom(address from, address to, uint value) public returns (bool); + function approve(address spender, uint value) public returns (bool); + function balanceOf(address owner) public constant returns (uint); + function allowance(address owner, address spender) public constant returns (uint); + function totalSupply() public constant returns (uint); +} diff --git a/test/compilationTests/gnosis/Utils/Math.sol b/test/compilationTests/gnosis/Utils/Math.sol new file mode 100644 index 000000000..95d95346f --- /dev/null +++ b/test/compilationTests/gnosis/Utils/Math.sol @@ -0,0 +1,340 @@ +pragma solidity ^0.4.11; + + +/// @title Math library - Allows calculation of logarithmic and exponential functions +/// @author Alan Lu - +/// @author Stefan George - +library Math { + + /* + * Constants + */ + // This is equal to 1 in our calculations + uint public constant ONE = 0x10000000000000000; + uint public constant LN2 = 0xb17217f7d1cf79ac; + uint public constant LOG2_E = 0x171547652b82fe177; + + /* + * Public functions + */ + /// @dev Returns natural exponential function value of given x + /// @param x x + /// @return e**x + function exp(int x) + public + constant + returns (uint) + { + // revert if x is > MAX_POWER, where + // MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE)) + require(x <= 2454971259878909886679); + // return 0 if exp(x) is tiny, using + // MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE)) + if (x < -818323753292969962227) + return 0; + // Transform so that e^x -> 2^x + x = x * int(ONE) / int(LN2); + // 2^x = 2^whole(x) * 2^frac(x) + // ^^^^^^^^^^ is a bit shift + // so Taylor expand on z = frac(x) + int shift; + uint z; + if (x >= 0) { + shift = x / int(ONE); + z = uint(x % int(ONE)); + } + else { + shift = x / int(ONE) - 1; + z = ONE - uint(-x % int(ONE)); + } + // 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ... + // + // Can generate the z coefficients using mpmath and the following lines + // >>> from mpmath import mp + // >>> mp.dps = 100 + // >>> ONE = 0x10000000000000000 + // >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7))) + // 0xb17217f7d1cf79ab + // 0x3d7f7bff058b1d50 + // 0xe35846b82505fc5 + // 0x276556df749cee5 + // 0x5761ff9e299cc4 + // 0xa184897c363c3 + uint zpow = z; + uint result = ONE; + result += 0xb17217f7d1cf79ab * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x3d7f7bff058b1d50 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xe35846b82505fc5 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x276556df749cee5 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x5761ff9e299cc4 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xa184897c363c3 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xffe5fe2c4586 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x162c0223a5c8 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1b5253d395e * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1e4cf5158b * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1e8cac735 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1c3bd650 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1816193 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x131496 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xe1b7 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x9c7 * zpow / ONE; + if (shift >= 0) { + if (result >> (256-shift) > 0) + return (2**256-1); + return result << shift; + } + else + return result >> (-shift); + } + + /// @dev Returns natural logarithm value of given x + /// @param x x + /// @return ln(x) + function ln(uint x) + public + constant + returns (int) + { + require(x > 0); + // binary search for floor(log2(x)) + int ilog2 = floorLog2(x); + int z; + if (ilog2 < 0) + z = int(x << uint(-ilog2)); + else + z = int(x >> uint(ilog2)); + // z = x * 2^-⌊log₂x⌋ + // so 1 <= z < 2 + // and ln z = ln x - ⌊log₂x⌋/log₂e + // so just compute ln z using artanh series + // and calculate ln x from that + int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); + int halflnz = term; + int termpow = term * term / int(ONE) * term / int(ONE); + halflnz += termpow / 3; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 5; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 7; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 9; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 11; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 13; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 15; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 17; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 19; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 21; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 23; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 25; + return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; + } + + /// @dev Returns base 2 logarithm value of given x + /// @param x x + /// @return logarithmic value + function floorLog2(uint x) + public + constant + returns (int lo) + { + lo = -64; + int hi = 193; + // I use a shift here instead of / 2 because it floors instead of rounding towards 0 + int mid = (hi + lo) >> 1; + while((lo + 1) < hi) { + if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) + hi = mid; + else + lo = mid; + mid = (hi + lo) >> 1; + } + } + + /// @dev Returns maximum of an array + /// @param nums Numbers to look through + /// @return Maximum number + function max(int[] nums) + public + constant + returns (int max) + { + require(nums.length > 0); + max = -2**255; + for (uint i = 0; i < nums.length; i++) + if (nums[i] > max) + max = nums[i]; + } + + /// @dev Returns whether an add operation causes an overflow + /// @param a First addend + /// @param b Second addend + /// @return Did no overflow occur? + function safeToAdd(uint a, uint b) + public + constant + returns (bool) + { + return a + b >= a; + } + + /// @dev Returns whether a subtraction operation causes an underflow + /// @param a Minuend + /// @param b Subtrahend + /// @return Did no underflow occur? + function safeToSub(uint a, uint b) + public + constant + returns (bool) + { + return a >= b; + } + + /// @dev Returns whether a multiply operation causes an overflow + /// @param a First factor + /// @param b Second factor + /// @return Did no overflow occur? + function safeToMul(uint a, uint b) + public + constant + returns (bool) + { + return b == 0 || a * b / b == a; + } + + /// @dev Returns sum if no overflow occurred + /// @param a First addend + /// @param b Second addend + /// @return Sum + function add(uint a, uint b) + public + constant + returns (uint) + { + require(safeToAdd(a, b)); + return a + b; + } + + /// @dev Returns difference if no overflow occurred + /// @param a Minuend + /// @param b Subtrahend + /// @return Difference + function sub(uint a, uint b) + public + constant + returns (uint) + { + require(safeToSub(a, b)); + return a - b; + } + + /// @dev Returns product if no overflow occurred + /// @param a First factor + /// @param b Second factor + /// @return Product + function mul(uint a, uint b) + public + constant + returns (uint) + { + require(safeToMul(a, b)); + return a * b; + } + + /// @dev Returns whether an add operation causes an overflow + /// @param a First addend + /// @param b Second addend + /// @return Did no overflow occur? + function safeToAdd(int a, int b) + public + constant + returns (bool) + { + return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); + } + + /// @dev Returns whether a subtraction operation causes an underflow + /// @param a Minuend + /// @param b Subtrahend + /// @return Did no underflow occur? + function safeToSub(int a, int b) + public + constant + returns (bool) + { + return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); + } + + /// @dev Returns whether a multiply operation causes an overflow + /// @param a First factor + /// @param b Second factor + /// @return Did no overflow occur? + function safeToMul(int a, int b) + public + constant + returns (bool) + { + return (b == 0) || (a * b / b == a); + } + + /// @dev Returns sum if no overflow occurred + /// @param a First addend + /// @param b Second addend + /// @return Sum + function add(int a, int b) + public + constant + returns (int) + { + require(safeToAdd(a, b)); + return a + b; + } + + /// @dev Returns difference if no overflow occurred + /// @param a Minuend + /// @param b Subtrahend + /// @return Difference + function sub(int a, int b) + public + constant + returns (int) + { + require(safeToSub(a, b)); + return a - b; + } + + /// @dev Returns product if no overflow occurred + /// @param a First factor + /// @param b Second factor + /// @return Product + function mul(int a, int b) + public + constant + returns (int) + { + require(safeToMul(a, b)); + return a * b; + } +}