Commit 49522406 by Francisco Giordano

Merge tag 'v2.1.2' of github.com:OpenZeppelin/openzeppelin-solidity into merge-v2.1

v2.1.2
parents 00f7c19d 8617c4b4
...@@ -38,9 +38,4 @@ build/ ...@@ -38,9 +38,4 @@ build/
# truffle # truffle
.node-xmlhttprequest-* .node-xmlhttprequest-*
<<<<<<< HEAD
.zos.session .zos.session
=======
# Temporary directory for 0.5.x compilation
solc-0.5
>>>>>>> 8fc0a3af313d9372fc9b8d3e5dc57b804df0588e
...@@ -25,10 +25,11 @@ jobs: ...@@ -25,10 +25,11 @@ jobs:
name: "Unit tests" name: "Unit tests"
script: npm run test script: npm run test
- stage: tests # solidity-coverage fails at parsing 0.5.x code
name: "Unit tests with coverage report" # - stage: tests
script: npm run test # name: "Unit tests with coverage report"
env: SOLIDITY_COVERAGE=true # script: npm run test
# env: SOLIDITY_COVERAGE=true
- stage: tests - stage: tests
name: "Unit tests using solc nightly" name: "Unit tests using solc nightly"
......
# Changelog # Changelog
## 2.2.0 (unreleased)
## 2.1.2 (2019-17-01)
* Removed most of the test suite from the npm package, except `PublicRole.behavior.js`, which may be useful to users testing their own `Roles`.
## 2.1.1 (2019-04-01) ## 2.1.1 (2019-04-01)
* Version bump to avoid conflict in the npm registry. * Version bump to avoid conflict in the npm registry.
......
{ {
"package_name": "zeppelin", "package_name": "zeppelin",
"version": "2.1.1", "version": "2.1.2",
"description": "Secure Smart Contract library for Solidity", "description": "Secure Smart Contract library for Solidity",
"authors": [ "authors": [
"OpenZeppelin Community <maintainers@openzeppelin.org>" "OpenZeppelin Community <maintainers@openzeppelin.org>"
......
This source diff could not be displayed because it is too large. You can view the blob instead.
{ {
"name": "openzeppelin-eth", "name": "openzeppelin-eth",
"version": "2.1.1", "version": "2.1.2",
"description": "Secure Smart Contract library for Solidity", "description": "Secure Smart Contract library for Solidity",
"files": [ "files": [
"build", "build",
"contracts", "contracts",
"test", "test/behaviors",
"zos.json", "zos.json",
"zos.*.json" "zos.*.json"
], ],
"scripts": { "scripts": {
"build": "scripts/build.sh", "build": "scripts/build.sh",
"compile": "scripts/compile.sh", "compile": "truffle compile",
"console": "truffle console", "console": "truffle console",
"coverage": "scripts/coverage.sh", "coverage": "scripts/coverage.sh",
"lint": "npm run lint:js && npm run lint:sol", "lint": "npm run lint:js && npm run lint:sol",
...@@ -43,7 +43,6 @@ ...@@ -43,7 +43,6 @@
"homepage": "https://github.com/OpenZeppelin/openzeppelin-eth", "homepage": "https://github.com/OpenZeppelin/openzeppelin-eth",
"devDependencies": { "devDependencies": {
"chai": "^4.1.2", "chai": "^4.1.2",
"chai-bignumber": "^2.0.2",
"coveralls": "^3.0.1", "coveralls": "^3.0.1",
"eslint": "^4.19.1", "eslint": "^4.19.1",
"eslint-config-standard": "^10.2.1", "eslint-config-standard": "^10.2.1",
...@@ -56,11 +55,11 @@ ...@@ -56,11 +55,11 @@
"ethjs-abi": "^0.2.1", "ethjs-abi": "^0.2.1",
"ganache-cli": "6.1.8", "ganache-cli": "6.1.8",
"npm-install-peers": "^1.2.1", "npm-install-peers": "^1.2.1",
"openzeppelin-test-helpers": "^0.1.1",
"pify": "^4.0.1", "pify": "^4.0.1",
"solhint": "^1.5.0", "solhint": "^1.5.0",
"solidity-coverage": "^0.5.4", "solidity-coverage": "^0.5.4",
"truffle": "^4.1.13", "truffle": "^5.0.0",
"web3-utils": "^1.0.0-beta.34",
"zos": "^2.0.0", "zos": "^2.0.0",
"zos-lib": "^2.1.0" "zos-lib": "^2.1.0"
}, },
......
#!/usr/bin/env bash
# Configure to exit script as soon as a command fails.
set -o errexit
SOLC_05_DIR=solc-0.5
# Delete any previous build artifacts
rm -rf build/
# Create a subproject where 0.5.x compilation will take place
mkdir -p "$SOLC_05_DIR"
cd "$SOLC_05_DIR"
echo '{ "private": true }' > package.json
npm install --save-dev truffle@5.0.0
rm -rf contracts
ln --symbolic ../contracts contracts
# Delete any previous build artifacts
rm -rf build/
# Compile
echo "
module.exports = {
compilers: {
solc: {
version: \"0.5.0\",
},
},
};
" > truffle-config.js
npx truffle compile
# Modify the paths in the artifacts to make it look as if they were built in the root
sed --in-place --expression "s/\/$SOLC_05_DIR//g" build/contracts/*.json
# Copy them back into the root
cd ..
cp --recursive "$SOLC_05_DIR"/build build
const shouldFail = require('../helpers/shouldFail'); const { shouldFail, constants } = require('openzeppelin-test-helpers');
const { ZERO_ADDRESS } = require('../helpers/constants'); const { ZERO_ADDRESS } = constants;
const RolesMock = artifacts.require('RolesMock'); const RolesMock = artifacts.require('RolesMock');
require('./../helpers/setup');
contract('Roles', function ([_, authorized, otherAuthorized, anyone]) { contract('Roles', function ([_, authorized, otherAuthorized, anyone]) {
beforeEach(async function () { beforeEach(async function () {
this.roles = await RolesMock.new(); this.roles = await RolesMock.new();
......
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const CapperRoleMock = artifacts.require('CapperRoleMock'); const CapperRoleMock = artifacts.require('CapperRoleMock');
contract('CapperRole', function ([_, capper, otherCapper, ...otherAccounts]) { contract('CapperRole', function ([_, capper, otherCapper, ...otherAccounts]) {
......
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const MinterRoleMock = artifacts.require('MinterRoleMock'); const MinterRoleMock = artifacts.require('MinterRoleMock');
contract('MinterRole', function ([_, minter, otherMinter, ...otherAccounts]) { contract('MinterRole', function ([_, minter, otherMinter, ...otherAccounts]) {
......
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const PauserRoleMock = artifacts.require('PauserRoleMock'); const PauserRoleMock = artifacts.require('PauserRoleMock');
contract('PauserRole', function ([_, pauser, otherPauser, ...otherAccounts]) { contract('PauserRole', function ([_, pauser, otherPauser, ...otherAccounts]) {
......
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const SignerRoleMock = artifacts.require('SignerRoleMock'); const SignerRoleMock = artifacts.require('SignerRoleMock');
contract('SignerRole', function ([_, signer, otherSigner, ...otherAccounts]) { contract('SignerRole', function ([_, signer, otherSigner, ...otherAccounts]) {
......
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const WhitelistAdminRoleMock = artifacts.require('WhitelistAdminRoleMock'); const WhitelistAdminRoleMock = artifacts.require('WhitelistAdminRoleMock');
contract('WhitelistAdminRole', function ([_, whitelistAdmin, otherWhitelistAdmin, ...otherAccounts]) { contract('WhitelistAdminRole', function ([_, whitelistAdmin, otherWhitelistAdmin, ...otherAccounts]) {
......
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const WhitelistedRoleMock = artifacts.require('WhitelistedRoleMock'); const WhitelistedRoleMock = artifacts.require('WhitelistedRoleMock');
contract('WhitelistedRole', function ([_, whitelisted, otherWhitelisted, whitelistAdmin, ...otherAccounts]) { contract('WhitelistedRole', function ([_, whitelisted, otherWhitelisted, whitelistAdmin, ...otherAccounts]) {
......
const shouldFail = require('../../helpers/shouldFail'); const { shouldFail, constants, expectEvent } = require('openzeppelin-test-helpers');
const { ZERO_ADDRESS } = require('../../helpers/constants'); const { ZERO_ADDRESS } = constants;
const expectEvent = require('../../helpers/expectEvent');
require('../../helpers/setup');
function capitalize (str) { function capitalize (str) {
return str.replace(/\b\w/g, l => l.toUpperCase()); return str.replace(/\b\w/g, l => l.toUpperCase());
} }
// Tests that a role complies with the standard role interface, that is:
// * an onlyRole modifier
// * an isRole function
// * an addRole function, accessible to role havers
// * a renounceRole function
// * roleAdded and roleRemoved events
// Both the modifier and an additional internal remove function are tested through a mock contract that exposes them.
// This mock contract should be stored in this.contract.
//
// @param authorized an account that has the role
// @param otherAuthorized another account that also has the role
// @param anyone an account that doesn't have the role, passed inside an array for ergonomics
// @param rolename a string with the name of the role
// @param manager undefined for regular roles, or a manager account for managed roles. In these, only the manager
// account can create and remove new role bearers.
function shouldBehaveLikePublicRole (authorized, otherAuthorized, [anyone], rolename, manager) { function shouldBehaveLikePublicRole (authorized, otherAuthorized, [anyone], rolename, manager) {
rolename = capitalize(rolename); rolename = capitalize(rolename);
......
const expectEvent = require('../helpers/expectEvent'); const { balance, BN, constants, ether, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const { ether } = require('../helpers/ether'); const { ZERO_ADDRESS } = constants;
const shouldFail = require('../helpers/shouldFail');
const { balanceDifference } = require('../helpers/balanceDifference');
const { ZERO_ADDRESS } = require('../helpers/constants');
const { BigNumber } = require('../helpers/setup');
const AllowanceCrowdsaleImpl = artifacts.require('AllowanceCrowdsaleImpl'); const AllowanceCrowdsaleImpl = artifacts.require('AllowanceCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenWallet]) { contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenWallet]) {
const rate = new BigNumber(1); const rate = new BN('1');
const value = ether(0.42); const value = ether('0.42');
const expectedTokenAmount = rate.mul(value); const expectedTokenAmount = rate.mul(value);
const tokenAllowance = new BigNumber('1e22'); const tokenAllowance = new BN('10').pow(new BN('22'));
beforeEach(async function () { beforeEach(async function () {
this.token = await SimpleToken.new({ from: tokenWallet }); this.token = await SimpleToken.new({ from: tokenWallet });
...@@ -52,7 +47,7 @@ contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenW ...@@ -52,7 +47,7 @@ contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenW
}); });
it('should forward funds to wallet', async function () { it('should forward funds to wallet', async function () {
(await balanceDifference(wallet, () => (await balance.difference(wallet, () =>
this.crowdsale.sendTransaction({ value, from: investor })) this.crowdsale.sendTransaction({ value, from: investor }))
).should.be.bignumber.equal(value); ).should.be.bignumber.equal(value);
}); });
...@@ -60,7 +55,7 @@ contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenW ...@@ -60,7 +55,7 @@ contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenW
describe('check remaining allowance', function () { describe('check remaining allowance', function () {
it('should report correct allowace left', async function () { it('should report correct allowace left', async function () {
const remainingAllowance = tokenAllowance - expectedTokenAmount; const remainingAllowance = tokenAllowance.sub(expectedTokenAmount);
await this.crowdsale.buyTokens(investor, { value: value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value: value, from: purchaser });
(await this.crowdsale.remainingTokens()).should.be.bignumber.equal(remainingAllowance); (await this.crowdsale.remainingTokens()).should.be.bignumber.equal(remainingAllowance);
}); });
...@@ -68,7 +63,7 @@ contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenW ...@@ -68,7 +63,7 @@ contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenW
context('when the allowance is larger than the token amount', function () { context('when the allowance is larger than the token amount', function () {
beforeEach(async function () { beforeEach(async function () {
const amount = await this.token.balanceOf(tokenWallet); const amount = await this.token.balanceOf(tokenWallet);
await this.token.approve(this.crowdsale.address, amount.plus(1), { from: tokenWallet }); await this.token.approve(this.crowdsale.address, amount.addn(1), { from: tokenWallet });
}); });
it('should report the amount instead of the allowance', async function () { it('should report the amount instead of the allowance', async function () {
......
const { ether } = require('../helpers/ether'); const { BN, ether, shouldFail } = require('openzeppelin-test-helpers');
const shouldFail = require('../helpers/shouldFail');
const { BigNumber } = require('../helpers/setup');
const CappedCrowdsaleImpl = artifacts.require('CappedCrowdsaleImpl'); const CappedCrowdsaleImpl = artifacts.require('CappedCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('CappedCrowdsale', function ([_, wallet]) { contract('CappedCrowdsale', function ([_, wallet]) {
const rate = new BigNumber(1); const rate = new BN('1');
const cap = ether(100); const cap = ether('100');
const lessThanCap = ether(60); const lessThanCap = ether('60');
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
beforeEach(async function () { beforeEach(async function () {
this.token = await SimpleToken.new(); this.token = await SimpleToken.new();
...@@ -28,7 +25,7 @@ contract('CappedCrowdsale', function ([_, wallet]) { ...@@ -28,7 +25,7 @@ contract('CappedCrowdsale', function ([_, wallet]) {
describe('accepting payments', function () { describe('accepting payments', function () {
it('should accept payments within cap', async function () { it('should accept payments within cap', async function () {
await this.crowdsale.send(cap.minus(lessThanCap)); await this.crowdsale.send(cap.sub(lessThanCap));
await this.crowdsale.send(lessThanCap); await this.crowdsale.send(lessThanCap);
}); });
...@@ -38,7 +35,7 @@ contract('CappedCrowdsale', function ([_, wallet]) { ...@@ -38,7 +35,7 @@ contract('CappedCrowdsale', function ([_, wallet]) {
}); });
it('should reject payments that exceed cap', async function () { it('should reject payments that exceed cap', async function () {
await shouldFail.reverting(this.crowdsale.send(cap.plus(1))); await shouldFail.reverting(this.crowdsale.send(cap.addn(1)));
}); });
}); });
...@@ -49,7 +46,7 @@ contract('CappedCrowdsale', function ([_, wallet]) { ...@@ -49,7 +46,7 @@ contract('CappedCrowdsale', function ([_, wallet]) {
}); });
it('should not reach cap if sent just under cap', async function () { it('should not reach cap if sent just under cap', async function () {
await this.crowdsale.send(cap.minus(1)); await this.crowdsale.send(cap.subn(1));
(await this.crowdsale.capReached()).should.equal(false); (await this.crowdsale.capReached()).should.equal(false);
}); });
......
const expectEvent = require('../helpers/expectEvent'); const { balance, BN, constants, ether, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const shouldFail = require('../helpers/shouldFail'); const { ZERO_ADDRESS } = constants;
const { balanceDifference } = require('../helpers/balanceDifference');
const { ether } = require('../helpers/ether');
const { ZERO_ADDRESS } = require('../helpers/constants');
const { BigNumber } = require('../helpers/setup');
const Crowdsale = artifacts.require('CrowdsaleMock'); const Crowdsale = artifacts.require('CrowdsaleMock');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('Crowdsale', function ([_, investor, wallet, purchaser]) { contract('Crowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BigNumber(1); const rate = new BN(1);
const value = ether(42); const value = ether('42');
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
const expectedTokenAmount = rate.mul(value); const expectedTokenAmount = rate.mul(value);
it('requires a non-null token', async function () { it('requires a non-null token', async function () {
...@@ -93,7 +88,7 @@ contract('Crowdsale', function ([_, investor, wallet, purchaser]) { ...@@ -93,7 +88,7 @@ contract('Crowdsale', function ([_, investor, wallet, purchaser]) {
}); });
it('should forward funds to wallet', async function () { it('should forward funds to wallet', async function () {
(await balanceDifference(wallet, () => (await balance.difference(wallet, () =>
this.crowdsale.sendTransaction({ value, from: investor })) this.crowdsale.sendTransaction({ value, from: investor }))
).should.be.bignumber.equal(value); ).should.be.bignumber.equal(value);
}); });
...@@ -116,7 +111,7 @@ contract('Crowdsale', function ([_, investor, wallet, purchaser]) { ...@@ -116,7 +111,7 @@ contract('Crowdsale', function ([_, investor, wallet, purchaser]) {
}); });
it('should forward funds to wallet', async function () { it('should forward funds to wallet', async function () {
(await balanceDifference(wallet, () => (await balance.difference(wallet, () =>
this.crowdsale.buyTokens(investor, { value, from: purchaser })) this.crowdsale.buyTokens(investor, { value, from: purchaser }))
).should.be.bignumber.equal(value); ).should.be.bignumber.equal(value);
}); });
......
const expectEvent = require('../helpers/expectEvent'); const { BN, expectEvent, shouldFail, time } = require('openzeppelin-test-helpers');
const time = require('../helpers/time');
const shouldFail = require('../helpers/shouldFail');
const { BigNumber } = require('../helpers/setup');
const FinalizableCrowdsaleImpl = artifacts.require('FinalizableCrowdsaleImpl'); const FinalizableCrowdsaleImpl = artifacts.require('FinalizableCrowdsaleImpl');
const ERC20 = artifacts.require('ERC20'); const ERC20 = artifacts.require('ERC20');
contract('FinalizableCrowdsale', function ([_, wallet, anyone]) { contract('FinalizableCrowdsale', function ([_, wallet, anyone]) {
const rate = new BigNumber(1000); const rate = new BN('1000');
before(async function () { before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache // Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache
...@@ -16,9 +12,9 @@ contract('FinalizableCrowdsale', function ([_, wallet, anyone]) { ...@@ -16,9 +12,9 @@ contract('FinalizableCrowdsale', function ([_, wallet, anyone]) {
}); });
beforeEach(async function () { beforeEach(async function () {
this.openingTime = (await time.latest()) + time.duration.weeks(1); this.openingTime = (await time.latest()).add(time.duration.weeks(1));
this.closingTime = this.openingTime + time.duration.weeks(1); this.closingTime = this.openingTime.add(time.duration.weeks(1));
this.afterClosingTime = this.closingTime + time.duration.seconds(1); this.afterClosingTime = this.closingTime.add(time.duration.seconds(1));
this.token = await ERC20.new(); this.token = await ERC20.new();
this.crowdsale = await FinalizableCrowdsaleImpl.new( this.crowdsale = await FinalizableCrowdsaleImpl.new(
......
const { ether } = require('../helpers/ether'); const { BN, ether, shouldFail, time } = require('openzeppelin-test-helpers');
const time = require('../helpers/time');
const shouldFail = require('../helpers/shouldFail');
const { BigNumber } = require('../helpers/setup');
const IncreasingPriceCrowdsaleImpl = artifacts.require('IncreasingPriceCrowdsaleImpl'); const IncreasingPriceCrowdsaleImpl = artifacts.require('IncreasingPriceCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('IncreasingPriceCrowdsale', function ([_, investor, wallet, purchaser]) { contract('IncreasingPriceCrowdsale', function ([_, investor, wallet, purchaser]) {
const value = ether(1); const value = ether('1');
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
describe('rate during crowdsale should change at a fixed step every block', async function () { describe('rate during crowdsale should change at a fixed step every block', async function () {
const initialRate = new BigNumber(9166); const initialRate = new BN('9166');
const finalRate = new BigNumber(5500); const finalRate = new BN('5500');
const rateAtTime150 = new BigNumber(9166); const rateAtTime150 = new BN('9166');
const rateAtTime300 = new BigNumber(9165); const rateAtTime300 = new BN('9165');
const rateAtTime1500 = new BigNumber(9157); const rateAtTime1500 = new BN('9157');
const rateAtTime30 = new BigNumber(9166); const rateAtTime30 = new BN('9166');
const rateAtTime150000 = new BigNumber(8257); const rateAtTime150000 = new BN('8257');
const rateAtTime450000 = new BigNumber(6439); const rateAtTime450000 = new BN('6439');
beforeEach(async function () { beforeEach(async function () {
await time.advanceBlock(); await time.advanceBlock();
this.startTime = (await time.latest()) + time.duration.weeks(1); this.startTime = (await time.latest()).add(time.duration.weeks(1));
this.closingTime = this.startTime + time.duration.weeks(1); this.closingTime = this.startTime.add(time.duration.weeks(1));
this.afterClosingTime = this.closingTime + time.duration.seconds(1); this.afterClosingTime = this.closingTime.add(time.duration.seconds(1));
this.token = await SimpleToken.new(); this.token = await SimpleToken.new();
}); });
it('reverts with a final rate larger than the initial rate', async function () { it('reverts with a final rate larger than the initial rate', async function () {
await shouldFail.reverting(IncreasingPriceCrowdsaleImpl.new( await shouldFail.reverting(IncreasingPriceCrowdsaleImpl.new(
this.startTime, this.closingTime, wallet, this.token.address, initialRate, initialRate.plus(1) this.startTime, this.closingTime, wallet, this.token.address, initialRate, initialRate.addn(1)
)); ));
}); });
...@@ -65,12 +61,12 @@ contract('IncreasingPriceCrowdsale', function ([_, investor, wallet, purchaser]) ...@@ -65,12 +61,12 @@ contract('IncreasingPriceCrowdsale', function ([_, investor, wallet, purchaser])
}); });
it('returns a rate of 0 before the crowdsale starts', async function () { it('returns a rate of 0 before the crowdsale starts', async function () {
(await this.crowdsale.getCurrentRate()).should.be.bignumber.equal(0); (await this.crowdsale.getCurrentRate()).should.be.bignumber.equal('0');
}); });
it('returns a rate of 0 after the crowdsale ends', async function () { it('returns a rate of 0 after the crowdsale ends', async function () {
await time.increaseTo(this.afterClosingTime); await time.increaseTo(this.afterClosingTime);
(await this.crowdsale.getCurrentRate()).should.be.bignumber.equal(0); (await this.crowdsale.getCurrentRate()).should.be.bignumber.equal('0');
}); });
it('at start', async function () { it('at start', async function () {
...@@ -80,37 +76,37 @@ contract('IncreasingPriceCrowdsale', function ([_, investor, wallet, purchaser]) ...@@ -80,37 +76,37 @@ contract('IncreasingPriceCrowdsale', function ([_, investor, wallet, purchaser])
}); });
it('at time 150', async function () { it('at time 150', async function () {
await time.increaseTo(this.startTime + 150); await time.increaseTo(this.startTime.addn(150));
await this.crowdsale.buyTokens(investor, { value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value, from: purchaser });
(await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime150)); (await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime150));
}); });
it('at time 300', async function () { it('at time 300', async function () {
await time.increaseTo(this.startTime + 300); await time.increaseTo(this.startTime.addn(300));
await this.crowdsale.buyTokens(investor, { value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value, from: purchaser });
(await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime300)); (await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime300));
}); });
it('at time 1500', async function () { it('at time 1500', async function () {
await time.increaseTo(this.startTime + 1500); await time.increaseTo(this.startTime.addn(1500));
await this.crowdsale.buyTokens(investor, { value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value, from: purchaser });
(await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime1500)); (await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime1500));
}); });
it('at time 30', async function () { it('at time 30', async function () {
await time.increaseTo(this.startTime + 30); await time.increaseTo(this.startTime.addn(30));
await this.crowdsale.buyTokens(investor, { value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value, from: purchaser });
(await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime30)); (await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime30));
}); });
it('at time 150000', async function () { it('at time 150000', async function () {
await time.increaseTo(this.startTime + 150000); await time.increaseTo(this.startTime.addn(150000));
await this.crowdsale.buyTokens(investor, { value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value, from: purchaser });
(await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime150000)); (await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime150000));
}); });
it('at time 450000', async function () { it('at time 450000', async function () {
await time.increaseTo(this.startTime + 450000); await time.increaseTo(this.startTime.addn(450000));
await this.crowdsale.buyTokens(investor, { value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value, from: purchaser });
(await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime450000)); (await this.token.balanceOf(investor)).should.be.bignumber.equal(value.mul(rateAtTime450000));
}); });
......
const { ether } = require('../helpers/ether'); const { BN, ether, shouldFail } = require('openzeppelin-test-helpers');
const shouldFail = require('../helpers/shouldFail');
const { BigNumber } = require('../helpers/setup');
const IndividuallyCappedCrowdsaleImpl = artifacts.require('IndividuallyCappedCrowdsaleImpl'); const IndividuallyCappedCrowdsaleImpl = artifacts.require('IndividuallyCappedCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
const { shouldBehaveLikePublicRole } = require('../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../behaviors/access/roles/PublicRole.behavior');
contract('IndividuallyCappedCrowdsale', function ( contract('IndividuallyCappedCrowdsale', function (
[_, capper, otherCapper, wallet, alice, bob, charlie, anyone, ...otherAccounts]) { [_, capper, otherCapper, wallet, alice, bob, charlie, anyone, ...otherAccounts]) {
const rate = new BigNumber(1); const rate = new BN(1);
const capAlice = ether(10); const capAlice = ether('10');
const capBob = ether(2); const capBob = ether('2');
const lessThanCapAlice = ether(6); const lessThanCapAlice = ether('6');
const lessThanCapBoth = ether(1); const lessThanCapBoth = ether('1');
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
beforeEach(async function () { beforeEach(async function () {
this.token = await SimpleToken.new(); this.token = await SimpleToken.new();
...@@ -59,8 +56,8 @@ contract('IndividuallyCappedCrowdsale', function ( ...@@ -59,8 +56,8 @@ contract('IndividuallyCappedCrowdsale', function (
}); });
it('should reject payments that exceed cap', async function () { it('should reject payments that exceed cap', async function () {
await shouldFail.reverting(this.crowdsale.buyTokens(alice, { value: capAlice.plus(1) })); await shouldFail.reverting(this.crowdsale.buyTokens(alice, { value: capAlice.addn(1) }));
await shouldFail.reverting(this.crowdsale.buyTokens(bob, { value: capBob.plus(1) })); await shouldFail.reverting(this.crowdsale.buyTokens(bob, { value: capBob.addn(1) }));
}); });
it('should manage independent caps', async function () { it('should manage independent caps', async function () {
......
const expectEvent = require('../helpers/expectEvent'); const { balance, expectEvent } = require('openzeppelin-test-helpers');
const { balanceDifference } = require('../helpers/balanceDifference');
require('../helpers/setup');
function shouldBehaveLikeMintedCrowdsale ([_, investor, wallet, purchaser], rate, value) { function shouldBehaveLikeMintedCrowdsale ([_, investor, wallet, purchaser], rate, value) {
const expectedTokenAmount = rate.mul(value); const expectedTokenAmount = rate.mul(value);
...@@ -31,7 +28,7 @@ function shouldBehaveLikeMintedCrowdsale ([_, investor, wallet, purchaser], rate ...@@ -31,7 +28,7 @@ function shouldBehaveLikeMintedCrowdsale ([_, investor, wallet, purchaser], rate
}); });
it('should forward funds to wallet', async function () { it('should forward funds to wallet', async function () {
(await balanceDifference(wallet, () => (await balance.difference(wallet, () =>
this.crowdsale.sendTransaction({ value, from: investor })) this.crowdsale.sendTransaction({ value, from: investor }))
).should.be.bignumber.equal(value); ).should.be.bignumber.equal(value);
}); });
......
const { BN, ether, shouldFail } = require('openzeppelin-test-helpers');
const { shouldBehaveLikeMintedCrowdsale } = require('./MintedCrowdsale.behavior'); const { shouldBehaveLikeMintedCrowdsale } = require('./MintedCrowdsale.behavior');
const { ether } = require('../helpers/ether');
const shouldFail = require('../helpers/shouldFail');
const { BigNumber } = require('../helpers/setup');
const MintedCrowdsaleImpl = artifacts.require('MintedCrowdsaleImpl'); const MintedCrowdsaleImpl = artifacts.require('MintedCrowdsaleImpl');
const ERC20Mintable = artifacts.require('ERC20MintableMock'); const ERC20Mintable = artifacts.require('ERC20MintableMock');
const ERC20 = artifacts.require('ERC20'); const ERC20 = artifacts.require('ERC20');
contract('MintedCrowdsale', function ([_, deployer, investor, wallet, purchaser]) { contract('MintedCrowdsale', function ([_, deployer, investor, wallet, purchaser]) {
const rate = new BigNumber(1000); const rate = new BN('1000');
const value = ether(5); const value = ether('5');
describe('using ERC20Mintable', function () { describe('using ERC20Mintable', function () {
beforeEach(async function () { beforeEach(async function () {
......
const shouldFail = require('../helpers/shouldFail'); const { BN, shouldFail } = require('openzeppelin-test-helpers');
const PausableCrowdsale = artifacts.require('PausableCrowdsaleImpl'); const PausableCrowdsale = artifacts.require('PausableCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
require('../helpers/setup');
contract('PausableCrowdsale', function ([_, pauser, wallet, anyone]) { contract('PausableCrowdsale', function ([_, pauser, wallet, anyone]) {
const rate = 1; const rate = new BN(1);
const value = 1; const value = new BN(1);
beforeEach(async function () { beforeEach(async function () {
const from = pauser; const from = pauser;
this.token = await SimpleToken.new({ from }); this.token = await SimpleToken.new({ from });
this.crowdsale = await PausableCrowdsale.new(rate, wallet, this.token.address, { from }); this.crowdsale = await PausableCrowdsale.new(rate, wallet, this.token.address, { from });
await this.token.transfer(this.crowdsale.address, 2 * value, { from }); await this.token.transfer(this.crowdsale.address, value.muln(2), { from });
}); });
it('purchases work', async function () { it('purchases work', async function () {
......
const time = require('../helpers/time'); const { BN, ether, shouldFail, time } = require('openzeppelin-test-helpers');
const shouldFail = require('../helpers/shouldFail');
const { ether } = require('../helpers/ether');
const { BigNumber } = require('../helpers/setup');
const PostDeliveryCrowdsaleImpl = artifacts.require('PostDeliveryCrowdsaleImpl'); const PostDeliveryCrowdsaleImpl = artifacts.require('PostDeliveryCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) { contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BigNumber(1); const rate = new BN(1);
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
before(async function () { before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache // Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache
...@@ -17,9 +13,9 @@ contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) { ...@@ -17,9 +13,9 @@ contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) {
}); });
beforeEach(async function () { beforeEach(async function () {
this.openingTime = (await time.latest()) + time.duration.weeks(1); this.openingTime = (await time.latest()).add(time.duration.weeks(1));
this.closingTime = this.openingTime + time.duration.weeks(1); this.closingTime = this.openingTime.add(time.duration.weeks(1));
this.afterClosingTime = this.closingTime + time.duration.seconds(1); this.afterClosingTime = this.closingTime.add(time.duration.seconds(1));
this.token = await SimpleToken.new(); this.token = await SimpleToken.new();
this.crowdsale = await PostDeliveryCrowdsaleImpl.new( this.crowdsale = await PostDeliveryCrowdsaleImpl.new(
this.openingTime, this.closingTime, rate, wallet, this.token.address this.openingTime, this.closingTime, rate, wallet, this.token.address
...@@ -33,7 +29,7 @@ contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) { ...@@ -33,7 +29,7 @@ contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) {
}); });
context('with bought tokens', function () { context('with bought tokens', function () {
const value = ether(42); const value = ether('42');
beforeEach(async function () { beforeEach(async function () {
await this.crowdsale.buyTokens(investor, { value: value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value: value, from: purchaser });
...@@ -41,7 +37,7 @@ contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) { ...@@ -41,7 +37,7 @@ contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) {
it('does not immediately assign tokens to beneficiaries', async function () { it('does not immediately assign tokens to beneficiaries', async function () {
(await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal(value); (await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal(value);
(await this.token.balanceOf(investor)).should.be.bignumber.equal(0); (await this.token.balanceOf(investor)).should.be.bignumber.equal('0');
}); });
it('does not allow beneficiaries to withdraw tokens before crowdsale ends', async function () { it('does not allow beneficiaries to withdraw tokens before crowdsale ends', async function () {
...@@ -55,7 +51,7 @@ contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) { ...@@ -55,7 +51,7 @@ contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) {
it('allows beneficiaries to withdraw tokens', async function () { it('allows beneficiaries to withdraw tokens', async function () {
await this.crowdsale.withdrawTokens(investor); await this.crowdsale.withdrawTokens(investor);
(await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal(0); (await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal('0');
(await this.token.balanceOf(investor)).should.be.bignumber.equal(value); (await this.token.balanceOf(investor)).should.be.bignumber.equal(value);
}); });
......
const { ether } = require('../helpers/ether'); const { balance, BN, ether, shouldFail, time } = require('openzeppelin-test-helpers');
const { balanceDifference } = require('../helpers/balanceDifference');
const shouldFail = require('../helpers/shouldFail');
const time = require('../helpers/time');
const { ethGetBalance } = require('../helpers/web3');
const { BigNumber } = require('../helpers/setup');
const RefundableCrowdsaleImpl = artifacts.require('RefundableCrowdsaleImpl'); const RefundableCrowdsaleImpl = artifacts.require('RefundableCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyone]) { contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyone]) {
const rate = new BigNumber(1); const rate = new BN(1);
const goal = ether(50); const goal = ether('50');
const lessThanGoal = ether(45); const lessThanGoal = ether('45');
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
before(async function () { before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache // Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache
...@@ -21,10 +15,10 @@ contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyon ...@@ -21,10 +15,10 @@ contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyon
}); });
beforeEach(async function () { beforeEach(async function () {
this.openingTime = (await time.latest()) + time.duration.weeks(1); this.openingTime = (await time.latest()).add(time.duration.weeks(1));
this.closingTime = this.openingTime + time.duration.weeks(1); this.closingTime = this.openingTime.add(time.duration.weeks(1));
this.afterClosingTime = this.closingTime + time.duration.seconds(1); this.afterClosingTime = this.closingTime.add(time.duration.seconds(1));
this.preWalletBalance = await ethGetBalance(wallet); this.preWalletBalance = await balance.current(wallet);
this.token = await SimpleToken.new(); this.token = await SimpleToken.new();
}); });
...@@ -71,7 +65,7 @@ contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyon ...@@ -71,7 +65,7 @@ contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyon
}); });
it('refunds', async function () { it('refunds', async function () {
(await balanceDifference(investor, () => (await balance.difference(investor, () =>
this.crowdsale.claimRefund(investor, { gasPrice: 0 })) this.crowdsale.claimRefund(investor, { gasPrice: 0 }))
).should.be.bignumber.equal(lessThanGoal); ).should.be.bignumber.equal(lessThanGoal);
}); });
...@@ -94,8 +88,8 @@ contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyon ...@@ -94,8 +88,8 @@ contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyon
}); });
it('forwards funds to wallet', async function () { it('forwards funds to wallet', async function () {
const postWalletBalance = await ethGetBalance(wallet); const postWalletBalance = await balance.current(wallet);
postWalletBalance.minus(this.preWalletBalance).should.be.bignumber.equal(goal); postWalletBalance.sub(this.preWalletBalance).should.be.bignumber.equal(goal);
}); });
}); });
}); });
......
const time = require('../helpers/time'); const { BN, ether, shouldFail, time } = require('openzeppelin-test-helpers');
const shouldFail = require('../helpers/shouldFail');
const { ether } = require('../helpers/ether');
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-bignumber')(BigNumber))
.should();
const RefundablePostDeliveryCrowdsaleImpl = artifacts.require('RefundablePostDeliveryCrowdsaleImpl'); const RefundablePostDeliveryCrowdsaleImpl = artifacts.require('RefundablePostDeliveryCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) { contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BigNumber(1); const rate = new BN(1);
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
const goal = ether(100); const goal = ether('100');
before(async function () { before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache // Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache
...@@ -22,9 +14,9 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc ...@@ -22,9 +14,9 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc
}); });
beforeEach(async function () { beforeEach(async function () {
this.openingTime = (await time.latest()) + time.duration.weeks(1); this.openingTime = (await time.latest()).add(time.duration.weeks(1));
this.closingTime = this.openingTime + time.duration.weeks(1); this.closingTime = this.openingTime.add(time.duration.weeks(1));
this.afterClosingTime = this.closingTime + time.duration.seconds(1); this.afterClosingTime = this.closingTime.add(time.duration.seconds(1));
this.token = await SimpleToken.new(); this.token = await SimpleToken.new();
this.crowdsale = await RefundablePostDeliveryCrowdsaleImpl.new( this.crowdsale = await RefundablePostDeliveryCrowdsaleImpl.new(
this.openingTime, this.closingTime, rate, wallet, this.token.address, goal this.openingTime, this.closingTime, rate, wallet, this.token.address, goal
...@@ -38,7 +30,7 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc ...@@ -38,7 +30,7 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc
}); });
context('with bought tokens below the goal', function () { context('with bought tokens below the goal', function () {
const value = goal.sub(1); const value = goal.subn(1);
beforeEach(async function () { beforeEach(async function () {
await this.crowdsale.buyTokens(investor, { value: value, from: purchaser }); await this.crowdsale.buyTokens(investor, { value: value, from: purchaser });
...@@ -46,7 +38,7 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc ...@@ -46,7 +38,7 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc
it('does not immediately deliver tokens to beneficiaries', async function () { it('does not immediately deliver tokens to beneficiaries', async function () {
(await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal(value); (await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal(value);
(await this.token.balanceOf(investor)).should.be.bignumber.equal(0); (await this.token.balanceOf(investor)).should.be.bignumber.equal('0');
}); });
it('does not allow beneficiaries to withdraw tokens before crowdsale ends', async function () { it('does not allow beneficiaries to withdraw tokens before crowdsale ends', async function () {
...@@ -74,7 +66,7 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc ...@@ -74,7 +66,7 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc
it('does not immediately deliver tokens to beneficiaries', async function () { it('does not immediately deliver tokens to beneficiaries', async function () {
(await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal(value); (await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal(value);
(await this.token.balanceOf(investor)).should.be.bignumber.equal(0); (await this.token.balanceOf(investor)).should.be.bignumber.equal('0');
}); });
it('does not allow beneficiaries to withdraw tokens before crowdsale ends', async function () { it('does not allow beneficiaries to withdraw tokens before crowdsale ends', async function () {
...@@ -89,7 +81,7 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc ...@@ -89,7 +81,7 @@ contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purc
it('allows beneficiaries to withdraw tokens', async function () { it('allows beneficiaries to withdraw tokens', async function () {
await this.crowdsale.withdrawTokens(investor); await this.crowdsale.withdrawTokens(investor);
(await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal(0); (await this.crowdsale.balanceOf(investor)).should.be.bignumber.equal('0');
(await this.token.balanceOf(investor)).should.be.bignumber.equal(value); (await this.token.balanceOf(investor)).should.be.bignumber.equal(value);
}); });
......
const { ether } = require('../helpers/ether'); const { BN, ether, shouldFail, time } = require('openzeppelin-test-helpers');
const shouldFail = require('../helpers/shouldFail');
const time = require('../helpers/time');
const { BigNumber } = require('../helpers/setup');
const TimedCrowdsaleImpl = artifacts.require('TimedCrowdsaleImpl'); const TimedCrowdsaleImpl = artifacts.require('TimedCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('TimedCrowdsale', function ([_, investor, wallet, purchaser]) { contract('TimedCrowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BigNumber(1); const rate = new BN(1);
const value = ether(42); const value = ether('42');
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
before(async function () { before(async function () {
// Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache // Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache
...@@ -18,21 +14,21 @@ contract('TimedCrowdsale', function ([_, investor, wallet, purchaser]) { ...@@ -18,21 +14,21 @@ contract('TimedCrowdsale', function ([_, investor, wallet, purchaser]) {
}); });
beforeEach(async function () { beforeEach(async function () {
this.openingTime = (await time.latest()) + time.duration.weeks(1); this.openingTime = (await time.latest()).add(time.duration.weeks(1));
this.closingTime = this.openingTime + time.duration.weeks(1); this.closingTime = this.openingTime.add(time.duration.weeks(1));
this.afterClosingTime = this.closingTime + time.duration.seconds(1); this.afterClosingTime = this.closingTime.add(time.duration.seconds(1));
this.token = await SimpleToken.new(); this.token = await SimpleToken.new();
}); });
it('reverts if the opening time is in the past', async function () { it('reverts if the opening time is in the past', async function () {
await shouldFail.reverting(TimedCrowdsaleImpl.new( await shouldFail.reverting(TimedCrowdsaleImpl.new(
(await time.latest()) - time.duration.days(1), this.closingTime, rate, wallet, this.token.address (await time.latest()).sub(time.duration.days(1)), this.closingTime, rate, wallet, this.token.address
)); ));
}); });
it('reverts if the closing time is before the opening time', async function () { it('reverts if the closing time is before the opening time', async function () {
await shouldFail.reverting(TimedCrowdsaleImpl.new( await shouldFail.reverting(TimedCrowdsaleImpl.new(
this.openingTime, this.openingTime - time.duration.seconds(1), rate, wallet, this.token.address this.openingTime, this.openingTime.sub(time.duration.seconds(1)), rate, wallet, this.token.address
)); ));
}); });
......
require('../helpers/setup'); const { BN, ether, shouldFail } = require('openzeppelin-test-helpers');
const { ether } = require('../helpers/ether');
const shouldFail = require('../helpers/shouldFail');
const BigNumber = web3.BigNumber;
const WhitelistCrowdsale = artifacts.require('WhitelistCrowdsaleImpl'); const WhitelistCrowdsale = artifacts.require('WhitelistCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
contract('WhitelistCrowdsale', function ([_, wallet, whitelister, whitelisted, otherWhitelisted, anyone]) { contract('WhitelistCrowdsale', function ([_, wallet, whitelister, whitelisted, otherWhitelisted, anyone]) {
const rate = 1; const rate = new BN(1);
const value = ether(42); const value = ether('42');
const tokenSupply = new BigNumber('1e22'); const tokenSupply = new BN('10').pow(new BN('22'));
beforeEach(async function () { beforeEach(async function () {
this.token = await SimpleToken.new({ from: whitelister }); this.token = await SimpleToken.new({ from: whitelister });
......
const { shouldFail } = require('openzeppelin-test-helpers');
const { signMessage, toEthSignedMessageHash } = require('../helpers/sign'); const { signMessage, toEthSignedMessageHash } = require('../helpers/sign');
const shouldFail = require('../helpers/shouldFail');
const ECDSAMock = artifacts.require('ECDSAMock'); const ECDSAMock = artifacts.require('ECDSAMock');
require('../helpers/setup'); const TEST_MESSAGE = web3.utils.sha3('OpenZeppelin');
const WRONG_MESSAGE = web3.utils.sha3('Nope');
const TEST_MESSAGE = web3.sha3('OpenZeppelin');
const WRONG_MESSAGE = web3.sha3('Nope');
contract('ECDSA', function ([_, anyone]) { contract('ECDSA', function ([_, anyone]) {
beforeEach(async function () { beforeEach(async function () {
...@@ -16,7 +14,7 @@ contract('ECDSA', function ([_, anyone]) { ...@@ -16,7 +14,7 @@ contract('ECDSA', function ([_, anyone]) {
context('recover with valid signature', function () { context('recover with valid signature', function () {
context('with v0 signature', function () { context('with v0 signature', function () {
// Signature generated outside ganache with method web3.eth.sign(signer, message) // Signature generated outside ganache with method web3.eth.sign(signer, message)
const signer = '0x2cc1166f6212628a0deef2b33befb2187d35b86c'; const signer = '0x2cc1166f6212628A0deEf2B33BEFB2187D35b86c';
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
const signatureWithoutVersion = '0x5d99b6f7f6d1f73d1a26497f2b1c89b24c0993913f86e9a2d02cd69887d9c94f3c880358579d811b21dd1b7fd9bb01c1d81d10e69f0384e675c32b39643be892'; const signatureWithoutVersion = '0x5d99b6f7f6d1f73d1a26497f2b1c89b24c0993913f86e9a2d02cd69887d9c94f3c880358579d811b21dd1b7fd9bb01c1d81d10e69f0384e675c32b39643be892';
...@@ -49,7 +47,7 @@ contract('ECDSA', function ([_, anyone]) { ...@@ -49,7 +47,7 @@ contract('ECDSA', function ([_, anyone]) {
}); });
context('with v1 signature', function () { context('with v1 signature', function () {
const signer = '0x1e318623ab09fe6de3c9b8672098464aeda9100e'; const signer = '0x1E318623aB09Fe6de3C9b8672098464Aeda9100E';
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
const signatureWithoutVersion = '0x331fe75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e0'; const signatureWithoutVersion = '0x331fe75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e0';
...@@ -85,7 +83,7 @@ contract('ECDSA', function ([_, anyone]) { ...@@ -85,7 +83,7 @@ contract('ECDSA', function ([_, anyone]) {
context('with correct signature', function () { context('with correct signature', function () {
it('returns signer address', async function () { it('returns signer address', async function () {
// Create the signature // Create the signature
const signature = signMessage(anyone, TEST_MESSAGE); const signature = await signMessage(anyone, TEST_MESSAGE);
// Recover the signer address from the generated message and signature. // Recover the signer address from the generated message and signature.
(await this.ecdsa.recover( (await this.ecdsa.recover(
...@@ -98,7 +96,7 @@ contract('ECDSA', function ([_, anyone]) { ...@@ -98,7 +96,7 @@ contract('ECDSA', function ([_, anyone]) {
context('with wrong signature', function () { context('with wrong signature', function () {
it('does not return signer address', async function () { it('does not return signer address', async function () {
// Create the signature // Create the signature
const signature = signMessage(anyone, TEST_MESSAGE); const signature = await signMessage(anyone, TEST_MESSAGE);
// Recover the signer address from the generated message and wrong signature. // Recover the signer address from the generated message and wrong signature.
(await this.ecdsa.recover(WRONG_MESSAGE, signature)).should.not.equal(anyone); (await this.ecdsa.recover(WRONG_MESSAGE, signature)).should.not.equal(anyone);
...@@ -111,7 +109,7 @@ contract('ECDSA', function ([_, anyone]) { ...@@ -111,7 +109,7 @@ contract('ECDSA', function ([_, anyone]) {
// @TODO - remove `skip` once we upgrade to solc^0.5 // @TODO - remove `skip` once we upgrade to solc^0.5
it.skip('reverts', async function () { it.skip('reverts', async function () {
// Create the signature // Create the signature
const signature = signMessage(anyone, TEST_MESSAGE); const signature = await signMessage(anyone, TEST_MESSAGE);
await shouldFail.reverting( await shouldFail.reverting(
this.ecdsa.recover(TEST_MESSAGE.substring(2), signature) this.ecdsa.recover(TEST_MESSAGE.substring(2), signature)
); );
......
require('openzeppelin-test-helpers');
const { MerkleTree } = require('../helpers/merkleTree.js'); const { MerkleTree } = require('../helpers/merkleTree.js');
const { keccak256, bufferToHex } = require('ethereumjs-util'); const { keccak256, bufferToHex } = require('ethereumjs-util');
const MerkleProofWrapper = artifacts.require('MerkleProofWrapper'); const MerkleProofWrapper = artifacts.require('MerkleProofWrapper');
require('../helpers/setup');
contract('MerkleProof', function () { contract('MerkleProof', function () {
beforeEach(async function () { beforeEach(async function () {
this.merkleProof = await MerkleProofWrapper.new(); this.merkleProof = await MerkleProofWrapper.new();
......
const { BN } = require('openzeppelin-test-helpers');
const CounterImpl = artifacts.require('CounterImpl'); const CounterImpl = artifacts.require('CounterImpl');
require('../helpers/setup'); const EXPECTED = [new BN(1), new BN(2), new BN(3), new BN(4)];
const KEY1 = web3.utils.sha3('key1');
const EXPECTED = [1, 2, 3, 4]; const KEY2 = web3.utils.sha3('key2');
const KEY1 = web3.sha3('key1');
const KEY2 = web3.sha3('key2');
contract('Counter', function ([_, owner]) { contract('Counter', function ([_, owner]) {
beforeEach(async function () { beforeEach(async function () {
......
const ERC20WithMetadataMock = artifacts.require('ERC20WithMetadataMock'); require('openzeppelin-test-helpers');
require('../../helpers/setup'); const ERC20WithMetadataMock = artifacts.require('ERC20WithMetadataMock');
const metadataURI = 'https://example.com'; const metadataURI = 'https://example.com';
......
const shouldFail = require('../helpers/shouldFail'); const { BN, constants, shouldFail } = require('openzeppelin-test-helpers');
const { ZERO_ADDRESS } = require('../helpers/constants'); const { ZERO_ADDRESS } = constants;
const ERC20Mock = artifacts.require('ERC20Mock'); const ERC20Mock = artifacts.require('ERC20Mock');
const ERC20Mintable = artifacts.require('ERC20MintableMock'); const ERC20Mintable = artifacts.require('ERC20MintableMock');
const ERC20Migrator = artifacts.require('ERC20MigratorMock'); const ERC20Migrator = artifacts.require('ERC20MigratorMock');
require('../helpers/setup');
contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) { contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) {
const totalSupply = 200; const totalSupply = new BN('200');
it('reverts with a null legacy token address', async function () { it('reverts with a null legacy token address', async function () {
await shouldFail.reverting(ERC20Migrator.new(ZERO_ADDRESS)); await shouldFail.reverting(ERC20Migrator.new(ZERO_ADDRESS));
...@@ -81,7 +79,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) { ...@@ -81,7 +79,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) {
currentBurnedBalance.should.be.bignumber.equal(amount); currentBurnedBalance.should.be.bignumber.equal(amount);
const currentLegacyTokenBalance = await this.legacyToken.balanceOf(owner); const currentLegacyTokenBalance = await this.legacyToken.balanceOf(owner);
currentLegacyTokenBalance.should.be.bignumber.equal(0); currentLegacyTokenBalance.should.be.bignumber.equal('0');
}); });
it('updates the total supply', async function () { it('updates the total supply', async function () {
...@@ -91,7 +89,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) { ...@@ -91,7 +89,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) {
}); });
describe('when the approved balance is lower than the owned balance', function () { describe('when the approved balance is lower than the owned balance', function () {
const amount = baseAmount - 1; const amount = baseAmount.subn(1);
beforeEach('approving part of the balance to the new contract', async function () { beforeEach('approving part of the balance to the new contract', async function () {
await this.legacyToken.approve(this.migrator.address, amount, { from: owner }); await this.legacyToken.approve(this.migrator.address, amount, { from: owner });
...@@ -106,7 +104,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) { ...@@ -106,7 +104,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) {
}); });
describe('migrate', function () { describe('migrate', function () {
const baseAmount = 50; const baseAmount = new BN(50);
beforeEach('approving tokens to the new contract', async function () { beforeEach('approving tokens to the new contract', async function () {
await this.legacyToken.approve(this.migrator.address, baseAmount, { from: owner }); await this.legacyToken.approve(this.migrator.address, baseAmount, { from: owner });
...@@ -129,7 +127,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) { ...@@ -129,7 +127,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) {
currentBurnedBalance.should.be.bignumber.equal(amount); currentBurnedBalance.should.be.bignumber.equal(amount);
const currentLegacyTokenBalance = await this.legacyToken.balanceOf(owner); const currentLegacyTokenBalance = await this.legacyToken.balanceOf(owner);
currentLegacyTokenBalance.should.be.bignumber.equal(totalSupply - amount); currentLegacyTokenBalance.should.be.bignumber.equal(totalSupply.sub(amount));
}); });
it('updates the total supply', async function () { it('updates the total supply', async function () {
...@@ -139,7 +137,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) { ...@@ -139,7 +137,7 @@ contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) {
}); });
describe('when the given amount is higher than the one approved', function () { describe('when the given amount is higher than the one approved', function () {
const amount = baseAmount + 1; const amount = baseAmount.addn(1);
it('reverts', async function () { it('reverts', async function () {
await shouldFail.reverting(this.migrator.migrate(owner, amount)); await shouldFail.reverting(this.migrator.migrate(owner, amount));
......
const shouldFail = require('../helpers/shouldFail'); const { BN, constants, shouldFail } = require('openzeppelin-test-helpers');
const { MIN_INT256, MAX_INT256 } = require('../helpers/constants'); const { MAX_INT256, MIN_INT256 } = constants;
const SignedSafeMathMock = artifacts.require('SignedSafeMathMock'); const SignedSafeMathMock = artifacts.require('SignedSafeMathMock');
const { BigNumber } = require('../helpers/setup');
contract('SignedSafeMath', function () { contract('SignedSafeMath', function () {
beforeEach(async function () { beforeEach(async function () {
this.safeMath = await SignedSafeMathMock.new(); this.safeMath = await SignedSafeMathMock.new();
...@@ -12,10 +10,10 @@ contract('SignedSafeMath', function () { ...@@ -12,10 +10,10 @@ contract('SignedSafeMath', function () {
describe('add', function () { describe('add', function () {
it('adds correctly if it does not overflow and the result is positve', async function () { it('adds correctly if it does not overflow and the result is positve', async function () {
const a = new BigNumber(1234); const a = new BN('1234');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.add(a, b)).should.be.bignumber.equal(a.plus(b)); (await this.safeMath.add(a, b)).should.be.bignumber.equal(a.add(b));
}); });
it('adds correctly if it does not overflow and the result is negative', async function () { it('adds correctly if it does not overflow and the result is negative', async function () {
...@@ -23,19 +21,19 @@ contract('SignedSafeMath', function () { ...@@ -23,19 +21,19 @@ contract('SignedSafeMath', function () {
const b = MIN_INT256; const b = MIN_INT256;
const result = await this.safeMath.add(a, b); const result = await this.safeMath.add(a, b);
result.should.be.bignumber.equal(a.plus(b)); result.should.be.bignumber.equal(a.add(b));
}); });
it('reverts on positive addition overflow', async function () { it('reverts on positive addition overflow', async function () {
const a = MAX_INT256; const a = MAX_INT256;
const b = new BigNumber(1); const b = new BN('1');
await shouldFail.reverting(this.safeMath.add(a, b)); await shouldFail.reverting(this.safeMath.add(a, b));
}); });
it('reverts on negative addition overflow', async function () { it('reverts on negative addition overflow', async function () {
const a = MIN_INT256; const a = MIN_INT256;
const b = new BigNumber(-1); const b = new BN('-1');
await shouldFail.reverting(this.safeMath.add(a, b)); await shouldFail.reverting(this.safeMath.add(a, b));
}); });
...@@ -43,31 +41,31 @@ contract('SignedSafeMath', function () { ...@@ -43,31 +41,31 @@ contract('SignedSafeMath', function () {
describe('sub', function () { describe('sub', function () {
it('subtracts correctly if it does not overflow and the result is positive', async function () { it('subtracts correctly if it does not overflow and the result is positive', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(1234); const b = new BN('1234');
const result = await this.safeMath.sub(a, b); const result = await this.safeMath.sub(a, b);
result.should.be.bignumber.equal(a.minus(b)); result.should.be.bignumber.equal(a.sub(b));
}); });
it('subtracts correctly if it does not overflow and the result is negative', async function () { it('subtracts correctly if it does not overflow and the result is negative', async function () {
const a = new BigNumber(1234); const a = new BN('1234');
const b = new BigNumber(5678); const b = new BN('5678');
const result = await this.safeMath.sub(a, b); const result = await this.safeMath.sub(a, b);
result.should.be.bignumber.equal(a.minus(b)); result.should.be.bignumber.equal(a.sub(b));
}); });
it('reverts on positive subtraction overflow', async function () { it('reverts on positive subtraction overflow', async function () {
const a = MAX_INT256; const a = MAX_INT256;
const b = new BigNumber(-1); const b = new BN('-1');
await shouldFail.reverting(this.safeMath.sub(a, b)); await shouldFail.reverting(this.safeMath.sub(a, b));
}); });
it('reverts on negative subtraction overflow', async function () { it('reverts on negative subtraction overflow', async function () {
const a = MIN_INT256; const a = MIN_INT256;
const b = new BigNumber(1); const b = new BN('1');
await shouldFail.reverting(this.safeMath.sub(a, b)); await shouldFail.reverting(this.safeMath.sub(a, b));
}); });
...@@ -75,37 +73,37 @@ contract('SignedSafeMath', function () { ...@@ -75,37 +73,37 @@ contract('SignedSafeMath', function () {
describe('mul', function () { describe('mul', function () {
it('multiplies correctly', async function () { it('multiplies correctly', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(-1234); const b = new BN('-1234');
const result = await this.safeMath.mul(a, b); const result = await this.safeMath.mul(a, b);
result.should.be.bignumber.equal(a.times(b)); result.should.be.bignumber.equal(a.mul(b));
}); });
it('handles a zero product correctly', async function () { it('handles a zero product correctly', async function () {
const a = new BigNumber(0); const a = new BN('0');
const b = new BigNumber(5678); const b = new BN('5678');
const result = await this.safeMath.mul(a, b); const result = await this.safeMath.mul(a, b);
result.should.be.bignumber.equal(a.times(b)); result.should.be.bignumber.equal(a.mul(b));
}); });
it('reverts on multiplication overflow, positive operands', async function () { it('reverts on multiplication overflow, positive operands', async function () {
const a = MAX_INT256; const a = MAX_INT256;
const b = new BigNumber(2); const b = new BN('2');
await shouldFail.reverting(this.safeMath.mul(a, b)); await shouldFail.reverting(this.safeMath.mul(a, b));
}); });
it('reverts when minimum integer is multiplied by -1', async function () { it('reverts when minimum integer is multiplied by -1', async function () {
const a = MIN_INT256; const a = MIN_INT256;
const b = new BigNumber(-1); const b = new BN('-1');
await shouldFail.reverting(this.safeMath.mul(a, b)); await shouldFail.reverting(this.safeMath.mul(a, b));
}); });
it('reverts when -1 is multiplied by minimum integer', async function () { it('reverts when -1 is multiplied by minimum integer', async function () {
const a = new BigNumber(-1); const a = new BN('-1');
const b = MIN_INT256; const b = MIN_INT256;
await shouldFail.reverting(this.safeMath.mul(a, b)); await shouldFail.reverting(this.safeMath.mul(a, b));
...@@ -114,23 +112,23 @@ contract('SignedSafeMath', function () { ...@@ -114,23 +112,23 @@ contract('SignedSafeMath', function () {
describe('div', function () { describe('div', function () {
it('divides correctly', async function () { it('divides correctly', async function () {
const a = new BigNumber(-5678); const a = new BN('-5678');
const b = new BigNumber(5678); const b = new BN('5678');
const result = await this.safeMath.div(a, b); const result = await this.safeMath.div(a, b);
result.should.be.bignumber.equal(a.div(b)); result.should.be.bignumber.equal(a.div(b));
}); });
it('reverts on zero division', async function () { it('reverts on zero division', async function () {
const a = new BigNumber(-5678); const a = new BN('-5678');
const b = new BigNumber(0); const b = new BN('0');
await shouldFail.reverting(this.safeMath.div(a, b)); await shouldFail.reverting(this.safeMath.div(a, b));
}); });
it('reverts on overflow, negative second', async function () { it('reverts on overflow, negative second', async function () {
const a = new BigNumber(MIN_INT256); const a = new BN(MIN_INT256);
const b = new BigNumber(-1); const b = new BN('-1');
await shouldFail.reverting(this.safeMath.div(a, b)); await shouldFail.reverting(this.safeMath.div(a, b));
}); });
......
const shouldFail = require('../helpers/shouldFail'); const { BN, constants, expectEvent, shouldFail, time } = require('openzeppelin-test-helpers');
const expectEvent = require('../helpers/expectEvent'); const { ZERO_ADDRESS } = constants;
const time = require('../helpers/time');
const { ethGetBlock } = require('../helpers/web3');
const { ZERO_ADDRESS } = require('../helpers/constants');
const { BigNumber } = require('../helpers/setup');
const ERC20Mintable = artifacts.require('ERC20MintableMock'); const ERC20Mintable = artifacts.require('ERC20MintableMock');
const TokenVesting = artifacts.require('TokenVestingMock'); const TokenVesting = artifacts.require('TokenVestingMock');
contract('TokenVesting', function ([_, owner, beneficiary]) { contract('TokenVesting', function ([_, owner, beneficiary]) {
const amount = new BigNumber(1000); const amount = new BN('1000');
beforeEach(async function () { beforeEach(async function () {
// +1 minute so it starts after contract instantiation // +1 minute so it starts after contract instantiation
this.start = (await time.latest()) + time.duration.minutes(1); this.start = (await time.latest()).add(time.duration.minutes(1));
this.cliffDuration = time.duration.years(1); this.cliffDuration = time.duration.years(1);
this.duration = time.duration.years(2); this.duration = time.duration.years(2);
}); });
...@@ -23,7 +18,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { ...@@ -23,7 +18,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
const cliffDuration = this.duration; const cliffDuration = this.duration;
const duration = this.cliffDuration; const duration = this.cliffDuration;
cliffDuration.should.be.gt(duration); cliffDuration.should.be.bignumber.that.is.at.least(duration);
await shouldFail.reverting( await shouldFail.reverting(
TokenVesting.new(beneficiary, this.start, cliffDuration, duration, true, { from: owner }) TokenVesting.new(beneficiary, this.start, cliffDuration, duration, true, { from: owner })
...@@ -46,7 +41,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { ...@@ -46,7 +41,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
it('reverts if the end time is in the past', async function () { it('reverts if the end time is in the past', async function () {
const now = await time.latest(); const now = await time.latest();
this.start = now - this.duration - time.duration.minutes(1); this.start = now.sub(this.duration).sub(time.duration.minutes(1));
await shouldFail.reverting( await shouldFail.reverting(
TokenVesting.new(beneficiary, this.start, this.cliffDuration, this.duration, true, { from: owner }) TokenVesting.new(beneficiary, this.start, this.cliffDuration, this.duration, true, { from: owner })
); );
...@@ -63,7 +58,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { ...@@ -63,7 +58,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
it('can get state', async function () { it('can get state', async function () {
(await this.vesting.beneficiary()).should.be.equal(beneficiary); (await this.vesting.beneficiary()).should.be.equal(beneficiary);
(await this.vesting.cliff()).should.be.bignumber.equal(this.start + this.cliffDuration); (await this.vesting.cliff()).should.be.bignumber.equal(this.start.add(this.cliffDuration));
(await this.vesting.start()).should.be.bignumber.equal(this.start); (await this.vesting.start()).should.be.bignumber.equal(this.start);
(await this.vesting.duration()).should.be.bignumber.equal(this.duration); (await this.vesting.duration()).should.be.bignumber.equal(this.duration);
(await this.vesting.revocable()).should.be.equal(true); (await this.vesting.revocable()).should.be.equal(true);
...@@ -74,7 +69,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { ...@@ -74,7 +69,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
}); });
it('can be released after cliff', async function () { it('can be released after cliff', async function () {
await time.increaseTo(this.start + this.cliffDuration + time.duration.weeks(1)); await time.increaseTo(this.start.add(this.cliffDuration).add(time.duration.weeks(1)));
const { logs } = await this.vesting.release(this.token.address); const { logs } = await this.vesting.release(this.token.address);
expectEvent.inLogs(logs, 'TokensReleased', { expectEvent.inLogs(logs, 'TokensReleased', {
token: this.token.address, token: this.token.address,
...@@ -83,34 +78,33 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { ...@@ -83,34 +78,33 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
}); });
it('should release proper amount after cliff', async function () { it('should release proper amount after cliff', async function () {
await time.increaseTo(this.start + this.cliffDuration); await time.increaseTo(this.start.add(this.cliffDuration));
const { receipt } = await this.vesting.release(this.token.address); await this.vesting.release(this.token.address);
const block = await ethGetBlock(receipt.blockNumber); const releaseTime = await time.latest();
const releaseTime = block.timestamp;
const releasedAmount = amount.mul(releaseTime - this.start).div(this.duration).floor(); const releasedAmount = amount.mul(releaseTime.sub(this.start)).div(this.duration);
(await this.token.balanceOf(beneficiary)).should.bignumber.equal(releasedAmount); (await this.token.balanceOf(beneficiary)).should.bignumber.equal(releasedAmount);
(await this.vesting.released(this.token.address)).should.bignumber.equal(releasedAmount); (await this.vesting.released(this.token.address)).should.bignumber.equal(releasedAmount);
}); });
it('should linearly release tokens during vesting period', async function () { it('should linearly release tokens during vesting period', async function () {
const vestingPeriod = this.duration - this.cliffDuration; const vestingPeriod = this.duration.sub(this.cliffDuration);
const checkpoints = 4; const checkpoints = 4;
for (let i = 1; i <= checkpoints; i++) { for (let i = 1; i <= checkpoints; i++) {
const now = this.start + this.cliffDuration + i * (vestingPeriod / checkpoints); const now = this.start.add(this.cliffDuration).add((vestingPeriod.muln(i).divn(checkpoints)));
await time.increaseTo(now); await time.increaseTo(now);
await this.vesting.release(this.token.address); await this.vesting.release(this.token.address);
const expectedVesting = amount.mul(now - this.start).div(this.duration).floor(); const expectedVesting = amount.mul(now.sub(this.start)).div(this.duration);
(await this.token.balanceOf(beneficiary)).should.bignumber.equal(expectedVesting); (await this.token.balanceOf(beneficiary)).should.bignumber.equal(expectedVesting);
(await this.vesting.released(this.token.address)).should.bignumber.equal(expectedVesting); (await this.vesting.released(this.token.address)).should.bignumber.equal(expectedVesting);
} }
}); });
it('should have released all after end', async function () { it('should have released all after end', async function () {
await time.increaseTo(this.start + this.duration); await time.increaseTo(this.start.add(this.duration));
await this.vesting.release(this.token.address); await this.vesting.release(this.token.address);
(await this.token.balanceOf(beneficiary)).should.bignumber.equal(amount); (await this.token.balanceOf(beneficiary)).should.bignumber.equal(amount);
(await this.vesting.released(this.token.address)).should.bignumber.equal(amount); (await this.vesting.released(this.token.address)).should.bignumber.equal(amount);
...@@ -131,7 +125,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { ...@@ -131,7 +125,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
}); });
it('should return the non-vested tokens when revoked by owner', async function () { it('should return the non-vested tokens when revoked by owner', async function () {
await time.increaseTo(this.start + this.cliffDuration + time.duration.weeks(12)); await time.increaseTo(this.start.add(this.cliffDuration).add(time.duration.weeks(12)));
const vested = vestedAmount(amount, await time.latest(), this.start, this.cliffDuration, this.duration); const vested = vestedAmount(amount, await time.latest(), this.start, this.cliffDuration, this.duration);
...@@ -141,7 +135,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { ...@@ -141,7 +135,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
}); });
it('should keep the vested tokens when revoked by owner', async function () { it('should keep the vested tokens when revoked by owner', async function () {
await time.increaseTo(this.start + this.cliffDuration + time.duration.weeks(12)); await time.increaseTo(this.start.add(this.cliffDuration).add(time.duration.weeks(12)));
const vestedPre = vestedAmount(amount, await time.latest(), this.start, this.cliffDuration, this.duration); const vestedPre = vestedAmount(amount, await time.latest(), this.start, this.cliffDuration, this.duration);
...@@ -158,7 +152,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { ...@@ -158,7 +152,7 @@ contract('TokenVesting', function ([_, owner, beneficiary]) {
}); });
function vestedAmount (total, now, start, cliffDuration, duration) { function vestedAmount (total, now, start, cliffDuration, duration) {
return (now < start + cliffDuration) ? 0 : Math.round(total * (now - start) / duration); return (now.lt(start.add(cliffDuration))) ? new BN(0) : total.mul((now.sub(start))).div(duration);
} }
}); });
}); });
const { ether } = require('../helpers/ether'); const { BN, balance, ether, should, shouldFail, time } = require('openzeppelin-test-helpers');
const shouldFail = require('../helpers/shouldFail');
const time = require('../helpers/time');
const { balanceDifference } = require('../helpers/balanceDifference');
const { should, BigNumber } = require('../helpers/setup');
const SampleCrowdsale = artifacts.require('SampleCrowdsaleMock'); const SampleCrowdsale = artifacts.require('SampleCrowdsaleMock');
const SampleCrowdsaleToken = artifacts.require('SampleCrowdsaleTokenMock'); const SampleCrowdsaleToken = artifacts.require('SampleCrowdsaleTokenMock');
contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) { contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) {
const RATE = new BigNumber(10); const RATE = new BN(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 ganache // Advance to the next block to correctly read time in the solidity "now" function interpreted by ganache
...@@ -19,9 +14,9 @@ contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) { ...@@ -19,9 +14,9 @@ contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) {
}); });
beforeEach(async function () { beforeEach(async function () {
this.openingTime = (await time.latest()) + time.duration.weeks(1); this.openingTime = (await time.latest()).add(time.duration.weeks(1));
this.closingTime = this.openingTime + time.duration.weeks(1); this.closingTime = this.openingTime.add(time.duration.weeks(1));
this.afterClosingTime = this.closingTime + time.duration.seconds(1); this.afterClosingTime = this.closingTime.add(time.duration.seconds(1));
this.token = await SampleCrowdsaleToken.new({ from: deployer }); this.token = await SampleCrowdsaleToken.new({ from: deployer });
this.crowdsale = await SampleCrowdsale.new( this.crowdsale = await SampleCrowdsale.new(
...@@ -46,12 +41,12 @@ contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) { ...@@ -46,12 +41,12 @@ contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) {
}); });
it('should not accept payments before start', async function () { it('should not accept payments before start', async function () {
await shouldFail.reverting(this.crowdsale.send(ether(1))); await shouldFail.reverting(this.crowdsale.send(ether('1')));
await shouldFail.reverting(this.crowdsale.buyTokens(investor, { from: investor, value: ether(1) })); await shouldFail.reverting(this.crowdsale.buyTokens(investor, { from: investor, value: ether('1') }));
}); });
it('should accept payments during the sale', async function () { it('should accept payments during the sale', async function () {
const investmentAmount = ether(1); const investmentAmount = ether('1');
const expectedTokenAmount = RATE.mul(investmentAmount); const expectedTokenAmount = RATE.mul(investmentAmount);
await time.increaseTo(this.openingTime); await time.increaseTo(this.openingTime);
...@@ -63,8 +58,8 @@ contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) { ...@@ -63,8 +58,8 @@ contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) {
it('should reject payments after end', async function () { it('should reject payments after end', async function () {
await time.increaseTo(this.afterClosingTime); await time.increaseTo(this.afterClosingTime);
await shouldFail.reverting(this.crowdsale.send(ether(1))); await shouldFail.reverting(this.crowdsale.send(ether('1')));
await shouldFail.reverting(this.crowdsale.buyTokens(investor, { value: ether(1), from: investor })); await shouldFail.reverting(this.crowdsale.buyTokens(investor, { value: ether('1'), from: investor }));
}); });
it('should reject payments over cap', async function () { it('should reject payments over cap', async function () {
...@@ -77,26 +72,26 @@ contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) { ...@@ -77,26 +72,26 @@ contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) {
await time.increaseTo(this.openingTime); await time.increaseTo(this.openingTime);
await this.crowdsale.send(GOAL); await this.crowdsale.send(GOAL);
(await balanceDifference(wallet, async () => { (await balance.difference(wallet, async () => {
await time.increaseTo(this.afterClosingTime); await time.increaseTo(this.afterClosingTime);
await this.crowdsale.finalize({ from: owner }); await this.crowdsale.finalize({ from: owner });
})).should.be.bignumber.equal(GOAL); })).should.be.bignumber.equal(GOAL);
}); });
it('should allow refunds if the goal is not reached', async function () { it('should allow refunds if the goal is not reached', async function () {
(await balanceDifference(investor, async () => { (await balance.difference(investor, async () => {
await time.increaseTo(this.openingTime); await time.increaseTo(this.openingTime);
await this.crowdsale.sendTransaction({ value: ether(1), from: investor, gasPrice: 0 }); await this.crowdsale.sendTransaction({ value: ether('1'), from: investor, gasPrice: 0 });
await time.increaseTo(this.afterClosingTime); await time.increaseTo(this.afterClosingTime);
await this.crowdsale.finalize({ from: owner }); await this.crowdsale.finalize({ from: owner });
await this.crowdsale.claimRefund(investor, { gasPrice: 0 }); await this.crowdsale.claimRefund(investor, { gasPrice: 0 });
})).should.be.bignumber.equal(0); })).should.be.bignumber.equal('0');
}); });
describe('when goal > cap', function () { describe('when goal > cap', function () {
// goal > cap // goal > cap
const HIGH_GOAL = ether(30); const HIGH_GOAL = ether('30');
it('creation reverts', async function () { it('creation reverts', async function () {
await shouldFail.reverting(SampleCrowdsale.new( await shouldFail.reverting(SampleCrowdsale.new(
......
const expectEvent = require('../helpers/expectEvent'); const { constants, expectEvent } = require('openzeppelin-test-helpers');
const { ZERO_ADDRESS } = require('../helpers/constants'); const { ZERO_ADDRESS } = constants;
const SimpleToken = artifacts.require('SimpleTokenMock');
require('../helpers/setup'); const SimpleToken = artifacts.require('SimpleToken');
contract('SimpleToken', function ([_, creator]) { contract('SimpleToken', function ([_, creator]) {
beforeEach(async function () { beforeEach(async function () {
...@@ -18,7 +17,7 @@ contract('SimpleToken', function ([_, creator]) { ...@@ -18,7 +17,7 @@ contract('SimpleToken', function ([_, creator]) {
}); });
it('has 18 decimals', async function () { it('has 18 decimals', async function () {
(await this.token.decimals()).should.be.bignumber.equal(18); (await this.token.decimals()).should.be.bignumber.equal('18');
}); });
it('assigns the initial total supply to the creator', async function () { it('assigns the initial total supply to the creator', async function () {
......
const { ethGetBalance } = require('./web3');
async function balanceDifference (account, promiseFunc) {
const balanceBefore = await ethGetBalance(account);
await promiseFunc();
const balanceAfter = await ethGetBalance(account);
return balanceAfter.minus(balanceBefore);
}
module.exports = {
balanceDifference,
};
const BigNumber = web3.BigNumber;
module.exports = {
ZERO_ADDRESS: '0x0000000000000000000000000000000000000000',
MAX_UINT256: new BigNumber(2).pow(256).minus(1),
MAX_INT256: new BigNumber(2).pow(255).minus(1),
MIN_INT256: new BigNumber(2).pow(255).times(-1),
};
function ether (n) {
return new web3.BigNumber(web3.toWei(n, 'ether'));
}
module.exports = {
ether,
};
const { should, BigNumber } = require('./setup');
const SolidityEvent = require('web3/lib/web3/event.js');
const { ethGetTransactionReceipt } = require('./web3');
function inLogs (logs, eventName, eventArgs = {}) {
const event = logs.find(function (e) {
if (e.event === eventName) {
for (const [k, v] of Object.entries(eventArgs)) {
contains(e.args, k, v);
}
return true;
}
});
should.exist(event);
return event;
}
async function inConstruction (contract, eventName, eventArgs = {}) {
return inTransaction(contract.transactionHash, contract.constructor, eventName, eventArgs);
}
async function inTransaction (txHash, emitter, eventName, eventArgs = {}) {
const receipt = await ethGetTransactionReceipt(txHash);
const logs = decodeLogs(receipt.logs, emitter.events);
return inLogs(logs, eventName, eventArgs);
}
function contains (args, key, value) {
if (isBigNumber(args[key])) {
args[key].should.be.bignumber.equal(value);
} else {
args[key].should.be.equal(value);
}
}
function isBigNumber (object) {
return object.isBigNumber ||
object instanceof BigNumber ||
(object.constructor && object.constructor.name === 'BigNumber');
}
function decodeLogs (logs, events) {
return Array.prototype.concat(...logs.map(log =>
log.topics.filter(topic => topic in events).map(topic => {
const event = new SolidityEvent(null, events[topic], 0);
return event.decode(log);
})
));
}
module.exports = {
inLogs,
inConstruction,
inTransaction,
};
const { soliditySha3 } = require('web3-utils');
const INTERFACE_ID_LENGTH = 4;
function makeInterfaceId (interfaces = []) {
const interfaceIdBuffer = interfaces
.map(methodSignature => soliditySha3(methodSignature)) // keccak256
.map(h =>
Buffer
.from(h.substring(2), 'hex')
.slice(0, 4) // bytes4()
)
.reduce((memo, bytes) => {
for (let i = 0; i < INTERFACE_ID_LENGTH; i++) {
memo[i] = memo[i] ^ bytes[i]; // xor
}
return memo;
}, Buffer.alloc(INTERFACE_ID_LENGTH));
return `0x${interfaceIdBuffer.toString('hex')}`;
}
module.exports = {
makeInterfaceId,
};
const ethjsABI = require('ethjs-abi');
const { ethSendTransaction } = require('./web3');
function findMethod (abi, name, args) {
for (let i = 0; i < abi.length; i++) {
const methodArgs = abi[i].inputs.map(input => input.type).join(',');
if ((abi[i].name === name) && (methodArgs === args)) {
return abi[i];
}
}
}
async function transaction (target, name, argsTypes, argsValues, opts) {
const abiMethod = findMethod(target.abi, name, argsTypes);
const encodedData = ethjsABI.encodeMethod(abiMethod, argsValues);
return target.sendTransaction(Object.assign({ data: encodedData }, opts));
}
function ether (from, to, value) {
return ethSendTransaction({ from, to, value, gasPrice: 0 });
}
module.exports = {
ether,
transaction,
};
const chai = require('chai');
const BigNumber = web3.BigNumber;
const should = chai.use(require('chai-bignumber')(BigNumber)).should();
module.exports = {
BigNumber,
should,
};
const { should } = require('./setup');
async function shouldFailWithMessage (promise, message) {
try {
await promise;
} catch (error) {
if (message) {
error.message.should.include(message, `Wrong failure type, expected '${message}'`);
}
return;
}
should.fail('Expected failure not received');
}
async function reverting (promise) {
await shouldFailWithMessage(promise, 'revert');
}
async function throwing (promise) {
await shouldFailWithMessage(promise, 'invalid opcode');
}
async function outOfGas (promise) {
await shouldFailWithMessage(promise, 'out of gas');
}
async function shouldFail (promise) {
await shouldFailWithMessage(promise);
}
shouldFail.reverting = reverting;
shouldFail.throwing = throwing;
shouldFail.outOfGas = outOfGas;
module.exports = shouldFail;
const { sha3, soliditySha3 } = require('web3-utils');
const REAL_SIGNATURE_SIZE = 2 * 65; // 65 bytes in hexadecimal string legnth const REAL_SIGNATURE_SIZE = 2 * 65; // 65 bytes in hexadecimal string legnth
const PADDED_SIGNATURE_SIZE = 2 * 96; // 96 bytes in hexadecimal string length const PADDED_SIGNATURE_SIZE = 2 * 96; // 96 bytes in hexadecimal string length
const DUMMY_SIGNATURE = `0x${web3.padLeft('', REAL_SIGNATURE_SIZE)}`; const DUMMY_SIGNATURE = `0x${web3.utils.padLeft('', REAL_SIGNATURE_SIZE)}`;
// messageHex = '0xdeadbeef'
function toEthSignedMessageHash (messageHex) { function toEthSignedMessageHash (messageHex) {
const messageBuffer = Buffer.from(messageHex.substring(2), 'hex'); const messageBuffer = Buffer.from(messageHex.substring(2), 'hex');
const prefix = Buffer.from(`\u0019Ethereum Signed Message:\n${messageBuffer.length}`); const prefix = Buffer.from(`\u0019Ethereum Signed Message:\n${messageBuffer.length}`);
return sha3(Buffer.concat([prefix, messageBuffer])); return web3.utils.sha3(Buffer.concat([prefix, messageBuffer]));
} }
// signs message in node (ganache auto-applies "Ethereum Signed Message" prefix) // signs message in node (ganache auto-applies "Ethereum Signed Message" prefix)
// messageHex = '0xdeadbeef'
const signMessage = (signer, messageHex = '0x') => { const signMessage = (signer, messageHex = '0x') => {
return web3.eth.sign(signer, messageHex); // actually personal_sign return web3.eth.sign(messageHex, signer);
};
// @TODO - remove this when we migrate to web3-1.0.0
const transformToFullName = function (json) {
if (json.name.indexOf('(') !== -1) {
return json.name;
}
const typeName = json.inputs.map(function (i) { return i.type; }).join();
return json.name + '(' + typeName + ')';
}; };
/** /**
* Create a signer between a contract and a signer for a voucher of method, args, and redeemer * Create a signer between a contract and a signer for a voucher of method, args, and redeemer
* Note that `method` is the web3 method, not the truffle-contract method * Note that `method` is the web3 method, not the truffle-contract method
* Well truffle is terrible, but luckily (?) so is web3 < 1.0, so we get to make our own method id
* fetcher because the method on the contract isn't actually the SolidityFunction object ಠ_ಠ
* @param contract TruffleContract * @param contract TruffleContract
* @param signer address * @param signer address
* @param redeemer address * @param redeemer address
...@@ -49,21 +33,17 @@ const getSignFor = (contract, signer) => (redeemer, methodName, methodArgs = []) ...@@ -49,21 +33,17 @@ const getSignFor = (contract, signer) => (redeemer, methodName, methodArgs = [])
if (methodName) { if (methodName) {
if (methodArgs.length > 0) { if (methodArgs.length > 0) {
parts.push( parts.push(
contract.contract[methodName].getData(...methodArgs.concat([DUMMY_SIGNATURE])).slice( contract.contract.methods[methodName](...methodArgs.concat([DUMMY_SIGNATURE])).encodeABI()
0, .slice(0, -1 * PADDED_SIGNATURE_SIZE)
-1 * PADDED_SIGNATURE_SIZE
)
); );
} else { } else {
const abi = contract.abi.find(abi => abi.name === methodName); const abi = contract.abi.find(abi => abi.name === methodName);
const name = transformToFullName(abi); parts.push(abi.signature);
const signature = sha3(name).slice(0, 10);
parts.push(signature);
} }
} }
// return the signature of the "Ethereum Signed Message" hash of the hash of `parts` // return the signature of the "Ethereum Signed Message" hash of the hash of `parts`
const messageHex = soliditySha3(...parts); const messageHex = web3.utils.soliditySha3(...parts);
return signMessage(signer, messageHex); return signMessage(signer, messageHex);
}; };
......
const { balanceDifference } = require('../balanceDifference');
const send = require('../send');
const { ether } = require('../ether');
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-bignumber')(BigNumber))
.should();
contract('balanceDifference', function ([sender, receiver]) {
it('returns balance increments', async function () {
(await balanceDifference(receiver, () =>
send.ether(sender, receiver, ether(1)))
).should.be.bignumber.equal(ether(1));
});
it('returns balance decrements', async function () {
(await balanceDifference(sender, () =>
send.ether(sender, receiver, ether(1)))
).should.be.bignumber.equal(ether(-1));
});
});
const { ether } = require('../ether');
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-bignumber')(BigNumber))
.should();
describe('ether', function () {
it('returns a BigNumber', function () {
ether(1, 'ether').should.be.bignumber.equal(new BigNumber(1000000000000000000));
});
it('works with negative amounts', function () {
ether(-1, 'ether').should.be.bignumber.equal(new BigNumber(-1000000000000000000));
});
});
const { makeInterfaceId } = require('../makeInterfaceId');
const OwnableInterfaceId = artifacts.require('OwnableInterfaceId');
require('chai')
.should();
describe('makeInterfaceId', function () {
it('calculates the EIP165 interface id from function signatures', async function () {
const calculator = await OwnableInterfaceId.new();
const ownableId = await calculator.getInterfaceId();
makeInterfaceId([
'owner()',
'isOwner()',
'renounceOwnership()',
'transferOwnership(address)',
]).should.equal(ownableId);
});
});
const send = require('../send');
const shouldFail = require('../shouldFail');
const expectEvent = require('../expectEvent');
const { ether } = require('../ether');
const { ethGetBalance } = require('../web3');
const Acknowledger = artifacts.require('Acknowledger');
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-bignumber')(BigNumber))
.should();
contract('send', function ([sender, receiver]) {
describe('ether', function () {
it('sends ether with no gas cost', async function () {
const value = ether(1);
const initialSenderBalance = await ethGetBalance(sender);
const initialReceiverBalance = await ethGetBalance(receiver);
await send.ether(sender, receiver, value);
const finalSenderBalance = await ethGetBalance(sender);
const finalReceiverBalance = await ethGetBalance(receiver);
finalSenderBalance.sub(initialSenderBalance).should.be.bignumber.equal(-value);
finalReceiverBalance.sub(initialReceiverBalance).should.be.bignumber.equal(value);
});
it('throws if the sender balance is insufficient', async function () {
const value = (await ethGetBalance(sender)).plus(1);
await shouldFail(send.ether(sender, receiver, value));
});
});
describe('transaction', function () {
beforeEach(async function () {
this.acknowledger = await Acknowledger.new();
});
it('calls a function from its signature ', async function () {
const { logs } = await send.transaction(this.acknowledger, 'foo', 'uint256', [3]);
expectEvent.inLogs(logs, 'AcknowledgeFoo', { a: 3 });
});
it('calls overloaded functions with less arguments', async function () {
const { logs } = await send.transaction(this.acknowledger, 'bar', 'uint256', [3]);
expectEvent.inLogs(logs, 'AcknowledgeBarSingle', { a: 3 });
});
it('calls overloaded functions with more arguments', async function () {
const { logs } = await send.transaction(this.acknowledger, 'bar', 'uint256,uint256', [3, 5]);
expectEvent.inLogs(logs, 'AcknowledgeBarDouble', { a: 3, b: 5 });
});
it('throws if the number of arguments does not match', async function () {
await shouldFail(send.transaction(this.acknowledger, 'foo', 'uint256, uint256', [3, 5]));
});
it('throws if the method does not exist', async function () {
await shouldFail(send.transaction(this.acknowledger, 'baz', 'uint256', [3]));
});
it('throws if there is a mismatch in the number of types and values', async function () {
await shouldFail(send.transaction(this.acknowledger, 'foo', 'uint256', [3, 3]));
});
});
});
const shouldFail = require('../shouldFail');
const BigNumber = web3.BigNumber;
const should = require('chai')
.use(require('chai-bignumber')(BigNumber))
.should();
const Failer = artifacts.require('Failer');
async function assertFailure (promise) {
try {
await promise;
} catch (error) {
return;
}
should.fail();
}
describe('shouldFail', function () {
beforeEach(async function () {
this.failer = await Failer.new();
});
describe('shouldFail', function () {
it('rejects if no failure occurs', async function () {
await assertFailure(shouldFail(this.failer.dontFail()));
});
it('accepts a revert', async function () {
await shouldFail(this.failer.failWithRevert());
});
it('accepts a throw', async function () {
await shouldFail(this.failer.failWithThrow());
});
it('accepts an out of gas', async function () {
await shouldFail(this.failer.failWithOutOfGas({ gas: 2000000 }));
});
});
describe('reverting', function () {
it('rejects if no failure occurs', async function () {
await assertFailure(shouldFail.reverting(this.failer.dontFail()));
});
it('accepts a revert', async function () {
await shouldFail.reverting(this.failer.failWithRevert());
});
it('rejects a throw', async function () {
await assertFailure(shouldFail.reverting(this.failer.failWithThrow()));
});
it('rejects an outOfGas', async function () {
await assertFailure(shouldFail.reverting(this.failer.failWithOutOfGas({ gas: 2000000 })));
});
});
describe('throwing', function () {
it('rejects if no failure occurs', async function () {
await assertFailure(shouldFail.throwing(this.failer.dontFail()));
});
it('accepts a throw', async function () {
await shouldFail.throwing(this.failer.failWithThrow());
});
it('rejects a throw', async function () {
await assertFailure(shouldFail.throwing(this.failer.failWithRevert()));
});
it('rejects an outOfGas', async function () {
await assertFailure(shouldFail.throwing(this.failer.failWithOutOfGas({ gas: 2000000 })));
});
});
describe('outOfGas', function () {
it('rejects if no failure occurs', async function () {
await assertFailure(shouldFail.outOfGas(this.failer.dontFail()));
});
it('accepts an out of gas', async function () {
await shouldFail.outOfGas(this.failer.failWithOutOfGas({ gas: 2000000 }));
});
it('rejects a revert', async function () {
await assertFailure(shouldFail.outOfGas(this.failer.failWithRevert()));
});
it('rejects a throw', async function () {
await assertFailure(shouldFail.outOfGas(this.failer.failWithThrow()));
});
});
});
const time = require('../time');
const shouldFail = require('../shouldFail');
const BigNumber = web3.BigNumber;
require('chai')
.use(require('chai-bignumber')(BigNumber))
.should();
describe('time', function () {
const TOLERANCE_SECONDS = 1;
describe('duration', function () {
it('converts seconds to seconds', function () {
time.duration.seconds(1).should.equal(1);
});
it('converts minutes to seconds', function () {
time.duration.minutes(1).should.equal(60);
});
it('converts hours to seconds', function () {
time.duration.hours(1).should.equal(60 * 60);
});
it('converts days to seconds', function () {
time.duration.days(1).should.equal(60 * 60 * 24);
});
it('converts weeks to seconds', function () {
time.duration.weeks(1).should.equal(60 * 60 * 24 * 7);
});
it('converts years to seconds', function () {
time.duration.years(1).should.equal(60 * 60 * 24 * 365);
});
});
describe('advanceBlock', function () {
it('increases the block number by one', async function () {
const startingBlock = web3.eth.blockNumber;
await time.advanceBlock();
web3.eth.blockNumber.should.be.bignumber.equal(startingBlock + 1);
});
});
context('with starting time', function () {
beforeEach(async function () {
await time.advanceBlock();
this.start = await time.latest();
});
describe('increase', function () {
it('increases time by a duration', async function () {
await time.increase(time.duration.hours(1));
const end = this.start + time.duration.hours(1);
(await time.latest()).should.be.closeTo(end, TOLERANCE_SECONDS);
});
it('throws with negative durations', async function () {
await shouldFail(time.increase(-1));
});
});
describe('increaseTo', function () {
it('increases time to a time in the future', async function () {
const end = this.start + time.duration.hours(1);
await time.increaseTo(end);
(await time.latest()).should.be.closeTo(end, TOLERANCE_SECONDS);
});
it('throws with a time in the past', async function () {
await shouldFail(time.increaseTo(this.start - 30));
});
});
});
});
const { ethGetBlock } = require('./web3');
const pify = require('pify');
function advanceBlock () {
return pify(web3.currentProvider.sendAsync)({
jsonrpc: '2.0',
method: 'evm_mine',
});
}
// Returns the time of the last mined block in seconds
async function latest () {
const block = await ethGetBlock('latest');
return block.timestamp;
}
// Increases ganache time by the passed duration in seconds
async function increase (duration) {
if (duration < 0) throw Error(`Cannot increase time by a negative amount (${duration})`);
await pify(web3.currentProvider.sendAsync)({
jsonrpc: '2.0',
method: 'evm_increaseTime',
params: [duration],
});
await advanceBlock();
}
/**
* Beware that due to the need of calling two separate ganache methods and rpc calls overhead
* it's hard to increase time precisely to a target point so design your test to tolerate
* small fluctuations from time to time.
*
* @param target time in seconds
*/
async function increaseTo (target) {
const now = (await latest());
if (target < now) throw Error(`Cannot increase current time (${now}) to a moment in the past (${target})`);
const diff = target - now;
return increase(diff);
}
const duration = {
seconds: function (val) { return val; },
minutes: function (val) { return val * this.seconds(60); },
hours: function (val) { return val * this.minutes(60); },
days: function (val) { return val * this.hours(24); },
weeks: function (val) { return val * this.days(7); },
years: function (val) { return val * this.days(365); },
};
module.exports = {
advanceBlock,
latest,
increase,
increaseTo,
duration,
};
const pify = require('pify');
const ethAsync = pify(web3.eth);
module.exports = {
ethGetBalance: ethAsync.getBalance,
ethGetBlock: ethAsync.getBlock,
ethGetTransactionReceipt: ethAsync.getTransactionReceipt,
ethSendTransaction: ethAsync.sendTransaction,
};
const { shouldFail } = require('openzeppelin-test-helpers');
const { shouldSupportInterfaces } = require('./SupportsInterface.behavior'); const { shouldSupportInterfaces } = require('./SupportsInterface.behavior');
const shouldFail = require('../helpers/shouldFail');
const ERC165Mock = artifacts.require('ERC165Mock'); const ERC165Mock = artifacts.require('ERC165Mock');
require('chai')
.should();
contract('ERC165', function () { contract('ERC165', function () {
beforeEach(async function () { beforeEach(async function () {
this.mock = await ERC165Mock.new(); this.mock = await ERC165Mock.new();
}); });
it('does not allow 0xffffffff', async function () { it('does not allow 0xffffffff', async function () {
await shouldFail.reverting( await shouldFail.reverting(this.mock.registerInterface('0xffffffff'));
this.mock.registerInterface(0xffffffff)
);
}); });
shouldSupportInterfaces([ shouldSupportInterfaces([
......
require('openzeppelin-test-helpers');
const ERC165CheckerMock = artifacts.require('ERC165CheckerMock'); const ERC165CheckerMock = artifacts.require('ERC165CheckerMock');
const ERC165NotSupported = artifacts.require('ERC165NotSupported'); const ERC165NotSupported = artifacts.require('ERC165NotSupported');
const ERC165InterfacesSupported = artifacts.require('ERC165InterfacesSupported'); const ERC165InterfacesSupported = artifacts.require('ERC165InterfacesSupported');
...@@ -9,8 +11,6 @@ const DUMMY_UNSUPPORTED_ID = '0xbaddcafe'; ...@@ -9,8 +11,6 @@ const DUMMY_UNSUPPORTED_ID = '0xbaddcafe';
const DUMMY_UNSUPPORTED_ID_2 = '0xbaadcafe'; const DUMMY_UNSUPPORTED_ID_2 = '0xbaadcafe';
const DUMMY_ACCOUNT = '0x1111111111111111111111111111111111111111'; const DUMMY_ACCOUNT = '0x1111111111111111111111111111111111111111';
require('../helpers/setup');
contract('ERC165Checker', function () { contract('ERC165Checker', function () {
beforeEach(async function () { beforeEach(async function () {
this.mock = await ERC165CheckerMock.new(); this.mock = await ERC165CheckerMock.new();
......
const { makeInterfaceId } = require('../helpers/makeInterfaceId'); const { makeInterfaceId } = require('openzeppelin-test-helpers');
const INTERFACE_IDS = { const INTERFACE_IDS = {
ERC165: makeInterfaceId([ ERC165: makeInterfaceId([
......
const shouldFail = require('../helpers/shouldFail'); const { expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const expectEvent = require('../helpers/expectEvent'); const { shouldBehaveLikePublicRole } = require('../behaviors/access/roles/PublicRole.behavior');
const PausableMock = artifacts.require('PausableMock'); const PausableMock = artifacts.require('PausableMock');
const { shouldBehaveLikePublicRole } = require('../access/roles/PublicRole.behavior');
require('../helpers/setup');
contract('Pausable', function ([_, pauser, otherPauser, anyone, ...otherAccounts]) { contract('Pausable', function ([_, pauser, otherPauser, anyone, ...otherAccounts]) {
beforeEach(async function () { beforeEach(async function () {
...@@ -26,10 +23,10 @@ contract('Pausable', function ([_, pauser, otherPauser, anyone, ...otherAccounts ...@@ -26,10 +23,10 @@ contract('Pausable', function ([_, pauser, otherPauser, anyone, ...otherAccounts
}); });
it('can perform normal process in non-pause', async function () { it('can perform normal process in non-pause', async function () {
(await this.pausable.count()).should.be.bignumber.equal(0); (await this.pausable.count()).should.be.bignumber.equal('0');
await this.pausable.normalProcess({ from: anyone }); await this.pausable.normalProcess({ from: anyone });
(await this.pausable.count()).should.be.bignumber.equal(1); (await this.pausable.count()).should.be.bignumber.equal('1');
}); });
it('cannot take drastic measure in non-pause', async function () { it('cannot take drastic measure in non-pause', async function () {
...@@ -89,9 +86,9 @@ contract('Pausable', function ([_, pauser, otherPauser, anyone, ...otherAccounts ...@@ -89,9 +86,9 @@ contract('Pausable', function ([_, pauser, otherPauser, anyone, ...otherAccounts
}); });
it('should resume allowing normal process', async function () { it('should resume allowing normal process', async function () {
(await this.pausable.count()).should.be.bignumber.equal(0); (await this.pausable.count()).should.be.bignumber.equal('0');
await this.pausable.normalProcess({ from: anyone }); await this.pausable.normalProcess({ from: anyone });
(await this.pausable.count()).should.be.bignumber.equal(1); (await this.pausable.count()).should.be.bignumber.equal('1');
}); });
it('should prevent drastic measure', async function () { it('should prevent drastic measure', async function () {
......
const MathMock = artifacts.require('MathMock'); const { BN } = require('openzeppelin-test-helpers');
const { BigNumber } = require('../helpers/setup'); const MathMock = artifacts.require('MathMock');
contract('Math', function () { contract('Math', function () {
const min = 1234; const min = new BN('1234');
const max = 5678; const max = new BN('5678');
beforeEach(async function () { beforeEach(async function () {
this.math = await MathMock.new(); this.math = await MathMock.new();
...@@ -32,24 +32,24 @@ contract('Math', function () { ...@@ -32,24 +32,24 @@ contract('Math', function () {
describe('average', function () { describe('average', function () {
function bnAverage (a, b) { function bnAverage (a, b) {
return a.plus(b).div(2).truncated(); return a.add(b).divn(2);
} }
it('is correctly calculated with two odd numbers', async function () { it('is correctly calculated with two odd numbers', async function () {
const a = new BigNumber(57417); const a = new BN('57417');
const b = new BigNumber(95431); const b = new BN('95431');
(await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b)); (await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b));
}); });
it('is correctly calculated with two even numbers', async function () { it('is correctly calculated with two even numbers', async function () {
const a = new BigNumber(42304); const a = new BN('42304');
const b = new BigNumber(84346); const b = new BN('84346');
(await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b)); (await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b));
}); });
it('is correctly calculated with one even and one odd number', async function () { it('is correctly calculated with one even and one odd number', async function () {
const a = new BigNumber(57417); const a = new BN('57417');
const b = new BigNumber(84346); const b = new BN('84346');
(await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b)); (await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b));
}); });
}); });
......
const shouldFail = require('../helpers/shouldFail'); const { BN, constants, shouldFail } = require('openzeppelin-test-helpers');
const { MAX_UINT256 } = require('../helpers/constants'); const { MAX_UINT256 } = constants;
const SafeMathMock = artifacts.require('SafeMathMock'); const SafeMathMock = artifacts.require('SafeMathMock');
const { BigNumber } = require('../helpers/setup');
contract('SafeMath', function () { contract('SafeMath', function () {
beforeEach(async function () { beforeEach(async function () {
this.safeMath = await SafeMathMock.new(); this.safeMath = await SafeMathMock.new();
...@@ -12,15 +10,15 @@ contract('SafeMath', function () { ...@@ -12,15 +10,15 @@ contract('SafeMath', function () {
describe('add', function () { describe('add', function () {
it('adds correctly', async function () { it('adds correctly', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(1234); const b = new BN('1234');
(await this.safeMath.add(a, b)).should.be.bignumber.equal(a.plus(b)); (await this.safeMath.add(a, b)).should.be.bignumber.equal(a.add(b));
}); });
it('reverts on addition overflow', async function () { it('reverts on addition overflow', async function () {
const a = MAX_UINT256; const a = MAX_UINT256;
const b = new BigNumber(1); const b = new BN('1');
await shouldFail.reverting(this.safeMath.add(a, b)); await shouldFail.reverting(this.safeMath.add(a, b));
}); });
...@@ -28,15 +26,15 @@ contract('SafeMath', function () { ...@@ -28,15 +26,15 @@ contract('SafeMath', function () {
describe('sub', function () { describe('sub', function () {
it('subtracts correctly', async function () { it('subtracts correctly', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(1234); const b = new BN('1234');
(await this.safeMath.sub(a, b)).should.be.bignumber.equal(a.minus(b)); (await this.safeMath.sub(a, b)).should.be.bignumber.equal(a.sub(b));
}); });
it('reverts if subtraction result would be negative', async function () { it('reverts if subtraction result would be negative', async function () {
const a = new BigNumber(1234); const a = new BN('1234');
const b = new BigNumber(5678); const b = new BN('5678');
await shouldFail.reverting(this.safeMath.sub(a, b)); await shouldFail.reverting(this.safeMath.sub(a, b));
}); });
...@@ -44,29 +42,29 @@ contract('SafeMath', function () { ...@@ -44,29 +42,29 @@ contract('SafeMath', function () {
describe('mul', function () { describe('mul', function () {
it('multiplies correctly', async function () { it('multiplies correctly', async function () {
const a = new BigNumber(1234); const a = new BN('1234');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.mul(a, b)).should.be.bignumber.equal(a.times(b)); (await this.safeMath.mul(a, b)).should.be.bignumber.equal(a.mul(b));
}); });
it('handles a zero product correctly (first number as zero)', async function () { it('handles a zero product correctly (first number as zero)', async function () {
const a = new BigNumber(0); const a = new BN('0');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.mul(a, b)).should.be.bignumber.equal(a.times(b)); (await this.safeMath.mul(a, b)).should.be.bignumber.equal(a.mul(b));
}); });
it('handles a zero product correctly (second number as zero)', async function () { it('handles a zero product correctly (second number as zero)', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(0); const b = new BN('0');
(await this.safeMath.mul(a, b)).should.be.bignumber.equal(a.times(b)); (await this.safeMath.mul(a, b)).should.be.bignumber.equal(a.mul(b));
}); });
it('reverts on multiplication overflow', async function () { it('reverts on multiplication overflow', async function () {
const a = MAX_UINT256; const a = MAX_UINT256;
const b = new BigNumber(2); const b = new BN('2');
await shouldFail.reverting(this.safeMath.mul(a, b)); await shouldFail.reverting(this.safeMath.mul(a, b));
}); });
...@@ -74,29 +72,29 @@ contract('SafeMath', function () { ...@@ -74,29 +72,29 @@ contract('SafeMath', function () {
describe('div', function () { describe('div', function () {
it('divides correctly', async function () { it('divides correctly', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.div(a, b)).should.be.bignumber.equal(a.div(b)); (await this.safeMath.div(a, b)).should.be.bignumber.equal(a.div(b));
}); });
it('divides zero correctly', async function () { it('divides zero correctly', async function () {
const a = new BigNumber(0); const a = new BN('0');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.div(a, b)).should.be.bignumber.equal(0); (await this.safeMath.div(a, b)).should.be.bignumber.equal('0');
}); });
it('returns complete number result on non-even division', async function () { it('returns complete number result on non-even division', async function () {
const a = new BigNumber(7000); const a = new BN('7000');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.div(a, b)).should.be.bignumber.equal(1); (await this.safeMath.div(a, b)).should.be.bignumber.equal('1');
}); });
it('reverts on zero division', async function () { it('reverts on zero division', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(0); const b = new BN('0');
await shouldFail.reverting(this.safeMath.div(a, b)); await shouldFail.reverting(this.safeMath.div(a, b));
}); });
...@@ -105,37 +103,37 @@ contract('SafeMath', function () { ...@@ -105,37 +103,37 @@ contract('SafeMath', function () {
describe('mod', function () { describe('mod', function () {
describe('modulos correctly', async function () { describe('modulos correctly', async function () {
it('when the dividend is smaller than the divisor', async function () { it('when the dividend is smaller than the divisor', async function () {
const a = new BigNumber(284); const a = new BN('284');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.mod(a, b)).should.be.bignumber.equal(a.mod(b)); (await this.safeMath.mod(a, b)).should.be.bignumber.equal(a.mod(b));
}); });
it('when the dividend is equal to the divisor', async function () { it('when the dividend is equal to the divisor', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.mod(a, b)).should.be.bignumber.equal(a.mod(b)); (await this.safeMath.mod(a, b)).should.be.bignumber.equal(a.mod(b));
}); });
it('when the dividend is larger than the divisor', async function () { it('when the dividend is larger than the divisor', async function () {
const a = new BigNumber(7000); const a = new BN('7000');
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.mod(a, b)).should.be.bignumber.equal(a.mod(b)); (await this.safeMath.mod(a, b)).should.be.bignumber.equal(a.mod(b));
}); });
it('when the dividend is a multiple of the divisor', async function () { it('when the dividend is a multiple of the divisor', async function () {
const a = new BigNumber(17034); // 17034 == 5678 * 3 const a = new BN('17034'); // 17034 == 5678 * 3
const b = new BigNumber(5678); const b = new BN('5678');
(await this.safeMath.mod(a, b)).should.be.bignumber.equal(a.mod(b)); (await this.safeMath.mod(a, b)).should.be.bignumber.equal(a.mod(b));
}); });
}); });
it('reverts with a 0 divisor', async function () { it('reverts with a 0 divisor', async function () {
const a = new BigNumber(5678); const a = new BN('5678');
const b = new BigNumber(0); const b = new BN('0');
await shouldFail.reverting(this.safeMath.mod(a, b)); await shouldFail.reverting(this.safeMath.mod(a, b));
}); });
......
const shouldFail = require('../helpers/shouldFail'); const { constants, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const expectEvent = require('../helpers/expectEvent'); const { ZERO_ADDRESS } = constants;
const { ZERO_ADDRESS } = require('../helpers/constants');
require('./../helpers/setup');
function shouldBehaveLikeOwnable (owner, [anyone]) { function shouldBehaveLikeOwnable (owner, [anyone]) {
describe('as an ownable', function () { describe('as an ownable', function () {
...@@ -23,7 +21,7 @@ function shouldBehaveLikeOwnable (owner, [anyone]) { ...@@ -23,7 +21,7 @@ function shouldBehaveLikeOwnable (owner, [anyone]) {
}); });
it('should guard ownership against stuck state', async function () { it('should guard ownership against stuck state', async function () {
await shouldFail.reverting(this.ownable.transferOwnership(null, { from: owner })); await shouldFail.reverting(this.ownable.transferOwnership(ZERO_ADDRESS, { from: owner }));
}); });
it('loses owner after renouncement', async function () { it('loses owner after renouncement', async function () {
......
const shouldFail = require('../helpers/shouldFail'); require('openzeppelin-test-helpers');
require('../helpers/setup');
const { shouldBehaveLikeOwnable } = require('./Ownable.behavior'); const { shouldBehaveLikeOwnable } = require('./Ownable.behavior');
const Ownable = artifacts.require('OwnableMock'); const Ownable = artifacts.require('OwnableMock');
......
const shouldFail = require('../helpers/shouldFail'); const { constants, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const expectEvent = require('../helpers/expectEvent'); const { ZERO_ADDRESS } = constants;
const { ZERO_ADDRESS } = require('../helpers/constants');
const SecondaryMock = artifacts.require('SecondaryMock'); const SecondaryMock = artifacts.require('SecondaryMock');
require('../helpers/setup');
contract('Secondary', function ([_, primary, newPrimary, anyone]) { contract('Secondary', function ([_, primary, newPrimary, anyone]) {
beforeEach(async function () { beforeEach(async function () {
this.secondary = await SecondaryMock.new({ from: primary }); this.secondary = await SecondaryMock.new({ from: primary });
......
const { ethGetBalance } = require('../helpers/web3'); const { balance, constants, ether, expectEvent, send, shouldFail } = require('openzeppelin-test-helpers');
const expectEvent = require('../helpers/expectEvent'); const { ZERO_ADDRESS } = constants;
const send = require('./../helpers/send');
const { ether } = require('../helpers/ether');
const { ZERO_ADDRESS } = require('./../helpers/constants');
require('../helpers/setup');
const shouldFail = require('../helpers/shouldFail');
const PaymentSplitter = artifacts.require('PaymentSplitterMock'); const PaymentSplitter = artifacts.require('PaymentSplitterMock');
contract('PaymentSplitter', function ([_, owner, payee1, payee2, payee3, nonpayee1, payer1]) { contract('PaymentSplitter', function ([_, owner, payee1, payee2, payee3, nonpayee1, payer1]) {
const amount = ether(1.0); const amount = ether('1');
it('rejects an empty set of payees', async function () { it('rejects an empty set of payees', async function () {
await shouldFail.reverting(PaymentSplitter.new([], [])); await shouldFail.reverting(PaymentSplitter.new([], []));
...@@ -45,28 +39,28 @@ contract('PaymentSplitter', function ([_, owner, payee1, payee2, payee3, nonpaye ...@@ -45,28 +39,28 @@ contract('PaymentSplitter', function ([_, owner, payee1, payee2, payee3, nonpaye
}); });
it('should have total shares', async function () { it('should have total shares', async function () {
(await this.contract.totalShares()).should.be.bignumber.equal(20 + 10 + 70); (await this.contract.totalShares()).should.be.bignumber.equal('100');
}); });
it('should have payees', async function () { it('should have payees', async function () {
await Promise.all(this.payees.map(async (payee, index) => { await Promise.all(this.payees.map(async (payee, index) => {
(await this.contract.payee(index)).should.be.equal(payee); (await this.contract.payee(index)).should.be.equal(payee);
(await this.contract.released(payee)).should.be.bignumber.equal(0); (await this.contract.released(payee)).should.be.bignumber.equal('0');
})); }));
}); });
it('should accept payments', async function () { it('should accept payments', async function () {
await send.ether(owner, this.contract.address, amount); await send.ether(owner, this.contract.address, amount);
(await ethGetBalance(this.contract.address)).should.be.bignumber.equal(amount); (await balance.current(this.contract.address)).should.be.bignumber.equal(amount);
}); });
it('should store shares if address is payee', async function () { it('should store shares if address is payee', async function () {
(await this.contract.shares(payee1)).should.be.bignumber.not.equal(0); (await this.contract.shares(payee1)).should.be.bignumber.not.equal('0');
}); });
it('should not store shares if address is not payee', async function () { it('should not store shares if address is not payee', async function () {
(await this.contract.shares(nonpayee1)).should.be.bignumber.equal(0); (await this.contract.shares(nonpayee1)).should.be.bignumber.equal('0');
}); });
it('should throw if no funds to claim', async function () { it('should throw if no funds to claim', async function () {
...@@ -82,30 +76,31 @@ contract('PaymentSplitter', function ([_, owner, payee1, payee2, payee3, nonpaye ...@@ -82,30 +76,31 @@ contract('PaymentSplitter', function ([_, owner, payee1, payee2, payee3, nonpaye
await send.ether(payer1, this.contract.address, amount); await send.ether(payer1, this.contract.address, amount);
// receive funds // receive funds
const initBalance = await ethGetBalance(this.contract.address); const initBalance = await balance.current(this.contract.address);
initBalance.should.be.bignumber.equal(amount); initBalance.should.be.bignumber.equal(amount);
// distribute to payees // distribute to payees
const initAmount1 = await ethGetBalance(payee1);
const { logs: logs1 } = await this.contract.release(payee1); const initAmount1 = await balance.current(payee1);
const profit1 = (await ethGetBalance(payee1)).sub(initAmount1); const { logs: logs1 } = await this.contract.release(payee1, { gasPrice: 0 });
profit1.sub(web3.toWei(0.20, 'ether')).abs().should.be.bignumber.lt(1e16); const profit1 = (await balance.current(payee1)).sub(initAmount1);
profit1.should.be.bignumber.equal(ether('0.20', 'ether'));
expectEvent.inLogs(logs1, 'PaymentReleased', { to: payee1, amount: profit1 }); expectEvent.inLogs(logs1, 'PaymentReleased', { to: payee1, amount: profit1 });
const initAmount2 = await ethGetBalance(payee2); const initAmount2 = await balance.current(payee2);
const { logs: logs2 } = await this.contract.release(payee2); const { logs: logs2 } = await this.contract.release(payee2, { gasPrice: 0 });
const profit2 = (await ethGetBalance(payee2)).sub(initAmount2); const profit2 = (await balance.current(payee2)).sub(initAmount2);
profit2.sub(web3.toWei(0.10, 'ether')).abs().should.be.bignumber.lt(1e16); profit2.should.be.bignumber.equal(ether('0.10', 'ether'));
expectEvent.inLogs(logs2, 'PaymentReleased', { to: payee2, amount: profit2 }); expectEvent.inLogs(logs2, 'PaymentReleased', { to: payee2, amount: profit2 });
const initAmount3 = await ethGetBalance(payee3); const initAmount3 = await balance.current(payee3);
const { logs: logs3 } = await this.contract.release(payee3); const { logs: logs3 } = await this.contract.release(payee3, { gasPrice: 0 });
const profit3 = (await ethGetBalance(payee3)).sub(initAmount3); const profit3 = (await balance.current(payee3)).sub(initAmount3);
profit3.sub(web3.toWei(0.70, 'ether')).abs().should.be.bignumber.lt(1e16); profit3.should.be.bignumber.equal(ether('0.70', 'ether'));
expectEvent.inLogs(logs3, 'PaymentReleased', { to: payee3, amount: profit3 }); expectEvent.inLogs(logs3, 'PaymentReleased', { to: payee3, amount: profit3 });
// end balance should be zero // end balance should be zero
(await ethGetBalance(this.contract.address)).should.be.bignumber.equal(0); (await balance.current(this.contract.address)).should.be.bignumber.equal('0');
// check correct funds released accounting // check correct funds released accounting
(await this.contract.totalReleased()).should.be.bignumber.equal(initBalance); (await this.contract.totalReleased()).should.be.bignumber.equal(initBalance);
......
const { balanceDifference } = require('../helpers/balanceDifference'); const { balance, ether } = require('openzeppelin-test-helpers');
const { ether } = require('../helpers/ether');
require('../helpers/setup');
const PullPaymentMock = artifacts.require('PullPaymentMock'); const PullPaymentMock = artifacts.require('PullPaymentMock');
contract('PullPayment', function ([_, payer, payee1, payee2]) { contract('PullPayment', function ([_, payer, payee1, payee2]) {
const amount = ether(17.0); const amount = ether('17');
beforeEach(async function () { beforeEach(async function () {
this.contract = await PullPaymentMock.new({ value: amount }); this.contract = await PullPaymentMock.new({ value: amount });
...@@ -14,32 +11,32 @@ contract('PullPayment', function ([_, payer, payee1, payee2]) { ...@@ -14,32 +11,32 @@ contract('PullPayment', function ([_, payer, payee1, payee2]) {
it('can record an async payment correctly', async function () { it('can record an async payment correctly', async function () {
await this.contract.callTransfer(payee1, 100, { from: payer }); await this.contract.callTransfer(payee1, 100, { from: payer });
(await this.contract.payments(payee1)).should.be.bignumber.equal(100); (await this.contract.payments(payee1)).should.be.bignumber.equal('100');
}); });
it('can add multiple balances on one account', async function () { it('can add multiple balances on one account', async function () {
await this.contract.callTransfer(payee1, 200, { from: payer }); await this.contract.callTransfer(payee1, 200, { from: payer });
await this.contract.callTransfer(payee1, 300, { from: payer }); await this.contract.callTransfer(payee1, 300, { from: payer });
(await this.contract.payments(payee1)).should.be.bignumber.equal(500); (await this.contract.payments(payee1)).should.be.bignumber.equal('500');
}); });
it('can add balances on multiple accounts', async function () { it('can add balances on multiple accounts', async function () {
await this.contract.callTransfer(payee1, 200, { from: payer }); await this.contract.callTransfer(payee1, 200, { from: payer });
await this.contract.callTransfer(payee2, 300, { from: payer }); await this.contract.callTransfer(payee2, 300, { from: payer });
(await this.contract.payments(payee1)).should.be.bignumber.equal(200); (await this.contract.payments(payee1)).should.be.bignumber.equal('200');
(await this.contract.payments(payee2)).should.be.bignumber.equal(300); (await this.contract.payments(payee2)).should.be.bignumber.equal('300');
}); });
it('can withdraw payment', async function () { it('can withdraw payment', async function () {
(await balanceDifference(payee1, async () => { (await balance.difference(payee1, async () => {
await this.contract.callTransfer(payee1, amount, { from: payer }); await this.contract.callTransfer(payee1, amount, { from: payer });
(await this.contract.payments(payee1)).should.be.bignumber.equal(amount); (await this.contract.payments(payee1)).should.be.bignumber.equal(amount);
await this.contract.withdrawPayments(payee1); await this.contract.withdrawPayments(payee1);
})).should.be.bignumber.equal(amount); })).should.be.bignumber.equal(amount);
(await this.contract.payments(payee1)).should.be.bignumber.equal(0); (await this.contract.payments(payee1)).should.be.bignumber.equal('0');
}); });
}); });
const { ether, shouldFail } = require('openzeppelin-test-helpers');
const { shouldBehaveLikeEscrow } = require('./Escrow.behavior'); const { shouldBehaveLikeEscrow } = require('./Escrow.behavior');
const shouldFail = require('../../helpers/shouldFail');
const { ether } = require('../../helpers/ether');
require('../../helpers/setup');
const ConditionalEscrowMock = artifacts.require('ConditionalEscrowMock'); const ConditionalEscrowMock = artifacts.require('ConditionalEscrowMock');
contract('ConditionalEscrow', function ([_, owner, payee, ...otherAccounts]) { contract('ConditionalEscrow', function ([_, owner, payee, ...otherAccounts]) {
...@@ -21,7 +17,7 @@ contract('ConditionalEscrow', function ([_, owner, payee, ...otherAccounts]) { ...@@ -21,7 +17,7 @@ contract('ConditionalEscrow', function ([_, owner, payee, ...otherAccounts]) {
}); });
context('when withdrawal is disallowed', function () { context('when withdrawal is disallowed', function () {
const amount = ether(23.0); const amount = ether('23');
beforeEach(async function () { beforeEach(async function () {
await this.escrow.setAllowed(payee, false); await this.escrow.setAllowed(payee, false);
......
const expectEvent = require('../../helpers/expectEvent'); const { balance, ether, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const shouldFail = require('../../helpers/shouldFail');
const { ethGetBalance } = require('../../helpers/web3');
const { balanceDifference } = require('../../helpers/balanceDifference');
const { ether } = require('../../helpers/ether');
require('../../helpers/setup');
function shouldBehaveLikeEscrow (primary, [payee1, payee2]) { function shouldBehaveLikeEscrow (primary, [payee1, payee2]) {
const amount = ether(42.0); const amount = ether('42');
describe('as an escrow', function () { describe('as an escrow', function () {
describe('deposits', function () { describe('deposits', function () {
it('can accept a single deposit', async function () { it('can accept a single deposit', async function () {
await this.escrow.deposit(payee1, { from: primary, value: amount }); await this.escrow.deposit(payee1, { from: primary, value: amount });
(await ethGetBalance(this.escrow.address)).should.be.bignumber.equal(amount); (await balance.current(this.escrow.address)).should.be.bignumber.equal(amount);
(await this.escrow.depositsOf(payee1)).should.be.bignumber.equal(amount); (await this.escrow.depositsOf(payee1)).should.be.bignumber.equal(amount);
}); });
...@@ -37,34 +31,34 @@ function shouldBehaveLikeEscrow (primary, [payee1, payee2]) { ...@@ -37,34 +31,34 @@ function shouldBehaveLikeEscrow (primary, [payee1, payee2]) {
it('can add multiple deposits on a single account', async function () { it('can add multiple deposits on a single account', async function () {
await this.escrow.deposit(payee1, { from: primary, value: amount }); await this.escrow.deposit(payee1, { from: primary, value: amount });
await this.escrow.deposit(payee1, { from: primary, value: amount * 2 }); await this.escrow.deposit(payee1, { from: primary, value: amount.muln(2) });
(await ethGetBalance(this.escrow.address)).should.be.bignumber.equal(amount * 3); (await balance.current(this.escrow.address)).should.be.bignumber.equal(amount.muln(3));
(await this.escrow.depositsOf(payee1)).should.be.bignumber.equal(amount * 3); (await this.escrow.depositsOf(payee1)).should.be.bignumber.equal(amount.muln(3));
}); });
it('can track deposits to multiple accounts', async function () { it('can track deposits to multiple accounts', async function () {
await this.escrow.deposit(payee1, { from: primary, value: amount }); await this.escrow.deposit(payee1, { from: primary, value: amount });
await this.escrow.deposit(payee2, { from: primary, value: amount * 2 }); await this.escrow.deposit(payee2, { from: primary, value: amount.muln(2) });
(await ethGetBalance(this.escrow.address)).should.be.bignumber.equal(amount * 3); (await balance.current(this.escrow.address)).should.be.bignumber.equal(amount.muln(3));
(await this.escrow.depositsOf(payee1)).should.be.bignumber.equal(amount); (await this.escrow.depositsOf(payee1)).should.be.bignumber.equal(amount);
(await this.escrow.depositsOf(payee2)).should.be.bignumber.equal(amount * 2); (await this.escrow.depositsOf(payee2)).should.be.bignumber.equal(amount.muln(2));
}); });
}); });
describe('withdrawals', async function () { describe('withdrawals', async function () {
it('can withdraw payments', async function () { it('can withdraw payments', async function () {
(await balanceDifference(payee1, async () => { (await balance.difference(payee1, async () => {
await this.escrow.deposit(payee1, { from: primary, value: amount }); await this.escrow.deposit(payee1, { from: primary, value: amount });
await this.escrow.withdraw(payee1, { from: primary }); await this.escrow.withdraw(payee1, { from: primary });
})).should.be.bignumber.equal(amount); })).should.be.bignumber.equal(amount);
(await ethGetBalance(this.escrow.address)).should.be.bignumber.equal(0); (await balance.current(this.escrow.address)).should.be.bignumber.equal('0');
(await this.escrow.depositsOf(payee1)).should.be.bignumber.equal(0); (await this.escrow.depositsOf(payee1)).should.be.bignumber.equal('0');
}); });
it('can do an empty withdrawal', async function () { it('can do an empty withdrawal', async function () {
......
require('openzeppelin-test-helpers');
const { shouldBehaveLikeEscrow } = require('./Escrow.behavior'); const { shouldBehaveLikeEscrow } = require('./Escrow.behavior');
const Escrow = artifacts.require('EscrowMock'); const Escrow = artifacts.require('EscrowMock');
......
const shouldFail = require('../../helpers/shouldFail'); const { balance, constants, ether, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const expectEvent = require('../../helpers/expectEvent'); const { ZERO_ADDRESS } = constants;
const { balanceDifference } = require('../../helpers/balanceDifference');
const { ether } = require('../../helpers/ether');
const { ZERO_ADDRESS } = require('../../helpers/constants');
require('../../helpers/setup');
const RefundEscrow = artifacts.require('RefundEscrowMock'); const RefundEscrow = artifacts.require('RefundEscrowMock');
contract('RefundEscrow', function ([_, primary, beneficiary, refundee1, refundee2]) { contract('RefundEscrow', function ([_, primary, beneficiary, refundee1, refundee2]) {
const amount = ether(54.0); const amount = ether('54');
const refundees = [refundee1, refundee2]; const refundees = [refundee1, refundee2];
it('requires a non-null beneficiary', async function () { it('requires a non-null beneficiary', async function () {
...@@ -26,7 +21,7 @@ contract('RefundEscrow', function ([_, primary, beneficiary, refundee1, refundee ...@@ -26,7 +21,7 @@ contract('RefundEscrow', function ([_, primary, beneficiary, refundee1, refundee
context('active state', function () { context('active state', function () {
it('has beneficiary and state', async function () { it('has beneficiary and state', async function () {
(await this.escrow.beneficiary()).should.be.equal(beneficiary); (await this.escrow.beneficiary()).should.be.equal(beneficiary);
(await this.escrow.state()).should.be.bignumber.equal(0); (await this.escrow.state()).should.be.bignumber.equal('0');
}); });
it('accepts deposits', async function () { it('accepts deposits', async function () {
...@@ -69,9 +64,9 @@ contract('RefundEscrow', function ([_, primary, beneficiary, refundee1, refundee ...@@ -69,9 +64,9 @@ contract('RefundEscrow', function ([_, primary, beneficiary, refundee1, refundee
}); });
it('allows beneficiary withdrawal', async function () { it('allows beneficiary withdrawal', async function () {
(await balanceDifference(beneficiary, () => (await balance.difference(beneficiary, () =>
this.escrow.beneficiaryWithdraw() this.escrow.beneficiaryWithdraw()
)).should.be.bignumber.equal(amount * refundees.length); )).should.be.bignumber.equal(amount.muln(refundees.length));
}); });
it('prevents entering the refund state', async function () { it('prevents entering the refund state', async function () {
...@@ -103,7 +98,7 @@ contract('RefundEscrow', function ([_, primary, beneficiary, refundee1, refundee ...@@ -103,7 +98,7 @@ contract('RefundEscrow', function ([_, primary, beneficiary, refundee1, refundee
it('refunds refundees', async function () { it('refunds refundees', async function () {
for (const refundee of [refundee1, refundee2]) { for (const refundee of [refundee1, refundee2]) {
(await balanceDifference(refundee, () => (await balance.difference(refundee, () =>
this.escrow.withdraw(refundee, { from: primary })) this.escrow.withdraw(refundee, { from: primary }))
).should.be.bignumber.equal(amount); ).should.be.bignumber.equal(amount);
} }
......
const { BN } = require('openzeppelin-test-helpers');
const { shouldBehaveLikeERC20Burnable } = require('./behaviors/ERC20Burnable.behavior'); const { shouldBehaveLikeERC20Burnable } = require('./behaviors/ERC20Burnable.behavior');
const ERC20BurnableMock = artifacts.require('ERC20BurnableMock'); const ERC20BurnableMock = artifacts.require('ERC20BurnableMock');
contract('ERC20Burnable', function ([_, owner, ...otherAccounts]) { contract('ERC20Burnable', function ([_, owner, ...otherAccounts]) {
const initialBalance = 1000; const initialBalance = new BN(1000);
beforeEach(async function () { beforeEach(async function () {
this.token = await ERC20BurnableMock.new(owner, initialBalance, { from: owner }); this.token = await ERC20BurnableMock.new(owner, initialBalance, { from: owner });
......
const shouldFail = require('../../helpers/shouldFail'); const { BN, ether, shouldFail } = require('openzeppelin-test-helpers');
const { ether } = require('../../helpers/ether');
const { shouldBehaveLikeERC20Mintable } = require('./behaviors/ERC20Mintable.behavior'); const { shouldBehaveLikeERC20Mintable } = require('./behaviors/ERC20Mintable.behavior');
const { shouldBehaveLikeERC20Capped } = require('./behaviors/ERC20Capped.behavior'); const { shouldBehaveLikeERC20Capped } = require('./behaviors/ERC20Capped.behavior');
const ERC20Capped = artifacts.require('ERC20CappedMock'); const ERC20Capped = artifacts.require('ERC20CappedMock');
contract('ERC20Capped', function ([_, minter, ...otherAccounts]) { contract('ERC20Capped', function ([_, minter, ...otherAccounts]) {
const cap = ether(1000); const cap = ether('1000');
it('requires a non-zero cap', async function () { it('requires a non-zero cap', async function () {
await shouldFail.reverting( await shouldFail.reverting(
ERC20Capped.new(0, { from: minter }) ERC20Capped.new(new BN(0), { from: minter })
); );
}); });
......
require('../../helpers/setup'); const { BN } = require('openzeppelin-test-helpers');
const ERC20DetailedMock = artifacts.require('ERC20DetailedMock'); const ERC20DetailedMock = artifacts.require('ERC20DetailedMock');
contract('ERC20Detailed', function () { contract('ERC20Detailed', function () {
const _name = 'My Detailed ERC20'; const _name = 'My Detailed ERC20';
const _symbol = 'MDT'; const _symbol = 'MDT';
const _decimals = 18; const _decimals = new BN(18);
beforeEach(async function () { beforeEach(async function () {
this.detailedERC20 = await ERC20DetailedMock.new(_name, _symbol, _decimals); this.detailedERC20 = await ERC20DetailedMock.new(_name, _symbol, _decimals);
......
const { shouldBehaveLikeERC20Mintable } = require('./behaviors/ERC20Mintable.behavior'); const { shouldBehaveLikeERC20Mintable } = require('./behaviors/ERC20Mintable.behavior');
const ERC20MintableMock = artifacts.require('ERC20MintableMock'); const ERC20MintableMock = artifacts.require('ERC20MintableMock');
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
contract('ERC20Mintable', function ([_, minter, otherMinter, ...otherAccounts]) { contract('ERC20Mintable', function ([_, minter, otherMinter, ...otherAccounts]) {
beforeEach(async function () { beforeEach(async function () {
......
const expectEvent = require('../../helpers/expectEvent'); const { BN, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const shouldFail = require('../../helpers/shouldFail');
const ERC20PausableMock = artifacts.require('ERC20PausableMock'); const ERC20PausableMock = artifacts.require('ERC20PausableMock');
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
contract('ERC20Pausable', function ([_, pauser, otherPauser, recipient, anotherAccount, ...otherAccounts]) { contract('ERC20Pausable', function ([_, pauser, otherPauser, recipient, anotherAccount, ...otherAccounts]) {
const initialSupply = new BN(100);
beforeEach(async function () { beforeEach(async function () {
this.token = await ERC20PausableMock.new(pauser, 100, { from: pauser }); this.token = await ERC20PausableMock.new(pauser, initialSupply, { from: pauser });
}); });
describe('pauser role', function () { describe('pauser role', function () {
...@@ -114,132 +115,142 @@ contract('ERC20Pausable', function ([_, pauser, otherPauser, recipient, anotherA ...@@ -114,132 +115,142 @@ contract('ERC20Pausable', function ([_, pauser, otherPauser, recipient, anotherA
describe('transfer', function () { describe('transfer', function () {
it('allows to transfer when unpaused', async function () { it('allows to transfer when unpaused', async function () {
await this.token.transfer(recipient, 100, { from: pauser }); await this.token.transfer(recipient, initialSupply, { from: pauser });
(await this.token.balanceOf(pauser)).should.be.bignumber.equal(0); (await this.token.balanceOf(pauser)).should.be.bignumber.equal('0');
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(100); (await this.token.balanceOf(recipient)).should.be.bignumber.equal(initialSupply);
}); });
it('allows to transfer when paused and then unpaused', async function () { it('allows to transfer when paused and then unpaused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await this.token.unpause({ from: pauser }); await this.token.unpause({ from: pauser });
await this.token.transfer(recipient, 100, { from: pauser }); await this.token.transfer(recipient, initialSupply, { from: pauser });
(await this.token.balanceOf(pauser)).should.be.bignumber.equal(0); (await this.token.balanceOf(pauser)).should.be.bignumber.equal('0');
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(100); (await this.token.balanceOf(recipient)).should.be.bignumber.equal(initialSupply);
}); });
it('reverts when trying to transfer when paused', async function () { it('reverts when trying to transfer when paused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await shouldFail.reverting(this.token.transfer(recipient, 100, { from: pauser })); await shouldFail.reverting(this.token.transfer(recipient, initialSupply, { from: pauser }));
}); });
}); });
describe('approve', function () { describe('approve', function () {
const allowance = new BN(40);
it('allows to approve when unpaused', async function () { it('allows to approve when unpaused', async function () {
await this.token.approve(anotherAccount, 40, { from: pauser }); await this.token.approve(anotherAccount, allowance, { from: pauser });
(await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(40); (await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(allowance);
}); });
it('allows to approve when paused and then unpaused', async function () { it('allows to approve when paused and then unpaused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await this.token.unpause({ from: pauser }); await this.token.unpause({ from: pauser });
await this.token.approve(anotherAccount, 40, { from: pauser }); await this.token.approve(anotherAccount, allowance, { from: pauser });
(await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(40); (await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(allowance);
}); });
it('reverts when trying to approve when paused', async function () { it('reverts when trying to approve when paused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await shouldFail.reverting(this.token.approve(anotherAccount, 40, { from: pauser })); await shouldFail.reverting(this.token.approve(anotherAccount, allowance, { from: pauser }));
}); });
}); });
describe('transfer from', function () { describe('transfer from', function () {
const allowance = new BN(40);
beforeEach(async function () { beforeEach(async function () {
await this.token.approve(anotherAccount, 50, { from: pauser }); await this.token.approve(anotherAccount, allowance, { from: pauser });
}); });
it('allows to transfer from when unpaused', async function () { it('allows to transfer from when unpaused', async function () {
await this.token.transferFrom(pauser, recipient, 40, { from: anotherAccount }); await this.token.transferFrom(pauser, recipient, allowance, { from: anotherAccount });
(await this.token.balanceOf(pauser)).should.be.bignumber.equal(60); (await this.token.balanceOf(recipient)).should.be.bignumber.equal(allowance);
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(40); (await this.token.balanceOf(pauser)).should.be.bignumber.equal(initialSupply.sub(allowance));
}); });
it('allows to transfer when paused and then unpaused', async function () { it('allows to transfer when paused and then unpaused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await this.token.unpause({ from: pauser }); await this.token.unpause({ from: pauser });
await this.token.transferFrom(pauser, recipient, 40, { from: anotherAccount }); await this.token.transferFrom(pauser, recipient, allowance, { from: anotherAccount });
(await this.token.balanceOf(pauser)).should.be.bignumber.equal(60); (await this.token.balanceOf(recipient)).should.be.bignumber.equal(allowance);
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(40); (await this.token.balanceOf(pauser)).should.be.bignumber.equal(initialSupply.sub(allowance));
}); });
it('reverts when trying to transfer from when paused', async function () { it('reverts when trying to transfer from when paused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await shouldFail.reverting(this.token.transferFrom(pauser, recipient, 40, { from: anotherAccount })); await shouldFail.reverting(this.token.transferFrom(pauser, recipient, allowance, { from: anotherAccount }));
}); });
}); });
describe('decrease approval', function () { describe('decrease approval', function () {
const allowance = new BN(40);
const decrement = new BN(10);
beforeEach(async function () { beforeEach(async function () {
await this.token.approve(anotherAccount, 100, { from: pauser }); await this.token.approve(anotherAccount, allowance, { from: pauser });
}); });
it('allows to decrease approval when unpaused', async function () { it('allows to decrease approval when unpaused', async function () {
await this.token.decreaseAllowance(anotherAccount, 40, { from: pauser }); await this.token.decreaseAllowance(anotherAccount, decrement, { from: pauser });
(await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(60); (await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(allowance.sub(decrement));
}); });
it('allows to decrease approval when paused and then unpaused', async function () { it('allows to decrease approval when paused and then unpaused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await this.token.unpause({ from: pauser }); await this.token.unpause({ from: pauser });
await this.token.decreaseAllowance(anotherAccount, 40, { from: pauser }); await this.token.decreaseAllowance(anotherAccount, decrement, { from: pauser });
(await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(60); (await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(allowance.sub(decrement));
}); });
it('reverts when trying to transfer when paused', async function () { it('reverts when trying to transfer when paused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await shouldFail.reverting(this.token.decreaseAllowance(anotherAccount, 40, { from: pauser })); await shouldFail.reverting(this.token.decreaseAllowance(anotherAccount, decrement, { from: pauser }));
}); });
}); });
describe('increase approval', function () { describe('increase approval', function () {
const allowance = new BN(40);
const increment = new BN(30);
beforeEach(async function () { beforeEach(async function () {
await this.token.approve(anotherAccount, 100, { from: pauser }); await this.token.approve(anotherAccount, allowance, { from: pauser });
}); });
it('allows to increase approval when unpaused', async function () { it('allows to increase approval when unpaused', async function () {
await this.token.increaseAllowance(anotherAccount, 40, { from: pauser }); await this.token.increaseAllowance(anotherAccount, increment, { from: pauser });
(await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(140); (await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(allowance.add(increment));
}); });
it('allows to increase approval when paused and then unpaused', async function () { it('allows to increase approval when paused and then unpaused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await this.token.unpause({ from: pauser }); await this.token.unpause({ from: pauser });
await this.token.increaseAllowance(anotherAccount, 40, { from: pauser }); await this.token.increaseAllowance(anotherAccount, increment, { from: pauser });
(await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(140); (await this.token.allowance(pauser, anotherAccount)).should.be.bignumber.equal(allowance.add(increment));
}); });
it('reverts when trying to increase approval when paused', async function () { it('reverts when trying to increase approval when paused', async function () {
await this.token.pause({ from: pauser }); await this.token.pause({ from: pauser });
await shouldFail.reverting(this.token.increaseAllowance(anotherAccount, 40, { from: pauser })); await shouldFail.reverting(this.token.increaseAllowance(anotherAccount, increment, { from: pauser }));
}); });
}); });
}); });
......
const shouldFail = require('../../helpers/shouldFail'); const { shouldFail } = require('openzeppelin-test-helpers');
require('../../helpers/setup');
const SafeERC20Helper = artifacts.require('SafeERC20Helper'); const SafeERC20Helper = artifacts.require('SafeERC20Helper');
......
const shouldFail = require('../../helpers/shouldFail'); const { BN, shouldFail, time } = require('openzeppelin-test-helpers');
const time = require('../../helpers/time');
const { BigNumber } = require('../../helpers/setup');
const ERC20Mintable = artifacts.require('ERC20MintableMock'); const ERC20Mintable = artifacts.require('ERC20MintableMock');
const TokenTimelock = artifacts.require('TokenTimelockMock'); const TokenTimelock = artifacts.require('TokenTimelockMock');
contract('TokenTimelock', function ([_, minter, beneficiary]) { contract('TokenTimelock', function ([_, minter, beneficiary]) {
const amount = new BigNumber(100); const amount = new BN(100);
context('with token', function () { context('with token', function () {
beforeEach(async function () { beforeEach(async function () {
...@@ -15,7 +12,7 @@ contract('TokenTimelock', function ([_, minter, beneficiary]) { ...@@ -15,7 +12,7 @@ contract('TokenTimelock', function ([_, minter, beneficiary]) {
}); });
it('rejects a release time in the past', async function () { it('rejects a release time in the past', async function () {
const pastReleaseTime = (await time.latest()) - time.duration.years(1); const pastReleaseTime = (await time.latest()).sub(time.duration.years(1));
await shouldFail.reverting( await shouldFail.reverting(
TokenTimelock.new(this.token.address, beneficiary, pastReleaseTime) TokenTimelock.new(this.token.address, beneficiary, pastReleaseTime)
); );
...@@ -23,7 +20,7 @@ contract('TokenTimelock', function ([_, minter, beneficiary]) { ...@@ -23,7 +20,7 @@ contract('TokenTimelock', function ([_, minter, beneficiary]) {
context('once deployed', function () { context('once deployed', function () {
beforeEach(async function () { beforeEach(async function () {
this.releaseTime = (await time.latest()) + time.duration.years(1); this.releaseTime = (await time.latest()).add(time.duration.years(1));
this.timelock = await TokenTimelock.new(this.token.address, beneficiary, this.releaseTime); this.timelock = await TokenTimelock.new(this.token.address, beneficiary, this.releaseTime);
await this.token.mint(this.timelock.address, amount, { from: minter }); await this.token.mint(this.timelock.address, amount, { from: minter });
}); });
...@@ -39,24 +36,24 @@ contract('TokenTimelock', function ([_, minter, beneficiary]) { ...@@ -39,24 +36,24 @@ contract('TokenTimelock', function ([_, minter, beneficiary]) {
}); });
it('cannot be released just before time limit', async function () { it('cannot be released just before time limit', async function () {
await time.increaseTo(this.releaseTime - time.duration.seconds(3)); await time.increaseTo(this.releaseTime.sub(time.duration.seconds(3)));
await shouldFail.reverting(this.timelock.release()); await shouldFail.reverting(this.timelock.release());
}); });
it('can be released just after limit', async function () { it('can be released just after limit', async function () {
await time.increaseTo(this.releaseTime + time.duration.seconds(1)); await time.increaseTo(this.releaseTime.add(time.duration.seconds(1)));
await this.timelock.release(); await this.timelock.release();
(await this.token.balanceOf(beneficiary)).should.be.bignumber.equal(amount); (await this.token.balanceOf(beneficiary)).should.be.bignumber.equal(amount);
}); });
it('can be released after time limit', async function () { it('can be released after time limit', async function () {
await time.increaseTo(this.releaseTime + time.duration.years(1)); await time.increaseTo(this.releaseTime.add(time.duration.years(1)));
await this.timelock.release(); await this.timelock.release();
(await this.token.balanceOf(beneficiary)).should.be.bignumber.equal(amount); (await this.token.balanceOf(beneficiary)).should.be.bignumber.equal(amount);
}); });
it('cannot be released twice', async function () { it('cannot be released twice', async function () {
await time.increaseTo(this.releaseTime + time.duration.years(1)); await time.increaseTo(this.releaseTime.add(time.duration.years(1)));
await this.timelock.release(); await this.timelock.release();
await shouldFail.reverting(this.timelock.release()); await shouldFail.reverting(this.timelock.release());
(await this.token.balanceOf(beneficiary)).should.be.bignumber.equal(amount); (await this.token.balanceOf(beneficiary)).should.be.bignumber.equal(amount);
......
const shouldFail = require('../../../helpers/shouldFail'); const { BN, constants, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const expectEvent = require('../../../helpers/expectEvent'); const { ZERO_ADDRESS } = constants;
const { ZERO_ADDRESS } = require('../../../helpers/constants');
require('../../../helpers/setup');
function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) {
describe('burn', function () { describe('burn', function () {
describe('when the given amount is not greater than balance of the sender', function () { describe('when the given amount is not greater than balance of the sender', function () {
context('for a zero amount', function () { context('for a zero amount', function () {
shouldBurn(0); shouldBurn(new BN(0));
}); });
context('for a non-zero amount', function () { context('for a non-zero amount', function () {
shouldBurn(100); shouldBurn(new BN(100));
}); });
function shouldBurn (amount) { function shouldBurn (amount) {
...@@ -21,7 +18,7 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { ...@@ -21,7 +18,7 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) {
}); });
it('burns the requested amount', async function () { it('burns the requested amount', async function () {
(await this.token.balanceOf(owner)).should.be.bignumber.equal(initialBalance - amount); (await this.token.balanceOf(owner)).should.be.bignumber.equal(initialBalance.sub(amount));
}); });
it('emits a transfer event', async function () { it('emits a transfer event', async function () {
...@@ -35,7 +32,7 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { ...@@ -35,7 +32,7 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) {
}); });
describe('when the given amount is greater than the balance of the sender', function () { describe('when the given amount is greater than the balance of the sender', function () {
const amount = initialBalance + 1; const amount = initialBalance.addn(1);
it('reverts', async function () { it('reverts', async function () {
await shouldFail.reverting(this.token.burn(amount, { from: owner })); await shouldFail.reverting(this.token.burn(amount, { from: owner }));
...@@ -46,15 +43,15 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { ...@@ -46,15 +43,15 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) {
describe('burnFrom', function () { describe('burnFrom', function () {
describe('on success', function () { describe('on success', function () {
context('for a zero amount', function () { context('for a zero amount', function () {
shouldBurnFrom(0); shouldBurnFrom(new BN(0));
}); });
context('for a non-zero amount', function () { context('for a non-zero amount', function () {
shouldBurnFrom(100); shouldBurnFrom(new BN(100));
}); });
function shouldBurnFrom (amount) { function shouldBurnFrom (amount) {
const originalAllowance = amount * 3; const originalAllowance = amount.muln(3);
beforeEach(async function () { beforeEach(async function () {
await this.token.approve(burner, originalAllowance, { from: owner }); await this.token.approve(burner, originalAllowance, { from: owner });
...@@ -63,11 +60,11 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { ...@@ -63,11 +60,11 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) {
}); });
it('burns the requested amount', async function () { it('burns the requested amount', async function () {
(await this.token.balanceOf(owner)).should.be.bignumber.equal(initialBalance - amount); (await this.token.balanceOf(owner)).should.be.bignumber.equal(initialBalance.sub(amount));
}); });
it('decrements allowance', async function () { it('decrements allowance', async function () {
(await this.token.allowance(owner, burner)).should.be.bignumber.equal(originalAllowance - amount); (await this.token.allowance(owner, burner)).should.be.bignumber.equal(originalAllowance.sub(amount));
}); });
it('emits a transfer event', async function () { it('emits a transfer event', async function () {
...@@ -81,7 +78,8 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { ...@@ -81,7 +78,8 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) {
}); });
describe('when the given amount is greater than the balance of the sender', function () { describe('when the given amount is greater than the balance of the sender', function () {
const amount = initialBalance + 1; const amount = initialBalance.addn(1);
it('reverts', async function () { it('reverts', async function () {
await this.token.approve(burner, amount, { from: owner }); await this.token.approve(burner, amount, { from: owner });
await shouldFail.reverting(this.token.burnFrom(owner, amount, { from: burner })); await shouldFail.reverting(this.token.burnFrom(owner, amount, { from: burner }));
...@@ -89,10 +87,11 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { ...@@ -89,10 +87,11 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) {
}); });
describe('when the given amount is greater than the allowance', function () { describe('when the given amount is greater than the allowance', function () {
const amount = 100; const allowance = new BN(100);
it('reverts', async function () { it('reverts', async function () {
await this.token.approve(burner, amount - 1, { from: owner }); await this.token.approve(burner, allowance, { from: owner });
await shouldFail.reverting(this.token.burnFrom(owner, amount, { from: burner })); await shouldFail.reverting(this.token.burnFrom(owner, allowance.addn(1), { from: burner }));
}); });
}); });
}); });
......
const shouldFail = require('../../../helpers/shouldFail'); const { shouldFail } = require('openzeppelin-test-helpers');
require('../../../helpers/setup');
function shouldBehaveLikeERC20Capped (minter, [anyone], cap) { function shouldBehaveLikeERC20Capped (minter, [anyone], cap) {
describe('capped token', function () { describe('capped token', function () {
...@@ -11,13 +9,13 @@ function shouldBehaveLikeERC20Capped (minter, [anyone], cap) { ...@@ -11,13 +9,13 @@ function shouldBehaveLikeERC20Capped (minter, [anyone], cap) {
}); });
it('should mint when amount is less than cap', async function () { it('should mint when amount is less than cap', async function () {
await this.token.mint(anyone, cap.sub(1), { from }); await this.token.mint(anyone, cap.subn(1), { from });
(await this.token.totalSupply()).should.be.bignumber.equal(cap.sub(1)); (await this.token.totalSupply()).should.be.bignumber.equal(cap.subn(1));
}); });
it('should fail to mint if the ammount exceeds the cap', async function () { it('should fail to mint if the amount exceeds the cap', async function () {
await this.token.mint(anyone, cap.sub(1), { from }); await this.token.mint(anyone, cap.subn(1), { from });
await shouldFail.reverting(this.token.mint(anyone, 100, { from })); await shouldFail.reverting(this.token.mint(anyone, 2, { from }));
}); });
it('should fail to mint after cap is reached', async function () { it('should fail to mint after cap is reached', async function () {
......
const shouldFail = require('../../../helpers/shouldFail'); const { BN, constants, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const expectEvent = require('../../../helpers/expectEvent'); const { ZERO_ADDRESS } = constants;
const { ZERO_ADDRESS } = require('../../../helpers/constants');
require('../../../helpers/setup');
function shouldBehaveLikeERC20Mintable (minter, [anyone]) { function shouldBehaveLikeERC20Mintable (minter, [anyone]) {
describe('as a mintable token', function () { describe('as a mintable token', function () {
describe('mint', function () { describe('mint', function () {
const amount = 100; const amount = new BN(100);
context('when the sender has minting permission', function () { context('when the sender has minting permission', function () {
const from = minter; const from = minter;
context('for a zero amount', function () { context('for a zero amount', function () {
shouldMint(0); shouldMint(new BN(0));
}); });
context('for a non-zero amount', function () { context('for a non-zero amount', function () {
......
const expectEvent = require('../../helpers/expectEvent'); const { BN, constants, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const { ZERO_ADDRESS } = constants;
const { shouldSupportInterfaces } = require('../../introspection/SupportsInterface.behavior'); const { shouldSupportInterfaces } = require('../../introspection/SupportsInterface.behavior');
const shouldFail = require('../../helpers/shouldFail');
const { ZERO_ADDRESS } = require('../../helpers/constants');
const send = require('../../helpers/send');
const ERC721ReceiverMock = artifacts.require('ERC721ReceiverMock.sol'); const ERC721ReceiverMock = artifacts.require('ERC721ReceiverMock.sol');
require('../../helpers/setup');
function shouldBehaveLikeERC721 ( function shouldBehaveLikeERC721 (
creator, creator,
minter, minter,
[owner, approved, anotherApproved, operator, anyone] [owner, approved, anotherApproved, operator, anyone]
) { ) {
const firstTokenId = 1; const firstTokenId = new BN(1);
const secondTokenId = 2; const secondTokenId = new BN(2);
const unknownTokenId = 3; const unknownTokenId = new BN(3);
const RECEIVER_MAGIC_VALUE = '0x150b7a02'; const RECEIVER_MAGIC_VALUE = '0x150b7a02';
describe('like an ERC721', function () { describe('like an ERC721', function () {
...@@ -27,19 +24,19 @@ function shouldBehaveLikeERC721 ( ...@@ -27,19 +24,19 @@ function shouldBehaveLikeERC721 (
describe('balanceOf', function () { describe('balanceOf', function () {
context('when the given address owns some tokens', function () { context('when the given address owns some tokens', function () {
it('returns the amount of tokens owned by the given address', async function () { it('returns the amount of tokens owned by the given address', async function () {
(await this.token.balanceOf(owner)).should.be.bignumber.equal(2); (await this.token.balanceOf(owner)).should.be.bignumber.equal('2');
}); });
}); });
context('when the given address does not own any tokens', function () { context('when the given address does not own any tokens', function () {
it('returns 0', async function () { it('returns 0', async function () {
(await this.token.balanceOf(anyone)).should.be.bignumber.equal(0); (await this.token.balanceOf(anyone)).should.be.bignumber.equal('0');
}); });
}); });
context('when querying the zero address', function () { context('when querying the zero address', function () {
it('throws', async function () { it('throws', async function () {
await shouldFail.reverting(this.token.balanceOf(0)); await shouldFail.reverting(this.token.balanceOf(ZERO_ADDRESS));
}); });
}); });
}); });
...@@ -101,15 +98,15 @@ function shouldBehaveLikeERC721 ( ...@@ -101,15 +98,15 @@ function shouldBehaveLikeERC721 (
} }
it('adjusts owners balances', async function () { it('adjusts owners balances', async function () {
(await this.token.balanceOf(owner)).should.be.bignumber.equal(1); (await this.token.balanceOf(owner)).should.be.bignumber.equal('1');
}); });
it('adjusts owners tokens by index', async function () { it('adjusts owners tokens by index', async function () {
if (!this.token.tokenOfOwnerByIndex) return; if (!this.token.tokenOfOwnerByIndex) return;
(await this.token.tokenOfOwnerByIndex(this.toWhom, 0)).toNumber().should.be.equal(tokenId); (await this.token.tokenOfOwnerByIndex(this.toWhom, 0)).should.be.bignumber.equal(tokenId);
(await this.token.tokenOfOwnerByIndex(owner, 0)).toNumber().should.not.be.equal(tokenId); (await this.token.tokenOfOwnerByIndex(owner, 0)).should.be.bignumber.not.equal(tokenId);
}); });
}; };
...@@ -165,7 +162,7 @@ function shouldBehaveLikeERC721 ( ...@@ -165,7 +162,7 @@ function shouldBehaveLikeERC721 (
}); });
it('keeps the owner balance', async function () { it('keeps the owner balance', async function () {
(await this.token.balanceOf(owner)).should.be.bignumber.equal(2); (await this.token.balanceOf(owner)).should.be.bignumber.equal('2');
}); });
it('keeps same tokens by index', async function () { it('keeps same tokens by index', async function () {
...@@ -173,7 +170,9 @@ function shouldBehaveLikeERC721 ( ...@@ -173,7 +170,9 @@ function shouldBehaveLikeERC721 (
const tokensListed = await Promise.all( const tokensListed = await Promise.all(
[0, 1].map(i => this.token.tokenOfOwnerByIndex(owner, i)) [0, 1].map(i => this.token.tokenOfOwnerByIndex(owner, i))
); );
tokensListed.map(t => t.toNumber()).should.have.members([firstTokenId, secondTokenId]); tokensListed.map(t => t.toNumber()).should.have.members(
[firstTokenId.toNumber(), secondTokenId.toNumber()]
);
}); });
}); });
...@@ -200,7 +199,9 @@ function shouldBehaveLikeERC721 ( ...@@ -200,7 +199,9 @@ function shouldBehaveLikeERC721 (
context('when the address to transfer the token to is the zero address', function () { context('when the address to transfer the token to is the zero address', function () {
it('reverts', async function () { it('reverts', async function () {
await shouldFail.reverting(transferFunction.call(this, owner, ZERO_ADDRESS, tokenId, { from: owner })); await shouldFail.reverting(
transferFunction.call(this, owner, ZERO_ADDRESS, tokenId, { from: owner })
);
}); });
}); });
}; };
...@@ -213,17 +214,11 @@ function shouldBehaveLikeERC721 ( ...@@ -213,17 +214,11 @@ function shouldBehaveLikeERC721 (
describe('via safeTransferFrom', function () { describe('via safeTransferFrom', function () {
const safeTransferFromWithData = function (from, to, tokenId, opts) { const safeTransferFromWithData = function (from, to, tokenId, opts) {
return send.transaction( return this.token.methods['safeTransferFrom(address,address,uint256,bytes)'](from, to, tokenId, data, opts);
this.token,
'safeTransferFrom',
'address,address,uint256,bytes',
[from, to, tokenId, data],
opts
);
}; };
const safeTransferFromWithoutData = function (from, to, tokenId, opts) { const safeTransferFromWithoutData = function (from, to, tokenId, opts) {
return this.token.safeTransferFrom(from, to, tokenId, opts); return this.token.methods['safeTransferFrom(address,address,uint256)'](from, to, tokenId, opts);
}; };
const shouldTransferSafely = function (transferFun, data) { const shouldTransferSafely = function (transferFun, data) {
...@@ -282,7 +277,7 @@ function shouldBehaveLikeERC721 ( ...@@ -282,7 +277,7 @@ function shouldBehaveLikeERC721 (
}); });
describe('without data', function () { describe('without data', function () {
shouldTransferSafely(safeTransferFromWithoutData, '0x'); shouldTransferSafely(safeTransferFromWithoutData, null);
}); });
describe('to a receiver contract returning unexpected value', function () { describe('to a receiver contract returning unexpected value', function () {
......
require('../../helpers/setup'); const { BN, constants, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const { ZERO_ADDRESS } = require('../../helpers/constants'); const { ZERO_ADDRESS } = constants;
const expectEvent = require('../../helpers/expectEvent');
const send = require('../../helpers/send');
const shouldFail = require('../../helpers/shouldFail');
const { shouldBehaveLikeERC721 } = require('./ERC721.behavior'); const { shouldBehaveLikeERC721 } = require('./ERC721.behavior');
const ERC721Mock = artifacts.require('ERC721Mock.sol'); const ERC721Mock = artifacts.require('ERC721Mock.sol');
...@@ -15,7 +12,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) { ...@@ -15,7 +12,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) {
shouldBehaveLikeERC721(creator, creator, accounts); shouldBehaveLikeERC721(creator, creator, accounts);
describe('internal functions', function () { describe('internal functions', function () {
const tokenId = 5042; const tokenId = new BN('5042');
describe('_mint(address, uint256)', function () { describe('_mint(address, uint256)', function () {
it('reverts with a null destination address', async function () { it('reverts with a null destination address', async function () {
...@@ -32,7 +29,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) { ...@@ -32,7 +29,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) {
}); });
it('creates the token', async function () { it('creates the token', async function () {
(await this.token.balanceOf(tokenOwner)).should.be.bignumber.equal(1); (await this.token.balanceOf(tokenOwner)).should.be.bignumber.equal('1');
(await this.token.ownerOf(tokenId)).should.equal(tokenOwner); (await this.token.ownerOf(tokenId)).should.equal(tokenOwner);
}); });
...@@ -44,7 +41,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) { ...@@ -44,7 +41,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) {
describe('_burn(address, uint256)', function () { describe('_burn(address, uint256)', function () {
it('reverts when burning a non-existent token id', async function () { it('reverts when burning a non-existent token id', async function () {
await shouldFail.reverting(send.transaction(this.token, 'burn', 'address,uint256', [tokenOwner, tokenId])); await shouldFail.reverting(this.token.methods['burn(address,uint256)'](tokenOwner, tokenId));
}); });
context('with minted token', function () { context('with minted token', function () {
...@@ -53,13 +50,12 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) { ...@@ -53,13 +50,12 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) {
}); });
it('reverts when the account is not the owner', async function () { it('reverts when the account is not the owner', async function () {
await shouldFail.reverting(send.transaction(this.token, 'burn', 'address,uint256', [anyone, tokenId])); await shouldFail.reverting(this.token.methods['burn(address,uint256)'](anyone, tokenId));
}); });
context('with burnt token', function () { context('with burnt token', function () {
beforeEach(async function () { beforeEach(async function () {
({ logs: this.logs } = ({ logs: this.logs } = await this.token.methods['burn(address,uint256)'](tokenOwner, tokenId));
await send.transaction(this.token, 'burn', 'address,uint256', [tokenOwner, tokenId]));
}); });
it('emits a Transfer event', function () { it('emits a Transfer event', function () {
...@@ -67,12 +63,12 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) { ...@@ -67,12 +63,12 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) {
}); });
it('deletes the token', async function () { it('deletes the token', async function () {
(await this.token.balanceOf(tokenOwner)).should.be.bignumber.equal(0); (await this.token.balanceOf(tokenOwner)).should.be.bignumber.equal('0');
await shouldFail.reverting(this.token.ownerOf(tokenId)); await shouldFail.reverting(this.token.ownerOf(tokenId));
}); });
it('reverts when burning a token id that has been deleted', async function () { it('reverts when burning a token id that has been deleted', async function () {
await shouldFail.reverting(send.transaction(this.token, 'burn', 'address,uint256', [tokenOwner, tokenId])); await shouldFail.reverting(this.token.methods['burn(address,uint256)'](tokenOwner, tokenId));
}); });
}); });
}); });
...@@ -80,7 +76,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) { ...@@ -80,7 +76,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) {
describe('_burn(uint256)', function () { describe('_burn(uint256)', function () {
it('reverts when burning a non-existent token id', async function () { it('reverts when burning a non-existent token id', async function () {
await shouldFail.reverting(send.transaction(this.token, 'burn', 'uint256', [tokenId])); await shouldFail.reverting(this.token.methods['burn(uint256)'](tokenId));
}); });
context('with minted token', function () { context('with minted token', function () {
...@@ -90,7 +86,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) { ...@@ -90,7 +86,7 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) {
context('with burnt token', function () { context('with burnt token', function () {
beforeEach(async function () { beforeEach(async function () {
({ logs: this.logs } = await send.transaction(this.token, 'burn', 'uint256', [tokenId])); ({ logs: this.logs } = await this.token.methods['burn(uint256)'](tokenId));
}); });
it('emits a Transfer event', function () { it('emits a Transfer event', function () {
...@@ -98,12 +94,12 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) { ...@@ -98,12 +94,12 @@ contract('ERC721', function ([_, creator, tokenOwner, anyone, ...accounts]) {
}); });
it('deletes the token', async function () { it('deletes the token', async function () {
(await this.token.balanceOf(tokenOwner)).should.be.bignumber.equal(0); (await this.token.balanceOf(tokenOwner)).should.be.bignumber.equal('0');
await shouldFail.reverting(this.token.ownerOf(tokenId)); await shouldFail.reverting(this.token.ownerOf(tokenId));
}); });
it('reverts when burning a token id that has been deleted', async function () { it('reverts when burning a token id that has been deleted', async function () {
await shouldFail.reverting(send.transaction(this.token, 'burn', 'uint256', [tokenId])); await shouldFail.reverting(this.token.methods['burn(uint256)'](tokenId));
}); });
}); });
}); });
......
require('openzeppelin-test-helpers');
const { shouldBehaveLikeERC721 } = require('./ERC721.behavior'); const { shouldBehaveLikeERC721 } = require('./ERC721.behavior');
const { const {
shouldBehaveLikeMintAndBurnERC721, shouldBehaveLikeMintAndBurnERC721,
...@@ -5,8 +7,6 @@ const { ...@@ -5,8 +7,6 @@ const {
const ERC721BurnableImpl = artifacts.require('ERC721MintableBurnableImpl.sol'); const ERC721BurnableImpl = artifacts.require('ERC721MintableBurnableImpl.sol');
require('../../helpers/setup');
contract('ERC721Burnable', function ([_, creator, ...accounts]) { contract('ERC721Burnable', function ([_, creator, ...accounts]) {
const minter = creator; const minter = creator;
......
const shouldFail = require('../../helpers/shouldFail'); const { BN, shouldFail } = require('openzeppelin-test-helpers');
const { shouldBehaveLikeERC721 } = require('./ERC721.behavior'); const { shouldBehaveLikeERC721 } = require('./ERC721.behavior');
const { shouldSupportInterfaces } = require('../../introspection/SupportsInterface.behavior'); const { shouldSupportInterfaces } = require('../../introspection/SupportsInterface.behavior');
const ERC721FullMock = artifacts.require('ERC721FullMock.sol'); const ERC721FullMock = artifacts.require('ERC721FullMock.sol');
require('../../helpers/setup');
contract('ERC721Full', function ([ contract('ERC721Full', function ([
creator, creator,
...accounts ...accounts
]) { ]) {
const name = 'Non Fungible Token'; const name = 'Non Fungible Token';
const symbol = 'NFT'; const symbol = 'NFT';
const firstTokenId = 100; const firstTokenId = new BN(100);
const secondTokenId = 200; const secondTokenId = new BN(200);
const thirdTokenId = 300; const thirdTokenId = new BN(300);
const nonExistentTokenId = 999; const nonExistentTokenId = new BN(999);
const minter = creator; const minter = creator;
...@@ -41,11 +40,11 @@ contract('ERC721Full', function ([ ...@@ -41,11 +40,11 @@ contract('ERC721Full', function ([
}); });
it('adjusts owner tokens by index', async function () { it('adjusts owner tokens by index', async function () {
(await this.token.tokenOfOwnerByIndex(newOwner, 0)).toNumber().should.be.equal(thirdTokenId); (await this.token.tokenOfOwnerByIndex(newOwner, 0)).should.be.bignumber.equal(thirdTokenId);
}); });
it('adjusts all tokens list', async function () { it('adjusts all tokens list', async function () {
(await this.token.tokenByIndex(2)).toNumber().should.be.equal(thirdTokenId); (await this.token.tokenByIndex(2)).should.be.bignumber.equal(thirdTokenId);
}); });
}); });
...@@ -55,16 +54,16 @@ contract('ERC721Full', function ([ ...@@ -55,16 +54,16 @@ contract('ERC721Full', function ([
}); });
it('removes that token from the token list of the owner', async function () { it('removes that token from the token list of the owner', async function () {
(await this.token.tokenOfOwnerByIndex(owner, 0)).toNumber().should.be.equal(secondTokenId); (await this.token.tokenOfOwnerByIndex(owner, 0)).should.be.bignumber.equal(secondTokenId);
}); });
it('adjusts all tokens list', async function () { it('adjusts all tokens list', async function () {
(await this.token.tokenByIndex(0)).toNumber().should.be.equal(secondTokenId); (await this.token.tokenByIndex(0)).should.be.bignumber.equal(secondTokenId);
}); });
it('burns all tokens', async function () { it('burns all tokens', async function () {
await this.token.burn(secondTokenId, { from: owner }); await this.token.burn(secondTokenId, { from: owner });
(await this.token.totalSupply()).toNumber().should.be.equal(0); (await this.token.totalSupply()).should.be.bignumber.equal('0');
await shouldFail.reverting(this.token.tokenByIndex(0)); await shouldFail.reverting(this.token.tokenByIndex(0));
}); });
}); });
...@@ -115,7 +114,7 @@ contract('ERC721Full', function ([ ...@@ -115,7 +114,7 @@ contract('ERC721Full', function ([
describe('totalSupply', function () { describe('totalSupply', function () {
it('returns total token supply', async function () { it('returns total token supply', async function () {
(await this.token.totalSupply()).should.be.bignumber.equal(2); (await this.token.totalSupply()).should.be.bignumber.equal('2');
}); });
}); });
...@@ -145,15 +144,15 @@ contract('ERC721Full', function ([ ...@@ -145,15 +144,15 @@ contract('ERC721Full', function ([
}); });
it('returns correct token IDs for target', async function () { it('returns correct token IDs for target', async function () {
(await this.token.balanceOf(another)).toNumber().should.be.equal(2); (await this.token.balanceOf(another)).should.be.bignumber.equal('2');
const tokensListed = await Promise.all( const tokensListed = await Promise.all(
[0, 1].map(i => this.token.tokenOfOwnerByIndex(another, i)) [0, 1].map(i => this.token.tokenOfOwnerByIndex(another, i))
); );
tokensListed.map(t => t.toNumber()).should.have.members([firstTokenId, secondTokenId]); tokensListed.map(t => t.toNumber()).should.have.members([firstTokenId.toNumber(), secondTokenId.toNumber()]);
}); });
it('returns empty collection for original owner', async function () { it('returns empty collection for original owner', async function () {
(await this.token.balanceOf(owner)).toNumber().should.be.equal(0); (await this.token.balanceOf(owner)).should.be.bignumber.equal('0');
await shouldFail.reverting(this.token.tokenOfOwnerByIndex(owner, 0)); await shouldFail.reverting(this.token.tokenOfOwnerByIndex(owner, 0));
}); });
}); });
...@@ -164,7 +163,7 @@ contract('ERC721Full', function ([ ...@@ -164,7 +163,7 @@ contract('ERC721Full', function ([
const tokensListed = await Promise.all( const tokensListed = await Promise.all(
[0, 1].map(i => this.token.tokenByIndex(i)) [0, 1].map(i => this.token.tokenByIndex(i))
); );
tokensListed.map(t => t.toNumber()).should.have.members([firstTokenId, secondTokenId]); tokensListed.map(t => t.toNumber()).should.have.members([firstTokenId.toNumber(), secondTokenId.toNumber()]);
}); });
it('should revert if index is greater than supply', async function () { it('should revert if index is greater than supply', async function () {
...@@ -173,14 +172,14 @@ contract('ERC721Full', function ([ ...@@ -173,14 +172,14 @@ contract('ERC721Full', function ([
[firstTokenId, secondTokenId].forEach(function (tokenId) { [firstTokenId, secondTokenId].forEach(function (tokenId) {
it(`should return all tokens after burning token ${tokenId} and minting new tokens`, async function () { it(`should return all tokens after burning token ${tokenId} and minting new tokens`, async function () {
const newTokenId = 300; const newTokenId = new BN(300);
const anotherNewTokenId = 400; const anotherNewTokenId = new BN(400);
await this.token.burn(tokenId, { from: owner }); await this.token.burn(tokenId, { from: owner });
await this.token.mint(newOwner, newTokenId, { from: minter }); await this.token.mint(newOwner, newTokenId, { from: minter });
await this.token.mint(newOwner, anotherNewTokenId, { from: minter }); await this.token.mint(newOwner, anotherNewTokenId, { from: minter });
(await this.token.totalSupply()).toNumber().should.be.equal(3); (await this.token.totalSupply()).should.be.bignumber.equal('3');
const tokensListed = await Promise.all( const tokensListed = await Promise.all(
[0, 1, 2].map(i => this.token.tokenByIndex(i)) [0, 1, 2].map(i => this.token.tokenByIndex(i))
...@@ -188,7 +187,7 @@ contract('ERC721Full', function ([ ...@@ -188,7 +187,7 @@ contract('ERC721Full', function ([
const expectedTokens = [firstTokenId, secondTokenId, newTokenId, anotherNewTokenId].filter( const expectedTokens = [firstTokenId, secondTokenId, newTokenId, anotherNewTokenId].filter(
x => (x !== tokenId) x => (x !== tokenId)
); );
tokensListed.map(t => t.toNumber()).should.have.members(expectedTokens); tokensListed.map(t => t.toNumber()).should.have.members(expectedTokens.map(t => t.toNumber()));
}); });
}); });
}); });
......
const { BN } = require('openzeppelin-test-helpers');
const ERC721Holder = artifacts.require('ERC721Holder.sol'); const ERC721Holder = artifacts.require('ERC721Holder.sol');
const ERC721Mintable = artifacts.require('ERC721MintableBurnableImpl.sol'); const ERC721Mintable = artifacts.require('ERC721MintableBurnableImpl.sol');
require('../../helpers/setup');
contract('ERC721Holder', function ([creator]) { contract('ERC721Holder', function ([creator]) {
it('receives an ERC721 token', async function () { it('receives an ERC721 token', async function () {
const token = await ERC721Mintable.new({ from: creator }); const token = await ERC721Mintable.new({ from: creator });
const tokenId = 1; const tokenId = new BN(1);
await token.mint(creator, tokenId, { from: creator }); await token.mint(creator, tokenId, { from: creator });
const receiver = await ERC721Holder.new(); const receiver = await ERC721Holder.new();
......
const shouldFail = require('../../helpers/shouldFail'); const { BN, constants, expectEvent, shouldFail } = require('openzeppelin-test-helpers');
const expectEvent = require('../../helpers/expectEvent'); const { ZERO_ADDRESS } = constants;
const { ZERO_ADDRESS } = require('../../helpers/constants');
require('../../helpers/setup');
function shouldBehaveLikeMintAndBurnERC721 ( function shouldBehaveLikeMintAndBurnERC721 (
creator, creator,
minter, minter,
[owner, newOwner, approved, anyone] [owner, newOwner, approved, anyone]
) { ) {
const firstTokenId = 1; const firstTokenId = new BN(1);
const secondTokenId = 2; const secondTokenId = new BN(2);
const thirdTokenId = 3; const thirdTokenId = new BN(3);
const unknownTokenId = 4; const unknownTokenId = new BN(4);
const MOCK_URI = 'https://example.com'; const MOCK_URI = 'https://example.com';
describe('like a mintable and burnable ERC721', function () { describe('like a mintable and burnable ERC721', function () {
...@@ -34,7 +32,7 @@ function shouldBehaveLikeMintAndBurnERC721 ( ...@@ -34,7 +32,7 @@ function shouldBehaveLikeMintAndBurnERC721 (
}); });
it('increases the balance of its owner', async function () { it('increases the balance of its owner', async function () {
(await this.token.balanceOf(newOwner)).should.be.bignumber.equal(1); (await this.token.balanceOf(newOwner)).should.be.bignumber.equal('1');
}); });
it('emits a transfer and minted event', async function () { it('emits a transfer and minted event', async function () {
...@@ -79,7 +77,7 @@ function shouldBehaveLikeMintAndBurnERC721 ( ...@@ -79,7 +77,7 @@ function shouldBehaveLikeMintAndBurnERC721 (
it('burns the given token ID and adjusts the balance of the owner', async function () { it('burns the given token ID and adjusts the balance of the owner', async function () {
await shouldFail.reverting(this.token.ownerOf(tokenId)); await shouldFail.reverting(this.token.ownerOf(tokenId));
(await this.token.balanceOf(owner)).should.be.bignumber.equal(1); (await this.token.balanceOf(owner)).should.be.bignumber.equal('1');
}); });
it('emits a burn event', async function () { it('emits a burn event', async function () {
......
require('openzeppelin-test-helpers');
const { shouldBehaveLikeERC721 } = require('./ERC721.behavior'); const { shouldBehaveLikeERC721 } = require('./ERC721.behavior');
const { const { shouldBehaveLikeMintAndBurnERC721 } = require('./ERC721MintBurn.behavior');
shouldBehaveLikeMintAndBurnERC721,
} = require('./ERC721MintBurn.behavior');
const ERC721MintableImpl = artifacts.require('ERC721MintableBurnableImpl.sol'); const ERC721MintableImpl = artifacts.require('ERC721MintableBurnableImpl.sol');
require('../../helpers/setup');
contract('ERC721Mintable', function ([_, creator, ...accounts]) { contract('ERC721Mintable', function ([_, creator, ...accounts]) {
const minter = creator; const minter = creator;
......
require('openzeppelin-test-helpers');
const { shouldBehaveLikeERC721PausedToken } = require('./ERC721PausedToken.behavior'); const { shouldBehaveLikeERC721PausedToken } = require('./ERC721PausedToken.behavior');
const { shouldBehaveLikeERC721 } = require('./ERC721.behavior'); const { shouldBehaveLikeERC721 } = require('./ERC721.behavior');
const { shouldBehaveLikePublicRole } = require('../../access/roles/PublicRole.behavior'); const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const ERC721PausableMock = artifacts.require('ERC721PausableMock.sol'); const ERC721PausableMock = artifacts.require('ERC721PausableMock.sol');
require('../../helpers/setup');
contract('ERC721Pausable', function ([ contract('ERC721Pausable', function ([
_, _,
creator, creator,
......
const shouldFail = require('../../helpers/shouldFail'); const { BN, constants, shouldFail } = require('openzeppelin-test-helpers');
const send = require('../../helpers/send'); const { ZERO_ADDRESS } = constants;
const { ZERO_ADDRESS } = require('../../helpers/constants');
require('../../helpers/setup');
function shouldBehaveLikeERC721PausedToken (owner, [recipient, operator]) { function shouldBehaveLikeERC721PausedToken (owner, [recipient, operator]) {
const firstTokenId = 1; const firstTokenId = new BN(1);
const mintedTokens = 1; const mintedTokens = new BN(1);
const mockData = '0x42'; const mockData = '0x42';
describe('like a paused ERC721', function () { describe('like a paused ERC721', function () {
...@@ -31,14 +28,8 @@ function shouldBehaveLikeERC721PausedToken (owner, [recipient, operator]) { ...@@ -31,14 +28,8 @@ function shouldBehaveLikeERC721PausedToken (owner, [recipient, operator]) {
}); });
it('reverts when trying to safeTransferFrom with data', async function () { it('reverts when trying to safeTransferFrom with data', async function () {
await shouldFail.reverting( await shouldFail.reverting(this.token.methods['safeTransferFrom(address,address,uint256,bytes)'](
send.transaction( owner, recipient, firstTokenId, mockData, { from: owner })
this.token,
'safeTransferFrom',
'address,address,uint256,bytes',
[owner, recipient, firstTokenId, mockData],
{ from: owner }
)
); );
}); });
...@@ -65,15 +56,13 @@ function shouldBehaveLikeERC721PausedToken (owner, [recipient, operator]) { ...@@ -65,15 +56,13 @@ function shouldBehaveLikeERC721PausedToken (owner, [recipient, operator]) {
describe('exists', function () { describe('exists', function () {
it('should return token existance', async function () { it('should return token existance', async function () {
const result = await this.token.exists(firstTokenId); (await this.token.exists(firstTokenId)).should.equal(true);
result.should.eq(true);
}); });
}); });
describe('isApprovedForAll', function () { describe('isApprovedForAll', function () {
it('returns the approval of the operator', async function () { it('returns the approval of the operator', async function () {
const isApproved = await this.token.isApprovedForAll(owner, operator); (await this.token.isApprovedForAll(owner, operator)).should.equal(false);
isApproved.should.eq(false);
}); });
}); });
}); });
......
require('openzeppelin-test-helpers');
const AddressImpl = artifacts.require('AddressImpl'); const AddressImpl = artifacts.require('AddressImpl');
const SimpleToken = artifacts.require('SimpleTokenMock'); const SimpleToken = artifacts.require('SimpleTokenMock');
require('../helpers/setup');
contract('Address', function ([_, anyone]) { contract('Address', function ([_, anyone]) {
beforeEach(async function () { beforeEach(async function () {
this.mock = await AddressImpl.new(); this.mock = await AddressImpl.new();
......
const ArraysImpl = artifacts.require('ArraysImpl'); require('openzeppelin-test-helpers');
require('../helpers/setup'); const ArraysImpl = artifacts.require('ArraysImpl');
contract('Arrays', function () { contract('Arrays', function () {
context('Even number of elements', function () { context('Even number of elements', function () {
...@@ -11,23 +11,23 @@ contract('Arrays', function () { ...@@ -11,23 +11,23 @@ contract('Arrays', function () {
}); });
it('should return correct index for the basic case', async function () { it('should return correct index for the basic case', async function () {
(await this.arrays.findUpperBound(16)).should.be.bignumber.equal(5); (await this.arrays.findUpperBound(16)).should.be.bignumber.equal('5');
}); });
it('should return 0 for the first element', async function () { it('should return 0 for the first element', async function () {
(await this.arrays.findUpperBound(11)).should.be.bignumber.equal(0); (await this.arrays.findUpperBound(11)).should.be.bignumber.equal('0');
}); });
it('should return index of the last element', async function () { it('should return index of the last element', async function () {
(await this.arrays.findUpperBound(20)).should.be.bignumber.equal(9); (await this.arrays.findUpperBound(20)).should.be.bignumber.equal('9');
}); });
it('should return first index after last element if searched value is over the upper boundary', async function () { it('should return first index after last element if searched value is over the upper boundary', async function () {
(await this.arrays.findUpperBound(32)).should.be.bignumber.equal(10); (await this.arrays.findUpperBound(32)).should.be.bignumber.equal('10');
}); });
it('should return 0 for the element under the lower boundary', async function () { it('should return 0 for the element under the lower boundary', async function () {
(await this.arrays.findUpperBound(2)).should.be.bignumber.equal(0); (await this.arrays.findUpperBound(2)).should.be.bignumber.equal('0');
}); });
}); });
...@@ -39,23 +39,23 @@ contract('Arrays', function () { ...@@ -39,23 +39,23 @@ contract('Arrays', function () {
}); });
it('should return correct index for the basic case', async function () { it('should return correct index for the basic case', async function () {
(await this.arrays.findUpperBound(16)).should.be.bignumber.equal(5); (await this.arrays.findUpperBound(16)).should.be.bignumber.equal('5');
}); });
it('should return 0 for the first element', async function () { it('should return 0 for the first element', async function () {
(await this.arrays.findUpperBound(11)).should.be.bignumber.equal(0); (await this.arrays.findUpperBound(11)).should.be.bignumber.equal('0');
}); });
it('should return index of the last element', async function () { it('should return index of the last element', async function () {
(await this.arrays.findUpperBound(21)).should.be.bignumber.equal(10); (await this.arrays.findUpperBound(21)).should.be.bignumber.equal('10');
}); });
it('should return first index after last element if searched value is over the upper boundary', async function () { it('should return first index after last element if searched value is over the upper boundary', async function () {
(await this.arrays.findUpperBound(32)).should.be.bignumber.equal(11); (await this.arrays.findUpperBound(32)).should.be.bignumber.equal('11');
}); });
it('should return 0 for the element under the lower boundary', async function () { it('should return 0 for the element under the lower boundary', async function () {
(await this.arrays.findUpperBound(2)).should.be.bignumber.equal(0); (await this.arrays.findUpperBound(2)).should.be.bignumber.equal('0');
}); });
}); });
...@@ -67,7 +67,7 @@ contract('Arrays', function () { ...@@ -67,7 +67,7 @@ contract('Arrays', function () {
}); });
it('should return index of first element in next filled range', async function () { it('should return index of first element in next filled range', async function () {
(await this.arrays.findUpperBound(17)).should.be.bignumber.equal(5); (await this.arrays.findUpperBound(17)).should.be.bignumber.equal('5');
}); });
}); });
...@@ -77,7 +77,7 @@ contract('Arrays', function () { ...@@ -77,7 +77,7 @@ contract('Arrays', function () {
}); });
it('should always return 0 for empty array', async function () { it('should always return 0 for empty array', async function () {
(await this.arrays.findUpperBound(10)).should.be.bignumber.equal(0); (await this.arrays.findUpperBound(10)).should.be.bignumber.equal('0');
}); });
}); });
}); });
const shouldFail = require('../helpers/shouldFail'); const { shouldFail } = require('openzeppelin-test-helpers');
const ReentrancyMock = artifacts.require('ReentrancyMock'); const ReentrancyMock = artifacts.require('ReentrancyMock');
const ReentrancyAttack = artifacts.require('ReentrancyAttack'); const ReentrancyAttack = artifacts.require('ReentrancyAttack');
require('../helpers/setup');
contract('ReentrancyGuard', function () { contract('ReentrancyGuard', function () {
beforeEach(async function () { beforeEach(async function () {
this.reentrancyMock = await ReentrancyMock.new(); this.reentrancyMock = await ReentrancyMock.new();
(await this.reentrancyMock.counter()).should.be.bignumber.equal(0); (await this.reentrancyMock.counter()).should.be.bignumber.equal('0');
}); });
it('should not allow remote callback', async function () { it('should not allow remote callback', async function () {
......
...@@ -13,4 +13,10 @@ module.exports = { ...@@ -13,4 +13,10 @@ module.exports = {
gasPrice: 0x01, gasPrice: 0x01,
}, },
}, },
compilers: {
solc: {
version: '0.5.0',
},
},
}; };
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment