Merge pull request #581 from Shrugs/feat/minor-additions

Minor standards and cleanup additions.
pull/597/head
Francisco Giordano 7 years ago committed by GitHub
commit dd1fd0002a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      .env.example
  2. 51
      .eslintrc
  3. 36
      .gitignore
  4. 3
      .travis.yml
  5. 2
      migrations/1_initial_migration.js
  6. 4
      migrations/2_deploy_contracts.js
  7. 955
      package-lock.json
  8. 12
      package.json
  9. 5
      test/.eslintrc
  10. 16
      test/BasicToken.test.js
  11. 10
      test/Bounty.test.js
  12. 39
      test/BurnableToken.js
  13. 38
      test/BurnableToken.test.js
  14. 6
      test/CanReclaimToken.test.js
  15. 96
      test/CappedCrowdsale.js
  16. 88
      test/CappedCrowdsale.test.js
  17. 15
      test/CappedToken.test.js
  18. 2
      test/Claimable.test.js
  19. 6
      test/Contactable.test.js
  20. 152
      test/Crowdsale.js
  21. 143
      test/Crowdsale.test.js
  22. 11
      test/DayLimit.test.js
  23. 2
      test/DelayedClaimble.test.js
  24. 3
      test/Destructible.test.js
  25. 8
      test/DetailedERC20.test.js
  26. 17
      test/ECRecovery.test.js
  27. 63
      test/FinalizableCrowdsale.js
  28. 60
      test/FinalizableCrowdsale.test.js
  29. 4
      test/HasNoContracts.test.js
  30. 9
      test/HasNoEther.test.js
  31. 6
      test/HasNoTokens.test.js
  32. 61
      test/LimitBalance.js
  33. 59
      test/LimitBalance.test.js
  34. 35
      test/MerkleProof.test.js
  35. 6
      test/MintableToken.test.js
  36. 3
      test/Ownable.test.js
  37. 6
      test/Pausable.test.js
  38. 4
      test/PausableToken.test.js
  39. 27
      test/PullPayment.test.js
  40. 2
      test/ReentrancyGuard.test.js
  41. 61
      test/RefundVault.js
  42. 59
      test/RefundVault.test.js
  43. 83
      test/RefundableCrowdsale.js
  44. 80
      test/RefundableCrowdsale.test.js
  45. 3
      test/SafeERC20.test.js
  46. 28
      test/SafeMath.test.js
  47. 40
      test/SampleCrowdsale.test.js
  48. 78
      test/SplitPayment.js
  49. 78
      test/SplitPayment.test.js
  50. 15
      test/StandardToken.test.js
  51. 3
      test/TokenDestructible.test.js
  52. 57
      test/TokenTimelock.js
  53. 54
      test/TokenTimelock.test.js
  54. 14
      test/TokenVesting.test.js
  55. 2
      test/helpers/EVMRevert.js
  56. 2
      test/helpers/EVMThrow.js
  57. 10
      test/helpers/advanceToBlock.js
  58. 2
      test/helpers/assertJump.js
  59. 2
      test/helpers/assertRevert.js
  60. 2
      test/helpers/ether.js
  61. 2
      test/helpers/expectThrow.js
  62. 2
      test/helpers/hashMessage.js
  63. 26
      test/helpers/increaseTime.js
  64. 12
      test/helpers/merkleTree.js
  65. 4
      test/helpers/toPromise.js
  66. 3
      test/helpers/transactionMined.js
  67. 0
      test/mocks/BasicTokenMock.sol
  68. 0
      test/mocks/BurnableTokenMock.sol
  69. 0
      test/mocks/CappedCrowdsaleImpl.sol
  70. 0
      test/mocks/DayLimitMock.sol
  71. 0
      test/mocks/DetailedERC20Mock.sol
  72. 0
      test/mocks/ERC23TokenMock.sol
  73. 0
      test/mocks/FinalizableCrowdsaleImpl.sol
  74. 0
      test/mocks/ForceEther.sol
  75. 0
      test/mocks/HasNoEtherTest.sol
  76. 0
      test/mocks/InsecureTargetBounty.sol
  77. 0
      test/mocks/LimitBalanceMock.sol
  78. 0
      test/mocks/PausableMock.sol
  79. 0
      test/mocks/PausableTokenMock.sol
  80. 0
      test/mocks/PullPaymentMock.sol
  81. 0
      test/mocks/ReentrancyAttack.sol
  82. 0
      test/mocks/ReentrancyMock.sol
  83. 0
      test/mocks/RefundableCrowdsaleImpl.sol
  84. 0
      test/mocks/SafeERC20Helper.sol
  85. 0
      test/mocks/SafeMathMock.sol
  86. 0
      test/mocks/SecureTargetBounty.sol
  87. 0
      test/mocks/StandardTokenMock.sol
  88. 44
      truffle-config.js

@ -0,0 +1,5 @@
# configure your infura api key (not technically required)
INFURA_API_KEY=
# change the mnemonic that your hd wallet is seeded with
MNEMONIC=

@ -0,0 +1,51 @@
{
"extends" : [
"standard",
"plugin:promise/recommended"
],
"plugins": [
"promise"
],
"env": {
"browser" : true,
"node" : true,
"mocha" : true,
"jest" : true
},
"globals" : {
"artifacts": false,
"contract": false,
"assert": false,
"web3": false
},
"rules": {
// Strict mode
"strict": [2, "global"],
// Code style
"indent": [2, 2],
"quotes": [2, "single"],
"semi": ["error", "always"],
"space-before-function-paren": ["error", "always"],
"no-use-before-define": 0,
"eqeqeq": [2, "smart"],
"dot-notation": [2, {"allowKeywords": true, "allowPattern": ""}],
"no-redeclare": [2, {"builtinGlobals": true}],
"no-trailing-spaces": [2, { "skipBlankLines": true }],
"eol-last": 1,
"comma-spacing": [2, {"before": false, "after": true}],
"camelcase": [2, {"properties": "always"}],
"no-mixed-spaces-and-tabs": [2, "smart-tabs"],
"comma-dangle": [1, "always-multiline"],
"no-dupe-args": 2,
"no-dupe-keys": 2,
"no-debugger": 0,
"no-undef": 2,
"object-curly-spacing": [2, "always"],
"max-len": [2, 120, 2],
"generator-star-spacing": ["error", "before"],
"promise/avoid-new": 0,
"promise/always-return": 0
}
}

36
.gitignore vendored

@ -1,9 +1,35 @@
*.swp *.swp
*.swo *.swo
node_modules/
build/ # Logs
.DS_Store/ logs
/coverage *.log
coverage.json
# Runtime data
pids
*.pid
*.seed
allFiredEvents allFiredEvents
scTopics scTopics
# Coverage directory used by tools like istanbul
coverage
coverage.json
# node-waf configuration
.lock-wscript
# Dependency directory
node_modules
# Debug log from npm
npm-debug.log
# local env variables
.env
# truffle build directory
build/
# lol macs
.DS_Store/

@ -10,7 +10,8 @@ cache:
before_script: before_script:
- truffle version - truffle version
script: script:
- npm test - npm run lint
- npm run test
notifications: notifications:
slack: slack:
rooms: rooms:

@ -1,4 +1,4 @@
var Migrations = artifacts.require("./Migrations.sol"); var Migrations = artifacts.require('./Migrations.sol');
module.exports = function (deployer) { module.exports = function (deployer) {
deployer.deploy(Migrations); deployer.deploy(Migrations);

@ -1,5 +1,9 @@
// var Ownable = artifacts.require("ownership/Ownable.sol"); // var Ownable = artifacts.require("ownership/Ownable.sol");
// NOTE: Use this file to easily deploy the contracts you're writing.
// (but make sure to reset this file before committing
// with `git checkout HEAD -- migrations/2_deploy_contracts.js`)
module.exports = function (deployer) { module.exports = function (deployer) {
// deployer.deploy(Ownable); // deployer.deploy(Ownable);
}; };

955
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -4,6 +4,7 @@
"description": "Secure Smart Contract library for Solidity", "description": "Secure Smart Contract library for Solidity",
"scripts": { "scripts": {
"test": "scripts/test.sh", "test": "scripts/test.sh",
"lint": "eslint .",
"console": "truffle console", "console": "truffle console",
"coverage": "scripts/coverage.sh" "coverage": "scripts/coverage.sh"
}, },
@ -35,11 +36,20 @@
"chai-as-promised": "^7.0.0", "chai-as-promised": "^7.0.0",
"chai-bignumber": "^2.0.0", "chai-bignumber": "^2.0.0",
"coveralls": "^2.13.1", "coveralls": "^2.13.1",
"ethereumjs-util": "^5.1.2", "eslint": "^4.11.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-node": "^5.2.1",
"eslint-plugin-promise": "^3.6.0",
"eslint-plugin-standard": "^3.0.1",
"ethereumjs-testrpc": "^6.0.1", "ethereumjs-testrpc": "^6.0.1",
"ethereumjs-util": "^5.1.2",
"mocha-lcov-reporter": "^1.3.0", "mocha-lcov-reporter": "^1.3.0",
"solidity-coverage": "^0.2.2", "solidity-coverage": "^0.2.2",
"truffle": "^4.0.0", "truffle": "^4.0.0",
"truffle-hdwallet-provider": "0.0.3" "truffle-hdwallet-provider": "0.0.3"
},
"dependencies": {
"dotenv": "^4.0.0"
} }
} }

@ -0,0 +1,5 @@
{
"rules": {
"no-unused-expressions": 0
}
}

