Compare commits

...

53 Commits

Author SHA1 Message Date
7b9c1429d9 v1.0.7 2017-06-09 19:31:09 -03:00
d53ddd4a95 Merge pull request #242 from DavidKnott/upgrade-truffle-and-solidity
Upgrade to Truffle version 3.2.2 and Solidity version 0.4.11
2017-06-07 15:04:57 -03:00
6ede3d9001 Upgrade to Truffle version 3.2.2 and Solidity version 0.4.11 2017-06-06 21:41:54 -06:00
c3cb0dcf80 Merge pull request #238 from DaveAppleton/master
remove redundant return
2017-06-06 11:02:46 -03:00
f214dccab9 removed redundant returns 2017-06-06 17:10:55 +08:00
c0cce27703 remove redundant return 2017-06-02 00:27:16 +08:00
2eded7a337 Merge pull request #237 from maraoz/coveralls
Add coveralls
2017-05-31 20:30:50 -03:00
41a6f1cd84 add coveralls 2017-05-31 17:15:50 -03:00
e1eed257f1 v1.0.6 2017-05-29 18:29:48 -03:00
2bcb54b3cb Merge pull request #231 from maraoz/fix-vested-token
Implement VestedToken bug mitigation #3
2017-05-29 18:27:44 -03:00
7100e30bed Implement VestedToken bug mitigation #3 2017-05-29 17:52:19 -03:00
7f6921e787 Merge pull request #222 from aragon/refactor
[VestedToken] Add revokability and burnablity options and general refactor and optimizations
2017-05-29 17:17:54 -03:00
73ec224c93 Merge pull request #2 from maraoz/aragon-refactor
rebase to master
2017-05-29 22:05:05 +02:00
a62621eb59 merge @izqui PR with new docs changes 2017-05-29 16:19:03 -03:00
84843d42da Merge pull request #225 from DavidKnott/fix-natspec-typos
Edit natspec documentation typos
2017-05-25 18:44:01 -03:00
d08185fc3e Edit natspec documentation typos 2017-05-26 00:29:15 +03:00
efe09575e3 Merge pull request #210 from maurelian/master
Add natspec comments to contracts
2017-05-24 18:33:28 -03:00
c4796bb918 Fix comments again 2017-05-24 17:27:05 -04:00
111f13f0ce Add doc comments to multisig wallet 2017-05-24 16:51:05 -04:00
d357cf3a2e Minor changes to doc comments for token and other contracts 2017-05-24 16:51:01 -04:00
83f2849446 Minor edits to doc commenst in lifecycle, ownership, payment contracts. 2017-05-24 16:49:43 -04:00
d85be4a866 Add natspec to vestedToken.sol 2017-05-24 16:47:25 -04:00
f6f91298f0 Add natspec to all remaing contracts, except for vestedToken.sol 2017-05-24 16:47:21 -04:00
1547922b61 Added natspec to the remaining ownership contracts and payment contracts 2017-05-24 16:45:45 -04:00
602c18b394 Applied change regarding the styling 2017-05-24 16:45:41 -04:00
b5d4120adb Added natsec for all lifecycle contracts + bounty.sol, DayLimit.sol and LimitBalance.sol 2017-05-24 16:43:14 -04:00
e851938199 Add natspec comments to four ownership contracts 2017-05-24 16:35:09 -04:00
48a2e11dfe merge 2017-05-22 18:08:03 -04:00
22f60eace0 Use libraries syntax sugar for revoking grants logic 2017-05-22 18:06:57 -04:00
b788f33c6a Merge pull request #218 from cgewecke/coverage
Add coverage
2017-05-21 23:40:18 -03:00
592548715f Add solidity-coverage 2017-05-21 19:19:50 -07:00
0983f0065d Merge pull request #223 from aragon/safe-math-div
[SafeMath] Remove unnecessary checks from safeDiv
2017-05-21 23:06:42 -03:00
c4f78a5dd5 Remove unnecessary checks from safeDiv 2017-05-21 16:41:18 -04:00
e032b86231 Merge with Zeppelin master 2017-05-21 16:14:06 -04:00
a6a2ee2bf1 Merge with master 2017-05-21 16:08:47 -04:00
929367f0ab Reorg code 2017-05-21 12:10:04 +02:00
5a6340395f Fix grant id parameter in NewTokenGrant event 2017-05-21 11:22:30 +02:00
f812433706 Small refactor and documentation 2017-05-21 11:18:24 +02:00
713b472253 Add tests for non-revokable and revokable/burnable cases 2017-05-21 11:17:24 +02:00
a1d2b673c6 Fix tests for revokable/non burn vesting calendar 2017-05-21 10:44:03 +02:00
5b2f0aa93d Implement revokable and burnsOnRevoke options 2017-05-21 10:38:56 +02:00
ecbfcbb302 Merge pull request #221 from TokenMarketNet/feat/transfer-from-mitigation
Protect transferFrom() against short hand attack.
2017-05-18 12:43:51 -03:00
964185dec3 Protect transferFrom against short hand attack. 2017-05-18 00:38:41 +03:00
5c491987f3 Merge pull request #219 from TokenMarketNet/feat/approve-mitigation
approve() race condition mitigation
2017-05-17 13:26:19 -06:00
e1cf602487 Fix variable naming. 2017-05-17 01:41:43 +03:00
a3446507ec Add fix for the approve() mitigation. 2017-05-17 01:33:13 +03:00
ff61c7d92d Merge pull request #212 from misteraverin/feature/destructible
Add destroy function, allowing send funds to recepient.
2017-05-15 07:19:45 -06:00
726593c0a2 Merge pull request #216 from maraoz/ethpm-npm
Revert to usig npm as preferred installation method
2017-05-12 09:12:24 -06:00
7826fddba7 revert to usig npm as preferred installation method 2017-05-12 12:10:28 -03:00
38a450460d Merge pull request #214 from maraoz/audit-report
Add external audit report
2017-05-11 13:17:53 -03:00
de7751aae2 Add external audit 2017-05-11 13:08:23 -03:00
cf7bc06856 Switch function name to destroyAndSend 2017-05-09 23:20:44 +03:00
4de772f5ed add destroy function, allowing send funds to recepient 2017-05-08 22:50:43 +03:00
66 changed files with 1129 additions and 368 deletions

1
.coveralls.yml Normal file
View File

@ -0,0 +1 @@
repo_token: AelGMv47LJ85e3KF1PhYBsjyduSjDmP0h

2
.gitignore vendored
View File

@ -3,3 +3,5 @@
node_modules/
build/
.DS_Store/
/coverage
coverage.json

View File

@ -5,8 +5,10 @@ language: node_js
node_js:
- "6"
before_install:
- npm install truffle@3.1.9 -g
- npm install truffle@3.2.2 -g
- npm i -g ethereumjs-testrpc
script:
- testrpc > /dev/null &
- truffle test
after_script:
- npm run coveralls

View File

@ -1,6 +1,7 @@
# Zeppelin Solidity
[![NPM Package](https://img.shields.io/npm/v/zeppelin-solidity.svg?style=flat-square)](https://www.npmjs.org/package/zeppelin-solidity)
[![Build Status](https://img.shields.io/travis/OpenZeppelin/zeppelin-solidity.svg?branch=master&style=flat-square)](https://travis-ci.org/OpenZeppelin/zeppelin-solidity)
[![Coverage Status](https://coveralls.io/repos/github/OpenZeppelin/zeppelin-solidity/badge.svg?branch=coveralls)](https://coveralls.io/github/OpenZeppelin/zeppelin-solidity?branch=coveralls)
OpenZeppelin is a library for writing secure [Smart Contracts](https://en.wikipedia.org/wiki/Smart_contract) on Ethereum.
@ -22,19 +23,20 @@ truffle init
To install the OpenZeppelin library, run:
```sh
truffle install zeppelin
npm install zeppelin-solidity
```
After that, you'll get all the library's contracts in the `installed_contracts` folder. You can use the contracts in the library like so:
After that, you'll get all the library's contracts in the `node_modules/zeppelin-solidity/contracts` folder. You can use the contracts in the library like so:
```js
import 'zeppelin/ownership/Ownable.sol';
import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
contract MyContract is Ownable {
...
}
```
## Security
OpenZeppelin is meant to provide secure, tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problem you might experience.

290
audit/ZeppelinAudit.md Normal file
View File

@ -0,0 +1,290 @@
# OpenZeppelin Audit
March, 2017
Authored by Dennis Peterson and Peter Vessenes
# Introduction
Zeppelin requested that New Alchemy perform an audit of the contracts in their OpenZeppelin library. The OpenZeppelin contracts are a set of contracts intended to be a safe building block for a variety of uses by parties that may not be as sophisticated as the OpenZeppelin team. It is a design goal that the contracts be deployable safely and "as-is".
The contracts are hosted at:
https://github.com/OpenZeppelin/zeppelin-solidity
All the contracts in the "contracts" folder are in scope.
The git commit hash we evaluated is:
9c5975a706b076b7000e8179f8101e0c61024c87
# Disclaimer
The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bugfree status. The audit documentation is for discussion purposes only.
# Executive Summary
Overall the OpenZeppelin codebase is of reasonably high quality -- it is clean, modular and follows best practices throughout.
It is still in flux as a codebase, and needs better documentation per file as to expected behavior and future plans. It probably needs more comprehensive and aggressive tests written by people less nice than the current OpenZeppelin team.
We identified two critical errors and one moderate issue, and would not recommend this commit hash for public use until these bugs are remedied.
The repository includes a set of Truffle unit tests, a requirement and best practice for smart contracts like these; we recommend these be bulked up.
# Discussion
## Big Picture: Is This A Worthwhile Project?
As soon as a developer touches OpenZeppelin contracts, they will modify something, leaving them in an un-audited state. We do not recommend developers deploy any unaudited code to the Blockchain if it will handle money, information or other things of value.
> "In accordance with Unix philosophy, Perl gives you enough rope to hang yourself"
> --Larry Wall
We think this is an incredibly worthwhile project -- aided by the high code quality. Creating a framework that can be easily extended helps increase the average code quality on the Blockchain by charting a course for developers and encouraging containment of modifications to certain sections.
> "Rust: The language that makes you take the safety off before shooting yourself in the foot"
> -- (@mbrubeck)
We think much more could be done here, and recommend the OpenZeppelin team keep at this and keep focusing on the design goal of removing rope and adding safety.
## Solidity Version Updates Recommended
Most of the code uses Solidity 0.4.11, but some files under `Ownership` are marked 0.4.0. These should be updated.
Solidity 0.4.10 will add several features which could be useful in these contracts:
- `assert(condition)`, which throws if the condition is false
- `revert()`, which rolls back without consuming all remaining gas.
- `address.transfer(value)`, which is like `send` but automatically propagates exceptions, and supports `.gas()`. See https://github.com/ethereum/solidity/issues/610 for more on this.
## Error Handling: Throw vs Return False
Solidity standards allow two ways to handle an error -- either calling `throw` or returning `false`. Both have benefits. In particular, a `throw` guarantees a complete wipe of the call stack (up to the preceding external call), whereas `false` allows a function to continue.
In general we prefer `throw` in our code audits, because it is simpler -- it's less for an engineer to keep track of. Returning `false` and using logic to check results can quickly become a poorly-tracked state machine, and this sort of complexity can cause errors.
In the OpenZeppelin contracts, both styles are used in different parts of the codebase. `SimpleToken` transfers throw upon failure, while the full ERC20 token returns `false`. Some modifiers `throw`, others just wrap the function body in a conditional, effectively allowing the function to return false if the condition is not met.
We don't love this, and would usually recommend you stick with one style or the other throughout the codebase.
In at least one case, these different techniques are combined cleverly (see the Multisig comments, line 65). As a set of contracts intended for general use, we recommend you either strive for more consistency or document explicit design criteria that govern which techniques are used where.
Note that it may be impossible to use either one in all situations. For example, SafeMath functions pretty much have to throw upon failure, but ERC20 specifies returning booleans. Therefore we make no particular recommendations, but simply point out inconsistencies to consider.
# Critical Issues
## Stuck Ether in Crowdsale contract
CrowdsaleToken.sol has no provision for withdrawing the raised ether. We *strongly* recommend a standard `withdraw` function be added. There is no scenario in which someone should deploy this contract as is, whether for testing or live.
## Recursive Call in MultisigWallet
Line 45 of `MultisigWallet.sol` checks if the amount being sent by `execute` is under a daily limit.
This function can only be called by the "Owner". As a first angle of attack, it's worth asking what will happen if the multisig wallet owners reset the daily limit by approving a call to `resetSpentToday`.
If a chain of calls can be constructed in which the owner confirms the `resetSpentToday` function and then withdraws through `execute` in a recursive call, the contract can be drained. In fact, this could be done without a recursive call, just through repeated `execute` calls alternating with the `confirm` calls.
We are still working through the confirmation protocol in `Shareable.sol`, but we are not convinced that this is impossible, in fact it looks possible. The flexibility any shared owner has in being able to revoke confirmation later is another worrisome angle of approach even if some simple patches are included.
This bug has a number of causes that need to be addressed:
1. `resetSpentToday` and `confirm` together do not limit the days on which the function can be called or (it appears) the number of times it can be called.
1. Once a call has been confirmed and `execute`d it appears that it can be re-executed. This is not good.
3. `confirmandCheck` doesn't seem to have logic about whether or not the function in question has been called.
4. Even if it did, `revoke` would need updates and logic to deal with revocation requests after a function call had been completed.
We do not recommend using the MultisigWallet until these issues are fixed.
# Moderate to Minor Issues
## PullPayment
PullPayment.sol needs some work. It has no explicit provision for cancelling a payment. This would be desirable in a number of scenarios; consider a payee losing their wallet, or giving a griefing address, or just an address that requires more than the default gas offered by `send`.
`asyncSend` has no overflow checking. This is a bad plan. We recommend overflow and underflow checking at the layer closest to the data manipulation.
`asyncSend` allows more balance to be queued up for sending than the contract holds. This is probably a bad idea, or at the very least should be called something different. If the intent is to allow this, it should have provisions for dealing with race conditions between competing `withdrawPayments` calls.
It would be nice to see how many payments are pending. This would imply a bit of a rewrite; we recommend this contract get some design time, and that developers don't rely on it in its current state.
## Shareable Contract
We do not believe the `Shareable.sol` contract is ready for primetime. It is missing functions, and as written may be vulnerable to a reordering attack -- an attack in which a miner or other party "racing" with a smart contract participant inserts their own information into a list or mapping.
The confirmation and revocation code needs to be looked over with a very careful eye imagining extraordinarily bad behavior by shared owners before this contract can be called safe.
No sanity checks on the initial constructor's `required` argument are worrisome as well.
# Line by Line Comments
## Lifecycle
### Killable
Very simple, allows owner to call selfdestruct, sending funds to owner. No issues. However, note that `selfdestruct` should typically not be used; it is common that a developer may want to access data in a former contract, and they may not understand that `selfdestruct` limits access to the contract. We recommend better documentation about this dynamic, and an alternate function name for `kill` like `completelyDestroy` while `kill` would perhaps merely send funds to the owner.
Also note that a killable function allows the owner to take funds regardless of other logic. This may be desirable or undesirable depending on the circumstances. Perhaps `Killable` should have a different name as well.
### Migrations
I presume that the goal of this contract is to allow and annotate a migration to a new smart contract address. We are not clear here how this would be accomplished by the code; we'd like to review with the OpenZeppelin team.
### Pausable
We like these pauses! Note that these allow significant griefing potential by owners, and that this might not be obvious to participants in smart contracts using the OpenZeppelin framework. We would recommend that additional sample logic be added to for instance the TokenContract showing safer use of the pause and resume functions. In particular, we would recommend a timelock after which anyone could unpause the contract.
The modifers use the pattern `if(bool){_;}`. This is fine for functions that return false upon failure, but could be problematic for functions expected to throw upon failure. See our comments above on standardizing on `throw` or `return(false)`.
## Ownership
### Ownable
Line 19: Modifier throws if doesn't meet condition, in contrast to some other inheritable modifiers (e.g. in Pausable) that use `if(bool){_;}`.
### Claimable
Inherits from Ownable but the existing owner sets a pendingOwner who has to claim ownership.
Line 17: Another modifier that throws.
### DelayedClaimable
Is there any reason to descend from Ownable directly, instead of just Claimable, which descends from Ownable? If not, descending from both just adds confusion.
### Contactable
Allows owner to set a public string of contract information. No issues.
### Shareable
This needs some work. Doesn't check if `_required <= len(_owners)` for instance, that would be a bummer. What if _required were like `MAX - 1`?
I have a general concern about the difference between `owners`, `_owners`, and `owner` in `Ownable.sol`. I recommend "Owners" be renamed. In general we do not recomment single character differences in variable names, although a preceding underscore is not uncommon in Solidity code.
Line 34: "this contract only has six types of events"...actually only two.
Line 61: Why is `ownerIndex` keyed by addresses hashed to `uint`s? Why not use the addresses directly, so `ownerIndex` is less obscure, and so there's stronger typing?
Line 62: Do not love `++i) ... owners[2+ i]`. Makes me do math, which is not what I want to do. I want to not have to do math.
There should probably be a function for adding a new operation, so the developer doesn't have to work directly with the internal data. (This would make the multisig contract even shorter.)
There's a `revoke` function but not a `propose` function that we can see.
Beware reordering. If `propose` allows the user to choose a bytes string for their proposal, bad things(TM) will happen as currently written.
### Multisig
Just an interface. Note it allows changing an owner address, but not changing the number of owners. This is somewhat limiting but also simplifies implementation.
## Payment
### PullPayment
Safe from reentrance attack since ether send is at the end, plus it uses `.send()` rather than `.call.value()`.
There's an argument to be made that `.call.value()` is a better option *if* you're sure that it will be done after all state updates, since `.send` will fail if the recipient has an expensive fallback function. However, in the context of a function meant to be embedded in other contracts, it's probably better to use `.send`. One possible compromise is to add a function which allows only the owner to send ether via `.call.value`.
If you don't use `call.value` you should implement a `cancel` function in case some value is pending here.
Line 14:
Doesn't use safeAdd. Although it appears that payout amounts can only be increased, in fact the payer could lower the payout as much as desired via overflow. Also, the payer could add a large non-overflowing amount, causing the payment to exceed the contract balance and therefore fail when withdraw is attempted.
Recommendation: track the sum of non-withdrawn asyncSends, and don't allow a new one which exceeds the leftover balance. If it's ever desirable to make payments revocable, it should be done explicitly.
## Tokens
### ERC20
Standard ERC20 interface only.
There's a security hole in the standard, reported at Edcon: `approve` does not protect against race conditions and simply replaces the current value. An approved spender could wait for the owner to call `approve` again, then attempt to spend the old limit before the new limit is applied. If successful, this attacker could successfully spend the sum of both limits.
This could be fixed by either (1) including the old limit as a parameter, so the update will fail if some gets spent, or (2) using the value parameter as a delta instead of replacement value.
This is not fixable while adhering to the current full ERC20 standard, though it would be possible to add a "secureApprove" function. The impact isn't extreme since at least you can only be attacked by addresses you approved. Also, users could mitigate this by always setting spending limits to zero and checking for spends, before setting the new limit.
Edcon slides:
https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view
### ERC20Basic
Simpler interface skipping the Approve function. Note this departs from ERC20 in another way: transfer throws instead of returning false.
### BasicToken
Uses `SafeSub` and `SafeMath`, so transfer `throw`s instead of returning false. This complies with ERC20Basic but not the actual ERC20 standard.
### StandardToken
Implementation of full ERC20 token.
Transfer() and transferFrom() use SafeMath functions, which will cause them to throw instead of returning false. Not a security issue but departs from standard.
### SimpleToken
Sample instantiation of StandardToken. Note that in this sample, decimals is 18 and supply only 10,000, so the supply is a small fraction of a single nominal token.
### CrowdsaleToken
StandardToken which mints tokens at a fixed price when sent ether.
There's no provision for owner withdrawing the ether. As a sample for crowdsales it should be Ownable and allow the owner to withdraw ether, rather than stranding the ether in the contract.
Note: an alternative pattern is a mint() function which is only callable from a separate crowdsale contract, so any sort of rules can be added without modifying the token itself.
### VestedToken
Lines 23, 27:
Functions `transfer()` and `transferFrom()` have a modifier canTransfer which throws if not enough tokens are available. However, transfer() returns a boolean success. Inconsistent treatment of failure conditions may cause problems for other contracts using the token. (Note that transferableTokens() relies on safeSub(), so will also throw if there's insufficient balance.)
Line 64:
Delete not actually necessary since the value is overwritten in the next line anyway.
## Root level
### Bounty
Avoids potential race condition by having each researcher deploy a separate contract for attack; if a research manages to break his associated contract, other researchers can't immediately claim the reward, they have to reproduce the attack in their own contracts.
A developer could subvert this intent by implementing `deployContract()` to always return the same address. However, this would break the `researchers` mapping, updating the researcher address associated with the contract. This could be prevented by blocking rewrites in `researchers`.
### DayLimit
The modifier `limitedDaily` calls `underLimit`, which both checks that the spend is below the daily limit, and adds the input value to the daily spend. This is fine if all functions throw upon failure. However, not all OpenZeppelin functions do this; there are functions that returns false, and modifiers that wrap the function body in `if (bool) {_;}`. In these cases, `_value` will be added to `spentToday`, but ether may not actually be sent because other preconditions were not met. (However in the OpenZeppelin multisig this is not a problem.)
Lines 4, 11:
Comment claims that `DayLimit` is multiowned, and Shareable is imported, but DayLimit does not actually inherit from Shareable. The intent may be for child contracts to inherit from Shareable (as Multisig does); in this case the import should be removed and the comment altered.
Line 46:
Manual overflow check instead of using safeAdd. Since this is called from a function that throws upon failure anyway, there's no real downside to using safeAdd.
### LimitBalance
No issues.
### MultisigWallet
Lines 28, 76, 80:
`kill`, `setDailyLimit`, and `resetSpentToday` only happen with multisig approval, and hashes for these actions are logged by Shareable. However, they should probably post their own events for easy reading.
Line 45:
This call to underLimit will reduce the daily limit, and then either throw or return 0. So in this case there's no danger that the limit will be reduced without the operation going through.
Line 65:
Shareable's onlyManyOwners will take the user's confirmation, and execute the function body if and only if enough users have confirmed. Whole thing throws if the send fails, which will roll back the confirmation. Confirm returns false if not enough have confirmed yet, true if the whole thing succeeds, and throws only in the exceptional circumstance that the designated transaction unexpectedly fails. Elegant design.
Line 68:
Throw here is good but note this function can fail either by returning false or by throwing.
Line 92:
A bit odd to split `clearPending()` between this contract and Shareable. However this does allow contracts inheriting from Shareable to use custom structs for pending transactions.
### SafeMath
Another interesting comment from the same Edcon presentation was that the overflow behavior of Solidity is undocumented, so in theory, source code that relies on it could break with a future revision.
However, compiled code should be fine, and in the unlikely event that the compiler is revised in this way, there should be plenty of warning. (But this is an argument for keeping overflow checks isolated in SafeMath.)
Aside from that small caveat, these are fine.

View File

@ -1,14 +1,13 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './payment/PullPayment.sol';
import './lifecycle/Destructible.sol';
/*
* Bounty
*
* This bounty will pay out to a researcher if they break invariant logic of the contract.
/**
* @title Bounty
* @dev This bounty will pay out to a researcher if they break invariant logic of the contract.
*/
contract Bounty is PullPayment, Destructible {
bool public claimed;
@ -16,12 +15,20 @@ contract Bounty is PullPayment, Destructible {
event TargetCreated(address createdAddress);
/**
* @dev Fallback function allowing the contract to recieve funds, if they haven't already been claimed.
*/
function() payable {
if (claimed) {
throw;
}
}
/**
* @dev Create and deploy the target contract (extension of Target contract), and sets the
* msg.sender as a researcher
* @return A target contract
*/
function createTarget() returns(Target) {
Target target = Target(deployContract());
researchers[target] = msg.sender;
@ -29,8 +36,16 @@ contract Bounty is PullPayment, Destructible {
return target;
}
/**
* @dev Internal function to deploy the target contract.
* @return A target contract address
*/
function deployContract() internal returns(address);
/**
* @dev Sends the contract funds to the researcher that proved the contract is broken.
* @param target contract
*/
function claim(Target target) {
address researcher = researchers[target];
if (researcher == 0) {
@ -47,12 +62,17 @@ contract Bounty is PullPayment, Destructible {
}
/*
* Target
*
* Your main contract should inherit from this class and implement the checkInvariant method. This is a function that should check everything your contract assumes to be true all the time. If this function returns false, it means your contract was broken in some way and is in an inconsistent state. This is what security researchers will try to acomplish when trying to get the bounty.
/**
* @title Target
* @dev Your main contract should inherit from this class and implement the checkInvariant method.
*/
contract Target {
/**
* @dev Checks all values a contract assumes to be true all the time. If this function returns
* false, the contract is broken in some way and is in an inconsistent state.
* In order to win the bounty, security researchers will try to cause this broken state.
* @return True if all invariant values are correct, false otherwise.
*/
function checkInvariant() returns(bool);
}

View File

@ -1,11 +1,9 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
/*
* DayLimit
*
* inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable)
* on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method
* uses is specified in the modifier.
/**
* @title DayLimit
* @dev Base contract that enables methods to be protected by placing a linear limit (specifiable)
* on a particular resource per calendar day. Is multiowned to allow the limit to be altered.
*/
contract DayLimit {
@ -13,24 +11,35 @@ contract DayLimit {
uint public spentToday;
uint public lastDay;
/**
* @dev Constructor that sets the passed value as a dailyLimit.
* @param _limit Uint to represent the daily limit.
*/
function DayLimit(uint _limit) {
dailyLimit = _limit;
lastDay = today();
}
// sets the daily limit. doesn't alter the amount already spent today
/**
* @dev sets the daily limit. Does not alter the amount already spent today.
* @param _newLimit Uint to represent the new limit.
*/
function _setDailyLimit(uint _newLimit) internal {
dailyLimit = _newLimit;
}
// resets the amount already spent today.
/**
* @dev Resets the amount already spent today.
*/
function _resetSpentToday() internal {
spentToday = 0;
}
// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
// returns true. otherwise just returns false.
/**
* @dev Checks to see if there is enough resource to spend today. If true, the resource may be expended.
* @param _value Uint representing the amount of resource to spend.
* @return A boolean that is True if the resource was spended and false otherwise.
*/
function underLimit(uint _value) internal returns (bool) {
// reset the spend limit if we're on a different day to last time.
if (today() > lastDay) {
@ -46,13 +55,17 @@ contract DayLimit {
return false;
}
// determines today's index.
/**
* @dev Private function to determine today's index
* @return Uint of today's index.
*/
function today() private constant returns (uint) {
return now / 1 days;
}
// simple modifier for daily limit.
/**
* @dev Simple modifier for daily limit.
*/
modifier limitedDaily(uint _value) {
if (!underLimit(_value)) {
throw;

View File

@ -1,27 +1,33 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
/**
* LimitBalance
* Simple contract to limit the balance of child contract.
* Note this doesn't prevent other contracts to send funds
* by using selfdestruct(address);
* See: https://github.com/ConsenSys/smart-contract-best-practices#remember-that-ether-can-be-forcibly-sent-to-an-account
* @title LimitBalance
* @dev Simple contract to limit the balance of child contract.
* @dev Note this doesn't prevent other contracts to send funds by using selfdestruct(address);
* @dev See: https://github.com/ConsenSys/smart-contract-best-practices#remember-that-ether-can-be-forcibly-sent-to-an-account
*/
contract LimitBalance {
uint public limit;
/**
* @dev Constructor that sets the passed value as a limit.
* @param _limit Uint to represent the limit.
*/
function LimitBalance(uint _limit) {
limit = _limit;
}
modifier limitedPayable() {
/**
* @dev Checks if limit was reached. Case true, it throws.
*/
modifier limitedPayable() {
if (this.balance > limit) {
throw;
}
_;
}
}

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./ownership/Multisig.sol";
@ -6,11 +6,11 @@ import "./ownership/Shareable.sol";
import "./DayLimit.sol";
/*
/**
* MultisigWallet
* usage:
* bytes32 h = Wallet(w).from(oneOwner).execute(to, value, data);
* Wallet(w).from(anotherOwner).confirm(h);
* Usage:
* bytes32 h = Wallet(w).from(oneOwner).execute(to, value, data);
* Wallet(w).from(anotherOwner).confirm(h);
*/
contract MultisigWallet is Multisig, Shareable, DayLimit {
@ -20,26 +20,41 @@ contract MultisigWallet is Multisig, Shareable, DayLimit {
bytes data;
}
/**
* Constructor, sets the owners addresses, number of approvals required, and daily spending limit
* @param _owners A list of owners.
* @param _required The amount required for a transaction to be approved.
*/
function MultisigWallet(address[] _owners, uint _required, uint _daylimit)
Shareable(_owners, _required)
DayLimit(_daylimit) { }
// destroys the contract sending everything to `_to`.
/**
* @dev destroys the contract sending everything to `_to`.
*/
function destroy(address _to) onlymanyowners(keccak256(msg.data)) external {
selfdestruct(_to);
}
// gets called when no other function matches
/**
* @dev Fallback function, receives value and emits a deposit event.
*/
function() payable {
// just being sent some cash?
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
// Outside-visible transact entry point. Executes transaction immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
/**
* @dev Outside-visible transaction entry point. Executes transaction immediately if below daily
* spending limit. If not, goes into multisig process. We provide a hash on return to allow the
* sender to provide shortcuts for the other confirmations (allowing them to avoid replicating
* the _to, _value, and _data arguments). They still get the option of using them if they want,
* anyways.
* @param _to The receiver address
* @param _value The value to send
* @param _data The data part of the transaction
*/
function execute(address _to, uint _value, bytes _data) external onlyOwner returns (bytes32 _r) {
// first, take the opportunity to check that we're under the daily limit.
if (underLimit(_value)) {
@ -60,8 +75,11 @@ contract MultisigWallet is Multisig, Shareable, DayLimit {
}
}
// confirm a transaction through just the hash. we use the previous transactions map, txs, in order
// to determine the body of the transaction from the hash provided.
/**
* @dev Confirm a transaction by providing just the hash. We use the previous transactions map,
* txs, in order to determine the body of the transaction from the hash provided.
* @param _h The transaction hash to approve.
*/
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) {
if (txs[_h].to != 0) {
if (!txs[_h].to.call.value(txs[_h].value)(txs[_h].data)) {
@ -73,17 +91,26 @@ contract MultisigWallet is Multisig, Shareable, DayLimit {
}
}
/**
* @dev Updates the daily limit value.
* @param _newLimit Uint to represent the new limit.
*/
function setDailyLimit(uint _newLimit) onlymanyowners(keccak256(msg.data)) external {
_setDailyLimit(_newLimit);
}
/**
* @dev Resets the value spent to enable more spending
*/
function resetSpentToday() onlymanyowners(keccak256(msg.data)) external {
_resetSpentToday();
}
// INTERNAL METHODS
/**
* @dev Clears the list of transactions pending approval.
*/
function clearPending() internal {
uint length = pendingsIndex.length;
for (uint i = 0; i < length; ++i) {

View File

@ -1,20 +1,26 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
/// @title Helps contracts guard agains rentrancy attacks.
/// @author Remco Bloemen <remco@2π.com>
/// @notice If you mark a function `nonReentrant`, you should also
/// mark it `external`.
/**
* @title Helps contracts guard agains rentrancy attacks.
* @author Remco Bloemen <remco@2π.com>
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev We use a single lock for the whole contract.
/**
* @dev We use a single lock for the whole contract.
*/
bool private rentrancy_lock = false;
/// Prevent contract from calling itself, directly or indirectly.
/// @notice If you mark a function `nonReentrant`, you should also
/// mark it `external`. Calling one nonReentrant function from
/// another is not supported. Instead, you can implement a
/// `private` function doing the actual work, and a `external`
/// wrapper marked as `nonReentrant`.
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
if(rentrancy_lock == false) {
rentrancy_lock = true;

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
/**
@ -12,9 +12,9 @@ library SafeMath {
}
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
assert(a == b * c + a % b);
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}

View File

@ -1,15 +1,25 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "../ownership/Ownable.sol";
/*
* Destructible
* Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner {
selfdestruct(_recipient);
}
}

View File

@ -1,10 +1,12 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../ownership/Ownable.sol';
// This is a truffle contract, needed for truffle integration, not meant for use by Zeppelin users.
/**
* @title Migrations
* @dev This is a truffle contract, needed for truffle integration, not meant for use by Zeppelin users.
*/
contract Migrations is Ownable {
uint public lastCompletedMigration;

View File

@ -1,13 +1,12 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "../ownership/Ownable.sol";
/*
* Pausable
* Abstract contract that allows children to implement a
* pause mechanism.
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
@ -15,24 +14,35 @@ contract Pausable is Ownable {
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
if (paused) throw;
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
if (!paused) throw;
_;
}
// called by the owner to pause, triggers stopped state
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
// called by the owner to unpause, returns to normal state
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();

View File

@ -1,20 +1,26 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "../ownership/Ownable.sol";
import "../token/ERC20Basic.sol";
/// @title TokenDestructible:
/// @author Remco Bloemen <remco@2π.com>
///.Base contract that can be destroyed by owner. All funds in contract including
/// listed tokens will be sent to the owner
/**
* @title TokenDestructible:
* @author Remco Bloemen <remco@2π.com>
* @dev Base contract that can be destroyed by owner. All funds in contract including
* listed tokens will be sent to the owner.
*/
contract TokenDestructible is Ownable {
/// @notice Terminate contract and refund to owner
/// @param tokens List of addresses of ERC20 or ERC20Basic token contracts to
// refund
/// @notice The called token contracts could try to re-enter this contract.
// Only supply token contracts you
function TokenDestructible() payable { }
/**
* @notice Terminate contract and refund to owner
* @param tokens List of addresses of ERC20 or ERC20Basic token contracts to
refund.
* @notice The called token contracts could try to re-enter this contract. Only
supply token contracts you trust.
*/
function destroy(address[] tokens) onlyOwner {
// Transfer tokens to owner

View File

@ -1,17 +1,20 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './Ownable.sol';
/*
* Claimable
*
* Extension for the Ownable contract, where the ownership needs to be claimed. This allows the new owner to accept the transfer.
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
if (msg.sender != pendingOwner) {
throw;
@ -19,13 +22,19 @@ contract Claimable is Ownable {
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner {
owner = pendingOwner;
pendingOwner = 0x0;
}
}

View File

@ -1,16 +1,21 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './Ownable.sol';
/*
* Contactable token
* Basic version of a contactable contract
/**
* @title Contactable token
* @dev Basic version of a contactable contract, allowing the owner to provide a string with their
* contact information.
*/
contract Contactable is Ownable{
string public contactInformation;
string public contactInformation;
function setContactInformation(string info) onlyOwner{
/**
* @dev Allows the owner to set a string with their contact information.
* @param info The contact information to attach to the contract.
*/
function setContactInformation(string info) onlyOwner{
contactInformation = info;
}
}

View File

@ -1,18 +1,25 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './Claimable.sol';
/*
* DelayedClaimable
* Extension for the Claimable contract, where the ownership needs to be claimed before/after certain block number
/**
* @title DelayedClaimable
* @dev Extension for the Claimable contract, where the ownership needs to be claimed before/after
* a certain block number.
*/
contract DelayedClaimable is Claimable {
uint public end;
uint public start;
/**
* @dev Used to specify the time period during which a pending
* owner can claim ownership.
* @param _start The earliest time ownership can be claimed.
* @param _end The latest time ownership can be claimed.
*/
function setLimits(uint _start, uint _end) onlyOwner {
if (_start > _end)
throw;
@ -20,6 +27,11 @@ contract DelayedClaimable is Claimable {
start = _start;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within
* the specified start and end time.
*/
function claimOwnership() onlyPendingOwner {
if ((block.number > end) || (block.number < start))
throw;

View File

@ -1,16 +1,19 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./Ownable.sol";
/// @title Contracts that should not own Contracts
/// @author Remco Bloemen <remco@2π.com>
///
/// Should contracts (anything Ownable) end up being owned by
/// this contract, it allows the owner of this contract to
/// reclaim ownership of the contracts.
/**
* @title Contracts that should not own Contracts
* @author Remco Bloemen <remco@2π.com>
* @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner
* of this contract to reclaim ownership of the contracts.
*/
contract HasNoContracts is Ownable {
/// Reclaim ownership of Ownable contracts
/**
* @dev Reclaim ownership of Ownable contracts
* @param contractAddr The address of the Ownable to be reclaimed.
*/
function reclaimContract(address contractAddr) external onlyOwner {
Ownable contractInst = Ownable(contractAddr);
contractInst.transferOwnership(owner);

View File

@ -1,39 +1,41 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./Ownable.sol";
/// @title Contracts that should not own Ether
/// @author Remco Bloemen <remco@2π.com>
///
/// This tries to block incoming ether to prevent accidental
/// loss of Ether. Should Ether end up in the contrat, it will
/// allow the owner to reclaim this ether.
///
/// @notice Ether can still be send to this contract by:
/// * calling functions labeled `payable`
/// * `selfdestruct(contract_address)`
/// * mining directly to the contract address
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/// Constructor that rejects incoming Ether
/// @dev The flag `payable` is added so we can access `msg.value`
/// without compiler warning. If we leave out payable, then
/// Solidity will allow inheriting contracts to implement a
/// payable constructor. By doing it this way we prevent a
/// payable constructor from working.
/// Alternatively we could use assembly to access msg.value.
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
function HasNoEther() payable {
if(msg.value > 0) {
throw;
}
}
/// Disallow direct send by settings a default function without `payable`
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/// Transfer all Ether owned by the contract to the owner
/// @dev What if owner is itself a contract marked HasNoEther?
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
if(!owner.send(this.balance)) {
throw;

View File

@ -1,23 +1,31 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./Ownable.sol";
import "../token/ERC20Basic.sol";
/// @title Contracts that should not own Tokens
/// @author Remco Bloemen <remco@2π.com>
///
/// This blocks incoming ERC23 tokens to prevent accidental
/// loss of tokens. Should tokens (any ERC20Basic compatible)
/// end up in the contract, it allows the owner to reclaim
/// the tokens.
/**
* @title Contracts that should not own Tokens
* @author Remco Bloemen <remco@2π.com>
* @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens.
* Should tokens (any ERC20Basic compatible) end up in the contract, it allows the
* owner to reclaim the tokens.
*/
contract HasNoTokens is Ownable {
/// Reject all ERC23 compatible tokens
/**
* @dev Reject all ERC23 compatible tokens
* @param from_ address The address that is transferring the tokens
* @param value_ Uint the amount of the specified token
* @param data_ Bytes The data passed from the caller.
*/
function tokenFallback(address from_, uint value_, bytes data_) external {
throw;
}
/// Reclaim all ERC20Basic compatible tokens
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param tokenAddr address The address of the token contract
*/
function reclaimToken(address tokenAddr) external onlyOwner {
ERC20Basic tokenInst = ERC20Basic(tokenAddr);
uint256 balance = tokenInst.balanceOf(this);

View File

@ -1,9 +1,9 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
/*
* Multisig
* Interface contract for multisig proxy contracts; see below for docs.
/**
* @title Multisig
* @dev Interface contract for multisig proxy contracts; see below for docs.
*/
contract Multisig {
// EVENTS
@ -26,4 +26,3 @@ contract Multisig {
function execute(address _to, uint _value, bytes _data) external returns (bytes32);
function confirm(bytes32 _h) returns (bool);
}

View File

@ -1,14 +1,14 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./HasNoEther.sol";
import "./HasNoTokens.sol";
import "./HasNoContracts.sol";
/// @title Base contract for contracts that should not own things.
/// @author Remco Bloemen <remco@2π.com>
///
/// Solves a class of errors where a contract accidentally
/// becomes owner of Ether, Tokens or Owned contracts. See
/// respective base contracts for details.
/**
* @title Base contract for contracts that should not own things.
* @author Remco Bloemen <remco@2π.com>
* @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or
* Owned contracts. See respective base contracts for details.
*/
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}

View File

@ -1,19 +1,27 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
/*
* Ownable
*
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
@ -21,6 +29,11 @@ contract Ownable {
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;

View File

@ -1,17 +1,14 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
/*
* Shareable
*
* Based on https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol
*
* inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a single, or, crucially, each of a number of, designated owners.
*
* usage:
* use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by some number (specified in constructor) of the set of owners (specified in the constructor) before the interior is executed.
/**
* @title Shareable
* @dev inheritable "property" contract that enables methods to be protected by requiring the
* acquiescence of either a single, or, crucially, each of a number of, designated owners.
* @dev Usage: use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by some number (specified in constructor) of the set of owners (specified in the constructor) before the interior is executed.
*/
contract Shareable {
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
@ -44,18 +41,24 @@ contract Shareable {
}
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
/**
* @dev Modifier for multisig functions.
* @param _operation The operation must have an intrinsic hash in order that later attempts can be
* realised as the same underlying operation and thus count as confirmations.
*/
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation)) {
_;
}
}
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them.
/**
* @dev Constructor is given the number of sigs required to do protected "onlymanyowners"
* transactions as well as the selection of addresses capable of confirming them.
* @param _owners A list of owners.
* @param _required The amount required for a transaction to be approved.
*/
function Shareable(address[] _owners, uint _required) {
owners[1] = msg.sender;
ownerIndex[msg.sender] = 1;
@ -69,7 +72,10 @@ contract Shareable {
}
}
// Revokes a prior confirmation of the given operation
/**
* @dev Revokes a prior confirmation of the given operation.
* @param _operation A string identifying the operation.
*/
function revoke(bytes32 _operation) external {
uint index = ownerIndex[msg.sender];
// make sure they're an owner
@ -85,15 +91,30 @@ contract Shareable {
}
}
// Gets an owner by 0-indexed position (using numOwners as the count)
/**
* @dev Gets an owner by 0-indexed position (using numOwners as the count)
* @param ownerIndex Uint The index of the owner
* @return The address of the owner
*/
function getOwner(uint ownerIndex) external constant returns (address) {
return address(owners[ownerIndex + 1]);
}
/**
* @dev Checks if given address is an owner.
* @param _addr address The address which you want to check.
* @return True if the address is an owner and fase otherwise.
*/
function isOwner(address _addr) constant returns (bool) {
return ownerIndex[_addr] > 0;
}
/**
* @dev Function to check is specific owner has already confirme the operation.
* @param _operation The operation identifier.
* @param _owner The owner address.
* @return True if the owner has confirmed and false otherwise.
*/
function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
var pending = pendings[_operation];
uint index = ownerIndex[_owner];
@ -108,7 +129,11 @@ contract Shareable {
return !(pending.ownersDone & ownerIndexBit == 0);
}
// returns true when operation can be executed
/**
* @dev Confirm and operation and checks if it's already executable.
* @param _operation The operation identifier.
* @return Returns true when operation can be executed.
*/
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint index = ownerIndex[msg.sender];
@ -147,6 +172,10 @@ contract Shareable {
return false;
}
/**
* @dev Clear the pending list.
*/
function clearPending() internal {
uint length = pendingsIndex.length;
for (uint i = 0; i < length; ++i) {

View File

@ -1,13 +1,13 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../SafeMath.sol';
/*
* PullPayment
* Base contract supporting async send for pull payments.
* Inherit from this contract and use asyncSend instead of send.
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncSend instead of send.
*/
contract PullPayment {
using SafeMath for uint;
@ -15,13 +15,19 @@ contract PullPayment {
mapping(address => uint) public payments;
uint public totalPayments;
// store sent amount as credit to be pulled, called by payer
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
// withdraw accumulated balance, called by payee
/**
* @dev withdraw accumulated balance, called by payee.
*/
function withdrawPayments() {
address payee = msg.sender;
uint payment = payments[payee];

View File

@ -1,21 +1,21 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './ERC20Basic.sol';
import '../SafeMath.sol';
/*
* Basic token
* Basic version of StandardToken, with no allowances
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/*
* Fix for the ERC20 short address attack
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
@ -24,14 +24,24 @@ contract BasicToken is ERC20Basic {
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}

View File

@ -1,32 +1,40 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./StandardToken.sol";
/*
* CrowdsaleToken
/**
* @title CrowdsaleToken
*
* Simple ERC20 Token example, with crowdsale token creation
* IMPORTANT NOTE: do not use or deploy this contract as-is.
* It needs some changes to be production ready.
* @dev Simple ERC20 Token example, with crowdsale token creation
* @dev IMPORTANT NOTE: do not use or deploy this contract as-is. It needs some changes to be
* production ready.
*/
contract CrowdsaleToken is StandardToken {
string public constant name = "CrowdsaleToken";
string public constant symbol = "CRW";
uint public constant decimals = 18;
// replace with your fund collection multisig address
address public constant multisig = 0x0;
// replace with your fund collection multisig address
address public constant multisig = 0x0;
// 1 ether = 500 example tokens
// 1 ether = 500 example tokens
uint public constant PRICE = 500;
/**
* @dev Fallback function which receives ether and sends the appropriate number of tokens to the
* msg.sender.
*/
function () payable {
createTokens(msg.sender);
}
/**
* @dev Creates tokens and send to the specified address.
* @param recipient The address which will recieve the new tokens.
*/
function createTokens(address recipient) payable {
if (msg.value == 0) {
throw;
@ -41,8 +49,11 @@ contract CrowdsaleToken is StandardToken {
throw;
}
}
// replace this with any other price function
/**
* @dev replace this with any other price function
* @return The price per unit of token.
*/
function getPrice() constant returns (uint result) {
return PRICE;
}

View File

@ -1,12 +1,12 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './ERC20Basic.sol';
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);

View File

@ -1,10 +1,10 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
/*
* ERC20Basic
* Simpler version of ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;

View File

@ -1,48 +1,56 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./ERC20.sol";
/*
LimitedTransferToken defines the generic interface and the implementation
to limit token transferability for different events.
It is intended to be used as a base class for other token contracts.
Overwriting transferableTokens(address holder, uint64 time) is the way to provide
the specific logic for limiting token transferability for a holder over time.
LimitedTransferToken has been designed to allow for different limiting factors,
this can be achieved by recursively calling super.transferableTokens() until the
base class is hit. For example:
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
return min256(unlockedTokens, super.transferableTokens(holder, time));
}
A working example is VestedToken.sol:
https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol
*/
/**
* @title LimitedTransferToken
* @dev LimitedTransferToken defines the generic interface and the implementation to limit token
* transferability for different events. It is intended to be used as a base class for other token
* contracts.
* LimitedTransferToken has been designed to allow for different limiting factors,
* this can be achieved by recursively calling super.transferableTokens() until the base class is
* hit. For example:
* function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
* return min256(unlockedTokens, super.transferableTokens(holder, time));
* }
* A working example is VestedToken.sol:
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol
*/
contract LimitedTransferToken is ERC20 {
// Checks whether it can transfer or otherwise throws.
/**
* @dev Checks whether it can transfer or otherwise throws.
*/
modifier canTransfer(address _sender, uint _value) {
if (_value > transferableTokens(_sender, uint64(now))) throw;
_;
}
// Checks modifier and allows transfer if tokens are not locked.
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _to The address that will recieve the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transfer(address _to, uint _value) canTransfer(msg.sender, _value) {
return super.transfer(_to, _value);
super.transfer(_to, _value);
}
// Checks modifier and allows transfer if tokens are not locked.
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _from The address that will send the tokens.
* @param _to The address that will recieve the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) {
return super.transferFrom(_from, _to, _value);
super.transferFrom(_from, _to, _value);
}
// Default transferable tokens function returns all tokens for a holder (no limit).
/**
* @dev Default transferable tokens function returns all tokens for a holder (no limit).
* @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the
* specific logic for limiting token transferability for a holder over time.
*/
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
return balanceOf(holder);
}

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './StandardToken.sol';
@ -7,13 +7,10 @@ import '../ownership/Ownable.sol';
/**
* Mintable token
*
* Simple ERC20 Token example, with mintable token creation
* Issue:
* https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet:
* https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
@ -23,11 +20,18 @@ contract MintableToken is StandardToken, Ownable {
bool public mintingFinished = false;
uint public totalSupply = 0;
modifier canMint() {
if(mintingFinished) throw;
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
@ -35,6 +39,10 @@ contract MintableToken is StandardToken, Ownable {
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './StandardToken.sol';
import '../lifecycle/Pausable.sol';
@ -16,10 +16,10 @@ import '../lifecycle/Pausable.sol';
contract PausableToken is Pausable, StandardToken {
function transfer(address _to, uint _value) whenNotPaused {
return super.transfer(_to, _value);
super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused {
return super.transferFrom(_from, _to, _value);
super.transferFrom(_from, _to, _value);
}
}
}

View File

@ -1,15 +1,14 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./StandardToken.sol";
/*
* SimpleToken
*
* Very simple ERC20 Token example, where all tokens are pre-assigned
* to the creator. Note they can later distribute these tokens
* as they wish using `transfer` and other `StandardToken` functions.
/**
* @title SimpleToken
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `StandardToken` functions.
*/
contract SimpleToken is StandardToken {
@ -17,7 +16,10 @@ contract SimpleToken is StandardToken {
string public symbol = "SIM";
uint public decimals = 18;
uint public INITIAL_SUPPLY = 10000;
/**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function SimpleToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import './BasicToken.sol';
@ -6,17 +6,24 @@ import './ERC20.sol';
/**
* Standard ERC20 token
* @title Standard ERC20 token
*
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
* @dev Implemantation of the basic standart token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
function transferFrom(address _from, address _to, uint _value) {
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
@ -28,11 +35,29 @@ contract StandardToken is BasicToken, ERC20 {
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}

View File

@ -1,67 +1,197 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "./StandardToken.sol";
import "./LimitedTransferToken.sol";
/**
* @title Vested token
* @dev Tokens that can be vested for a group of addresses.
*/
contract VestedToken is StandardToken, LimitedTransferToken {
uint256 MAX_GRANTS_PER_ADDRESS = 20;
struct TokenGrant {
address granter;
uint256 value;
address granter; // 20 bytes
uint256 value; // 32 bytes
uint64 cliff;
uint64 vesting;
uint64 start;
}
uint64 start; // 3 * 8 = 24 bytes
bool revokable;
bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes?
} // total 78 bytes = 3 sstore per operation (32 per sstore)
mapping (address => TokenGrant[]) public grants;
event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId);
/**
* @dev Grant tokens to a specified address
* @param _to address The address which the tokens will be granted to.
* @param _value uint256 The amount of tokens to be granted.
* @param _start uint64 Time of the beginning of the grant.
* @param _cliff uint64 Time of the cliff period.
* @param _vesting uint64 The vesting period.
*/
function grantVestedTokens(
address _to,
uint256 _value,
uint64 _start,
uint64 _cliff,
uint64 _vesting) {
uint64 _vesting,
bool _revokable,
bool _burnsOnRevoke
) public {
if (_cliff < _start) {
throw;
}
if (_vesting < _start) {
throw;
}
if (_vesting < _cliff) {
// Check for date inconsistencies that may cause unexpected behavior
if (_cliff < _start || _vesting < _cliff) {
throw;
}
if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) throw; // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).
TokenGrant memory grant = TokenGrant(msg.sender, _value, _cliff, _vesting, _start);
grants[_to].push(grant);
uint count = grants[_to].push(
TokenGrant(
_revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
_value,
_cliff,
_vesting,
_start,
_revokable,
_burnsOnRevoke
)
);
transfer(_to, _value);
NewTokenGrant(msg.sender, _to, _value, count - 1);
}
function revokeTokenGrant(address _holder, uint _grantId) {
/**
* @dev Revoke the grant of tokens of a specifed address.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
*/
function revokeTokenGrant(address _holder, uint _grantId) public {
TokenGrant grant = grants[_holder][_grantId];
if (grant.granter != msg.sender) {
if (!grant.revokable) { // Check if grant was revokable
throw;
}
if (grant.granter != msg.sender) { // Only granter can revoke it
throw;
}
address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;
uint256 nonVested = nonVestedTokens(grant, uint64(now));
// remove grant from array
delete grants[_holder][_grantId];
grants[_holder][_grantId] = grants[_holder][grants[_holder].length - 1];
grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)];
grants[_holder].length -= 1;
balances[msg.sender] = balances[msg.sender].add(nonVested);
balances[receiver] = balances[receiver].add(nonVested);
balances[_holder] = balances[_holder].sub(nonVested);
Transfer(_holder, msg.sender, nonVested);
Transfer(_holder, receiver, nonVested);
}
/**
* @dev Calculate the total amount of transferable tokens of a holder at a given time
* @param holder address The address of the holder
* @param time uint64 The specific time.
* @return An uint representing a holder's total amount of transferable tokens.
*/
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
uint256 grantIndex = tokenGrantsCount(holder);
if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants
// Iterate through all the grants the holder has, and add all non-vested tokens
uint256 nonVested = 0;
for (uint256 i = 0; i < grantIndex; i++) {
nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time));
}
// Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested);
// Return the minimum of how many vested can transfer and other value
// in case there are other limiting transferability factors (default is balanceOf)
return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time));
}
/**
* @dev Check the amount of grants that an address has.
* @param _holder The holder of the grants.
* @return A uint representing the total amount of grants.
*/
function tokenGrantsCount(address _holder) constant returns (uint index) {
return grants[_holder].length;
}
function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting) {
/**
* @dev Calculate amount of vested tokens at a specifc time.
* @param tokens uint256 The amount of tokens grantted.
* @param time uint64 The time to be checked
* @param start uint64 A time representing the begining of the grant
* @param cliff uint64 The cliff period.
* @param vesting uint64 The vesting period.
* @return An uint representing the amount of vested tokensof a specif grant.
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Clift Vesting
*/
function calculateVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vesting) constant returns (uint256)
{
// Shortcuts for before cliff and after vesting cases.
if (time < cliff) return 0;
if (time >= vesting) return tokens;
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can use just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = tokens * (time - start) / (vesting - start)
uint256 vestedTokens = SafeMath.div(
SafeMath.mul(
tokens,
SafeMath.sub(time, start)
),
SafeMath.sub(vesting, start)
);
return vestedTokens;
}
/**
* @dev Get all information about a specifc grant.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
* @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
* revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
*/
function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
TokenGrant grant = grants[_holder][_grantId];
granter = grant.granter;
@ -69,10 +199,18 @@ contract VestedToken is StandardToken, LimitedTransferToken {
start = grant.start;
cliff = grant.cliff;
vesting = grant.vesting;
revokable = grant.revokable;
burnsOnRevoke = grant.burnsOnRevoke;
vested = vestedTokens(grant, uint64(now));
}
/**
* @dev Get the amount of vested tokens at a specific time.
* @param grant TokenGrant The grant to be checked.
* @param time The time to be checked
* @return An uint representing the amount of vested tokens of a specific grant at a specific time.
*/
function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return calculateVestedTokens(
grant.value,
@ -83,33 +221,22 @@ contract VestedToken is StandardToken, LimitedTransferToken {
);
}
function calculateVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vesting) constant returns (uint256 vestedTokens)
{
if (time < cliff) {
return 0;
}
if (time >= vesting) {
return tokens;
}
uint256 cliffTokens = tokens.mul(cliff.sub(start)).div(vesting.sub(start));
vestedTokens = cliffTokens;
uint256 vestingTokens = tokens.sub(cliffTokens);
vestedTokens = vestedTokens.add(vestingTokens.mul(time.sub(cliff)).div(vesting.sub(cliff)));
}
/**
* @dev Calculate the amount of non vested tokens at a specific time.
* @param grant TokenGrant The grant to be checked.
* @param time uint64 The time to be checked
* @return An uint representing the amount of non vested tokens of a specifc grant on the
* passed time frame.
*/
function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return grant.value.sub(vestedTokens(grant, time));
}
/**
* @dev Calculate the date when the holder can trasfer all its tokens
* @param holder address The address of the holder
* @return An uint representing the date of the last transferable tokens.
*/
function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {
date = uint64(now);
uint256 grantIndex = grants[holder].length;
@ -117,14 +244,4 @@ contract VestedToken is StandardToken, LimitedTransferToken {
date = SafeMath.max64(grants[holder][i].vesting, date);
}
}
function transferableTokens(address holder, uint64 time) constant public returns (uint256 nonVested) {
uint256 grantIndex = grants[holder].length;
for (uint256 i = 0; i < grantIndex; i++) {
uint256 current = nonVestedTokens(grants[holder][i], time);
nonVested = nonVested.add(current);
}
return SafeMath.min256(balances[holder].sub(nonVested), super.transferableTokens(holder, time));
}
}

View File

@ -8,4 +8,9 @@ Inherits from contract Ownable.
destroy( ) onlyOwner
"""""""""""""""""""
Destroys the contract and sends funds back to the owner.
Destroys the contract and sends funds back to the owner.
destroyAndSend(address _recipient) onlyOwner
"""""""""""""""""""
Destroys the contract and sends funds back to the _recepient.

View File

@ -1,6 +1,6 @@
{
"package_name": "zeppelin",
"version": "1.0.5",
"version": "1.0.7",
"description": "Secure Smart Contract library for Solidity",
"authors": [
"Manuel Araoz <manuelaraoz@gmail.com>"

View File

@ -1,12 +1,14 @@
{
"name": "zeppelin-solidity",
"version": "1.0.5",
"version": "1.0.7",
"description": "Secure Smart Contract library for Solidity",
"main": "truffle.js",
"scripts": {
"test": "scripts/test.sh",
"console": "truffle console",
"install": "scripts/install.sh"
"install": "scripts/install.sh",
"coverage": "scripts/coverage.sh",
"coveralls": "scripts/coveralls.sh"
},
"repository": {
"type": "git",
@ -34,7 +36,10 @@
"babel-preset-stage-2": "^6.18.0",
"babel-preset-stage-3": "^6.17.0",
"babel-register": "^6.23.0",
"coveralls": "^2.13.1",
"ethereumjs-testrpc": "^3.0.2",
"truffle": "https://github.com/ConsenSys/truffle.git#3.1.9"
"mocha-lcov-reporter": "^1.3.0",
"solidity-coverage": "^0.1.0",
"truffle": "3.2.2"
}
}

3
scripts/coverage.sh Executable file
View File

@ -0,0 +1,3 @@
#! /bin/bash
SOLIDITY_COVERAGE=true ./node_modules/.bin/solidity-coverage

4
scripts/coveralls.sh Executable file
View File

@ -0,0 +1,4 @@
#! /bin/bash
npm run coverage && cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js

View File

@ -49,7 +49,7 @@ contract('DelayedClaimable', function(accounts) {
} catch (error) {
err = error;
}
assert.isFalse(err.message.search('invalid JUMP') === -1);
assert.isFalse(err.message.search('invalid opcode') === -1);
let owner = await delayedClaimable.owner();
assert.isTrue(owner !== accounts[1]);
});
@ -62,7 +62,7 @@ contract('DelayedClaimable', function(accounts) {
} catch (error) {
err = error;
}
assert.isFalse(err.message.search('invalid JUMP') === -1);
assert.isFalse(err.message.search('invalid opcode') === -1);
});
});

View File

@ -11,8 +11,16 @@ contract('Destructible', function(accounts) {
let initBalance = web3.eth.getBalance(owner);
await destructible.destroy({from: owner});
let newBalance = web3.eth.getBalance(owner);
assert.isTrue(newBalance > initBalance);
});
it('should send balance to recepient after destruction', async function() {
let destructible = await Destructible.new({from: accounts[0], value: web3.toWei('10','ether')});
let owner = await destructible.owner();
let initBalance = web3.eth.getBalance(accounts[1]);
await destructible.destroyAndSend(accounts[1], {from: owner} );
let newBalance = web3.eth.getBalance(accounts[1]);
assert.isTrue(newBalance.greaterThan(initBalance));
});
});

View File

@ -35,7 +35,8 @@ contract('HasNoEther', function(accounts) {
assert.equal(startBalance, 0);
// Force ether into it
await ForceEther.new(hasNoEther.address, {value: amount});
let forceEther = await ForceEther.new({value: amount});
await forceEther.destroyAndSend(hasNoEther.address);
const forcedBalance = await web3.eth.getBalance(hasNoEther.address);
assert.equal(forcedBalance, amount);
@ -53,7 +54,8 @@ contract('HasNoEther', function(accounts) {
let hasNoEther = await HasNoEtherTest.new({from: accounts[0]});
// Force ether into it
await ForceEther.new(hasNoEther.address, {value: amount});
let forceEther = await ForceEther.new({value: amount});
await forceEther.destroyAndSend(hasNoEther.address);
const forcedBalance = await web3.eth.getBalance(hasNoEther.address);
assert.equal(forcedBalance, amount);

View File

@ -23,12 +23,12 @@ contract('VestedToken', function(accounts) {
assert.equal(await token.transferableTokens(receiver, now), tokenAmount);
})
describe('getting a token grant', async () => {
describe('getting a revokable/non-burnable token grant', async () => {
const cliff = 10000
const vesting = 20000 // seconds
beforeEach(async () => {
await token.grantVestedTokens(receiver, tokenAmount, now, now + cliff, now + vesting, { from: granter })
await token.grantVestedTokens(receiver, tokenAmount, now, now + cliff, now + vesting, true, false, { from: granter })
})
it('tokens are received', async () => {
@ -103,7 +103,8 @@ contract('VestedToken', function(accounts) {
let newNow = web3.eth.getBlock(web3.eth.blockNumber).timestamp
await token.grantVestedTokens(receiver, tokenAmount, newNow, newNow + cliff, newNow + vesting, { from: granter })
await token.grantVestedTokens(receiver, tokenAmount, newNow, newNow + cliff, newNow + vesting, false, false, { from: granter })
await token.transfer(accounts[7], 13, { from: receiver })
assert.equal(await token.balanceOf(accounts[7]), tokenAmount / 2);
@ -114,4 +115,61 @@ contract('VestedToken', function(accounts) {
assert.equal(await token.balanceOf(accounts[7]), tokenAmount * 2)
})
})
describe('getting a non-revokable token grant', async () => {
const cliff = 10000
const vesting = 20000 // seconds
beforeEach(async () => {
await token.grantVestedTokens(receiver, tokenAmount, now, now + cliff, now + vesting, false, false, { from: granter })
})
it('tokens are received', async () => {
assert.equal(await token.balanceOf(receiver), tokenAmount);
})
it('throws when granter attempts to revoke', async () => {
try {
await token.revokeTokenGrant(receiver, 0, { from: granter });
} catch(error) {
return assertJump(error);
}
assert.fail('should have thrown before');
})
})
describe('getting a revokable/burnable token grant', async () => {
const cliff = 100000
const vesting = 200000 // seconds
const burnAddress = '0x000000000000000000000000000000000000dead'
beforeEach(async () => {
await token.grantVestedTokens(receiver, tokenAmount, now, now + cliff, now + vesting, true, true, { from: granter })
})
it('tokens are received', async () => {
assert.equal(await token.balanceOf(receiver), tokenAmount);
})
it('can be revoked by granter and tokens are burned', async () => {
await token.revokeTokenGrant(receiver, 0, { from: granter });
assert.equal(await token.balanceOf(receiver), 0);
assert.equal(await token.balanceOf(burnAddress), tokenAmount);
})
it('cannot be revoked by non granter', async () => {
try {
await token.revokeTokenGrant(receiver, 0, { from: accounts[3] });
} catch(error) {
return assertJump(error);
}
assert.fail('should have thrown before');
})
it('can be revoked by granter and non vested tokens are returned', async () => {
await timer(cliff);
await token.revokeTokenGrant(receiver, 0, { from: granter });
assert.equal(await token.balanceOf(burnAddress), tokenAmount * cliff / vesting);
})
})
});

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/token/BasicToken.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "../../contracts/DayLimit.sol";
contract DayLimitMock is DayLimit {

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/token/BasicToken.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
// @title Force Ether into a contract.
// @notice even
@ -6,8 +6,10 @@ pragma solidity ^0.4.8;
// @notice To use, construct the contract with the target as argument.
// @author Remco Bloemen <remco@neufund.org>
contract ForceEther {
function ForceEther(address target) payable {
// Selfdestruct transfers all Ether to the arget address
selfdestruct(target);
function ForceEther() payable { }
function destroyAndSend(address _recipient) {
selfdestruct(_recipient);
}
}

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "../../contracts/ownership/HasNoEther.sol";

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import {Bounty, Target} from "../../contracts/Bounty.sol";

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/LimitBalance.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "../../contracts/MultisigWallet.sol";
contract MultisigWalletMock is MultisigWallet {

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/lifecycle/Pausable.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/token/PausableToken.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/payment/PullPayment.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
contract ReentrancyAttack {

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/ReentrancyGuard.sol';
import './ReentrancyAttack.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/SafeMath.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import {Bounty, Target} from "../../contracts/Bounty.sol";

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import "../../contracts/ownership/Shareable.sol";
contract ShareableMock is Shareable {

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/token/StandardToken.sol';

View File

@ -1,4 +1,4 @@
pragma solidity ^0.4.8;
pragma solidity ^0.4.11;
import '../../contracts/token/VestedToken.sol';

View File

@ -1,3 +1,3 @@
module.exports = function(error) {
assert.isAbove(error.message.search('invalid JUMP'), -1, 'Invalid JUMP error must be returned');
assert.isAbove(error.message.search('invalid opcode'), -1, 'Invalid opcode error must be returned');
}

View File

@ -4,14 +4,14 @@ export default async promise => {
} catch (error) {
// TODO: Check jump destination to destinguish between a throw
// and an actual invalid jump.
const invalidJump = error.message.search('invalid JUMP') >= 0;
const invalidOpcode = error.message.search('invalid opcode') >= 0;
// TODO: When we contract A calls contract B, and B throws, instead
// of an 'invalid jump', we get an 'out of gas' error. How do
// we distinguish this from an actual out of gas event? (The
// testrpc log actually show an 'invalid jump' event.)
const outOfGas = error.message.search('out of gas') >= 0;
assert(
invalidJump || outOfGas,
invalidOpcode || outOfGas,
"Expected throw, got '" + error + "' instead",
);
return;

View File

@ -1,10 +1,13 @@
require('babel-register');
require('babel-polyfill');
var provider;
var HDWalletProvider = require('truffle-hdwallet-provider');
var mnemonic = '[REDACTED]';
var provider = new HDWalletProvider(mnemonic, 'https://ropsten.infura.io/');
if (!process.env.SOLIDITY_COVERAGE){
provider = new HDWalletProvider(mnemonic, 'https://ropsten.infura.io/')
}
module.exports = {
@ -17,6 +20,13 @@ module.exports = {
ropsten: {
provider: provider,
network_id: 3 // official id of the ropsten network
},
coverage: {
host: "localhost",
network_id: "*",
port: 8555,
gas: 0xfffffffffff,
gasPrice: 0x01
}
}
};