@ -1,19 +1,18 @@
const assertRevert = require('./helpers/assertRevert'); const assertRevert = require('./helpers/assertRevert');
var BasicTokenMock = artifacts.require("./helpers/BasicTokenMock.sol"); var BasicTokenMock = artifacts.require('./mocks/BasicTokenMock.sol');
contract('BasicToken', function (accounts) { contract('BasicToken', function (accounts) {
it('should return the correct totalSupply after construction', async function () {
it("should return the correct totalSupply after construction", async function() {
let token = await BasicTokenMock.new(accounts[0], 100); let token = await BasicTokenMock.new(accounts[0], 100);
let totalSupply = await token.totalSupply(); let totalSupply = await token.totalSupply();
assert.equal(totalSupply, 100); assert.equal(totalSupply, 100);
}) });
it("should return correct balances after transfer", async function(){ it('should return correct balances after transfer', async function () {
let token = await BasicTokenMock.new(accounts[0], 100); let token = await BasicTokenMock.new(accounts[0], 100);
let transfer = await token.transfer(accounts[1], 100); await token.transfer(accounts[1], 100);
let firstAccountBalance = await token.balanceOf(accounts[0]); let firstAccountBalance = await token.balanceOf(accounts[0]);
assert.equal(firstAccountBalance, 0); assert.equal(firstAccountBalance, 0);
@ -25,7 +24,7 @@ contract('BasicToken', function(accounts) {
it('should throw an error when trying to transfer more than balance', async function () { it('should throw an error when trying to transfer more than balance', async function () {
let token = await BasicTokenMock.new(accounts[0], 100); let token = await BasicTokenMock.new(accounts[0], 100);
try { try {
let transfer = await token.transfer(accounts[1], 101); await token.transfer(accounts[1], 101);
assert.fail('should have thrown before'); assert.fail('should have thrown before');
} catch (error) { } catch (error) {
assertRevert(error); assertRevert(error);
@ -35,11 +34,10 @@ contract('BasicToken', function(accounts) {
it('should throw an error when trying to transfer to 0x0', async function () { it('should throw an error when trying to transfer to 0x0', async function () {
let token = await BasicTokenMock.new(accounts[0], 100); let token = await BasicTokenMock.new(accounts[0], 100);
try { try {
let transfer = await token.transfer(0x0, 100); await token.transfer(0x0, 100);
assert.fail('should have thrown before'); assert.fail('should have thrown before');
} catch (error) { } catch (error) {
assertRevert(error); assertRevert(error);
} }
}); });
}); });

@ -1,14 +1,13 @@
'use strict';
let sendReward = function (sender, receiver, value) { let sendReward = function (sender, receiver, value) {
web3.eth.sendTransaction({ web3.eth.sendTransaction({
from: sender, from: sender,
to: receiver, to: receiver,
value: value value: value,
}); });
}; };
var SecureTargetBounty = artifacts.require('helpers/SecureTargetBounty.sol'); var SecureTargetBounty = artifacts.require('mocks/SecureTargetBounty.sol');
var InsecureTargetBounty = artifacts.require('helpers/InsecureTargetBounty.sol'); var InsecureTargetBounty = artifacts.require('mocks/InsecureTargetBounty.sol');
function awaitEvent (event, handler) { function awaitEvent (event, handler) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -21,7 +20,6 @@ function awaitEvent(event, handler) {
} }
contract('Bounty', function (accounts) { contract('Bounty', function (accounts) {
it('sets reward', async function () { it('sets reward', async function () {
let owner = accounts[0]; let owner = accounts[0];
let reward = web3.toWei(1, 'ether'); let reward = web3.toWei(1, 'ether');
@ -44,7 +42,6 @@ contract('Bounty', function(accounts) {
}); });
describe('Against secure contract', function () { describe('Against secure contract', function () {
it('cannot claim reward', async function () { it('cannot claim reward', async function () {
let owner = accounts[0]; let owner = accounts[0];
let researcher = accounts[1]; let researcher = accounts[1];
@ -68,7 +65,6 @@ contract('Bounty', function(accounts) {
} catch (error) { } catch (error) {
let reClaimedBounty = await bounty.claimed.call(); let reClaimedBounty = await bounty.claimed.call();
assert.isFalse(reClaimedBounty); assert.isFalse(reClaimedBounty);
} }
try { try {
await bounty.withdrawPayments({ from: researcher }); await bounty.withdrawPayments({ from: researcher });

@ -1,39 +0,0 @@
'use strict'
const EVMRevert = require('./helpers/EVMRevert.js')
const BurnableTokenMock = artifacts.require("./helpers/BurnableTokenMock.sol")
const BigNumber = web3.BigNumber
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
const expect = require('chai').expect
contract('BurnableToken', function (accounts) {
let token
let expectedTokenSupply = new BigNumber(999)
beforeEach(async function () {
token = await BurnableTokenMock.new(accounts[0], 1000)
})
it('owner should be able to burn tokens', async function () {
const { logs } = await token.burn(1, { from: accounts[0] })
const balance = await token.balanceOf(accounts[0])
balance.should.be.bignumber.equal(expectedTokenSupply)
const totalSupply = await token.totalSupply()
totalSupply.should.be.bignumber.equal(expectedTokenSupply)
const event = logs.find(e => e.event === 'Burn')
expect(event).to.exist
})
it('cannot burn more tokens than your balance', async function () {
await token.burn(2000, { from: accounts[0] })
.should.be.rejectedWith(EVMRevert)
})
})

@ -0,0 +1,38 @@
const EVMRevert = require('./helpers/EVMRevert.js');
const BurnableTokenMock = artifacts.require('./mocks/BurnableTokenMock.sol');
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const expect = require('chai').expect;
contract('BurnableToken', function (accounts) {
let token;
let expectedTokenSupply = new BigNumber(999);
beforeEach(async function () {
token = await BurnableTokenMock.new(accounts[0], 1000);
});
it('owner should be able to burn tokens', async function () {
const { logs } = await token.burn(1, { from: accounts[0] });
const balance = await token.balanceOf(accounts[0]);
balance.should.be.bignumber.equal(expectedTokenSupply);
const totalSupply = await token.totalSupply();
totalSupply.should.be.bignumber.equal(expectedTokenSupply);
const event = logs.find(e => e.event === 'Burn');
expect(event).to.exist;
});
it('cannot burn more tokens than your balance', async function () {
await token.burn(2000, { from: accounts[0] })
.should.be.rejectedWith(EVMRevert);
});
});

@ -1,8 +1,8 @@
'use strict';
import expectThrow from './helpers/expectThrow'; import expectThrow from './helpers/expectThrow';
import toPromise from './helpers/toPromise';
const CanReclaimToken = artifacts.require('../contracts/ownership/CanReclaimToken.sol'); const CanReclaimToken = artifacts.require('../contracts/ownership/CanReclaimToken.sol');
const BasicTokenMock = artifacts.require("./helpers/BasicTokenMock.sol"); const BasicTokenMock = artifacts.require('./mocks/BasicTokenMock.sol');
contract('CanReclaimToken', function (accounts) { contract('CanReclaimToken', function (accounts) {
let token = null; let token = null;

@ -1,96 +0,0 @@
import ether from './helpers/ether'
import {advanceBlock} from './helpers/advanceToBlock'
import {increaseTimeTo, duration} from './helpers/increaseTime'
import latestTime from './helpers/latestTime'
import EVMRevert from './helpers/EVMRevert'
const BigNumber = web3.BigNumber
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
const CappedCrowdsale = artifacts.require('./helpers/CappedCrowdsaleImpl.sol')
const MintableToken = artifacts.require('MintableToken')
contract('CappedCrowdsale', function ([_, wallet]) {
const rate = new BigNumber(1000)
const cap = ether(300)
const lessThanCap = ether(60)
before(async function() {
//Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock()
})
beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1);
this.endTime = this.startTime + duration.weeks(1);
this.crowdsale = await CappedCrowdsale.new(this.startTime, this.endTime, rate, wallet, cap)
this.token = MintableToken.at(await this.crowdsale.token())
})
describe('creating a valid crowdsale', function () {
it('should fail with zero cap', async function () {
await CappedCrowdsale.new(this.startTime, this.endTime, rate, wallet, 0).should.be.rejectedWith(EVMRevert);
})
});
describe('accepting payments', function () {
beforeEach(async function () {
await increaseTimeTo(this.startTime)
})
it('should accept payments within cap', async function () {
await this.crowdsale.send(cap.minus(lessThanCap)).should.be.fulfilled
await this.crowdsale.send(lessThanCap).should.be.fulfilled
})
it('should reject payments outside cap', async function () {
await this.crowdsale.send(cap)
await this.crowdsale.send(1).should.be.rejectedWith(EVMRevert)
})
it('should reject payments that exceed cap', async function () {
await this.crowdsale.send(cap.plus(1)).should.be.rejectedWith(EVMRevert)
})
})
describe('ending', function () {
beforeEach(async function () {
await increaseTimeTo(this.startTime)
})
it('should not be ended if under cap', async function () {
let hasEnded = await this.crowdsale.hasEnded()
hasEnded.should.equal(false)
await this.crowdsale.send(lessThanCap)
hasEnded = await this.crowdsale.hasEnded()
hasEnded.should.equal(false)
})
it('should not be ended if just under cap', async function () {
await this.crowdsale.send(cap.minus(1))
let hasEnded = await this.crowdsale.hasEnded()
hasEnded.should.equal(false)
})
it('should be ended if cap reached', async function () {
await this.crowdsale.send(cap)
let hasEnded = await this.crowdsale.hasEnded()
hasEnded.should.equal(true)
})
})
})

@ -0,0 +1,88 @@
import ether from './helpers/ether';
import { advanceBlock } from './helpers/advanceToBlock';
import { increaseTimeTo, duration } from './helpers/increaseTime';
import latestTime from './helpers/latestTime';
import EVMRevert from './helpers/EVMRevert';
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const CappedCrowdsale = artifacts.require('./mocks/CappedCrowdsaleImpl.sol');
const MintableToken = artifacts.require('MintableToken');
contract('CappedCrowdsale', function ([_, wallet]) {
const rate = new BigNumber(1000);
const cap = ether(300);
const lessThanCap = ether(60);
before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock();
});
beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1);
this.endTime = this.startTime + duration.weeks(1);
this.crowdsale = await CappedCrowdsale.new(this.startTime, this.endTime, rate, wallet, cap);
this.token = MintableToken.at(await this.crowdsale.token());
});
describe('creating a valid crowdsale', function () {
it('should fail with zero cap', async function () {
await CappedCrowdsale.new(this.startTime, this.endTime, rate, wallet, 0).should.be.rejectedWith(EVMRevert);
});
});
describe('accepting payments', function () {
beforeEach(async function () {
await increaseTimeTo(this.startTime);
});
it('should accept payments within cap', async function () {
await this.crowdsale.send(cap.minus(lessThanCap)).should.be.fulfilled;
await this.crowdsale.send(lessThanCap).should.be.fulfilled;
});
it('should reject payments outside cap', async function () {
await this.crowdsale.send(cap);
await this.crowdsale.send(1).should.be.rejectedWith(EVMRevert);
});
it('should reject payments that exceed cap', async function () {
await this.crowdsale.send(cap.plus(1)).should.be.rejectedWith(EVMRevert);
});
});
describe('ending', function () {
beforeEach(async function () {
await increaseTimeTo(this.startTime);
});
it('should not be ended if under cap', async function () {
let hasEnded = await this.crowdsale.hasEnded();
hasEnded.should.equal(false);
await this.crowdsale.send(lessThanCap);
hasEnded = await this.crowdsale.hasEnded();
hasEnded.should.equal(false);
});
it('should not be ended if just under cap', async function () {
await this.crowdsale.send(cap.minus(1));
let hasEnded = await this.crowdsale.hasEnded();
hasEnded.should.equal(false);
});
it('should be ended if cap reached', async function () {
await this.crowdsale.send(cap);
let hasEnded = await this.crowdsale.hasEnded();
hasEnded.should.equal(true);
});
});
});

@ -1,10 +1,8 @@
'use strict';
import expectThrow from './helpers/expectThrow'; import expectThrow from './helpers/expectThrow';
import ether from './helpers/ether'; import ether from './helpers/ether';
var CappedToken = artifacts.require('../contracts/Tokens/CappedToken.sol');
const BigNumber = web3.BigNumber var CappedToken = artifacts.require('../contracts/Tokens/CappedToken.sol');
contract('Capped', function (accounts) { contract('Capped', function (accounts) {
const cap = ether(1000); const cap = ether(1000);
@ -13,27 +11,26 @@ contract('Capped', function(accounts) {
beforeEach(async function () { beforeEach(async function () {
token = await CappedToken.new(cap); token = await CappedToken.new(cap);
}) });
it('should start with the correct cap', async function () { it('should start with the correct cap', async function () {
let _cap = await token.cap(); let _cap = await token.cap();
assert(cap.eq(_cap)); assert(cap.eq(_cap));
}) });
it('should mint when amount is less than cap', async function () { it('should mint when amount is less than cap', async function () {
const result = await token.mint(accounts[0], 100); const result = await token.mint(accounts[0], 100);
assert.equal(result.logs[0].event, 'Mint'); assert.equal(result.logs[0].event, 'Mint');
}) });
it('should fail to mint if the ammount exceeds the cap', async function () { it('should fail to mint if the ammount exceeds the cap', async function () {
await token.mint(accounts[0], cap.sub(1)); await token.mint(accounts[0], cap.sub(1));
await expectThrow(token.mint(accounts[0], 100)); await expectThrow(token.mint(accounts[0], 100));
}) });
it('should fail to mint after cap is reached', async function () { it('should fail to mint after cap is reached', async function () {
await token.mint(accounts[0], cap); await token.mint(accounts[0], cap);
await expectThrow(token.mint(accounts[0], 1)); await expectThrow(token.mint(accounts[0], 1));
}) });
}); });

@ -1,4 +1,4 @@
'use strict';
const assertRevert = require('./helpers/assertRevert'); const assertRevert = require('./helpers/assertRevert');
var Claimable = artifacts.require('../contracts/ownership/Claimable.sol'); var Claimable = artifacts.require('../contracts/ownership/Claimable.sol');

@ -1,5 +1,3 @@
'use strict';
const assertRevert = require('./helpers/assertRevert');
var Contactable = artifacts.require('../contracts/ownership/Contactable.sol'); var Contactable = artifacts.require('../contracts/ownership/Contactable.sol');
@ -12,11 +10,11 @@ contract('Contactable', function(accounts) {
it('should have an empty contact info', async function () { it('should have an empty contact info', async function () {
let info = await contactable.contactInformation(); let info = await contactable.contactInformation();
assert.isTrue(info == ""); assert.isTrue(info === '');
}); });
describe('after setting the contact information', function () { describe('after setting the contact information', function () {
let contactInfo = "contact information" let contactInfo = 'contact information';
beforeEach(async function () { beforeEach(async function () {
await contactable.setContactInformation(contactInfo); await contactable.setContactInformation(contactInfo);

@ -1,152 +0,0 @@
import ether from './helpers/ether'
import {advanceBlock} from './helpers/advanceToBlock'
import {increaseTimeTo, duration} from './helpers/increaseTime'
import latestTime from './helpers/latestTime'
import EVMRevert from './helpers/EVMRevert'
const BigNumber = web3.BigNumber
const should = require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
const Crowdsale = artifacts.require('Crowdsale')
const MintableToken = artifacts.require('MintableToken')
contract('Crowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BigNumber(1000)
const value = ether(42)
const expectedTokenAmount = rate.mul(value)
before(async function() {
//Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock()
})
beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1);
this.endTime = this.startTime + duration.weeks(1);
this.afterEndTime = this.endTime + duration.seconds(1)
this.crowdsale = await Crowdsale.new(this.startTime, this.endTime, rate, wallet)
this.token = MintableToken.at(await this.crowdsale.token())
})
it('should be token owner', async function () {
const owner = await this.token.owner()
owner.should.equal(this.crowdsale.address)
})
it('should be ended only after end', async function () {
let ended = await this.crowdsale.hasEnded()
ended.should.equal(false)
await increaseTimeTo(this.afterEndTime)
ended = await this.crowdsale.hasEnded()
ended.should.equal(true)
})
describe('accepting payments', function () {
it('should reject payments before start', async function () {
await this.crowdsale.send(value).should.be.rejectedWith(EVMRevert)
await this.crowdsale.buyTokens(investor, {from: purchaser, value: value}).should.be.rejectedWith(EVMRevert)
})
it('should accept payments after start', async function () {
await increaseTimeTo(this.startTime)
await this.crowdsale.send(value).should.be.fulfilled
await this.crowdsale.buyTokens(investor, {value: value, from: purchaser}).should.be.fulfilled
})
it('should reject payments after end', async function () {
await increaseTimeTo(this.afterEndTime)
await this.crowdsale.send(value).should.be.rejectedWith(EVMRevert)
await this.crowdsale.buyTokens(investor, {value: value, from: purchaser}).should.be.rejectedWith(EVMRevert)
})
})
describe('high-level purchase', function () {
beforeEach(async function() {
await increaseTimeTo(this.startTime)
})
it('should log purchase', async function () {
const {logs} = await this.crowdsale.sendTransaction({value: value, from: investor})
const event = logs.find(e => e.event === 'TokenPurchase')
should.exist(event)
event.args.purchaser.should.equal(investor)
event.args.beneficiary.should.equal(investor)
event.args.value.should.be.bignumber.equal(value)
event.args.amount.should.be.bignumber.equal(expectedTokenAmount)
})
it('should increase totalSupply', async function () {
await this.crowdsale.send(value)
const totalSupply = await this.token.totalSupply()
totalSupply.should.be.bignumber.equal(expectedTokenAmount)
})
it('should assign tokens to sender', async function () {
await this.crowdsale.sendTransaction({value: value, from: investor})
let balance = await this.token.balanceOf(investor);
balance.should.be.bignumber.equal(expectedTokenAmount)
})
it('should forward funds to wallet', async function () {
const pre = web3.eth.getBalance(wallet)
await this.crowdsale.sendTransaction({value, from: investor})
const post = web3.eth.getBalance(wallet)
post.minus(pre).should.be.bignumber.equal(value)
})
})
describe('low-level purchase', function () {
beforeEach(async function() {
await increaseTimeTo(this.startTime)
})
it('should log purchase', async function () {
const {logs} = await this.crowdsale.buyTokens(investor, {value: value, from: purchaser})
const event = logs.find(e => e.event === 'TokenPurchase')
should.exist(event)
event.args.purchaser.should.equal(purchaser)
event.args.beneficiary.should.equal(investor)
event.args.value.should.be.bignumber.equal(value)
event.args.amount.should.be.bignumber.equal(expectedTokenAmount)
})
it('should increase totalSupply', async function () {
await this.crowdsale.buyTokens(investor, {value, from: purchaser})
const totalSupply = await this.token.totalSupply()
totalSupply.should.be.bignumber.equal(expectedTokenAmount)
})
it('should assign tokens to beneficiary', async function () {
await this.crowdsale.buyTokens(investor, {value, from: purchaser})
const balance = await this.token.balanceOf(investor)
balance.should.be.bignumber.equal(expectedTokenAmount)
})
it('should forward funds to wallet', async function () {
const pre = web3.eth.getBalance(wallet)
await this.crowdsale.buyTokens(investor, {value, from: purchaser})
const post = web3.eth.getBalance(wallet)
post.minus(pre).should.be.bignumber.equal(value)
})
})
})

@ -0,0 +1,143 @@
import ether from './helpers/ether';
import { advanceBlock } from './helpers/advanceToBlock';
import { increaseTimeTo, duration } from './helpers/increaseTime';
import latestTime from './helpers/latestTime';
import EVMRevert from './helpers/EVMRevert';
const BigNumber = web3.BigNumber;
const should = require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const Crowdsale = artifacts.require('Crowdsale');
const MintableToken = artifacts.require('MintableToken');
contract('Crowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BigNumber(1000);
const value = ether(42);
const expectedTokenAmount = rate.mul(value);
before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock();
});
beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1);
this.endTime = this.startTime + duration.weeks(1);
this.afterEndTime = this.endTime + duration.seconds(1);
this.crowdsale = await Crowdsale.new(this.startTime, this.endTime, rate, wallet);
this.token = MintableToken.at(await this.crowdsale.token());
});
it('should be token owner', async function () {
const owner = await this.token.owner();
owner.should.equal(this.crowdsale.address);
});
it('should be ended only after end', async function () {
let ended = await this.crowdsale.hasEnded();
ended.should.equal(false);
await increaseTimeTo(this.afterEndTime);
ended = await this.crowdsale.hasEnded();
ended.should.equal(true);
});
describe('accepting payments', function () {
it('should reject payments before start', async function () {
await this.crowdsale.send(value).should.be.rejectedWith(EVMRevert);
await this.crowdsale.buyTokens(investor, { from: purchaser, value: value }).should.be.rejectedWith(EVMRevert);
});
it('should accept payments after start', async function () {
await increaseTimeTo(this.startTime);
await this.crowdsale.send(value).should.be.fulfilled;
await this.crowdsale.buyTokens(investor, { value: value, from: purchaser }).should.be.fulfilled;
});
it('should reject payments after end', async function () {
await increaseTimeTo(this.afterEndTime);
await this.crowdsale.send(value).should.be.rejectedWith(EVMRevert);
await this.crowdsale.buyTokens(investor, { value: value, from: purchaser }).should.be.rejectedWith(EVMRevert);
});
});
describe('high-level purchase', function () {
beforeEach(async function () {
await increaseTimeTo(this.startTime);
});
it('should log purchase', async function () {
const { logs } = await this.crowdsale.sendTransaction({ value: value, from: investor });
const event = logs.find(e => e.event === 'TokenPurchase');
should.exist(event);
event.args.purchaser.should.equal(investor);
event.args.beneficiary.should.equal(investor);
event.args.value.should.be.bignumber.equal(value);
event.args.amount.should.be.bignumber.equal(expectedTokenAmount);
});
it('should increase totalSupply', async function () {
await this.crowdsale.send(value);
const totalSupply = await this.token.totalSupply();
totalSupply.should.be.bignumber.equal(expectedTokenAmount);
});
it('should assign tokens to sender', async function () {
await this.crowdsale.sendTransaction({ value: value, from: investor });
let balance = await this.token.balanceOf(investor);
balance.should.be.bignumber.equal(expectedTokenAmount);
});
it('should forward funds to wallet', async function () {
const pre = web3.eth.getBalance(wallet);
await this.crowdsale.sendTransaction({ value, from: investor });
const post = web3.eth.getBalance(wallet);
post.minus(pre).should.be.bignumber.equal(value);
});
});
describe('low-level purchase', function () {
beforeEach(async function () {
await increaseTimeTo(this.startTime);
});
it('should log purchase', async function () {
const { logs } = await this.crowdsale.buyTokens(investor, { value: value, from: purchaser });
const event = logs.find(e => e.event === 'TokenPurchase');
should.exist(event);
event.args.purchaser.should.equal(purchaser);
event.args.beneficiary.should.equal(investor);
event.args.value.should.be.bignumber.equal(value);
event.args.amount.should.be.bignumber.equal(expectedTokenAmount);
});
it('should increase totalSupply', async function () {
await this.crowdsale.buyTokens(investor, { value, from: purchaser });
const totalSupply = await this.token.totalSupply();
totalSupply.should.be.bignumber.equal(expectedTokenAmount);
});
it('should assign tokens to beneficiary', async function () {
await this.crowdsale.buyTokens(investor, { value, from: purchaser });
const balance = await this.token.balanceOf(investor);
balance.should.be.bignumber.equal(expectedTokenAmount);
});
it('should forward funds to wallet', async function () {
const pre = web3.eth.getBalance(wallet);
await this.crowdsale.buyTokens(investor, { value, from: purchaser });
const post = web3.eth.getBalance(wallet);
post.minus(pre).should.be.bignumber.equal(value);
});
});
});

@ -1,12 +1,12 @@
'use strict';
import latestTime from './helpers/latestTime';
import { increaseTimeTo, duration } from './helpers/increaseTime';
const assertRevert = require('./helpers/assertRevert'); const assertRevert = require('./helpers/assertRevert');
import latestTime from './helpers/latestTime'
import {increaseTimeTo, duration} from './helpers/increaseTime'
var DayLimitMock = artifacts.require('./helpers/DayLimitMock.sol'); const DayLimitMock = artifacts.require('./mocks/DayLimitMock.sol');
contract('DayLimit', function (accounts) { contract('DayLimit', function (accounts) {
let dayLimit; let dayLimit;
let initLimit = 10; let initLimit = 10;
@ -106,5 +106,4 @@ contract('DayLimit', function(accounts) {
spentToday = await dayLimit.spentToday(); spentToday = await dayLimit.spentToday();
assert.equal(spentToday, 3); assert.equal(spentToday, 3);
}); });
}); });

@ -1,4 +1,3 @@
'use strict';
var DelayedClaimable = artifacts.require('../contracts/ownership/DelayedClaimable.sol'); var DelayedClaimable = artifacts.require('../contracts/ownership/DelayedClaimable.sol');
@ -64,5 +63,4 @@ contract('DelayedClaimable', function(accounts) {
} }
assert.isFalse(err.message.search('revert') === -1); assert.isFalse(err.message.search('revert') === -1);
}); });
}); });

@ -1,10 +1,8 @@
'use strict';
var Destructible = artifacts.require('../contracts/lifecycle/Destructible.sol'); var Destructible = artifacts.require('../contracts/lifecycle/Destructible.sol');
require('./helpers/transactionMined.js'); require('./helpers/transactionMined.js');
contract('Destructible', function (accounts) { contract('Destructible', function (accounts) {
it('should send balance to owner after destruction', async function () { it('should send balance to owner after destruction', async function () {
let destructible = await Destructible.new({ from: accounts[0], value: web3.toWei('10', 'ether') }); let destructible = await Destructible.new({ from: accounts[0], value: web3.toWei('10', 'ether') });
let owner = await destructible.owner(); let owner = await destructible.owner();
@ -22,5 +20,4 @@ contract('Destructible', function(accounts) {
let newBalance = web3.eth.getBalance(accounts[1]); let newBalance = web3.eth.getBalance(accounts[1]);
assert.isTrue(newBalance.greaterThan(initBalance)); assert.isTrue(newBalance.greaterThan(initBalance));
}); });
}); });

@ -5,13 +5,13 @@ require('chai')
.use(require('chai-bignumber')(BigNumber)) .use(require('chai-bignumber')(BigNumber))
.should(); .should();
const DetailedERC20Mock = artifacts.require('./helpers/DetailedERC20Mock.sol'); const DetailedERC20Mock = artifacts.require('./mocks/DetailedERC20Mock.sol');
contract('DetailedERC20', accounts => { contract('DetailedERC20', accounts => {
let detailedERC20 = null; let detailedERC20 = null;
const _name = "My Detailed ERC20"; const _name = 'My Detailed ERC20';
const _symbol = "MDT"; const _symbol = 'MDT';
const _decimals = 18; const _decimals = 18;
beforeEach(async function () { beforeEach(async function () {
@ -30,6 +30,6 @@ contract('DetailedERC20', accounts => {
it('has an amount of decimals', async function () { it('has an amount of decimals', async function () {
const decimals = await detailedERC20.decimals(); const decimals = await detailedERC20.decimals();
decimals.should.be.bignumber.equal(_decimals) decimals.should.be.bignumber.equal(_decimals);
}); });
}); });

@ -1,32 +1,32 @@
var ECRecovery = artifacts.require("../contracts/ECRecovery.sol"); var ECRecovery = artifacts.require('../contracts/ECRecovery.sol');
var utils = require('ethereumjs-util');
var hashMessage = require('./helpers/hashMessage.js'); var hashMessage = require('./helpers/hashMessage.js');
contract('ECRecovery', function (accounts) { contract('ECRecovery', function (accounts) {
let ecrecovery; let ecrecovery;
before(async function () { before(async function () {
ecrecovery = await ECRecovery.new(); ecrecovery = await ECRecovery.new();
}); });
it("recover v0", async function() { it('recover v0', async function () {
// Signature generated outside testrpc with method web3.eth.sign(signer, message) // Signature generated outside testrpc with method web3.eth.sign(signer, message)
let signer = '0x2cc1166f6212628a0deef2b33befb2187d35b86c'; let signer = '0x2cc1166f6212628a0deef2b33befb2187d35b86c';
let message = '0x7dbaf558b0a1a5dc7a67202117ab143c1d8605a983e4a743bc06fcc03162dc0d'; // web3.sha3('OpenZeppelin') let message = '0x7dbaf558b0a1a5dc7a67202117ab143c1d8605a983e4a743bc06fcc03162dc0d'; // web3.sha3('OpenZeppelin')
// eslint-disable-next-line max-len
let signature = '0x5d99b6f7f6d1f73d1a26497f2b1c89b24c0993913f86e9a2d02cd69887d9c94f3c880358579d811b21dd1b7fd9bb01c1d81d10e69f0384e675c32b39643be89200'; let signature = '0x5d99b6f7f6d1f73d1a26497f2b1c89b24c0993913f86e9a2d02cd69887d9c94f3c880358579d811b21dd1b7fd9bb01c1d81d10e69f0384e675c32b39643be89200';
assert.equal(signer, await ecrecovery.recover(message, signature)); assert.equal(signer, await ecrecovery.recover(message, signature));
}); });
it("recover v1", async function() { it('recover v1', async function () {
// Signature generated outside testrpc with method web3.eth.sign(signer, message) // Signature generated outside testrpc with method web3.eth.sign(signer, message)
let signer = '0x1e318623ab09fe6de3c9b8672098464aeda9100e'; let signer = '0x1e318623ab09fe6de3c9b8672098464aeda9100e';
let message = '0x7dbaf558b0a1a5dc7a67202117ab143c1d8605a983e4a743bc06fcc03162dc0d'; // web3.sha3('OpenZeppelin') let message = '0x7dbaf558b0a1a5dc7a67202117ab143c1d8605a983e4a743bc06fcc03162dc0d'; // web3.sha3('OpenZeppelin')
// eslint-disable-next-line max-len
let signature = '0x331fe75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e001'; let signature = '0x331fe75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e001';
assert.equal(signer, await ecrecovery.recover(message, signature)); assert.equal(signer, await ecrecovery.recover(message, signature));
}); });
it("recover using web3.eth.sign()", async function() { it('recover using web3.eth.sign()', async function () {
// Create the signature using account[0] // Create the signature using account[0]
const signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin')); const signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin'));
@ -34,7 +34,7 @@ contract('ECRecovery', function(accounts) {
assert.equal(web3.eth.accounts[0], await ecrecovery.recover(hashMessage('OpenZeppelin'), signature)); assert.equal(web3.eth.accounts[0], await ecrecovery.recover(hashMessage('OpenZeppelin'), signature));
}); });
it("recover using web3.eth.sign() should return wrong signer", async function() { it('recover using web3.eth.sign() should return wrong signer', async function () {
// Create the signature using account[0] // Create the signature using account[0]
const signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin')); const signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin'));
@ -42,7 +42,7 @@ contract('ECRecovery', function(accounts) {
assert.notEqual(web3.eth.accounts[0], await ecrecovery.recover(hashMessage('Test'), signature)); assert.notEqual(web3.eth.accounts[0], await ecrecovery.recover(hashMessage('Test'), signature));
}); });
it("recover should fail when a wrong hash is sent", async function() { it('recover should fail when a wrong hash is sent', async function () {
// Create the signature using account[0] // Create the signature using account[0]
let signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin')); let signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin'));
@ -51,5 +51,4 @@ contract('ECRecovery', function(accounts) {
await ecrecovery.recover(hashMessage('OpenZeppelin').substring(2), signature) await ecrecovery.recover(hashMessage('OpenZeppelin').substring(2), signature)
); );
}); });
}); });

@ -1,63 +0,0 @@
import {advanceBlock} from './helpers/advanceToBlock'
import {increaseTimeTo, duration} from './helpers/increaseTime'
import latestTime from './helpers/latestTime'
import EVMRevert from './helpers/EVMRevert'
const BigNumber = web3.BigNumber
const should = require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
const FinalizableCrowdsale = artifacts.require('./helpers/FinalizableCrowdsaleImpl.sol')
const MintableToken = artifacts.require('MintableToken')
contract('FinalizableCrowdsale', function ([_, owner, wallet, thirdparty]) {
const rate = new BigNumber(1000)
before(async function() {
//Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock()
})
beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1)
this.endTime = this.startTime + duration.weeks(1)
this.afterEndTime = this.endTime + duration.seconds(1)
this.crowdsale = await FinalizableCrowdsale.new(this.startTime, this.endTime, rate, wallet, {from: owner})
this.token = MintableToken.at(await this.crowdsale.token())
})
it('cannot be finalized before ending', async function () {
await this.crowdsale.finalize({from: owner}).should.be.rejectedWith(EVMRevert)
})
it('cannot be finalized by third party after ending', async function () {
await increaseTimeTo(this.afterEndTime)
await this.crowdsale.finalize({from: thirdparty}).should.be.rejectedWith(EVMRevert)
})
it('can be finalized by owner after ending', async function () {
await increaseTimeTo(this.afterEndTime)
await this.crowdsale.finalize({from: owner}).should.be.fulfilled
})
it('cannot be finalized twice', async function () {
await increaseTimeTo(this.afterEndTime)
await this.crowdsale.finalize({from: owner})
await this.crowdsale.finalize({from: owner}).should.be.rejectedWith(EVMRevert)
})
it('logs finalized', async function () {
await increaseTimeTo(this.afterEndTime)
const {logs} = await this.crowdsale.finalize({from: owner})
const event = logs.find(e => e.event === 'Finalized')
should.exist(event)
})
})

@ -0,0 +1,60 @@
import { advanceBlock } from './helpers/advanceToBlock';
import { increaseTimeTo, duration } from './helpers/increaseTime';
import latestTime from './helpers/latestTime';
import EVMRevert from './helpers/EVMRevert';
const BigNumber = web3.BigNumber;
const should = require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const FinalizableCrowdsale = artifacts.require('./mocks/FinalizableCrowdsaleImpl.sol');
const MintableToken = artifacts.require('MintableToken');
contract('FinalizableCrowdsale', function ([_, owner, wallet, thirdparty]) {
const rate = new BigNumber(1000);
before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock();
});
beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1);
this.endTime = this.startTime + duration.weeks(1);
this.afterEndTime = this.endTime + duration.seconds(1);
this.crowdsale = await FinalizableCrowdsale.new(this.startTime, this.endTime, rate, wallet, { from: owner });
this.token = MintableToken.at(await this.crowdsale.token());
});
it('cannot be finalized before ending', async function () {
await this.crowdsale.finalize({ from: owner }).should.be.rejectedWith(EVMRevert);
});
it('cannot be finalized by third party after ending', async function () {
await increaseTimeTo(this.afterEndTime);
await this.crowdsale.finalize({ from: thirdparty }).should.be.rejectedWith(EVMRevert);
});
it('can be finalized by owner after ending', async function () {
await increaseTimeTo(this.afterEndTime);
await this.crowdsale.finalize({ from: owner }).should.be.fulfilled;
});
it('cannot be finalized twice', async function () {
await increaseTimeTo(this.afterEndTime);
await this.crowdsale.finalize({ from: owner });
await this.crowdsale.finalize({ from: owner }).should.be.rejectedWith(EVMRevert);
});
it('logs finalized', async function () {
await increaseTimeTo(this.afterEndTime);
const { logs } = await this.crowdsale.finalize({ from: owner });
const event = logs.find(e => e.event === 'Finalized');
should.exist(event);
});
});

@ -1,6 +1,6 @@
'use strict';
import expectThrow from './helpers/expectThrow'; import expectThrow from './helpers/expectThrow';
import toPromise from './helpers/toPromise';
const Ownable = artifacts.require('../contracts/ownership/Ownable.sol'); const Ownable = artifacts.require('../contracts/ownership/Ownable.sol');
const HasNoContracts = artifacts.require( const HasNoContracts = artifacts.require(
'../contracts/ownership/HasNoContracts.sol', '../contracts/ownership/HasNoContracts.sol',

@ -1,15 +1,14 @@
'use strict';
import expectThrow from './helpers/expectThrow'; import expectThrow from './helpers/expectThrow';
import toPromise from './helpers/toPromise'; import toPromise from './helpers/toPromise';
const HasNoEther = artifacts.require('../contracts/lifecycle/HasNoEther.sol'); const HasNoEtherTest = artifacts.require('../mocks/HasNoEtherTest.sol');
const HasNoEtherTest = artifacts.require('../helpers/HasNoEtherTest.sol'); const ForceEther = artifacts.require('../mocks/ForceEther.sol');
const ForceEther = artifacts.require('../helpers/ForceEther.sol');
contract('HasNoEther', function (accounts) { contract('HasNoEther', function (accounts) {
const amount = web3.toWei('1', 'ether'); const amount = web3.toWei('1', 'ether');
it('should be constructorable', async function () { it('should be constructorable', async function () {
let hasNoEther = await HasNoEtherTest.new(); await HasNoEtherTest.new();
}); });
it('should not accept ether in constructor', async function () { it('should not accept ether in constructor', async function () {

@ -1,8 +1,8 @@
'use strict';
import expectThrow from './helpers/expectThrow'; import expectThrow from './helpers/expectThrow';
import toPromise from './helpers/toPromise';
const HasNoTokens = artifacts.require('../contracts/lifecycle/HasNoTokens.sol'); const HasNoTokens = artifacts.require('../contracts/lifecycle/HasNoTokens.sol');
const ERC23TokenMock = artifacts.require('./helpers/ERC23TokenMock.sol'); const ERC23TokenMock = artifacts.require('./mocks/ERC23TokenMock.sol');
contract('HasNoTokens', function (accounts) { contract('HasNoTokens', function (accounts) {
let hasNoTokens = null; let hasNoTokens = null;

@ -1,61 +0,0 @@
'use strict';
var LimitBalanceMock = artifacts.require('helpers/LimitBalanceMock.sol');
const assertRevert = require('./helpers/assertRevert');
contract('LimitBalance', function(accounts) {
let lb;
beforeEach(async function() {
lb = await LimitBalanceMock.new();
});
let LIMIT = 1000;
it('should expose limit', async function() {
let limit = await lb.limit();
assert.equal(limit, LIMIT);
});
it('should allow sending below limit', async function() {
let amount = 1;
await lb.limitedDeposit({value: amount});
assert.equal(web3.eth.getBalance(lb.address), amount);
});
it('shouldnt allow sending above limit', async function() {
let amount = 1110;
try {
await lb.limitedDeposit({value: amount});
assert.fail('should have thrown before');
} catch(error) {
assertRevert(error);
}
});
it('should allow multiple sends below limit', async function() {
let amount = 500;
await lb.limitedDeposit({value: amount});
assert.equal(web3.eth.getBalance(lb.address), amount);
await lb.limitedDeposit({value: amount});
assert.equal(web3.eth.getBalance(lb.address), amount*2);
});
it('shouldnt allow multiple sends above limit', async function() {
let amount = 500;
await lb.limitedDeposit({value: amount});
assert.equal(web3.eth.getBalance(lb.address), amount);
try {
await lb.limitedDeposit({value: amount+1});
assert.fail('should have thrown before');
} catch(error) {
assertRevert(error);
}
});
});

@ -0,0 +1,59 @@
var LimitBalanceMock = artifacts.require('mocks/LimitBalanceMock.sol');
const assertRevert = require('./helpers/assertRevert');
contract('LimitBalance', function (accounts) {
let lb;
beforeEach(async function () {
lb = await LimitBalanceMock.new();
});
let LIMIT = 1000;
it('should expose limit', async function () {
let limit = await lb.limit();
assert.equal(limit, LIMIT);
});
it('should allow sending below limit', async function () {
let amount = 1;
await lb.limitedDeposit({ value: amount });
assert.equal(web3.eth.getBalance(lb.address), amount);
});
it('shouldnt allow sending above limit', async function () {
let amount = 1110;
try {
await lb.limitedDeposit({ value: amount });
assert.fail('should have thrown before');
} catch (error) {
assertRevert(error);
}
});
it('should allow multiple sends below limit', async function () {
let amount = 500;
await lb.limitedDeposit({ value: amount });
assert.equal(web3.eth.getBalance(lb.address), amount);
await lb.limitedDeposit({ value: amount });
assert.equal(web3.eth.getBalance(lb.address), amount * 2);
});
it('shouldnt allow multiple sends above limit', async function () {
let amount = 500;
await lb.limitedDeposit({ value: amount });
assert.equal(web3.eth.getBalance(lb.address), amount);
try {
await lb.limitedDeposit({ value: amount + 1 });
assert.fail('should have thrown before');
} catch (error) {
assertRevert(error);
}
});
});

@ -1,7 +1,8 @@
var MerkleProof = artifacts.require("./MerkleProof.sol");
import MerkleTree from "./helpers/merkleTree.js"; import MerkleTree from './helpers/merkleTree.js';
import { sha3, bufferToHex } from "ethereumjs-util"; import { sha3, bufferToHex } from 'ethereumjs-util';
var MerkleProof = artifacts.require('./MerkleProof.sol');
contract('MerkleProof', function (accounts) { contract('MerkleProof', function (accounts) {
let merkleProof; let merkleProof;
@ -10,9 +11,9 @@ contract('MerkleProof', function(accounts) {
merkleProof = await MerkleProof.new(); merkleProof = await MerkleProof.new();
}); });
describe("verifyProof", function() { describe('verifyProof', function () {
it("should return true for a valid Merkle proof", async function() { it('should return true for a valid Merkle proof', async function () {
const elements = ["a", "b", "c", "d"]; const elements = ['a', 'b', 'c', 'd'];
const merkleTree = new MerkleTree(elements); const merkleTree = new MerkleTree(elements);
const root = merkleTree.getHexRoot(); const root = merkleTree.getHexRoot();
@ -22,28 +23,28 @@ contract('MerkleProof', function(accounts) {
const leaf = bufferToHex(sha3(elements[0])); const leaf = bufferToHex(sha3(elements[0]));
const result = await merkleProof.verifyProof(proof, root, leaf); const result = await merkleProof.verifyProof(proof, root, leaf);
assert.isOk(result, "verifyProof did not return true for a valid proof"); assert.isOk(result, 'verifyProof did not return true for a valid proof');
}); });
it("should return false for an invalid Merkle proof", async function() { it('should return false for an invalid Merkle proof', async function () {
const correctElements = ["a", "b", "c"] const correctElements = ['a', 'b', 'c'];
const correctMerkleTree = new MerkleTree(correctElements); const correctMerkleTree = new MerkleTree(correctElements);
const correctRoot = correctMerkleTree.getHexRoot(); const correctRoot = correctMerkleTree.getHexRoot();
const correctLeaf = bufferToHex(sha3(correctElements[0])); const correctLeaf = bufferToHex(sha3(correctElements[0]));
const badElements = ["d", "e", "f"] const badElements = ['d', 'e', 'f'];
const badMerkleTree = new MerkleTree(badElements) const badMerkleTree = new MerkleTree(badElements);
const badProof = badMerkleTree.getHexProof(badElements[0]) const badProof = badMerkleTree.getHexProof(badElements[0]);
const result = await merkleProof.verifyProof(badProof, correctRoot, correctLeaf); const result = await merkleProof.verifyProof(badProof, correctRoot, correctLeaf);
assert.isNotOk(result, "verifyProof did not return false for an invalid proof"); assert.isNotOk(result, 'verifyProof did not return false for an invalid proof');
}); });
it("should return false for a Merkle proof of invalid length", async function() { it('should return false for a Merkle proof of invalid length', async function () {
const elements = ["a", "b", "c"] const elements = ['a', 'b', 'c'];
const merkleTree = new MerkleTree(elements); const merkleTree = new MerkleTree(elements);
const root = merkleTree.getHexRoot(); const root = merkleTree.getHexRoot();
@ -54,7 +55,7 @@ contract('MerkleProof', function(accounts) {
const leaf = bufferToHex(sha3(elements[0])); const leaf = bufferToHex(sha3(elements[0]));
const result = await merkleProof.verifyProof(badProof, root, leaf); const result = await merkleProof.verifyProof(badProof, root, leaf);
assert.isNotOk(result, "verifyProof did not return false for proof of invalid length"); assert.isNotOk(result, 'verifyProof did not return false for proof of invalid length');
}) });
}); });
}); });

@ -1,4 +1,3 @@
'use strict';
import expectThrow from './helpers/expectThrow'; import expectThrow from './helpers/expectThrow';
var MintableToken = artifacts.require('../contracts/Tokens/MintableToken.sol'); var MintableToken = artifacts.require('../contracts/Tokens/MintableToken.sol');
@ -35,12 +34,11 @@ contract('Mintable', function(accounts) {
let totalSupply = await token.totalSupply(); let totalSupply = await token.totalSupply();
assert(totalSupply, 100); assert(totalSupply, 100);
}) });
it('should fail to mint after call to finishMinting', async function () { it('should fail to mint after call to finishMinting', async function () {
await token.finishMinting(); await token.finishMinting();
assert.equal(await token.mintingFinished(), true); assert.equal(await token.mintingFinished(), true);
await expectThrow(token.mint(accounts[0], 100)); await expectThrow(token.mint(accounts[0], 100));
}) });
}); });

@ -1,4 +1,4 @@
'use strict';
const assertRevert = require('./helpers/assertRevert'); const assertRevert = require('./helpers/assertRevert');
var Ownable = artifacts.require('../contracts/ownership/Ownable.sol'); var Ownable = artifacts.require('../contracts/ownership/Ownable.sol');
@ -44,5 +44,4 @@ contract('Ownable', function(accounts) {
assertRevert(error); assertRevert(error);
} }
}); });
}); });

@ -1,10 +1,8 @@
'use strict';
const assertRevert = require('./helpers/assertRevert'); const assertRevert = require('./helpers/assertRevert');
const PausableMock = artifacts.require('helpers/PausableMock.sol'); const PausableMock = artifacts.require('mocks/PausableMock.sol');
contract('Pausable', function (accounts) { contract('Pausable', function (accounts) {
it('can perform normal process in non-pause', async function () { it('can perform normal process in non-pause', async function () {
let Pausable = await PausableMock.new(); let Pausable = await PausableMock.new();
let count0 = await Pausable.count(); let count0 = await Pausable.count();
@ -31,7 +29,6 @@ contract('Pausable', function(accounts) {
assert.equal(count1, 0); assert.equal(count1, 0);
}); });
it('can not take drastic measure in non-pause', async function () { it('can not take drastic measure in non-pause', async function () {
let Pausable = await PausableMock.new(); let Pausable = await PausableMock.new();
try { try {
@ -77,5 +74,4 @@ contract('Pausable', function(accounts) {
const drasticMeasureTaken = await Pausable.drasticMeasureTaken(); const drasticMeasureTaken = await Pausable.drasticMeasureTaken();
assert.isFalse(drasticMeasureTaken); assert.isFalse(drasticMeasureTaken);
}); });
}); });

@ -1,7 +1,7 @@
'user strict'; 'user strict';
const assertRevert = require('./helpers/assertRevert'); const assertRevert = require('./helpers/assertRevert');
var PausableTokenMock = artifacts.require('./helpers/PausableTokenMock.sol'); var PausableTokenMock = artifacts.require('./mocks/PausableTokenMock.sol');
contract('PausableToken', function (accounts) { contract('PausableToken', function (accounts) {
let token; let token;
@ -70,4 +70,4 @@ contract('PausableToken', function(accounts) {
assertRevert(error); assertRevert(error);
} }
}); });
}) });

@ -1,4 +1,4 @@
var PullPaymentMock = artifacts.require("./helpers/PullPaymentMock.sol"); var PullPaymentMock = artifacts.require('./mocks/PullPaymentMock.sol');
contract('PullPayment', function (accounts) { contract('PullPayment', function (accounts) {
let ppce; let ppce;
@ -8,13 +8,13 @@ contract('PullPayment', function(accounts) {
ppce = await PullPaymentMock.new({ value: amount }); ppce = await PullPaymentMock.new({ value: amount });
}); });
it("can't call asyncSend externally", async function() { it('can\'t call asyncSend externally', async function () {
assert.isUndefined(ppce.asyncSend); assert.isUndefined(ppce.asyncSend);
}); });
it("can record an async payment correctly", async function() { it('can record an async payment correctly', async function () {
let AMOUNT = 100; let AMOUNT = 100;
let callSend = await ppce.callSend(accounts[0], AMOUNT); await ppce.callSend(accounts[0], AMOUNT);
let paymentsToAccount0 = await ppce.payments(accounts[0]); let paymentsToAccount0 = await ppce.payments(accounts[0]);
let totalPayments = await ppce.totalPayments(); let totalPayments = await ppce.totalPayments();
@ -22,9 +22,9 @@ contract('PullPayment', function(accounts) {
assert.equal(paymentsToAccount0, AMOUNT); assert.equal(paymentsToAccount0, AMOUNT);
}); });
it("can add multiple balances on one account", async function() { it('can add multiple balances on one account', async function () {
let call1 = await ppce.callSend(accounts[0], 200); await ppce.callSend(accounts[0], 200);
let call2 = await ppce.callSend(accounts[0], 300); await ppce.callSend(accounts[0], 300);
let paymentsToAccount0 = await ppce.payments(accounts[0]); let paymentsToAccount0 = await ppce.payments(accounts[0]);
let totalPayments = await ppce.totalPayments(); let totalPayments = await ppce.totalPayments();
@ -32,9 +32,9 @@ contract('PullPayment', function(accounts) {
assert.equal(paymentsToAccount0, 500); assert.equal(paymentsToAccount0, 500);
}); });
it("can add balances on multiple accounts", async function() { it('can add balances on multiple accounts', async function () {
let call1 = await ppce.callSend(accounts[0], 200); await ppce.callSend(accounts[0], 200);
let call2 = await ppce.callSend(accounts[1], 300); await ppce.callSend(accounts[1], 300);
let paymentsToAccount0 = await ppce.payments(accounts[0]); let paymentsToAccount0 = await ppce.payments(accounts[0]);
assert.equal(paymentsToAccount0, 200); assert.equal(paymentsToAccount0, 200);
@ -46,11 +46,11 @@ contract('PullPayment', function(accounts) {
assert.equal(totalPayments, 500); assert.equal(totalPayments, 500);
}); });
it("can withdraw payment", async function() { it('can withdraw payment', async function () {
let payee = accounts[1]; let payee = accounts[1];
let initialBalance = web3.eth.getBalance(payee); let initialBalance = web3.eth.getBalance(payee);
let call1 = await ppce.callSend(payee, amount); await ppce.callSend(payee, amount);
let payment1 = await ppce.payments(payee); let payment1 = await ppce.payments(payee);
assert.equal(payment1, amount); assert.equal(payment1, amount);
@ -58,7 +58,7 @@ contract('PullPayment', function(accounts) {
let totalPayments = await ppce.totalPayments(); let totalPayments = await ppce.totalPayments();
assert.equal(totalPayments, amount); assert.equal(totalPayments, amount);
let withdraw = await ppce.withdrawPayments({from: payee}); await ppce.withdrawPayments({ from: payee });
let payment2 = await ppce.payments(payee); let payment2 = await ppce.payments(payee);
assert.equal(payment2, 0); assert.equal(payment2, 0);
@ -68,5 +68,4 @@ contract('PullPayment', function(accounts) {
let balance = web3.eth.getBalance(payee); let balance = web3.eth.getBalance(payee);
assert(Math.abs(balance - initialBalance - amount) < 1e16); assert(Math.abs(balance - initialBalance - amount) < 1e16);
}); });
}); });

@ -1,4 +1,4 @@
'use strict';
import expectThrow from './helpers/expectThrow'; import expectThrow from './helpers/expectThrow';
const ReentrancyMock = artifacts.require('./helper/ReentrancyMock.sol'); const ReentrancyMock = artifacts.require('./helper/ReentrancyMock.sol');
const ReentrancyAttack = artifacts.require('./helper/ReentrancyAttack.sol'); const ReentrancyAttack = artifacts.require('./helper/ReentrancyAttack.sol');

@ -1,61 +0,0 @@
const BigNumber = web3.BigNumber
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
import ether from './helpers/ether'
import EVMRevert from './helpers/EVMRevert'
const RefundVault = artifacts.require('RefundVault')
contract('RefundVault', function ([_, owner, wallet, investor]) {
const value = ether(42)
beforeEach(async function () {
this.vault = await RefundVault.new(wallet, {from: owner})
})
it('should accept contributions', async function () {
await this.vault.deposit(investor, {value, from: owner}).should.be.fulfilled
})
it('should not refund contribution during active state', async function () {
await this.vault.deposit(investor, {value, from: owner})
await this.vault.refund(investor).should.be.rejectedWith(EVMRevert)
})
it('only owner can enter refund mode', async function () {
await this.vault.enableRefunds({from: _}).should.be.rejectedWith(EVMRevert)
await this.vault.enableRefunds({from: owner}).should.be.fulfilled
})
it('should refund contribution after entering refund mode', async function () {
await this.vault.deposit(investor, {value, from: owner})
await this.vault.enableRefunds({from: owner})
const pre = web3.eth.getBalance(investor)
await this.vault.refund(investor)
const post = web3.eth.getBalance(investor)
post.minus(pre).should.be.bignumber.equal(value)
})
it('only owner can close', async function () {
await this.vault.close({from: _}).should.be.rejectedWith(EVMRevert)
await this.vault.close({from: owner}).should.be.fulfilled
})
it('should forward funds to wallet after closing', async function () {
await this.vault.deposit(investor, {value, from: owner})
const pre = web3.eth.getBalance(wallet)
await this.vault.close({from: owner})
const post = web3.eth.getBalance(wallet)
post.minus(pre).should.be.bignumber.equal(value)
})
})

@ -0,0 +1,59 @@
import ether from './helpers/ether';
import EVMRevert from './helpers/EVMRevert';
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const RefundVault = artifacts.require('RefundVault');
contract('RefundVault', function ([_, owner, wallet, investor]) {
const value = ether(42);
beforeEach(async function () {
this.vault = await RefundVault.new(wallet, { from: owner });
});
it('should accept contributions', async function () {
await this.vault.deposit(investor, { value, from: owner }).should.be.fulfilled;
});
it('should not refund contribution during active state', async function () {
await this.vault.deposit(investor, { value, from: owner });
await this.vault.refund(investor).should.be.rejectedWith(EVMRevert);
});
it('only owner can enter refund mode', async function () {
await this.vault.enableRefunds({ from: _ }).should.be.rejectedWith(EVMRevert);
await this.vault.enableRefunds({ from: owner }).should.be.fulfilled;
});
it('should refund contribution after entering refund mode', async function () {
await this.vault.deposit(investor, { value, from: owner });
await this.vault.enableRefunds({ from: owner });
const pre = web3.eth.getBalance(investor);
await this.vault.refund(investor);
const post = web3.eth.getBalance(investor);
post.minus(pre).should.be.bignumber.equal(value);
});
it('only owner can close', async function () {
await this.vault.close({ from: _ }).should.be.rejectedWith(EVMRevert);
await this.vault.close({ from: owner }).should.be.fulfilled;
});
it('should forward funds to wallet after closing', async function () {
await this.vault.deposit(investor, { value, from: owner });
const pre = web3.eth.getBalance(wallet);
await this.vault.close({ from: owner });
const post = web3.eth.getBalance(wallet);
post.minus(pre).should.be.bignumber.equal(value);
});
});

@ -1,83 +0,0 @@
import ether from './helpers/ether'
import {advanceBlock} from './helpers/advanceToBlock'
import {increaseTimeTo, duration} from './helpers/increaseTime'
import latestTime from './helpers/latestTime'
import EVMRevert from './helpers/EVMRevert'
const BigNumber = web3.BigNumber
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
const RefundableCrowdsale = artifacts.require('./helpers/RefundableCrowdsaleImpl.sol')
contract('RefundableCrowdsale', function ([_, owner, wallet, investor]) {
const rate = new BigNumber(1000)
const goal = ether(800)
const lessThanGoal = ether(750)
before(async function() {
//Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock()
})
beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1)
this.endTime = this.startTime + duration.weeks(1)
this.afterEndTime = this.endTime + duration.seconds(1)
this.crowdsale = await RefundableCrowdsale.new(this.startTime, this.endTime, rate, wallet, goal, {from: owner})
})
describe('creating a valid crowdsale', function () {
it('should fail with zero goal', async function () {
await RefundableCrowdsale.new(this.startTime, this.endTime, rate, wallet, 0, {from: owner}).should.be.rejectedWith(EVMRevert);
})
});
it('should deny refunds before end', async function () {
await this.crowdsale.claimRefund({from: investor}).should.be.rejectedWith(EVMRevert)
await increaseTimeTo(this.startTime)
await this.crowdsale.claimRefund({from: investor}).should.be.rejectedWith(EVMRevert)
})
it('should deny refunds after end if goal was reached', async function () {
await increaseTimeTo(this.startTime)
await this.crowdsale.sendTransaction({value: goal, from: investor})
await increaseTimeTo(this.afterEndTime)
await this.crowdsale.claimRefund({from: investor}).should.be.rejectedWith(EVMRevert)
})
it('should allow refunds after end if goal was not reached', async function () {
await increaseTimeTo(this.startTime)
await this.crowdsale.sendTransaction({value: lessThanGoal, from: investor})
await increaseTimeTo(this.afterEndTime)
await this.crowdsale.finalize({from: owner})
const pre = web3.eth.getBalance(investor)
await this.crowdsale.claimRefund({from: investor, gasPrice: 0})
.should.be.fulfilled
const post = web3.eth.getBalance(investor)
post.minus(pre).should.be.bignumber.equal(lessThanGoal)
})
it('should forward funds to wallet after end if goal was reached', async function () {
await increaseTimeTo(this.startTime)
await this.crowdsale.sendTransaction({value: goal, from: investor})
await increaseTimeTo(this.afterEndTime)
const pre = web3.eth.getBalance(wallet)
await this.crowdsale.finalize({from: owner})
const post = web3.eth.getBalance(wallet)
post.minus(pre).should.be.bignumber.equal(goal)
})
})

@ -0,0 +1,80 @@
import ether from './helpers/ether';
import { advanceBlock } from './helpers/advanceToBlock';
import { increaseTimeTo, duration } from './helpers/increaseTime';
import latestTime from './helpers/latestTime';
import EVMRevert from './helpers/EVMRevert';
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const RefundableCrowdsale = artifacts.require('./mocks/RefundableCrowdsaleImpl.sol');
contract('RefundableCrowdsale', function ([_, owner, wallet, investor]) {
const rate = new BigNumber(1000);
const goal = ether(800);
const lessThanGoal = ether(750);
before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock();
});
beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1);
this.endTime = this.startTime + duration.weeks(1);
this.afterEndTime = this.endTime + duration.seconds(1);
this.crowdsale = await RefundableCrowdsale.new(this.startTime, this.endTime, rate, wallet, goal, { from: owner });
});
describe('creating a valid crowdsale', function () {
it('should fail with zero goal', async function () {
await RefundableCrowdsale.new(this.startTime, this.endTime, rate, wallet, 0, { from: owner })
.should.be.rejectedWith(EVMRevert);
});
});
it('should deny refunds before end', async function () {
await this.crowdsale.claimRefund({ from: investor }).should.be.rejectedWith(EVMRevert);
await increaseTimeTo(this.startTime);
await this.crowdsale.claimRefund({ from: investor }).should.be.rejectedWith(EVMRevert);
});
it('should deny refunds after end if goal was reached', async function () {
await increaseTimeTo(this.startTime);
await this.crowdsale.sendTransaction({ value: goal, from: investor });
await increaseTimeTo(this.afterEndTime);
await this.crowdsale.claimRefund({ from: investor }).should.be.rejectedWith(EVMRevert);
});
it('should allow refunds after end if goal was not reached', async function () {
await increaseTimeTo(this.startTime);
await this.crowdsale.sendTransaction({ value: lessThanGoal, from: investor });
await increaseTimeTo(this.afterEndTime);
await this.crowdsale.finalize({ from: owner });
const pre = web3.eth.getBalance(investor);
await this.crowdsale.claimRefund({ from: investor, gasPrice: 0 })
.should.be.fulfilled;
const post = web3.eth.getBalance(investor);
post.minus(pre).should.be.bignumber.equal(lessThanGoal);
});
it('should forward funds to wallet after end if goal was reached', async function () {
await increaseTimeTo(this.startTime);
await this.crowdsale.sendTransaction({ value: goal, from: investor });
await increaseTimeTo(this.afterEndTime);
const pre = web3.eth.getBalance(wallet);
await this.crowdsale.finalize({ from: owner });
const post = web3.eth.getBalance(wallet);
post.minus(pre).should.be.bignumber.equal(goal);
});
});

@ -4,10 +4,9 @@ require('chai')
.use(require('chai-as-promised')) .use(require('chai-as-promised'))
.should(); .should();
const SafeERC20Helper = artifacts.require('./helpers/SafeERC20Helper.sol'); const SafeERC20Helper = artifacts.require('./mocks/SafeERC20Helper.sol');
contract('SafeERC20', function () { contract('SafeERC20', function () {
beforeEach(async function () { beforeEach(async function () {
this.helper = await SafeERC20Helper.new(); this.helper = await SafeERC20Helper.new();
}); });

@ -1,72 +1,70 @@
const assertRevert = require('./helpers/assertRevert'); const assertRevert = require('./helpers/assertRevert');
const assertJump = require('./helpers/assertJump'); const assertJump = require('./helpers/assertJump');
var SafeMathMock = artifacts.require("./helpers/SafeMathMock.sol"); var SafeMathMock = artifacts.require('./mocks/SafeMathMock.sol');
contract('SafeMath', function (accounts) { contract('SafeMath', function (accounts) {
let safeMath; let safeMath;
before(async function () { before(async function () {
safeMath = await SafeMathMock.new(); safeMath = await SafeMathMock.new();
}); });
it("multiplies correctly", async function() { it('multiplies correctly', async function () {
let a = 5678; let a = 5678;
let b = 1234; let b = 1234;
let mult = await safeMath.multiply(a, b); await safeMath.multiply(a, b);
let result = await safeMath.result(); let result = await safeMath.result();
assert.equal(result, a * b); assert.equal(result, a * b);
}); });
it("adds correctly", async function() { it('adds correctly', async function () {
let a = 5678; let a = 5678;
let b = 1234; let b = 1234;
let add = await safeMath.add(a, b); await safeMath.add(a, b);
let result = await safeMath.result(); let result = await safeMath.result();
assert.equal(result, a + b); assert.equal(result, a + b);
}); });
it("subtracts correctly", async function() { it('subtracts correctly', async function () {
let a = 5678; let a = 5678;
let b = 1234; let b = 1234;
let subtract = await safeMath.subtract(a, b); await safeMath.subtract(a, b);
let result = await safeMath.result(); let result = await safeMath.result();
assert.equal(result, a - b); assert.equal(result, a - b);
}); });
it("should throw an error if subtraction result would be negative", async function () { it('should throw an error if subtraction result would be negative', async function () {
let a = 1234; let a = 1234;
let b = 5678; let b = 5678;
try { try {
let subtract = await safeMath.subtract(a, b); await safeMath.subtract(a, b);
assert.fail('should have thrown before'); assert.fail('should have thrown before');
} catch (error) { } catch (error) {
assertJump(error); assertJump(error);
} }
}); });
it("should throw an error on addition overflow", async function() { it('should throw an error on addition overflow', async function () {
let a = 115792089237316195423570985008687907853269984665640564039457584007913129639935; let a = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
let b = 1; let b = 1;
try { try {
let add = await safeMath.add(a, b); await safeMath.add(a, b);
assert.fail('should have thrown before'); assert.fail('should have thrown before');
} catch (error) { } catch (error) {
assertRevert(error); assertRevert(error);
} }
}); });
it("should throw an error on multiplication overflow", async function() { it('should throw an error on multiplication overflow', async function () {
let a = 115792089237316195423570985008687907853269984665640564039457584007913129639933; let a = 115792089237316195423570985008687907853269984665640564039457584007913129639933;
let b = 2; let b = 2;
try { try {
let multiply = await safeMath.multiply(a, b); await safeMath.multiply(a, b);
assert.fail('should have thrown before'); assert.fail('should have thrown before');
} catch (error) { } catch (error) {
assertRevert(error); assertRevert(error);
} }
}); });
}); });

@ -1,12 +1,12 @@
import ether from './helpers/ether' import ether from './helpers/ether';
import {advanceBlock} from './helpers/advanceToBlock' import { advanceBlock } from './helpers/advanceToBlock';
import {increaseTimeTo, duration} from './helpers/increaseTime' import { increaseTimeTo, duration } from './helpers/increaseTime';
import latestTime from './helpers/latestTime' import latestTime from './helpers/latestTime';
import EVMRevert from './helpers/EVMRevert' import EVMRevert from './helpers/EVMRevert';
const BigNumber = web3.BigNumber; const BigNumber = web3.BigNumber;
const should = require('chai') require('chai')
.use(require('chai-as-promised')) .use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber)) .use(require('chai-bignumber')(BigNumber))
.should(); .should();
@ -14,16 +14,15 @@ const should = require('chai')
const SampleCrowdsale = artifacts.require('SampleCrowdsale'); const SampleCrowdsale = artifacts.require('SampleCrowdsale');
const SampleCrowdsaleToken = artifacts.require('SampleCrowdsaleToken'); const SampleCrowdsaleToken = artifacts.require('SampleCrowdsaleToken');
contract('Crowdsale', function ([owner, wallet, investor]) { contract('SampleCrowdsale', function ([owner, wallet, investor]) {
const RATE = new BigNumber(10); const RATE = new BigNumber(10);
const GOAL = ether(10); const GOAL = ether(10);
const CAP = ether(20); const CAP = ether(20);
before(async function () { before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc // Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
await advanceBlock() await advanceBlock();
}) });
beforeEach(async function () { beforeEach(async function () {
this.startTime = latestTime() + duration.weeks(1); this.startTime = latestTime() + duration.weeks(1);
@ -34,17 +33,23 @@ contract('Crowdsale', function ([owner, wallet, investor]) {
this.token = SampleCrowdsaleToken.at(await this.crowdsale.token()); this.token = SampleCrowdsaleToken.at(await this.crowdsale.token());
}); });
it('should create crowdsale with correct parameters', async function () { it('should create crowdsale with correct parameters', async function () {
this.crowdsale.should.exist; this.crowdsale.should.exist;
this.token.should.exist; this.token.should.exist;
(await this.crowdsale.startTime()).should.be.bignumber.equal(this.startTime); const startTime = await this.crowdsale.startTime();
(await this.crowdsale.endTime()).should.be.bignumber.equal(this.endTime); const endTime = await this.crowdsale.endTime();
(await this.crowdsale.rate()).should.be.bignumber.equal(RATE); const rate = await this.crowdsale.rate();
(await this.crowdsale.wallet()).should.be.equal(wallet); const walletAddress = await this.crowdsale.wallet();
(await this.crowdsale.goal()).should.be.bignumber.equal(GOAL); const goal = await this.crowdsale.goal();
(await this.crowdsale.cap()).should.be.bignumber.equal(CAP); const cap = await this.crowdsale.cap();
startTime.should.be.bignumber.equal(this.startTime);
endTime.should.be.bignumber.equal(this.endTime);
rate.should.be.bignumber.equal(RATE);
walletAddress.should.be.equal(wallet);
goal.should.be.bignumber.equal(GOAL);
cap.should.be.bignumber.equal(CAP);
}); });
it('should not accept payments before start', async function () { it('should not accept payments before start', async function () {
@ -100,5 +105,4 @@ contract('Crowdsale', function ([owner, wallet, investor]) {
const balanceAfterRefund = web3.eth.getBalance(investor); const balanceAfterRefund = web3.eth.getBalance(investor);
balanceBeforeInvestment.should.be.bignumber.equal(balanceAfterRefund); balanceBeforeInvestment.should.be.bignumber.equal(balanceAfterRefund);
}); });
}); });

@ -1,78 +0,0 @@
const BigNumber = web3.BigNumber
const should = require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
const EVMThrow = require('./helpers/EVMThrow.js')
const SplitPayment = artifacts.require('../contracts/payment/SplitPayment.sol')
contract('SplitPayment', function ([owner, payee1, payee2, payee3, nonpayee1, payer1]) {
const amount = web3.toWei(1.0, 'ether')
beforeEach(async function () {
this.payees = [payee1, payee2, payee3]
this.shares = [20, 10, 70]
this.contract = await SplitPayment.new(this.payees, this.shares)
})
it('should accept payments', async function () {
await web3.eth.sendTransaction({ from: owner, to: this.contract.address, value: amount })
const balance = web3.eth.getBalance(this.contract.address)
balance.should.be.bignumber.equal(amount)
})
it('should store shares if address is payee', async function () {
const shares = await this.contract.shares.call(payee1)
shares.should.be.bignumber.not.equal(0)
})
it('should not store shares if address is not payee', async function () {
const shares = await this.contract.shares.call(nonpayee1)
shares.should.be.bignumber.equal(0)
})
it('should throw if no funds to claim', async function () {
await this.contract.claim({from: payee1}).should.be.rejectedWith(EVMThrow)
})
it('should throw if non-payee want to claim', async function () {
await web3.eth.sendTransaction({from: payer1, to: this.contract.address, value: amount})
await this.contract.claim({from: nonpayee1}).should.be.rejectedWith(EVMThrow)
})
it('should distribute funds to payees', async function () {
await web3.eth.sendTransaction({from: payer1, to: this.contract.address, value: amount})
// receive funds
const initBalance = web3.eth.getBalance(this.contract.address)
initBalance.should.be.bignumber.equal(amount)
// distribute to payees
const initAmount1 = web3.eth.getBalance(payee1)
await this.contract.claim({from: payee1})
const profit1 = web3.eth.getBalance(payee1) - initAmount1
assert(Math.abs(profit1 - web3.toWei(0.20, 'ether')) < 1e16)
const initAmount2 = web3.eth.getBalance(payee2)
await this.contract.claim({from: payee2})
const profit2 = web3.eth.getBalance(payee2) - initAmount2
assert(Math.abs(profit2 - web3.toWei(0.10, 'ether')) < 1e16)
const initAmount3 = web3.eth.getBalance(payee3)
await this.contract.claim({from: payee3})
const profit3 = web3.eth.getBalance(payee3) - initAmount3
assert(Math.abs(profit3 - web3.toWei(0.70, 'ether')) < 1e16)
// end balance should be zero
const endBalance = web3.eth.getBalance(this.contract.address)
endBalance.should.be.bignumber.equal(0)
// check correct funds released accounting
const totalReleased = await this.contract.totalReleased.call()
totalReleased.should.be.bignumber.equal(initBalance)
})
})

@ -0,0 +1,78 @@
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const EVMThrow = require('./helpers/EVMThrow.js');
const SplitPayment = artifacts.require('../contracts/payment/SplitPayment.sol');
contract('SplitPayment', function ([owner, payee1, payee2, payee3, nonpayee1, payer1]) {
const amount = web3.toWei(1.0, 'ether');
beforeEach(async function () {
this.payees = [payee1, payee2, payee3];
this.shares = [20, 10, 70];
this.contract = await SplitPayment.new(this.payees, this.shares);
});
it('should accept payments', async function () {
await web3.eth.sendTransaction({ from: owner, to: this.contract.address, value: amount });
const balance = web3.eth.getBalance(this.contract.address);
balance.should.be.bignumber.equal(amount);
});
it('should store shares if address is payee', async function () {
const shares = await this.contract.shares.call(payee1);
shares.should.be.bignumber.not.equal(0);
});
it('should not store shares if address is not payee', async function () {
const shares = await this.contract.shares.call(nonpayee1);
shares.should.be.bignumber.equal(0);
});
it('should throw if no funds to claim', async function () {
await this.contract.claim({ from: payee1 }).should.be.rejectedWith(EVMThrow);
});
it('should throw if non-payee want to claim', async function () {
await web3.eth.sendTransaction({ from: payer1, to: this.contract.address, value: amount });
await this.contract.claim({ from: nonpayee1 }).should.be.rejectedWith(EVMThrow);
});
it('should distribute funds to payees', async function () {
await web3.eth.sendTransaction({ from: payer1, to: this.contract.address, value: amount });
// receive funds
const initBalance = web3.eth.getBalance(this.contract.address);
initBalance.should.be.bignumber.equal(amount);
// distribute to payees
const initAmount1 = web3.eth.getBalance(payee1);
await this.contract.claim({ from: payee1 });
const profit1 = web3.eth.getBalance(payee1) - initAmount1;
assert(Math.abs(profit1 - web3.toWei(0.20, 'ether')) < 1e16);
const initAmount2 = web3.eth.getBalance(payee2);
await this.contract.claim({ from: payee2 });
const profit2 = web3.eth.getBalance(payee2) - initAmount2;
assert(Math.abs(profit2 - web3.toWei(0.10, 'ether')) < 1e16);
const initAmount3 = web3.eth.getBalance(payee3);
await this.contract.claim({ from: payee3 });
const profit3 = web3.eth.getBalance(payee3) - initAmount3;
assert(Math.abs(profit3 - web3.toWei(0.70, 'ether')) < 1e16);
// end balance should be zero
const endBalance = web3.eth.getBalance(this.contract.address);
endBalance.should.be.bignumber.equal(0);
// check correct funds released accounting
const totalReleased = await this.contract.totalReleased.call();
totalReleased.should.be.bignumber.equal(initBalance);
});
});

@ -1,11 +1,9 @@
'use strict';
const assertRevert = require('./helpers/assertRevert'); const assertRevert = require('./helpers/assertRevert');
const expectThrow = require('./helpers/expectThrow');
var StandardTokenMock = artifacts.require('./helpers/StandardTokenMock.sol');
contract('StandardToken', function(accounts) { var StandardTokenMock = artifacts.require('./mocks/StandardTokenMock.sol');
contract('StandardToken', function (accounts) {
let token; let token;
beforeEach(async function () { beforeEach(async function () {
@ -88,7 +86,7 @@ contract('StandardToken', function(accounts) {
it('should start with zero', async function () { it('should start with zero', async function () {
preApproved = await token.allowance(accounts[0], accounts[1]); preApproved = await token.allowance(accounts[0], accounts[1]);
assert.equal(preApproved, 0); assert.equal(preApproved, 0);
}) });
it('should increase by 50 then decrease by 10', async function () { it('should increase by 50 then decrease by 10', async function () {
await token.increaseApproval(accounts[1], 50); await token.increaseApproval(accounts[1], 50);
@ -97,7 +95,7 @@ contract('StandardToken', function(accounts) {
await token.decreaseApproval(accounts[1], 10); await token.decreaseApproval(accounts[1], 10);
let postDecrease = await token.allowance(accounts[0], accounts[1]); let postDecrease = await token.allowance(accounts[0], accounts[1]);
postIncrease.minus(10).should.be.bignumber.equal(postDecrease); postIncrease.minus(10).should.be.bignumber.equal(postDecrease);
}) });
}); });
it('should increase by 50 then set to 0 when decreasing by more than 50', async function () { it('should increase by 50 then set to 0 when decreasing by more than 50', async function () {
@ -110,7 +108,7 @@ contract('StandardToken', function(accounts) {
it('should throw an error when trying to transfer to 0x0', async function () { it('should throw an error when trying to transfer to 0x0', async function () {
let token = await StandardTokenMock.new(accounts[0], 100); let token = await StandardTokenMock.new(accounts[0], 100);
try { try {
let transfer = await token.transfer(0x0, 100); await token.transfer(0x0, 100);
assert.fail('should have thrown before'); assert.fail('should have thrown before');
} catch (error) { } catch (error) {
assertRevert(error); assertRevert(error);
@ -121,11 +119,10 @@ contract('StandardToken', function(accounts) {
let token = await StandardTokenMock.new(accounts[0], 100); let token = await StandardTokenMock.new(accounts[0], 100);
await token.approve(accounts[1], 100); await token.approve(accounts[1], 100);
try { try {
let transfer = await token.transferFrom(accounts[0], 0x0, 100, {from: accounts[1]}); await token.transferFrom(accounts[0], 0x0, 100, { from: accounts[1] });
assert.fail('should have thrown before'); assert.fail('should have thrown before');
} catch (error) { } catch (error) {
assertRevert(error); assertRevert(error);
} }
}); });
}); });

@ -1,7 +1,6 @@
'use strict';
var TokenDestructible = artifacts.require('../contracts/lifecycle/TokenDestructible.sol'); var TokenDestructible = artifacts.require('../contracts/lifecycle/TokenDestructible.sol');
var StandardTokenMock = artifacts.require("./helpers/StandardTokenMock.sol"); var StandardTokenMock = artifacts.require('./mocks/StandardTokenMock.sol');
require('./helpers/transactionMined.js'); require('./helpers/transactionMined.js');
contract('TokenDestructible', function (accounts) { contract('TokenDestructible', function (accounts) {

@ -1,57 +0,0 @@
const BigNumber = web3.BigNumber
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
import latestTime from './helpers/latestTime'
import {increaseTimeTo, duration} from './helpers/increaseTime'
const MintableToken = artifacts.require('MintableToken')
const TokenTimelock = artifacts.require('TokenTimelock')
contract('TokenTimelock', function ([_, owner, beneficiary]) {
const amount = new BigNumber(100)
beforeEach(async function () {
this.token = await MintableToken.new({from: owner})
this.releaseTime = latestTime() + duration.years(1)
this.timelock = await TokenTimelock.new(this.token.address, beneficiary, this.releaseTime)
await this.token.mint(this.timelock.address, amount, {from: owner})
})
it('cannot be released before time limit', async function () {
await this.timelock.release().should.be.rejected
})
it('cannot be released just before time limit', async function () {
await increaseTimeTo(this.releaseTime - duration.seconds(3))
await this.timelock.release().should.be.rejected
})
it('can be released just after limit', async function () {
await increaseTimeTo(this.releaseTime + duration.seconds(1))
await this.timelock.release().should.be.fulfilled
const balance = await this.token.balanceOf(beneficiary)
balance.should.be.bignumber.equal(amount)
})
it('can be released after time limit', async function () {
await increaseTimeTo(this.releaseTime + duration.years(1))
await this.timelock.release().should.be.fulfilled
const balance = await this.token.balanceOf(beneficiary)
balance.should.be.bignumber.equal(amount)
})
it('cannot be released twice', async function () {
await increaseTimeTo(this.releaseTime + duration.years(1))
await this.timelock.release().should.be.fulfilled
await this.timelock.release().should.be.rejected
const balance = await this.token.balanceOf(beneficiary)
balance.should.be.bignumber.equal(amount)
})
})

@ -0,0 +1,54 @@
import latestTime from './helpers/latestTime';
import { increaseTimeTo, duration } from './helpers/increaseTime';
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const MintableToken = artifacts.require('MintableToken');
const TokenTimelock = artifacts.require('TokenTimelock');
contract('TokenTimelock', function ([_, owner, beneficiary]) {
const amount = new BigNumber(100);
beforeEach(async function () {
this.token = await MintableToken.new({ from: owner });
this.releaseTime = latestTime() + duration.years(1);
this.timelock = await TokenTimelock.new(this.token.address, beneficiary, this.releaseTime);
await this.token.mint(this.timelock.address, amount, { from: owner });
});
it('cannot be released before time limit', async function () {
await this.timelock.release().should.be.rejected;
});
it('cannot be released just before time limit', async function () {
await increaseTimeTo(this.releaseTime - duration.seconds(3));
await this.timelock.release().should.be.rejected;
});
it('can be released just after limit', async function () {
await increaseTimeTo(this.releaseTime + duration.seconds(1));
await this.timelock.release().should.be.fulfilled;
const balance = await this.token.balanceOf(beneficiary);
balance.should.be.bignumber.equal(amount);
});
it('can be released after time limit', async function () {
await increaseTimeTo(this.releaseTime + duration.years(1));
await this.timelock.release().should.be.fulfilled;
const balance = await this.token.balanceOf(beneficiary);
balance.should.be.bignumber.equal(amount);
});
it('cannot be released twice', async function () {
await increaseTimeTo(this.releaseTime + duration.years(1));
await this.timelock.release().should.be.fulfilled;
await this.timelock.release().should.be.rejected;
const balance = await this.token.balanceOf(beneficiary);
balance.should.be.bignumber.equal(amount);
});
});

@ -1,19 +1,18 @@
const BigNumber = web3.BigNumber import EVMRevert from './helpers/EVMRevert';
import latestTime from './helpers/latestTime';
import { increaseTimeTo, duration } from './helpers/increaseTime';
const BigNumber = web3.BigNumber;
require('chai') require('chai')
.use(require('chai-as-promised')) .use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber)) .use(require('chai-bignumber')(BigNumber))
.should(); .should();
import EVMRevert from './helpers/EVMRevert'
import latestTime from './helpers/latestTime';
import {increaseTimeTo, duration} from './helpers/increaseTime';
const MintableToken = artifacts.require('MintableToken'); const MintableToken = artifacts.require('MintableToken');
const TokenVesting = artifacts.require('TokenVesting'); const TokenVesting = artifacts.require('TokenVesting');
contract('TokenVesting', function ([_, owner, beneficiary]) { contract('TokenVesting', function ([_, owner, beneficiary]) {
const amount = new BigNumber(1000); const amount = new BigNumber(1000);
beforeEach(async function () { beforeEach(async function () {
@ -105,11 +104,10 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
it('should fail to be revoked a second time', async function () { it('should fail to be revoked a second time', async function () {
await increaseTimeTo(this.start + this.cliff + duration.weeks(12)); await increaseTimeTo(this.start + this.cliff + duration.weeks(12));
const vested = await this.vesting.vestedAmount(this.token.address); await this.vesting.vestedAmount(this.token.address);
await this.vesting.revoke(this.token.address, { from: owner }); await this.vesting.revoke(this.token.address, { from: owner });
await this.vesting.revoke(this.token.address, { from: owner }).should.be.rejectedWith(EVMRevert); await this.vesting.revoke(this.token.address, { from: owner }).should.be.rejectedWith(EVMRevert);
}); });
}); });

@ -1 +1 @@
export default 'revert' export default 'revert';

@ -1 +1 @@
export default 'invalid opcode' export default 'invalid opcode';

@ -5,18 +5,18 @@ export function advanceBlock() {
method: 'evm_mine', method: 'evm_mine',
id: Date.now(), id: Date.now(),
}, (err, res) => { }, (err, res) => {
return err ? reject(err) : resolve(res) return err ? reject(err) : resolve(res);
}) });
}) });
} }
// Advances the block number so that the last mined block is `number`. // Advances the block number so that the last mined block is `number`.
export default async function advanceToBlock (number) { export default async function advanceToBlock (number) {
if (web3.eth.blockNumber > number) { if (web3.eth.blockNumber > number) {
throw Error(`block number ${number} is in the past (current is ${web3.eth.blockNumber})`) throw Error(`block number ${number} is in the past (current is ${web3.eth.blockNumber})`);
} }
while (web3.eth.blockNumber < number) { while (web3.eth.blockNumber < number) {
await advanceBlock() await advanceBlock();
} }
} }

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

@ -1,3 +1,3 @@
module.exports = function (error) { module.exports = function (error) {
assert.isAbove(error.message.search('revert'), -1, 'Error containing "revert" must be returned'); assert.isAbove(error.message.search('revert'), -1, 'Error containing "revert" must be returned');
} };

@ -1,3 +1,3 @@
export default function ether (n) { export default function ether (n) {
return new web3.BigNumber(web3.toWei(n, 'ether')) return new web3.BigNumber(web3.toWei(n, 'ether'));
} }

@ -13,7 +13,7 @@ export default async promise => {
const revert = error.message.search('revert') >= 0; const revert = error.message.search('revert') >= 0;
assert( assert(
invalidOpcode || outOfGas || revert, invalidOpcode || outOfGas || revert,
"Expected throw, got '" + error + "' instead", 'Expected throw, got \'' + error + '\' instead',
); );
return; return;
} }

@ -2,7 +2,7 @@ import utils from 'ethereumjs-util';
// Hash and add same prefix to the hash that testrpc use. // Hash and add same prefix to the hash that testrpc use.
module.exports = function (message) { module.exports = function (message) {
const messageHex = new Buffer(utils.sha3(message).toString('hex'), 'hex'); const messageHex = Buffer.from(utils.sha3(message).toString('hex'), 'hex');
const prefix = utils.toBuffer('\u0019Ethereum Signed Message:\n' + messageHex.length.toString()); const prefix = utils.toBuffer('\u0019Ethereum Signed Message:\n' + messageHex.length.toString());
return utils.bufferToHex(utils.sha3(Buffer.concat([prefix, messageHex]))); return utils.bufferToHex(utils.sha3(Buffer.concat([prefix, messageHex])));
}; };

@ -1,8 +1,8 @@
import latestTime from './latestTime' import latestTime from './latestTime';
// Increases testrpc time by the passed duration in seconds // Increases testrpc time by the passed duration in seconds
export default function increaseTime (duration) { export default function increaseTime (duration) {
const id = Date.now() const id = Date.now();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
web3.currentProvider.sendAsync({ web3.currentProvider.sendAsync({
@ -11,17 +11,17 @@ export default function increaseTime(duration) {
params: [duration], params: [duration],
id: id, id: id,
}, err1 => { }, err1 => {
if (err1) return reject(err1) if (err1) return reject(err1);
web3.currentProvider.sendAsync({ web3.currentProvider.sendAsync({
jsonrpc: '2.0', jsonrpc: '2.0',
method: 'evm_mine', method: 'evm_mine',
id: id + 1, id: id + 1,
}, (err2, res) => { }, (err2, res) => {
return err2 ? reject(err2) : resolve(res) return err2 ? reject(err2) : resolve(res);
}) });
}) });
}) });
} }
/** /**
@ -39,10 +39,10 @@ export function increaseTimeTo(target) {
} }
export const duration = { export const duration = {
seconds: function(val) { return val}, seconds: function (val) { return val; },
minutes: function(val) { return val * this.seconds(60) }, minutes: function (val) { return val * this.seconds(60); },
hours: function(val) { return val * this.minutes(60) }, hours: function (val) { return val * this.minutes(60); },
days: function(val) { return val * this.hours(24) }, days: function (val) { return val * this.hours(24); },
weeks: function(val) { return val * this.days(7) }, weeks: function (val) { return val * this.days(7); },
years: function(val) { return val * this.days(365)} years: function (val) { return val * this.days(365); },
}; };

@ -1,4 +1,4 @@
import { sha3, bufferToHex } from "ethereumjs-util"; import { sha3, bufferToHex } from 'ethereumjs-util';
export default class MerkleTree { export default class MerkleTree {
constructor (elements) { constructor (elements) {
@ -15,8 +15,8 @@ export default class MerkleTree {
} }
getLayers (elements) { getLayers (elements) {
if (elements.length == 0) { if (elements.length === 0) {
return [[""]]; return [['']];
} }
const layers = []; const layers = [];
@ -60,7 +60,7 @@ export default class MerkleTree {
let idx = this.bufIndexOf(el, this.elements); let idx = this.bufIndexOf(el, this.elements);
if (idx === -1) { if (idx === -1) {
throw new Error("Element does not exist in Merkle tree"); throw new Error('Element does not exist in Merkle tree');
} }
return this.layers.reduce((proof, layer) => { return this.layers.reduce((proof, layer) => {
@ -119,10 +119,10 @@ export default class MerkleTree {
bufArrToHex (arr) { bufArrToHex (arr) {
if (arr.some(el => !Buffer.isBuffer(el))) { if (arr.some(el => !Buffer.isBuffer(el))) {
throw new Error("Array is not an array of buffers"); throw new Error('Array is not an array of buffers');
} }
return "0x" + arr.map(el => el.toString("hex")).join(""); return '0x' + arr.map(el => el.toString('hex')).join('');
} }
sortAndConcat (...args) { sortAndConcat (...args) {

@ -1,4 +1,4 @@
export default func => export default func =>
(...args) => (...args) =>
new Promise((accept, reject) => new Promise((resolve, reject) =>
func(...args, (error, data) => error ? reject(error) : accept(data))); func(...args, (error, data) => error ? reject(error) : resolve(data)));

@ -1,9 +1,8 @@
'use strict';
// from https://gist.github.com/xavierlepretre/88682e871f4ad07be4534ae560692ee6 // from https://gist.github.com/xavierlepretre/88682e871f4ad07be4534ae560692ee6
module.export = web3.eth.transactionMined = function (txnHash, interval) { module.export = web3.eth.transactionMined = function (txnHash, interval) {
var transactionReceiptAsync; var transactionReceiptAsync;
interval = interval ? interval : 500; interval = interval || 500;
transactionReceiptAsync = function (txnHash, resolve, reject) { transactionReceiptAsync = function (txnHash, resolve, reject) {
try { try {
var receipt = web3.eth.getTransactionReceipt(txnHash); var receipt = web3.eth.getTransactionReceipt(txnHash);

@ -1,32 +1,48 @@
require('dotenv').config();
require('babel-register'); require('babel-register');
require('babel-polyfill'); require('babel-polyfill');
var provider; const HDWalletProvider = require('truffle-hdwallet-provider');
var HDWalletProvider = require('truffle-hdwallet-provider');
var mnemonic = '[REDACTED]';
if (!process.env.SOLIDITY_COVERAGE){ const providerWithMnemonic = (mnemonic, rpcEndpoint) =>
provider = new HDWalletProvider(mnemonic, 'https://ropsten.infura.io/') new HDWalletProvider(mnemonic, rpcEndpoint);
}
const infuraProvider = network => providerWithMnemonic(
process.env.MNEMONIC || '',
`https://${network}.infura.io/${process.env.INFURA_API_KEY}`
);
const ropstenProvider = process.env.SOLIDITY_COVERAGE
? undefined
: infuraProvider('ropsten');
module.exports = { module.exports = {
networks: { networks: {
development: { development: {
host: 'localhost', host: 'localhost',
port: 8545, port: 8545,
network_id: '*' network_id: '*', // eslint-disable-line camelcase
}, },
ropsten: { ropsten: {
provider: provider, provider: ropstenProvider,
network_id: 3 // official id of the ropsten network network_id: 3, // eslint-disable-line camelcase
}, },
coverage: { coverage: {
host: "localhost", host: 'localhost',
network_id: "*", network_id: '*', // eslint-disable-line camelcase
port: 8555, port: 8555,
gas: 0xfffffffffff, gas: 0xfffffffffff,
gasPrice: 0x01 gasPrice: 0x01,
} },
} testrpc: {
host: 'localhost',
port: 8545,
network_id: '*', // eslint-disable-line camelcase
},
ganache: {
host: 'localhost',
port: 7545,
network_id: '*', // eslint-disable-line camelcase
},
},
}; };

Loading…
Cancel
Save