diff --git a/package.json b/package.json index 17463d552..254617a59 100644 --- a/package.json +++ b/package.json @@ -15,12 +15,12 @@ ], "scripts": { "compile": "truffle compile", - "test": "TRUFFLE_TEST=true npm run ganache-cli:test", + "lint": "solium --dir ./contracts", + "test": "TRUFFLE_TEST=true npm run test:ganache-cli", "test:gas": "GAS_REPORTER=true npm test", "test:gas:ci": "npm run test:gas && npx codechecks", - "lint": "solium --dir ./contracts", - "coverage": "SOLIDITY_COVERAGE=true npm run ganache-cli:test", - "ganache-cli:test": "scripts/ganache-cli.sh", + "test:ganache-cli": "./node_modules/@aragon/contract-helpers-test/scripts/ganache-cli.sh", + "coverage": "SOLIDITY_COVERAGE=true npm run test:ganache-cli", "abi:extract": "truffle-extract --output abi/ --keys abi", "bytecode:extract": "truffle-bytecode extract -o bytecode", "bytecode:extract:new": "truffle-bytecode extract -o bytecode_new", @@ -29,17 +29,19 @@ }, "dependencies": {}, "devDependencies": { - "@aragon/truffle-config-v4": "^1.0.1", + "@aragon/contract-helpers-test": "^0.1.0-rc.2", + "@aragon/truffle-config-v5": "^1.0.1", "@codechecks/client": "^0.1.5", + "chai": "^4.2.0", "coveralls": "^3.0.9", "eth-ens-namehash": "^2.0.8", "eth-gas-reporter": "^0.2.14", "ethereumjs-abi": "^0.6.5", "ganache-cli": "^6.9.0", "mocha-lcov-reporter": "^1.3.0", - "solidity-coverage": "0.6.2", + "solidity-coverage": "0.7.5", "solium": "^1.2.3", - "truffle": "4.1.14", + "truffle": "^5.0.34", "truffle-bytecode-manager": "^1.1.1", "truffle-extract": "^1.2.1", "web3-eth-abi": "1.2.5", diff --git a/scripts/ganache-cli.sh b/scripts/ganache-cli.sh deleted file mode 100755 index ed8098853..000000000 --- a/scripts/ganache-cli.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash - -# Exit script as soon as a command fails. -set -o errexit - -if [ "$SOLIDITY_COVERAGE" = true ]; then - testrpc_port=8555 -else - testrpc_port=8545 -fi - -testrpc_running() { - nc -z localhost "$testrpc_port" -} - -start_testrpc() { - if [ "$SOLIDITY_COVERAGE" = true ]; then - npx testrpc-sc -i 16 --gasLimit 0xfffffffffff --port "$testrpc_port" > /dev/null & - else - npx ganache-cli -i 15 --gasLimit 50000000 --port "$testrpc_port" > /dev/null & - fi - - testrpc_pid=$! -} - -if testrpc_running; then - echo "Killing testrpc instance at port $testrpc_port" - kill -9 $(lsof -i:$testrpc_port -t) -fi - -echo "Starting our own testrpc instance at port $testrpc_port" -start_testrpc -sleep 5 - -# Exit error mode so the testrpc instance always gets killed -set +e -result=0 -if [ "$SOLIDITY_COVERAGE" = true ]; then - npx solidity-coverage "$@" - result=$? -elif [ "$TRUFFLE_TEST" = true ]; then - npx truffle test --network rpc "$@" - result=$? -fi - -kill -9 $testrpc_pid - -exit $result diff --git a/test/contracts/acl/acl_params.js b/test/contracts/acl/acl_params.js index f9d1cc96b..ebe9b0e9d 100644 --- a/test/contracts/acl/acl_params.js +++ b/test/contracts/acl/acl_params.js @@ -1,4 +1,4 @@ -const { assertRevert } = require('../../helpers/assertThrow') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') const { skipSuiteCoverage } = require('../../helpers/coverage') const { permissionParamEqOracle } = require('../../helpers/permissionParams') @@ -28,9 +28,9 @@ contract('ACL params', ([permissionsRoot, specificEntity, noPermission, mockAppA }) beforeEach(async () => { - kernel = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + kernel = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) await kernel.initialize(aclBase.address, permissionsRoot) - acl = ACL.at(await kernel.acl()) + acl = await ACL.at(await kernel.acl()) await acl.createPermission(permissionsRoot, mockAppAddress, MOCK_APP_ROLE, permissionsRoot) }) @@ -142,8 +142,8 @@ contract('ACL params', ([permissionsRoot, specificEntity, noPermission, mockAppA it('ACL disallows and uses all gas when given large amount of gas', async () => { assert.isFalse(await acl.hasPermission(ANY_ADDR, mockAppAddress, MOCK_APP_ROLE, { gas: MAX_GAS_AVAILABLE })) - const hasPermissionTxHash = await acl.hasPermission.sendTransaction(ANY_ADDR, mockAppAddress, MOCK_APP_ROLE, { gas: MAX_GAS_AVAILABLE }) - const hasPermissionGasConsumed = web3.eth.getTransactionReceipt(hasPermissionTxHash).gasUsed + const hasPermissionReceipt = await acl.hasPermission.sendTransaction(ANY_ADDR, mockAppAddress, MOCK_APP_ROLE, { gas: MAX_GAS_AVAILABLE }) + const hasPermissionGasConsumed = hasPermissionReceipt.receipt.gasUsed // Surprisingly, the actual gas used is quite a lot lower than expected, but it is // unclear if this is a ganache issue or if there are gas refunds we're not taking // into account @@ -153,8 +153,8 @@ contract('ACL params', ([permissionsRoot, specificEntity, noPermission, mockAppA it('ACL disallows and uses all gas when given medium amount of gas', async () => { assert.isFalse(await acl.hasPermission(ANY_ADDR, mockAppAddress, MOCK_APP_ROLE, { gas: MEDIUM_GAS })) - const hasPermissionTxHash = await acl.hasPermission.sendTransaction(ANY_ADDR, mockAppAddress, MOCK_APP_ROLE, { gas: MEDIUM_GAS }) - const hasPermissionGasConsumed = web3.eth.getTransactionReceipt(hasPermissionTxHash).gasUsed + const hasPermissionReceipt = await acl.hasPermission.sendTransaction(ANY_ADDR, mockAppAddress, MOCK_APP_ROLE, { gas: MEDIUM_GAS }) + const hasPermissionGasConsumed = hasPermissionReceipt.receipt.gasUsed assert.closeTo(hasPermissionGasConsumed, getExpectedGas(MEDIUM_GAS), 10000) }) @@ -179,8 +179,8 @@ contract('ACL params', ([permissionsRoot, specificEntity, noPermission, mockAppA it('ACL disallows and uses all gas when given large amount of gas', async () => { assert.isFalse(await acl.hasPermission(specificEntity, mockAppAddress, MOCK_APP_ROLE, { gas: MAX_GAS_AVAILABLE })) - const hasPermissionTxHash = await acl.hasPermission.sendTransaction(specificEntity, mockAppAddress, MOCK_APP_ROLE, { gas: MAX_GAS_AVAILABLE }) - const hasPermissionGasConsumed = web3.eth.getTransactionReceipt(hasPermissionTxHash).gasUsed + const hasPermissionReceipt = await acl.hasPermission.sendTransaction(specificEntity, mockAppAddress, MOCK_APP_ROLE, { gas: MAX_GAS_AVAILABLE }) + const hasPermissionGasConsumed = hasPermissionReceipt.receipt.gasUsed // Surprisingly, the actual gas used is quite a lot lower than expected, but it is // unclear if this is a ganache issue or if there are gas refunds we're not taking // into account @@ -190,8 +190,8 @@ contract('ACL params', ([permissionsRoot, specificEntity, noPermission, mockAppA it('ACL disallows and uses all gas when given medium amount of gas', async () => { assert.isFalse(await acl.hasPermission(specificEntity, mockAppAddress, MOCK_APP_ROLE, { gas: MEDIUM_GAS })) - const hasPermissionTxHash = await acl.hasPermission.sendTransaction(specificEntity, mockAppAddress, MOCK_APP_ROLE, { gas: MEDIUM_GAS }) - const hasPermissionGasConsumed = web3.eth.getTransactionReceipt(hasPermissionTxHash).gasUsed + const hasPermissionReceipt = await acl.hasPermission.sendTransaction(specificEntity, mockAppAddress, MOCK_APP_ROLE, { gas: MEDIUM_GAS }) + const hasPermissionGasConsumed = hasPermissionReceipt.receipt.gasUsed assert.closeTo(hasPermissionGasConsumed, getExpectedGas(MEDIUM_GAS), 10000) }) diff --git a/test/contracts/apps/app_acl.js b/test/contracts/apps/app_acl.js index ca7e5467e..18b28948b 100644 --- a/test/contracts/apps/app_acl.js +++ b/test/contracts/apps/app_acl.js @@ -1,6 +1,6 @@ const { hash } = require('eth-ens-namehash') -const { onlyIf } = require('../../helpers/onlyIf') -const { assertRevert } = require('../../helpers/assertThrow') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') +const { bn, onlyIf } = require('@aragon/contract-helpers-test') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -12,8 +12,8 @@ const AppProxyPinned = artifacts.require('AppProxyPinned') const AppStub = artifacts.require('AppStub') const UnsafeAppStub = artifacts.require('UnsafeAppStub') -const APP_ID = hash('stub.aragonpm.test') const EMPTY_BYTES = '0x' +const APP_ID = hash('stub.aragonpm.test') contract('App ACL', accounts => { let aclBase, kernelBase, acl, kernel @@ -35,9 +35,9 @@ contract('App ACL', accounts => { }) beforeEach(async () => { - kernel = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + kernel = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) await kernel.initialize(aclBase.address, permissionsRoot) - acl = ACL.at(await kernel.acl()) + acl = await ACL.at(await kernel.acl()) // Set up app management permissions const APP_MANAGER_ROLE = await kernelBase.APP_MANAGER_ROLE() @@ -71,7 +71,7 @@ contract('App ACL', accounts => { } else if (appType === 'AppProxyPinned') { appProxy = await AppProxyPinned.new(kernel.address, APP_ID, EMPTY_BYTES) } - app = AppStub.at(appProxy.address) + app = await AppStub.at(appProxy.address) } await app.initialize() @@ -102,7 +102,7 @@ contract('App ACL', accounts => { it('fails if using app proxy without reference in kernel', async () => { const unknownId = hash('unknown.aragonpm.test') const appProxy = await AppProxyUpgradeable.new(kernel.address, unknownId, EMPTY_BYTES) - const app = AppStub.at(appProxy.address) + const app = await AppStub.at(appProxy.address) await assertRevert(app.setValue(10)) }) @@ -118,7 +118,7 @@ contract('App ACL', accounts => { const argId = '0x00' // arg 0 const op = '03' // greater than const value = `00000000000000000000000000000000000000000000000000000000000${paramValue}` // 5 - const param = new web3.BigNumber(`${argId}${op}${value}`) + const param = bn(`${argId}${op}${value}`) await acl.grantPermissionP(paramsGrantee, app.address, APP_ROLE, [param], { from: permissionsRoot }) }) diff --git a/test/contracts/apps/app_base_lifecycle.js b/test/contracts/apps/app_base_lifecycle.js index b9bf5fecc..d43857ec3 100644 --- a/test/contracts/apps/app_base_lifecycle.js +++ b/test/contracts/apps/app_base_lifecycle.js @@ -1,7 +1,6 @@ -const { hash } = require('eth-ens-namehash') -const { soliditySha3 } = require('web3-utils') -const { getBlockNumber } = require('../../helpers/web3') -const { assertRevert } = require('../../helpers/assertThrow') +const { sha3 } = require('web3-utils') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') +const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -11,8 +10,7 @@ const AragonApp = artifacts.require('AragonApp') // Mocks const UnsafeAragonAppMock = artifacts.require('UnsafeAragonAppMock') -const FAKE_ROLE = soliditySha3('FAKE_ROLE') -const ZERO_ADDR = '0x0000000000000000000000000000000000000000' +const FAKE_ROLE = sha3('FAKE_ROLE') contract('App base lifecycle', ([permissionsRoot]) => { let aclBase, kernelBase @@ -80,7 +78,7 @@ contract('App base lifecycle', ([permissionsRoot]) => { }) it('has correct initialization block', async () => { - assert.equal(await app.getInitializationBlock(), await getBlockNumber(), 'initialization block should be correct') + assert.equal(await app.getInitializationBlock(), await web3.eth.getBlockNumber(), 'initialization block should be correct') }) it('throws on reinitialization', async () => { @@ -88,7 +86,7 @@ contract('App base lifecycle', ([permissionsRoot]) => { }) it('should still not be usable without a kernel', async () => { - assert.equal(await app.getKernel(), ZERO_ADDR, 'app should still be missing kernel reference') + assert.equal(await app.getKernel(), ZERO_ADDRESS, 'app should still be missing kernel reference') assert.isFalse(await app.canPerform(permissionsRoot, FAKE_ROLE, [])) }) @@ -98,9 +96,9 @@ contract('App base lifecycle', ([permissionsRoot]) => { beforeEach(async () => { const kernelProxy = await KernelProxy.new(kernelBase.address) - kernel = Kernel.at(kernelProxy.address) + kernel = await Kernel.at(kernelProxy.address) await kernel.initialize(aclBase.address, permissionsRoot) - acl = ACL.at(await kernel.acl()) + acl = await ACL.at(await kernel.acl()) await app.setKernelOnMock(kernel.address) }) diff --git a/test/contracts/apps/app_funds.js b/test/contracts/apps/app_funds.js index df4f0b8db..88bcad555 100644 --- a/test/contracts/apps/app_funds.js +++ b/test/contracts/apps/app_funds.js @@ -1,7 +1,6 @@ const { hash } = require('eth-ens-namehash') -const { onlyIf } = require('../../helpers/onlyIf') -const { assertRevert } = require('../../helpers/assertThrow') -const { getBalance } = require('../../helpers/web3') +const { bn, onlyIf } = require('@aragon/contract-helpers-test') +const { assertRevert, assertBn } = require('@aragon/contract-helpers-test/src/asserts') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -60,7 +59,7 @@ contract('App funds', ([permissionsRoot]) => { }) beforeEach(async () => { - const kernel = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + const kernel = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) await kernel.initialize(aclBase.address, permissionsRoot) if (appType === 'App') { @@ -68,7 +67,7 @@ contract('App funds', ([permissionsRoot]) => { app = await unsafeAppBaseType.new(kernel.address) } else { // Install app - const acl = ACL.at(await kernel.acl()) + const acl = await ACL.at(await kernel.acl()) const APP_MANAGER_ROLE = await kernelBase.APP_MANAGER_ROLE() await acl.createPermission(permissionsRoot, kernel.address, APP_MANAGER_ROLE, permissionsRoot) await kernel.setApp(APP_BASES_NAMESPACE, APP_ID, appBase.address) @@ -80,7 +79,7 @@ contract('App funds', ([permissionsRoot]) => { appProxy = await AppProxyPinned.new(kernel.address, APP_ID, EMPTY_BYTES) } - app = appBaseType.at(appProxy.address) + app = await appBaseType.at(appProxy.address) } await app.initialize() @@ -99,14 +98,14 @@ contract('App funds', ([permissionsRoot]) => { }) it('can receive ETH after being set to depositable', async () => { - const amount = 1 - const initialBalance = await getBalance(app.address) + const amount = bn(1) + const initialBalance = bn(await web3.eth.getBalance(app.address)) await app.enableDeposits() assert.isTrue(await app.isDepositable(), 'should be depositable') await app.sendTransaction({ value: 1, gas: SEND_ETH_GAS }) - assert.equal((await getBalance(app.address)).valueOf(), initialBalance.plus(amount)) + assertBn(bn(await web3.eth.getBalance(app.address)), initialBalance.add(amount)) }) }) }) diff --git a/test/contracts/apps/app_interface.js b/test/contracts/apps/app_interface.js index d2be5aee3..0e8490b52 100644 --- a/test/contracts/apps/app_interface.js +++ b/test/contracts/apps/app_interface.js @@ -1,5 +1,5 @@ -const { getEventArgument } = require('../../helpers/events') -const { getNewProxyAddress } = require('../../helpers/events') +const { getEventArgument } = require('@aragon/contract-helpers-test') +const { getInstalledApp } = require('@aragon/contract-helpers-test/src/aragon-os') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -8,7 +8,7 @@ const AragonApp = artifacts.require('AragonAppMock') const ERC165 = artifacts.require('ERC165Mock') const EVMScriptRegistryFactory = artifacts.require('EVMScriptRegistryFactory') -contract('AragonApp', ([_, owner, agreement, anotherAgreement, someone]) => { +contract('AragonApp', ([_, owner]) => { let aragonApp const ARAGON_APP_INTERFACE = '0x54053e6c' @@ -21,15 +21,15 @@ contract('AragonApp', ([_, owner, agreement, anotherAgreement, someone]) => { const daoFact = await DAOFactory.new(kernelBase.address, aclBase.address, registryFactory.address) const receiptDao = await daoFact.newDAO(owner) - dao = await Kernel.at(getEventArgument(receiptDao, 'DeployDAO', 'dao')) - acl = await ACL.at(await dao.acl()) + const dao = await Kernel.at(getEventArgument(receiptDao, 'DeployDAO', 'dao')) + const acl = await ACL.at(await dao.acl()) const aragonAppBase = await AragonApp.new() const APP_MANAGER_ROLE = await kernelBase.APP_MANAGER_ROLE() await acl.createPermission(owner, dao.address, APP_MANAGER_ROLE, owner, { from: owner }) - const initializeData = aragonAppBase.contract.initialize.getData() + const initializeData = aragonAppBase.contract.methods.initialize().encodeABI() const receiptInstance = await dao.newAppInstance('0x1234', aragonAppBase.address, initializeData, false, { from: owner }) - aragonApp = await AragonApp.at(getNewProxyAddress(receiptInstance)) + aragonApp = await AragonApp.at(getInstalledApp(receiptInstance)) }) describe('supportsInterface', () => { diff --git a/test/contracts/apps/app_proxy.js b/test/contracts/apps/app_proxy.js index c8862e7ca..2d5fec743 100644 --- a/test/contracts/apps/app_proxy.js +++ b/test/contracts/apps/app_proxy.js @@ -1,7 +1,6 @@ const { hash } = require('eth-ens-namehash') -const { onlyIf } = require('../../helpers/onlyIf') -const { getBlockNumber } = require('../../helpers/web3') -const { assertRevert } = require('../../helpers/assertThrow') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') +const { onlyIf, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -15,11 +14,10 @@ const AppStub2 = artifacts.require('AppStub2') const ERCProxyMock = artifacts.require('ERCProxyMock') const KernelSetAppMock = artifacts.require('KernelSetAppMock') -const APP_ID = hash('stub.aragonpm.test') -const ZERO_ADDR = '0x0000000000000000000000000000000000000000' const EMPTY_BYTES = '0x' +const APP_ID = hash('stub.aragonpm.test') -contract('App proxy', ([permissionsRoot]) => { +contract('App proxy', ([permissionsRoot, nonContract]) => { let aclBase, appBase1, appBase2, kernelBase, acl, kernel let APP_BASES_NAMESPACE, APP_ROLE let UPGRADEABLE, FORWARDING @@ -42,9 +40,9 @@ contract('App proxy', ([permissionsRoot]) => { }) beforeEach(async () => { - kernel = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + kernel = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) await kernel.initialize(aclBase.address, permissionsRoot) - acl = ACL.at(await kernel.acl()) + acl = await ACL.at(await kernel.acl()) // Set up app management permissions const APP_MANAGER_ROLE = await kernelBase.APP_MANAGER_ROLE() @@ -67,7 +65,7 @@ contract('App proxy', ([permissionsRoot]) => { // Suite of basic tests for each proxy type checkProxyType = () => { it('checks ERC897 functions', async () => { - const proxy = appProxyContract.at(app.address) + const proxy = await appProxyContract.at(app.address) const implementation = await proxy.implementation() assert.equal(implementation, appBase1.address, 'app address should match base') @@ -82,12 +80,12 @@ contract('App proxy', ([permissionsRoot]) => { if (appProxyType === 'AppProxyUpgradeable') { it('is upgradeable', async () => { - const proxy = appProxyContract.at(app.address) + const proxy = await appProxyContract.at(app.address) assert.equal((await proxy.proxyType()).toString(), UPGRADEABLE, 'app should be upgradeable') }) } else if (appProxyType === 'AppProxyPinned') { it('is not upgradeable', async () => { - const proxy = appProxyContract.at(app.address) + const proxy = await appProxyContract.at(app.address) assert.notEqual((await proxy.proxyType()).toString(), UPGRADEABLE, 'app should not be upgradeable') }) } @@ -99,7 +97,7 @@ contract('App proxy', ([permissionsRoot]) => { }) it('fails if initializing on constructor before setting app code', async () => { - const initializationPayload = appBase1.contract.initialize.getData() + const initializationPayload = appBase1.contract.methods.initialize().encodeABI() await assertRevert(AppProxyUpgradeable.new(kernel.address, APP_ID, initializationPayload)) }) @@ -114,7 +112,7 @@ contract('App proxy', ([permissionsRoot]) => { it("fails if code set isn't a contract", async () => { const kernelMock = await KernelSetAppMock.new() - await kernelMock.setApp(APP_BASES_NAMESPACE, FAKE_APP_ID, '0x1234') + await kernelMock.setApp(APP_BASES_NAMESPACE, FAKE_APP_ID, nonContract) await assertRevert(AppProxyPinned.new(kernelMock.address, FAKE_APP_ID, EMPTY_BYTES)) }) @@ -122,11 +120,11 @@ contract('App proxy', ([permissionsRoot]) => { context('> Fails on bad kernel', () => { it('fails if kernel address is 0', async () => { - await assertRevert(appProxyContract.new(ZERO_ADDR, APP_ID, EMPTY_BYTES)) + await assertRevert(appProxyContract.new(ZERO_ADDRESS, APP_ID, EMPTY_BYTES)) }) it('fails if kernel address is not a contract', async () => { - await assertRevert(appProxyContract.new('0x1234', APP_ID, EMPTY_BYTES)) + await assertRevert(appProxyContract.new(nonContract, APP_ID, EMPTY_BYTES)) }) }) @@ -134,9 +132,9 @@ contract('App proxy', ([permissionsRoot]) => { beforeEach(async () => { await kernel.setApp(APP_BASES_NAMESPACE, APP_ID, appBase1.address) - const initializationPayload = appBase1.contract.initialize.getData() + const initializationPayload = appBase1.contract.methods.initialize().encodeABI() const appProxy = await appProxyContract.new(kernel.address, APP_ID, initializationPayload) - app = AppStub.at(appProxy.address) + app = await AppStub.at(appProxy.address) }) // Run generic checks for proxy type @@ -151,7 +149,7 @@ contract('App proxy', ([permissionsRoot]) => { }) it('has correct initialization block', async () => { - assert.equal(await app.getInitializationBlock(), await getBlockNumber(), 'initialization block should be correct') + assert.equal(await app.getInitializationBlock(), await web3.eth.getBlockNumber(), 'initialization block should be correct') }) it('cannot reinitialize', async () => { @@ -174,7 +172,7 @@ contract('App proxy', ([permissionsRoot]) => { const initializationPayload = EMPTY_BYTES // don't initialize const appProxy = await appProxyContract.new(kernel.address, APP_ID, initializationPayload) - app = AppStub.at(appProxy.address) + app = await AppStub.at(appProxy.address) }) // Run generic checks for proxy type @@ -206,9 +204,9 @@ contract('App proxy', ([permissionsRoot]) => { beforeEach(async () => { await kernel.setApp(APP_BASES_NAMESPACE, APP_ID, appBase1.address) - const initializationPayload = appBase1.contract.initialize.getData() + const initializationPayload = appBase1.contract.methods.initialize().encodeABI() const appProxy = await appProxyContract.new(kernel.address, APP_ID, initializationPayload) - app = AppStub.at(appProxy.address) + app = await AppStub.at(appProxy.address) // Assign app permissions await acl.createPermission(permissionsRoot, appProxy.address, APP_ROLE, permissionsRoot) diff --git a/test/contracts/apps/disputable/disputable_app.js b/test/contracts/apps/disputable/disputable_app.js index c663704e3..2cbba1fbc 100644 --- a/test/contracts/apps/disputable/disputable_app.js +++ b/test/contracts/apps/disputable/disputable_app.js @@ -1,8 +1,7 @@ const { sha3 } = require('web3-utils') -const { assertRevert } = require('../../../helpers/assertThrow') -const { getEventArgument } = require('../../../helpers/events') -const { getNewProxyAddress } = require('../../../helpers/events') -const { assertEvent, assertAmountOfEvents } = require('../../../helpers/assertEvent')(web3) +const { getInstalledApp } = require('@aragon/contract-helpers-test/src/aragon-os') +const { getEventArgument, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { assertRevert, assertEvent, assertAmountOfEvents } = require('@aragon/contract-helpers-test/src/asserts') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -16,7 +15,6 @@ const EVMScriptRegistryFactory = artifacts.require('EVMScriptRegistryFactory') contract('DisputableApp', ([_, owner, agreement, anotherAgreement, someone]) => { let disputable, disputableBase, dao, acl - const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' const DISPUTABLE_INTERFACE = '0xf3d3bb51' const ARAGON_APP_INTERFACE = '0x54053e6c' const ERC165_INTERFACE = '0x01ffc9a7' @@ -37,9 +35,9 @@ contract('DisputableApp', ([_, owner, agreement, anotherAgreement, someone]) => }) beforeEach('install disputable app', async () => { - const initializeData = disputableBase.contract.initialize.getData() + const initializeData = disputableBase.contract.methods.initialize().encodeABI() const receipt = await dao.newAppInstance('0x1234', disputableBase.address, initializeData, false, { from: owner }) - disputable = await DisputableApp.at(getNewProxyAddress(receipt)) + disputable = await DisputableApp.at(getInstalledApp(receipt)) const SET_AGREEMENT_ROLE = await disputable.SET_AGREEMENT_ROLE() await acl.createPermission(owner, disputable.address, SET_AGREEMENT_ROLE, owner, { from: owner }) @@ -90,7 +88,7 @@ contract('DisputableApp', ([_, owner, agreement, anotherAgreement, someone]) => const receipt = await disputable.setAgreement(agreement, { from }) assertAmountOfEvents(receipt, 'AgreementSet') - assertEvent(receipt, 'AgreementSet', { agreement }) + assertEvent(receipt, 'AgreementSet', { expectedArgs: { agreement } }) }) } diff --git a/test/contracts/apps/recovery_to_vault.js b/test/contracts/apps/recovery_to_vault.js index d913260ad..768cfe0c0 100644 --- a/test/contracts/apps/recovery_to_vault.js +++ b/test/contracts/apps/recovery_to_vault.js @@ -1,8 +1,7 @@ const { hash } = require('eth-ens-namehash') -const { assertAmountOfEvents, assertEvent } = require('../../helpers/assertEvent')(web3) -const { assertRevert } = require('../../helpers/assertThrow') -const { getNewProxyAddress } = require('../../helpers/events') -const { getBalance } = require('../../helpers/web3') +const { bn } = require('@aragon/contract-helpers-test') +const { getInstalledApp } = require('@aragon/contract-helpers-test/src/aragon-os') +const { assertAmountOfEvents, assertEvent, assertRevert, assertBn } = require('@aragon/contract-helpers-test/src/asserts') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -29,59 +28,59 @@ contract('Recovery to vault', ([permissionsRoot]) => { // Helpers const recoverEth = async ({ shouldFail, target, vault }) => { - const amount = 1 - const initialBalance = await getBalance(target.address) - const initialVaultBalance = await getBalance(vault.address) - await target.sendTransaction({ value: 1, gas: SEND_ETH_GAS }) - assert.equal((await getBalance(target.address)).valueOf(), initialBalance.plus(amount), 'Target initial balance should be correct') + const amount = bn(1) + const initialBalance = bn(await web3.eth.getBalance(target.address)) + const initialVaultBalance = bn(await web3.eth.getBalance(vault.address)) + await target.sendTransaction({ value: amount, gas: SEND_ETH_GAS }) + assertBn(bn(await web3.eth.getBalance(target.address)), initialBalance.add(amount), 'Target initial balance should be correct') const recoverAction = () => target.transferToVault(ETH) if (shouldFail) { await assertRevert(recoverAction) - assert.equal((await getBalance(target.address)).valueOf(), initialBalance.plus(amount), 'Target balance should be same as before') - assert.equal((await getBalance(vault.address)).valueOf(), initialVaultBalance, 'Vault balance should should be same as before') + assertBn(bn(await web3.eth.getBalance(target.address)), initialBalance.add(amount), 'Target balance should be same as before') + assertBn(bn(await web3.eth.getBalance(vault.address)), initialVaultBalance, 'Vault balance should should be same as before') } else { const recoverReceipt = await recoverAction() - assert.equal((await getBalance(target.address)).valueOf(), 0, 'Target balance should be 0') - assert.equal((await getBalance(vault.address)).valueOf(), initialVaultBalance.plus(initialBalance).plus(amount), 'Vault balance should include recovered amount') + assertBn(bn(await web3.eth.getBalance(target.address)), bn(0), 'Target balance should be 0') + assertBn(bn(await web3.eth.getBalance(vault.address)), initialVaultBalance.add(initialBalance).add(amount), 'Vault balance should include recovered amount') assertAmountOfEvents(recoverReceipt, 'RecoverToVault') - assertEvent(recoverReceipt, 'RecoverToVault', { vault: vault.address, token: ETH, amount: amount }) + assertEvent(recoverReceipt, 'RecoverToVault', { expectedArgs: { vault: vault.address, token: ETH, amount: amount } }) } } const recoverTokens = async ({ shouldFail, tokenContract, target, vault }) => { - const amount = 1 + const amount = bn(1) const token = await tokenContract.new(permissionsRoot, 1000) const initialBalance = await token.balanceOf(target.address) const initialVaultBalance = await token.balanceOf(vault.address) await token.transfer(target.address, amount) - assert.equal((await token.balanceOf(target.address)).valueOf(), initialBalance.plus(amount), 'Target initial balance should be correct') + assertBn(bn(await token.balanceOf(target.address)), initialBalance.add(amount), 'Target initial balance should be correct') const recoverAction = () => target.transferToVault(token.address) if (shouldFail) { await assertRevert(recoverAction) - assert.equal((await token.balanceOf(target.address)).valueOf(), initialBalance.plus(amount), 'Target balance should be same as before') - assert.equal((await token.balanceOf(vault.address)).valueOf(), initialVaultBalance, 'Vault balance should should be same as before') + assertBn((await token.balanceOf(target.address)), initialBalance.add(amount), 'Target balance should be same as before') + assertBn((await token.balanceOf(vault.address)), initialVaultBalance, 'Vault balance should should be same as before') } else { const recoverReceipt = await recoverAction() - assert.equal((await token.balanceOf(target.address)).valueOf(), 0, 'Target balance should be 0') - assert.equal((await token.balanceOf(vault.address)).valueOf(), initialVaultBalance.plus(initialBalance).plus(amount), 'Vault balance should include recovered amount') + assertBn((await token.balanceOf(target.address)), 0, 'Target balance should be 0') + assertBn((await token.balanceOf(vault.address)), initialVaultBalance.add(initialBalance).add(amount), 'Vault balance should include recovered amount') assertAmountOfEvents(recoverReceipt, 'RecoverToVault') - assertEvent(recoverReceipt, 'RecoverToVault', { vault: vault.address, token: token.address, amount: amount }) + assertEvent(recoverReceipt, 'RecoverToVault', { expectedArgs: { vault: vault.address, token: token.address, amount: amount } }) } } const failingRecoverTokens = async ({ tokenContract, target, vault }) => { - const amount = 1 + const amount = bn(1) const token = await tokenContract.new(permissionsRoot, 1000) const initialBalance = await token.balanceOf(target.address) const initialVaultBalance = await token.balanceOf(vault.address) await token.transfer(target.address, amount) - assert.equal((await token.balanceOf(target.address)).valueOf(), initialBalance.plus(amount), 'Target initial balance should be correct') + assertBn((await token.balanceOf(target.address)), initialBalance.add(amount), 'Target initial balance should be correct') // Stop token from being transferable await token.setAllowTransfer(false) @@ -89,17 +88,17 @@ contract('Recovery to vault', ([permissionsRoot]) => { // Try to transfer await assertRevert(target.transferToVault(token.address)) - assert.equal((await token.balanceOf(target.address)).valueOf(), initialBalance.plus(amount), 'Target balance should be same as before') - assert.equal((await token.balanceOf(vault.address)).valueOf(), initialVaultBalance, 'Vault balance should should be same as before') + assertBn((await token.balanceOf(target.address)), initialBalance.add(amount), 'Target balance should be same as before') + assertBn((await token.balanceOf(vault.address)), initialVaultBalance, 'Vault balance should should be same as before') } const failWithoutVault = async (target, kernel) => { - const amount = 1 + const amount = bn(1) const vaultId = hash('vaultfake.aragonpm.test') - const initialBalance = await getBalance(target.address) + const initialBalance = bn(await web3.eth.getBalance(target.address)) await kernel.setRecoveryVaultAppId(vaultId) const r = await target.sendTransaction({ value: 1, gas: SEND_ETH_GAS }) - assert.equal((await getBalance(target.address)).valueOf(), initialBalance.plus(amount), 'Target initial balance should be correct') + assertBn(bn(await web3.eth.getBalance(target.address)), initialBalance.add(amount), 'Target initial balance should be correct') await assertRevert(target.transferToVault(ETH)) } @@ -149,11 +148,11 @@ contract('Recovery to vault', ([permissionsRoot]) => { if (kernelType === 'Kernel') { kernel = await Kernel.new(false) // don't petrify so it can be used } else if (kernelType === 'KernelProxy') { - kernel = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + kernel = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) } await kernel.initialize(aclBase.address, permissionsRoot) - const acl = ACL.at(await kernel.acl()) + const acl = await ACL.at(await kernel.acl()) const r = await kernel.APP_MANAGER_ROLE() await acl.createPermission(permissionsRoot, kernel.address, r, permissionsRoot) }) @@ -172,8 +171,8 @@ contract('Recovery to vault', ([permissionsRoot]) => { } else if (vaultType === 'VaultProxy') { // This doesn't automatically setup the recovery address const receipt = await kernel.newAppInstance(vaultId, vaultBase.address, EMPTY_BYTES, false) - const vaultProxyAddress = getNewProxyAddress(receipt) - vault = VaultMock.at(vaultProxyAddress) + const vaultProxyAddress = getInstalledApp(receipt) + vault = await VaultMock.at(vaultProxyAddress) } await vault.initialize() @@ -227,8 +226,8 @@ contract('Recovery to vault', ([permissionsRoot]) => { beforeEach(async () => { // Setup app const receipt = await kernel.newAppInstance(APP_ID, appBase.address, EMPTY_BYTES, false) - const appProxy = getNewProxyAddress(receipt) - const app = AppStubDepositable.at(appProxy) + const appProxy = getInstalledApp(receipt, APP_ID) + const app = await AppStubDepositable.at(appProxy) await app.enableDeposits() target = app @@ -273,8 +272,8 @@ contract('Recovery to vault', ([permissionsRoot]) => { beforeEach(async () => { // Setup app with conditional recovery code const receipt = await kernel.newAppInstance(APP_ID, appConditionalRecoveryBase.address, EMPTY_BYTES, false) - const appProxy = getNewProxyAddress(receipt) - const app = AppStubConditionalRecovery.at(appProxy) + const appProxy = getInstalledApp(receipt) + const app = await AppStubConditionalRecovery.at(appProxy) await app.initialize() target = app @@ -317,10 +316,10 @@ contract('Recovery to vault', ([permissionsRoot]) => { const kernelBase = await KernelDepositableMock.new(true) // petrify immediately const kernelProxy = await KernelProxy.new(kernelBase.address) const aclBase = await ACL.new() - kernel = KernelDepositableMock.at(kernelProxy.address) + kernel = await KernelDepositableMock.at(kernelProxy.address) await kernel.initialize(aclBase.address, permissionsRoot) await kernel.enableDeposits() - const acl = ACL.at(await kernel.acl()) + const acl = await ACL.at(await kernel.acl()) const APP_MANAGER_ROLE = await kernelBase.APP_MANAGER_ROLE() await acl.createPermission(permissionsRoot, kernel.address, APP_MANAGER_ROLE, permissionsRoot, { from: permissionsRoot }) @@ -328,8 +327,8 @@ contract('Recovery to vault', ([permissionsRoot]) => { const vaultId = hash('vault.aragonpm.test') const vaultBase = await VaultMock.new() const vaultReceipt = await kernel.newAppInstance(vaultId, vaultBase.address, EMPTY_BYTES, true) - const vaultAddress = getNewProxyAddress(vaultReceipt) - vault = VaultMock.at(vaultAddress) + const vaultAddress = getInstalledApp(vaultReceipt) + vault = await VaultMock.at(vaultAddress) await vault.initialize() await kernel.setRecoveryVaultAppId(vaultId) @@ -339,4 +338,4 @@ contract('Recovery to vault', ([permissionsRoot]) => { await recoverEth({ target: kernel, vault }) }) }) -}) \ No newline at end of file +}) diff --git a/test/contracts/common/depositable_delegate_proxy.js b/test/contracts/common/depositable_delegate_proxy.js index 07ce0537e..8edd889ad 100644 --- a/test/contracts/common/depositable_delegate_proxy.js +++ b/test/contracts/common/depositable_delegate_proxy.js @@ -1,9 +1,6 @@ -const { toChecksumAddress } = require('web3-utils') -const { assertAmountOfEvents, assertEvent } = require('../../helpers/assertEvent')(web3) const { skipCoverage } = require('../../helpers/coverage') -const { decodeEventsOfType } = require('../../helpers/decodeEvent') -const { assertRevert, assertOutOfGas } = require('../../helpers/assertThrow') -const { getBalance } = require('../../helpers/web3') +const { bn } = require('@aragon/contract-helpers-test') +const { assertAmountOfEvents, assertEvent, assertRevert, assertOutOfGas, assertBn } = require('@aragon/contract-helpers-test/src/asserts') // Mocks const DepositableDelegateProxyMock = artifacts.require('DepositableDelegateProxyMock') @@ -29,7 +26,7 @@ contract('DepositableDelegateProxy', ([ sender ]) => { beforeEach(async () => { proxy = await DepositableDelegateProxyMock.new() - target = ProxyTargetWithFallback.at(proxy.address) + target = await ProxyTargetWithFallback.at(proxy.address) }) const itForwardsToImplementationIfGasIsOverThreshold = () => { @@ -96,22 +93,22 @@ contract('DepositableDelegateProxy', ([ sender ]) => { }) context('when call gas is below the forwarding threshold', () => { - const value = 100 + const value = bn(100) const assertSendEthToProxy = async ({ value, gas, shouldOOG }) => { - const initialBalance = await getBalance(proxy.address) + const initialBalance = bn(await web3.eth.getBalance(proxy.address)) const sendEthAction = () => proxy.sendTransaction({ from: sender, gas, value }) if (shouldOOG) { await assertOutOfGas(sendEthAction()) - assert.equal((await getBalance(proxy.address)).valueOf(), initialBalance, 'Target balance should be the same as before') + assertBn(bn(await web3.eth.getBalance(proxy.address)), initialBalance, 'Target balance should be the same as before') } else { - const { receipt, logs } = await sendEthAction() + const receipt = await sendEthAction() - assert.equal((await getBalance(proxy.address)).valueOf(), initialBalance.plus(value), 'Target balance should be correct') - assertAmountOfEvents({ logs }, 'ProxyDeposit') - assertEvent({ logs }, 'ProxyDeposit', { sender, value }) + assertBn(bn(await web3.eth.getBalance(proxy.address)), initialBalance.add(value), 'Target balance should be correct') + assertAmountOfEvents(receipt, 'ProxyDeposit', { decodeForAbi: DepositableDelegateProxyMock.abi }) + assertEvent(receipt, 'ProxyDeposit', { decodeForAbi: DepositableDelegateProxyMock.abi, expectedArgs: { sender, value } }) return receipt } @@ -134,11 +131,10 @@ contract('DepositableDelegateProxy', ([ sender ]) => { ) it('can receive ETH from contract', async () => { - const { tx } = await ethSender.sendEth(proxy.address, { value }) - const receipt = await web3.eth.getTransactionReceipt(tx) - const logs = decodeEventsOfType(receipt, DepositableDelegateProxyMock.abi, 'ProxyDeposit') - assertAmountOfEvents({ logs }, 'ProxyDeposit') - assertEvent({ logs }, 'ProxyDeposit', { sender: toChecksumAddress(ethSender.address), value }) + const receipt = await ethSender.sendEth(proxy.address, { value }) + + assertAmountOfEvents(receipt, 'ProxyDeposit', { decodeForAbi: proxy.abi }) + assertEvent(receipt, 'ProxyDeposit', { decodeForAbi: proxy.abi, expectedArgs: { sender: ethSender.address, value } }) }) itRevertsOnInvalidDeposits() diff --git a/test/contracts/common/lifecycle.js b/test/contracts/common/lifecycle.js index ee0d11d6e..9f9e63494 100644 --- a/test/contracts/common/lifecycle.js +++ b/test/contracts/common/lifecycle.js @@ -1,6 +1,5 @@ -const reverts = require('../../helpers/revertStrings') -const { assertRevert } = require('../../helpers/assertThrow') -const { getBlockNumber } = require('../../helpers/web3') +const ERRORS = require('../../helpers/errors') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') // Mocks const LifecycleMock = artifacts.require('LifecycleMock') @@ -34,15 +33,15 @@ contract('Lifecycle', () => { }) it('has correct initialization block', async () => { - assert.equal(await lifecycle.getInitializationBlock(), await getBlockNumber(), 'initialization block should be correct') + assert.equal(await lifecycle.getInitializationBlock(), await web3.eth.getBlockNumber(), 'initialization block should be correct') }) it('cannot be re-initialized', async () => { - await assertRevert(lifecycle.initializeMock(), reverts.INIT_ALREADY_INITIALIZED) + await assertRevert(lifecycle.initializeMock(), ERRORS.INIT_ALREADY_INITIALIZED) }) it('cannot be petrified', async () => { - await assertRevert(lifecycle.petrifyMock(), reverts.INIT_ALREADY_INITIALIZED) + await assertRevert(lifecycle.petrifyMock(), ERRORS.INIT_ALREADY_INITIALIZED) }) }) @@ -60,13 +59,13 @@ contract('Lifecycle', () => { }) it('cannot be petrified again', async () => { - await assertRevert(lifecycle.petrifyMock(), reverts.INIT_ALREADY_INITIALIZED) + await assertRevert(lifecycle.petrifyMock(), ERRORS.INIT_ALREADY_INITIALIZED) }) it('has initialization block in the future', async () => { const petrifiedBlock = await lifecycle.getInitializationBlock() - const blockNumber = await getBlockNumber() - assert.isTrue(petrifiedBlock.greaterThan(blockNumber), 'petrified block should be in the future') + const blockNumber = await web3.eth.getBlockNumber() + assert.isTrue(petrifiedBlock.gt(blockNumber), 'petrified block should be in the future') }) }) }) diff --git a/test/contracts/common/reentrancy_guard.js b/test/contracts/common/reentrancy_guard.js index 6a3c4c8ec..95c715b20 100644 --- a/test/contracts/common/reentrancy_guard.js +++ b/test/contracts/common/reentrancy_guard.js @@ -1,6 +1,5 @@ -const { assertRevert } = require('../../helpers/assertThrow') - -const ZERO_ADDR = '0x0000000000000000000000000000000000000000' +const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') contract('ReentrancyGuard', () => { let reentrancyMock @@ -26,13 +25,13 @@ contract('ReentrancyGuard', () => { }) it('can call re-entrant function normally', async () => { - await reentrancyMock.reentrantCall(ZERO_ADDR) + await reentrancyMock.reentrantCall(ZERO_ADDRESS) assert.equal((await reentrancyMock.callCounter()).toString(), 1, 'should have registered one call') await assertReentrancyMutex(false, 're-entrancy mutex should end false') }) it('can call non-re-entrant function normally', async () => { - await reentrancyMock.nonReentrantCall(ZERO_ADDR) + await reentrancyMock.nonReentrantCall(ZERO_ADDRESS) assert.equal((await reentrancyMock.callCounter()).toString(), 1, 'should have registered one call') await assertReentrancyMutex(false, 're-entrancy mutex should end false') }) @@ -44,12 +43,12 @@ contract('ReentrancyGuard', () => { }) it('can call re-entrant function if re-entrancy mutex is enabled', async () => { - await reentrancyMock.reentrantCall(ZERO_ADDR) + await reentrancyMock.reentrantCall(ZERO_ADDRESS) assert.equal((await reentrancyMock.callCounter()).toString(), 1, 'should have called') }) it('can not call non-re-entrant function if re-entrancy mutex is enabled', async () => { - await assertRevert(reentrancyMock.nonReentrantCall(ZERO_ADDR)) + await assertRevert(reentrancyMock.nonReentrantCall(ZERO_ADDRESS)) assert.equal((await reentrancyMock.callCounter()).toString(), 0, 'should not have called') }) }) diff --git a/test/contracts/common/safe_erc20.js b/test/contracts/common/safe_erc20.js index 2b8d58505..ee5356894 100644 --- a/test/contracts/common/safe_erc20.js +++ b/test/contracts/common/safe_erc20.js @@ -1,4 +1,5 @@ -const { getEventArgument } = require('../../helpers/events') +const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') +const { bn, getEventArgument } = require('@aragon/contract-helpers-test') // Mocks const SafeERC20Mock = artifacts.require('SafeERC20Mock') @@ -9,7 +10,7 @@ const TokenReturnMissingMock = artifacts.require('TokenReturnMissingMock') const assertMockResult = (receipt, result) => assert.equal(getEventArgument(receipt, 'Result', 'result'), result, `result does not match`) contract('SafeERC20', ([owner, receiver]) => { - const initialBalance = 10000 + const initialBalance = bn(10000) let safeERC20Mock before(async () => { @@ -41,14 +42,14 @@ contract('SafeERC20', ([owner, receiver]) => { it('can correctly transfer', async () => { // Add balance to the mock - const transferAmount = 5000 + const transferAmount = bn(5000) await tokenMock.transfer(safeERC20Mock.address, transferAmount) // Transfer it all back from the mock const receipt = await safeERC20Mock.transfer(tokenMock.address, owner, transferAmount) assertMockResult(receipt, true) - assert.equal((await tokenMock.balanceOf(owner)).valueOf(), initialBalance, 'Balance of owner should be correct') - assert.equal((await tokenMock.balanceOf(safeERC20Mock.address)).valueOf(), 0, 'Balance of mock should be correct') + assertBn((await tokenMock.balanceOf(owner)), initialBalance, 'Balance of owner should be correct') + assertBn((await tokenMock.balanceOf(safeERC20Mock.address)), 0, 'Balance of mock should be correct') }) it('detects failed transfer', async () => { @@ -56,21 +57,21 @@ contract('SafeERC20', ([owner, receiver]) => { const receipt = await safeERC20Mock.transfer(tokenMock.address, owner, 1000) assertMockResult(receipt, false) - assert.equal((await tokenMock.balanceOf(owner)).valueOf(), initialBalance, 'Balance of owner should stay the same') - assert.equal((await tokenMock.balanceOf(safeERC20Mock.address)).valueOf(), 0, 'Balance of mock should stay the same') + assertBn(await tokenMock.balanceOf(owner), initialBalance, 'Balance of owner should stay the same') + assertBn(await tokenMock.balanceOf(safeERC20Mock.address), 0, 'Balance of mock should stay the same') }) it('can correctly approve', async () => { - const approvedAmount = 5000 + const approvedAmount = bn(5000) // Create approval from the mock const receipt = await safeERC20Mock.approve(tokenMock.address, receiver, approvedAmount) assertMockResult(receipt, true) - assert.equal((await tokenMock.allowance(safeERC20Mock.address, receiver)).valueOf(), approvedAmount, 'Allowance of receiver should be correct') + assertBn(await tokenMock.allowance(safeERC20Mock.address, receiver), approvedAmount, 'Allowance of receiver should be correct') }) it('detects failed approve', async () => { - const preApprovedAmount = 5000 + const preApprovedAmount = bn(5000) // Create pre-exisiting approval await safeERC20Mock.approve(tokenMock.address, receiver, preApprovedAmount) @@ -79,20 +80,20 @@ contract('SafeERC20', ([owner, receiver]) => { const receipt = await safeERC20Mock.approve(tokenMock.address, receiver, preApprovedAmount - 500) assertMockResult(receipt, false) - assert.equal((await tokenMock.allowance(safeERC20Mock.address, receiver)).valueOf(), preApprovedAmount, 'Allowance of receiver should be the pre-existing value') + assertBn(await tokenMock.allowance(safeERC20Mock.address, receiver), preApprovedAmount, 'Allowance of receiver should be the pre-existing value') }) it('can correctly transferFrom', async () => { // Create approval - const approvedAmount = 5000 + const approvedAmount = bn(5000) await tokenMock.approve(safeERC20Mock.address, approvedAmount) // Transfer to receiver through the mock const receipt = await safeERC20Mock.transferFrom(tokenMock.address, owner, receiver, approvedAmount) assertMockResult(receipt, true) - assert.equal((await tokenMock.balanceOf(owner)).valueOf(), initialBalance - approvedAmount, 'Balance of owner should be correct') - assert.equal((await tokenMock.balanceOf(receiver)).valueOf(), approvedAmount, 'Balance of receiver should be correct') - assert.equal((await tokenMock.balanceOf(safeERC20Mock.address)).valueOf(), 0, 'Balance of mock should stay the same') + assertBn(await tokenMock.balanceOf(owner), initialBalance - approvedAmount, 'Balance of owner should be correct') + assertBn(await tokenMock.balanceOf(receiver), approvedAmount, 'Balance of receiver should be correct') + assertBn(await tokenMock.balanceOf(safeERC20Mock.address), 0, 'Balance of mock should stay the same') }) it('detects failed transferFrom', async () => { @@ -100,31 +101,31 @@ contract('SafeERC20', ([owner, receiver]) => { const receipt = await safeERC20Mock.transferFrom(tokenMock.address, owner, receiver, 5000) assertMockResult(receipt, false) - assert.equal((await tokenMock.balanceOf(owner)).valueOf(), initialBalance, 'Balance of owner should stay the same') - assert.equal((await tokenMock.balanceOf(receiver)).valueOf(), 0, 'Balance of receiver should stay the same') - assert.equal((await tokenMock.balanceOf(safeERC20Mock.address)).valueOf(), 0, 'Balance of mock should stay the same') + assertBn(await tokenMock.balanceOf(owner), initialBalance, 'Balance of owner should stay the same') + assertBn(await tokenMock.balanceOf(receiver), 0, 'Balance of receiver should stay the same') + assertBn(await tokenMock.balanceOf(safeERC20Mock.address), 0, 'Balance of mock should stay the same') }) it('gives correct value with static allowance', async () => { // Create approval - const approvedAmount = 5000 + const approvedAmount = bn(5000) await tokenMock.approve(safeERC20Mock.address, approvedAmount) - const approval = (await safeERC20Mock.allowance(tokenMock.address, owner, safeERC20Mock.address)).valueOf() - assert.equal(approval, approvedAmount, 'Mock should return correct allowance') - assert.equal((await tokenMock.allowance(owner, safeERC20Mock.address)).valueOf(), approval, "Mock should match token contract's allowance") + const approval = (await safeERC20Mock.allowance(tokenMock.address, owner, safeERC20Mock.address)) + assertBn(approval, approvedAmount, 'Mock should return correct allowance') + assertBn(await tokenMock.allowance(owner, safeERC20Mock.address), approval, "Mock should match token contract's allowance") }) it('gives correct value with static balanceOf', async () => { - const balance = (await safeERC20Mock.balanceOf(tokenMock.address, owner)).valueOf() - assert.equal(balance, initialBalance, 'Mock should return correct balance') - assert.equal((await tokenMock.balanceOf(owner)).valueOf(), balance, "Mock should match token contract's balance") + const balance = await safeERC20Mock.balanceOf(tokenMock.address, owner) + assertBn(balance, initialBalance, 'Mock should return correct balance') + assertBn(await tokenMock.balanceOf(owner), balance, "Mock should match token contract's balance") }) it('gives correct value with static totalSupply', async () => { - const totalSupply = (await safeERC20Mock.totalSupply(tokenMock.address)).valueOf() - assert.equal(totalSupply, initialBalance, 'Mock should return correct total supply') - assert.equal((await tokenMock.totalSupply()).valueOf(), totalSupply, "Mock should match token contract's total supply") + const totalSupply = (await safeERC20Mock.totalSupply(tokenMock.address)) + assertBn(totalSupply, initialBalance, 'Mock should return correct total supply') + assertBn(await tokenMock.totalSupply(), totalSupply, "Mock should match token contract's total supply") }) }) } diff --git a/test/contracts/common/time_helpers.js b/test/contracts/common/time_helpers.js index 13530fd32..d6da56145 100644 --- a/test/contracts/common/time_helpers.js +++ b/test/contracts/common/time_helpers.js @@ -1,3 +1,5 @@ +const { bn } = require('@aragon/contract-helpers-test') + contract('TimeHelpers', () => { let timeHelpersMock @@ -7,7 +9,7 @@ contract('TimeHelpers', () => { it('checks block number', async () => { assert.equal((await timeHelpersMock.getBlockNumberExt()).toString(), (await timeHelpersMock.getBlockNumber64Ext()).toString(), "block numbers should match") - assert.equal((await timeHelpersMock.getBlockNumberExt()).toString(), (await timeHelpersMock.getBlockNumberDirect()).toString(), web3.eth.blockNumber, "block number should match with real one", "block number should match with real one") + assert.equal((await timeHelpersMock.getBlockNumberExt()).toString(), (await timeHelpersMock.getBlockNumberDirect()).toString(), web3.eth.getBlockNumber, "block number should match with real one", "block number should match with real one") }) it('checks time stamp', async () => { @@ -15,9 +17,10 @@ contract('TimeHelpers', () => { const timestamp64 = await timeHelpersMock.getTimestamp64Ext() const timestampReal = await timeHelpersMock.getTimestampDirect() - const timestamp64Diff = timestamp64.minus(timestamp) - const timestampRealDiff = timestampReal.minus(timestamp) - assert.isTrue(timestamp64Diff.lessThanOrEqualTo(1), "time stamps should match (or be very close to)") - assert.isTrue(timestampRealDiff.lessThanOrEqualTo(1), "time stamp should match with real one (or be very close to)") + const timestamp64Diff = timestamp64.sub(timestamp) + assert.isTrue(timestamp64Diff.lte(bn(1)), 'time stamps should match (or be very close to)') + + const timestampRealDiff = timestampReal.sub(timestamp) + assert.isTrue(timestampRealDiff.lte(bn(1)), 'time stamp should match with real one (or be very close to)') }) }) diff --git a/test/contracts/common/uint256_helpers.js b/test/contracts/common/uint256_helpers.js index 7be2a8ff4..d97139132 100644 --- a/test/contracts/common/uint256_helpers.js +++ b/test/contracts/common/uint256_helpers.js @@ -1,4 +1,5 @@ -const { assertRevert } = require('../../helpers/assertThrow') +const { bn } = require('@aragon/contract-helpers-test') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') contract('Uint256 Helpers test', () => { let uint256Mock @@ -13,7 +14,7 @@ contract('Uint256 Helpers test', () => { }) it('fails converting from uint256 to uint64 if too big', async () => { - const a = new web3.BigNumber(2).pow(64) + const a = bn(2).pow(bn(64)) await assertRevert(uint256Mock.convert(a)) }) }) diff --git a/test/contracts/common/unstructured_storage.js b/test/contracts/common/unstructured_storage.js index a5bff25c1..249b362ea 100644 --- a/test/contracts/common/unstructured_storage.js +++ b/test/contracts/common/unstructured_storage.js @@ -23,12 +23,12 @@ contract('Unstructured storage', () => { // checks assert.equal( await web3.eth.getStorageAt(appStorage.address, (await appStorage.getKernelPosition())), - (await appStorage.kernel()).toString(), + (await appStorage.kernel()).toString().toLowerCase(), 'Kernel should match' ) assert.equal( await web3.eth.getStorageAt(appStorage.address, (await appStorage.getKernelPosition())), - kernel.address, + kernel.address.toLowerCase(), 'Kernel original value should match' ) }) @@ -105,7 +105,7 @@ contract('Unstructured storage', () => { it('tests init block', async () => { // set values await initializableMock.initialize() - const blockNumber = web3.eth.blockNumber + const blockNumber = await web3.eth.getBlockNumber() // checks assert.equal( parseInt( diff --git a/test/contracts/evmscript/evm_script.js b/test/contracts/evmscript/evm_script.js index 3b36ae593..b3e3fc370 100644 --- a/test/contracts/evmscript/evm_script.js +++ b/test/contracts/evmscript/evm_script.js @@ -1,10 +1,9 @@ -const reverts = require('../../helpers/revertStrings') -const { rawEncode } = require('ethereumjs-abi') +const ERRORS = require('../../helpers/errors') const { soliditySha3 } = require('web3-utils') -const { assertRevert } = require('../../helpers/assertThrow') -const { createExecutorId, encodeCallScript } = require('../../helpers/evmScript') -const { assertEvent, assertAmountOfEvents } = require('../../helpers/assertEvent')(web3) -const { getEventArgument, getNewProxyAddress } = require('../../helpers/events') +const { rawEncode } = require('ethereumjs-abi') +const { getEventArgument, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { assertEvent, assertAmountOfEvents, assertRevert } = require('@aragon/contract-helpers-test/src/asserts') +const { getInstalledApp, createExecutorId, encodeCallScript } = require('@aragon/contract-helpers-test/src/aragon-os') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -21,10 +20,9 @@ const EVMScriptExecutorNoReturnMock = artifacts.require('EVMScriptExecutorNoRetu const EVMScriptExecutorRevertMock = artifacts.require('EVMScriptExecutorRevertMock') const EVMScriptRegistryConstantsMock = artifacts.require('EVMScriptRegistryConstantsMock') -const ZERO_ADDR = '0x0000000000000000000000000000000000000000' const EMPTY_BYTES = '0x' -contract('EVM Script', ([_, boss]) => { +contract('EVM Script', ([_, boss, nonContract]) => { let kernelBase, aclBase, evmScriptRegBase, dao, acl, evmScriptReg let scriptExecutorMock, scriptExecutorNoReturnMock, scriptExecutorRevertMock let APP_BASES_NAMESPACE, APP_ADDR_NAMESPACE, APP_MANAGER_ROLE @@ -56,17 +54,17 @@ contract('EVM Script', ([_, boss]) => { }) beforeEach(async () => { - dao = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + dao = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) await dao.initialize(aclBase.address, boss) - acl = ACL.at(await dao.acl()) + acl = await ACL.at(await dao.acl()) // Set up app management permissions await acl.createPermission(boss, dao.address, APP_MANAGER_ROLE, boss, { from: boss }) // Set up script registry (MUST use correct app ID and set as default app) - const initPayload = evmScriptRegBase.contract.initialize.getData() + const initPayload = evmScriptRegBase.contract.methods.initialize().encodeABI() const evmScriptRegReceipt = await dao.newAppInstance(EVMSCRIPT_REGISTRY_APP_ID, evmScriptRegBase.address, initPayload, true, { from: boss }) - evmScriptReg = EVMScriptRegistry.at(getNewProxyAddress(evmScriptRegReceipt)) + evmScriptReg = await EVMScriptRegistry.at(getInstalledApp(evmScriptRegReceipt)) }) context('> Registry', () => { @@ -79,28 +77,28 @@ contract('EVM Script', ([_, boss]) => { }) it('fails if reinitializing registry', async () => { - await assertRevert(evmScriptReg.initialize(), reverts.INIT_ALREADY_INITIALIZED) + await assertRevert(evmScriptReg.initialize(), ERRORS.INIT_ALREADY_INITIALIZED) }) it('fails to get an executor if not enough bytes are given', async () => { // Not enough bytes are given (need 4, given 3) - await assertRevert(evmScriptReg.getScriptExecutor('0x'.padEnd(6, 0)), reverts.EVMREG_SCRIPT_LENGTH_TOO_SHORT) + await assertRevert(evmScriptReg.getScriptExecutor('0x'.padEnd(6, 0)), ERRORS.EVMREG_SCRIPT_LENGTH_TOO_SHORT) }) it('can add a new executor', async () => { const receipt = await evmScriptReg.addScriptExecutor(scriptExecutorMock.address, { from: boss }) const newExecutorId = getEventArgument(receipt, 'EnableExecutor', 'executorId') - const [executorAddress, executorEnabled] = await evmScriptReg.executors(newExecutorId) - const newExecutor = IEVMScriptExecutor.at(executorAddress) + const { executor, enabled } = await evmScriptReg.executors(newExecutorId) + const newExecutor = await IEVMScriptExecutor.at(executor) assert.equal(await scriptExecutorMock.executorType(), await newExecutor.executorType(), "executor type should be the same") - assert.equal(await scriptExecutorMock.address, await executorAddress, "executor address should be the same") - assert.isTrue(executorEnabled, "new executor should be enabled") + assert.equal(await scriptExecutorMock.address, await executor, "executor address should be the same") + assert.isTrue(enabled, "new executor should be enabled") }) it('fails to add a new executor without the correct permissions', async () => { - await assertRevert(evmScriptReg.addScriptExecutor(scriptExecutorMock.address), reverts.APP_AUTH_FAILED) + await assertRevert(evmScriptReg.addScriptExecutor(scriptExecutorMock.address), ERRORS.APP_AUTH_FAILED) }) context('> Existing executor', () => { @@ -122,7 +120,7 @@ contract('EVM Script', ([_, boss]) => { assertAmountOfEvents(receipt, 'DisableExecutor') assert.isFalse(executorEntry[1], "executor should now be disabled") - assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(installedExecutorId)), ZERO_ADDR, 'getting disabled executor should return zero addr') + assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(installedExecutorId)), ZERO_ADDRESS, 'getting disabled executor should return zero addr') }) it('can re-enable an executor', async () => { @@ -131,37 +129,37 @@ contract('EVM Script', ([_, boss]) => { await evmScriptReg.disableScriptExecutor(installedExecutorId, { from: boss }) let executorEntry = await evmScriptReg.executors(installedExecutorId) assert.isFalse(executorEntry[1], "executor should now be disabled") - assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(installedExecutorId)), ZERO_ADDR, 'getting disabled executor should return zero addr') + assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(installedExecutorId)), ZERO_ADDRESS, 'getting disabled executor should return zero addr') const receipt = await evmScriptReg.enableScriptExecutor(installedExecutorId, { from: boss }) executorEntry = await evmScriptReg.executors(installedExecutorId) assertAmountOfEvents(receipt, 'EnableExecutor') assert.isTrue(executorEntry[1], "executor should now be re-enabled") - assert.notEqual(await evmScriptReg.getScriptExecutor(createExecutorId(installedExecutorId)), ZERO_ADDR, 'getting disabled executor should return non-zero addr') + assert.notEqual(await evmScriptReg.getScriptExecutor(createExecutorId(installedExecutorId)), ZERO_ADDRESS, 'getting disabled executor should return non-zero addr') }) it('fails to disable an executor without the correct permissions', async () => { - await assertRevert(evmScriptReg.disableScriptExecutor(installedExecutorId), reverts.APP_AUTH_FAILED) + await assertRevert(evmScriptReg.disableScriptExecutor(installedExecutorId), ERRORS.APP_AUTH_FAILED) }) it('fails to enable an executor without the correct permissions', async () => { await acl.createPermission(boss, evmScriptReg.address, REGISTRY_MANAGER_ROLE, boss, { from: boss }) await evmScriptReg.disableScriptExecutor(installedExecutorId, { from: boss }) - await assertRevert(evmScriptReg.enableScriptExecutor(installedExecutorId), reverts.APP_AUTH_FAILED) + await assertRevert(evmScriptReg.enableScriptExecutor(installedExecutorId), ERRORS.APP_AUTH_FAILED) }) it('fails to enable an already enabled executor', async () => { await acl.createPermission(boss, evmScriptReg.address, REGISTRY_MANAGER_ROLE, boss, { from: boss }) - await assertRevert(evmScriptReg.enableScriptExecutor(installedExecutorId, { from: boss }), reverts.EVMREG_EXECUTOR_ENABLED) + await assertRevert(evmScriptReg.enableScriptExecutor(installedExecutorId, { from: boss }), ERRORS.EVMREG_EXECUTOR_ENABLED) }) it('fails to disable an already disabled executor', async () => { await acl.createPermission(boss, evmScriptReg.address, REGISTRY_MANAGER_ROLE, boss, { from: boss }) await evmScriptReg.disableScriptExecutor(installedExecutorId, { from: boss }) - await assertRevert(evmScriptReg.disableScriptExecutor(installedExecutorId, { from: boss }), reverts.EVMREG_EXECUTOR_DISABLED) + await assertRevert(evmScriptReg.disableScriptExecutor(installedExecutorId, { from: boss }), ERRORS.EVMREG_EXECUTOR_DISABLED) }) }) @@ -170,21 +168,21 @@ contract('EVM Script', ([_, boss]) => { await acl.createPermission(boss, evmScriptReg.address, REGISTRY_MANAGER_ROLE, boss, { from: boss }) // 0 is reserved - await assertRevert(evmScriptReg.enableScriptExecutor(0, { from: boss }), reverts.EVMREG_INEXISTENT_EXECUTOR) + await assertRevert(evmScriptReg.enableScriptExecutor(0, { from: boss }), ERRORS.EVMREG_INEXISTENT_EXECUTOR) // No executors should be installed yet - assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(1)), ZERO_ADDR, 'No executors should be installed yet') - await assertRevert(evmScriptReg.enableScriptExecutor(1, { from: boss }), reverts.EVMREG_INEXISTENT_EXECUTOR) + assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(1)), ZERO_ADDRESS, 'No executors should be installed yet') + await assertRevert(evmScriptReg.enableScriptExecutor(1, { from: boss }), ERRORS.EVMREG_INEXISTENT_EXECUTOR) }) it('fails to disable a non-existent executor', async () => { await acl.createPermission(boss, evmScriptReg.address, REGISTRY_MANAGER_ROLE, boss, { from: boss }) - assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(1)), ZERO_ADDR, 'No executors should be installed yet') + assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(1)), ZERO_ADDRESS, 'No executors should be installed yet') await assertRevert( evmScriptReg.disableScriptExecutor(1, { from: boss }), // On disable only an enable check is performed as it doubles as an existence check - reverts.EVMREG_EXECUTOR_DISABLED + ERRORS.EVMREG_EXECUTOR_DISABLED ) }) }) @@ -199,7 +197,7 @@ contract('EVM Script', ([_, boss]) => { beforeEach(async () => { const receipt = await dao.newAppInstance(SCRIPT_RUNNER_APP_ID, scriptRunnerAppBase.address, EMPTY_BYTES, false, { from: boss }) - scriptRunnerApp = AppStubScriptRunner.at(getNewProxyAddress(receipt)) + scriptRunnerApp = await AppStubScriptRunner.at(getInstalledApp(receipt)) await scriptRunnerApp.initialize() }) @@ -209,11 +207,11 @@ contract('EVM Script', ([_, boss]) => { }) it('fails to execute if spec ID is 0', async () => { - await assertRevert(scriptRunnerApp.runScript(createExecutorId(0)), reverts.EVMRUN_EXECUTOR_UNAVAILABLE) + await assertRevert(scriptRunnerApp.runScript(createExecutorId(0)), ERRORS.EVMRUN_EXECUTOR_UNAVAILABLE) }) it('fails to execute if spec ID is unknown', async () => { - await assertRevert(scriptRunnerApp.runScript(createExecutorId(4)), reverts.EVMRUN_EXECUTOR_UNAVAILABLE) + await assertRevert(scriptRunnerApp.runScript(createExecutorId(4)), ERRORS.EVMRUN_EXECUTOR_UNAVAILABLE) }) context('> Uninitialized', () => { @@ -224,12 +222,12 @@ contract('EVM Script', ([_, boss]) => { // Install new script runner app const receipt = await dao.newAppInstance(SCRIPT_RUNNER_APP_ID, scriptRunnerAppBase.address, EMPTY_BYTES, false, { from: boss }) - scriptRunnerApp = AppStubScriptRunner.at(getNewProxyAddress(receipt)) + scriptRunnerApp = await AppStubScriptRunner.at(getInstalledApp(receipt)) // Explicitly don't initialize the scriptRunnerApp }) it('fails to execute any executor', async () => { - await assertRevert(scriptRunnerApp.runScript(createExecutorId(1)), reverts.INIT_NOT_INITIALIZED) + await assertRevert(scriptRunnerApp.runScript(createExecutorId(1)), ERRORS.INIT_NOT_INITIALIZED) }) }) @@ -250,7 +248,7 @@ contract('EVM Script', ([_, boss]) => { it("can't execute disabled spec ID", async () => { await evmScriptReg.disableScriptExecutor(executorSpecId, { from: boss }) - await assertRevert(scriptRunnerApp.runScript(encodeCallScript([])), reverts.EVMRUN_EXECUTOR_UNAVAILABLE) + await assertRevert(scriptRunnerApp.runScript(encodeCallScript([])), ERRORS.EVMRUN_EXECUTOR_UNAVAILABLE) }) it('can execute once spec ID is re-enabled', async () => { @@ -281,7 +279,7 @@ contract('EVM Script', ([_, boss]) => { // Check logs // The executor app always uses 0x for the input and the mock script executor should return // an empty bytes array if only the spec ID is given - assertEvent(receipt, 'ScriptResult', { script: inputScript, input: EMPTY_BYTES, returnData: EMPTY_BYTES }) + assertEvent(receipt, 'ScriptResult', { expectedArgs: { script: inputScript, input: null, returnData: null } }) }) for (const inputBytes of [ @@ -297,7 +295,7 @@ contract('EVM Script', ([_, boss]) => { // Check logs // The executor app always uses 0x for the input and the mock script executor should return // the full input script since it's more than just the spec ID - assertEvent(receipt, 'ScriptResult', { script: inputScript, input: EMPTY_BYTES, returnData: inputScript }) + assertEvent(receipt, 'ScriptResult', { expectedArgs: { script: inputScript, input: null, returnData: inputScript } }) }) } @@ -306,7 +304,7 @@ contract('EVM Script', ([_, boss]) => { const receipt = await scriptRunnerApp.runScriptWithNewBytesAllocation(inputScript) // Check logs for returned bytes - assertEvent(receipt, 'ReturnedBytes', { returnedBytes: EMPTY_BYTES }) + assertEvent(receipt, 'ReturnedBytes', { expectedArgs: { returnedBytes: null } }) }) it('properly allocates the free memory pointer after returning bytes from executor', async () => { @@ -316,7 +314,7 @@ contract('EVM Script', ([_, boss]) => { const receipt = await scriptRunnerApp.runScriptWithNewBytesAllocation(inputScript) // Check logs for returned bytes - assertEvent(receipt, 'ReturnedBytes', { returnedBytes: inputScript }) + assertEvent(receipt, 'ReturnedBytes', { expectedArgs: { returnedBytes: inputScript } }) }) }) @@ -335,7 +333,7 @@ contract('EVM Script', ([_, boss]) => { const inputScript = createExecutorId(1) // Should revert with invalid return - await assertRevert(scriptRunnerApp.runScript(inputScript), reverts.EVMRUN_EXECUTOR_INVALID_RETURN) + await assertRevert(scriptRunnerApp.runScript(inputScript), ERRORS.EVMRUN_EXECUTOR_INVALID_RETURN) }) }) @@ -377,15 +375,15 @@ contract('EVM Script', ([_, boss]) => { }) it('fails if directly calling calls script', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScript([action]) - await assertRevert(callsScriptBase.execScript(script, EMPTY_BYTES, []), reverts.INIT_NOT_INITIALIZED) + await assertRevert(callsScriptBase.execScript(script, EMPTY_BYTES, []), ERRORS.INIT_NOT_INITIALIZED) }) it('is the correct executor type', async () => { const CALLS_SCRIPT_TYPE = soliditySha3('CALLS_SCRIPT') - const executor = IEVMScriptExecutor.at(await evmScriptReg.getScriptExecutor(createExecutorId(1))) + const executor = await IEVMScriptExecutor.at(await evmScriptReg.getScriptExecutor(createExecutorId(1))) assert.equal(await executor.executorType(), CALLS_SCRIPT_TYPE) }) @@ -398,7 +396,7 @@ contract('EVM Script', ([_, boss]) => { }) it('executes single action script', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScript([action]) const receipt = await scriptRunnerApp.runScript(script) @@ -408,20 +406,20 @@ contract('EVM Script', ([_, boss]) => { // Check logs // The executor app always uses 0x for the input and the calls script always returns 0x output const expectedExecutor = await evmScriptReg.getScriptExecutor(createExecutorId(1)) - assertEvent(receipt, 'ScriptResult', { executor: expectedExecutor, script, input: EMPTY_BYTES, returnData: EMPTY_BYTES }) + assertEvent(receipt, 'ScriptResult', { expectedArgs: { executor: expectedExecutor, script, input: null, returnData: null } }) }) it("can execute if call doesn't contain blacklist addresses", async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScript([action]) - await scriptRunnerApp.runScriptWithBan(script, ['0x1234']) + await scriptRunnerApp.runScriptWithBan(script, [nonContract]) assert.equal(await executionTarget.counter(), 1, 'should have executed action') }) it('executes multi action script', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScript([action, action, action, action]) await scriptRunnerApp.runScript(script) @@ -432,8 +430,8 @@ contract('EVM Script', ([_, boss]) => { it('executes multi action script to multiple addresses', async () => { const executionTarget2 = await ExecutionTarget.new() - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } - const action2 = { to: executionTarget2.address, calldata: executionTarget2.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } + const action2 = { to: executionTarget2.address, calldata: executionTarget2.contract.methods.execute().encodeABI() } const script = encodeCallScript([action2, action, action2, action, action2]) @@ -444,7 +442,7 @@ contract('EVM Script', ([_, boss]) => { }) it('executes with parameters', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.setCounter.getData(101) } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.setCounter(101).encodeABI() } const script = encodeCallScript([action]) await scriptRunnerApp.runScript(script) @@ -453,8 +451,8 @@ contract('EVM Script', ([_, boss]) => { }) it('execution fails if one call fails', async () => { - const action1 = { to: executionTarget.address, calldata: executionTarget.contract.setCounter.getData(101) } - const action2 = { to: executionTarget.address, calldata: executionTarget.contract.failExecute.getData(true) } + const action1 = { to: executionTarget.address, calldata: executionTarget.contract.methods.setCounter(101).encodeABI() } + const action2 = { to: executionTarget.address, calldata: executionTarget.contract.methods.failExecute(true).encodeABI() } const script = encodeCallScript([action1, action2]) @@ -462,7 +460,7 @@ contract('EVM Script', ([_, boss]) => { }) it('execution fails with correctly forwarded error data', async () => { - const action1 = { to: executionTarget.address, calldata: executionTarget.contract.failExecute.getData(true) } + const action1 = { to: executionTarget.address, calldata: executionTarget.contract.methods.failExecute(true).encodeABI() } const script = encodeCallScript([action1]) @@ -470,11 +468,11 @@ contract('EVM Script', ([_, boss]) => { }) it('execution fails with default error data if no error data is returned', async () => { - const action1 = { to: executionTarget.address, calldata: executionTarget.contract.failExecute.getData(false) } + const action1 = { to: executionTarget.address, calldata: executionTarget.contract.methods.failExecute(false).encodeABI() } const script = encodeCallScript([action1]) - await assertRevert(scriptRunnerApp.runScript(script), reverts.EVMCALLS_CALL_REVERTED) + await assertRevert(scriptRunnerApp.runScript(script), ERRORS.EVMCALLS_CALL_REVERTED) }) it('can execute empty script', async () => { @@ -482,10 +480,10 @@ contract('EVM Script', ([_, boss]) => { }) it('fails to execute if has blacklist addresses being called', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScript([action]) - await assertRevert(scriptRunnerApp.runScriptWithBan(script, [executionTarget.address]), reverts.EVMCALLS_BLACKLISTED_CALL) + await assertRevert(scriptRunnerApp.runScriptWithBan(script, [executionTarget.address]), ERRORS.EVMCALLS_BLACKLISTED_CALL) }) context('> Script underflow', () => { @@ -509,19 +507,19 @@ contract('EVM Script', ([_, boss]) => { } it('fails if data length is too small to contain address', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScriptAddressUnderflow([action]) // EVMScriptRunner doesn't pass through the revert yet - await assertRevert(scriptRunnerApp.runScript(script), reverts.EVMCALLS_INVALID_LENGTH) + await assertRevert(scriptRunnerApp.runScript(script), ERRORS.EVMCALLS_INVALID_LENGTH) }) it('fails if data length is too small to contain calldata', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScriptCalldataUnderflow([action]) // EVMScriptRunner doesn't pass through the revert yet - await assertRevert(scriptRunnerApp.runScript(script), reverts.EVMCALLS_INVALID_LENGTH) + await assertRevert(scriptRunnerApp.runScript(script), ERRORS.EVMCALLS_INVALID_LENGTH) }) }) @@ -539,11 +537,11 @@ contract('EVM Script', ([_, boss]) => { } it('fails if data length is too big', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScriptCalldataOverflow([action]) // EVMScriptRunner doesn't pass through the revert yet - await assertRevert(scriptRunnerApp.runScript(script), reverts.EVMCALLS_INVALID_LENGTH) + await assertRevert(scriptRunnerApp.runScript(script), ERRORS.EVMCALLS_INVALID_LENGTH) }) }) }) diff --git a/test/contracts/factory/dao_factory.js b/test/contracts/factory/dao_factory.js index c2603e3db..581109fa5 100644 --- a/test/contracts/factory/dao_factory.js +++ b/test/contracts/factory/dao_factory.js @@ -1,3 +1,5 @@ +const { ZERO_ADDRESS, getEventArgument } = require('@aragon/contract-helpers-test') + const DAOFactory = artifacts.require('DAOFactory') const ACL = artifacts.require('ACL') @@ -6,10 +8,6 @@ const EVMScriptRegistry = artifacts.require('EVMScriptRegistry') const EVMScriptRegistryFactory = artifacts.require('EVMScriptRegistryFactory') const EVMScriptRegistryConstants = artifacts.require('EVMScriptRegistryConstantsMock') -const ZERO_ADDRES = '0x0000000000000000000000000000000000000000' - -const getEventArgument = (receipt, event, arg) => receipt.logs.filter(l => l.event === event)[0].args[arg] - contract('DAO Factory', ([_, root]) => { let daoFactory, dao, acl, receipt @@ -23,7 +21,7 @@ contract('DAO Factory', ([_, root]) => { aclBase = await ACL.new() scriptsRegistryFactory = await EVMScriptRegistryFactory.new() scriptsRegistryConstants = await EVMScriptRegistryConstants.new() - scriptsRegistryBase = EVMScriptRegistry.at(await scriptsRegistryFactory.baseReg()) + scriptsRegistryBase = await EVMScriptRegistry.at(await scriptsRegistryFactory.baseReg()) }) before('load roles and constants', async () => { @@ -56,7 +54,7 @@ contract('DAO Factory', ([_, root]) => { }) it('does not create or grant app manager to the root address of the DAO', async () => { - assert.equal(await acl.getPermissionManager(dao.address, APP_MANAGER_ROLE), ZERO_ADDRES) + assert.equal(await acl.getPermissionManager(dao.address, APP_MANAGER_ROLE), ZERO_ADDRESS) assert.isFalse(await acl.hasPermission(root, dao.address, APP_MANAGER_ROLE)) assert.isFalse(await acl.hasPermission(daoFactory.address, dao.address, APP_MANAGER_ROLE)) }) @@ -64,16 +62,16 @@ contract('DAO Factory', ([_, root]) => { const itDoesCreateAnEVMScriptsRegistry = () => { it('deploys an EVM script registry with a script executor', async () => { - const scriptsRegistry = EVMScriptRegistry.at(getEventArgument(receipt, 'DeployEVMScriptRegistry', 'reg')) + const scriptsRegistry = await EVMScriptRegistry.at(getEventArgument(receipt, 'DeployEVMScriptRegistry', 'reg')) assert(await scriptsRegistry.hasInitialized(), 'EVM scripts registry should be initialized') assert.equal(await dao.getApp(APP_ADDR_NAMESPACE, EVM_SCRIPT_REGISTRY_APP_ID), scriptsRegistry.address) assert.equal(await dao.getApp(APP_BASES_NAMESPACE, EVM_SCRIPT_REGISTRY_APP_ID), scriptsRegistryBase.address) - const [executor] = await scriptsRegistry.executors(1) + const { executor } = await scriptsRegistry.executors(1) assert.equal(executor, await scriptsRegistryFactory.baseCallScript()) - assert.equal(await acl.getPermissionManager(scriptsRegistry.address, REGISTRY_ADD_EXECUTOR_ROLE), ZERO_ADDRES) + assert.equal(await acl.getPermissionManager(scriptsRegistry.address, REGISTRY_ADD_EXECUTOR_ROLE), ZERO_ADDRESS) assert.isFalse(await acl.hasPermission(root, scriptsRegistry.address, REGISTRY_ADD_EXECUTOR_ROLE)) assert.isFalse(await acl.hasPermission(scriptsRegistryFactory.address, scriptsRegistry.address, REGISTRY_ADD_EXECUTOR_ROLE)) }) @@ -81,8 +79,8 @@ contract('DAO Factory', ([_, root]) => { const itDoesNotCreateAnEVMScriptsRegistry = () => { it('does not deploy an EVM script registry with a script executor', async () => { - assert.equal(await dao.getApp(APP_ADDR_NAMESPACE, EVM_SCRIPT_REGISTRY_APP_ID), ZERO_ADDRES) - assert.equal(await dao.getApp(APP_BASES_NAMESPACE, EVM_SCRIPT_REGISTRY_APP_ID), ZERO_ADDRES) + assert.equal(await dao.getApp(APP_ADDR_NAMESPACE, EVM_SCRIPT_REGISTRY_APP_ID), ZERO_ADDRESS) + assert.equal(await dao.getApp(APP_BASES_NAMESPACE, EVM_SCRIPT_REGISTRY_APP_ID), ZERO_ADDRESS) }) } @@ -94,8 +92,8 @@ contract('DAO Factory', ([_, root]) => { before('create a DAO', async () => { receipt = await daoFactory.newDAO(root) - dao = Kernel.at(getEventArgument(receipt, 'DeployDAO', 'dao')) - acl = ACL.at(await dao.acl()) + dao = await Kernel.at(getEventArgument(receipt, 'DeployDAO', 'dao')) + acl = await ACL.at(await dao.acl()) }) itCreatesADao() @@ -104,13 +102,13 @@ contract('DAO Factory', ([_, root]) => { context('when it was created without an EVM scripts registry factory', () => { before('create factory without an EVM scripts registry factory', async () => { - daoFactory = await DAOFactory.new(kernelBase.address, aclBase.address, ZERO_ADDRES) + daoFactory = await DAOFactory.new(kernelBase.address, aclBase.address, ZERO_ADDRESS) }) before('create a DAO', async () => { receipt = await daoFactory.newDAO(root) - dao = Kernel.at(getEventArgument(receipt, 'DeployDAO', 'dao')) - acl = ACL.at(await dao.acl()) + dao = await Kernel.at(getEventArgument(receipt, 'DeployDAO', 'dao')) + acl = await ACL.at(await dao.acl()) }) itCreatesADao() diff --git a/test/contracts/factory/evm_script_factory.js b/test/contracts/factory/evm_script_factory.js index d75dc612d..8e0602928 100644 --- a/test/contracts/factory/evm_script_factory.js +++ b/test/contracts/factory/evm_script_factory.js @@ -1,6 +1,6 @@ -const { assertEvent } = require('../../helpers/assertEvent')(web3) -const { createExecutorId, encodeCallScript } = require('../../helpers/evmScript') -const { getEventArgument, getNewProxyAddress } = require('../../helpers/events') +const { assertEvent } = require('@aragon/contract-helpers-test/src/asserts') +const { ZERO_ADDRESS, getEventArgument } = require('@aragon/contract-helpers-test') +const { getInstalledApp, encodeCallScript, createExecutorId } = require('@aragon/contract-helpers-test/src/aragon-os') const Kernel = artifacts.require('Kernel') const ACL = artifacts.require('ACL') @@ -13,7 +13,6 @@ const AppStubScriptRunner = artifacts.require('AppStubScriptRunner') const ExecutionTarget = artifacts.require('ExecutionTarget') const EVMScriptRegistryConstantsMock = artifacts.require('EVMScriptRegistryConstantsMock') -const ZERO_ADDR = '0x0000000000000000000000000000000000000000' const EMPTY_BYTES = '0x' contract('EVM Script Factory', ([permissionsRoot]) => { @@ -31,7 +30,7 @@ contract('EVM Script Factory', ([permissionsRoot]) => { regFact = await EVMScriptRegistryFactory.new() daoFact = await DAOFactory.new(kernelBase.address, aclBase.address, regFact.address) callsScriptBase = await regFact.baseCallScript() - evmScriptRegBase = EVMScriptRegistry.at(await regFact.baseReg()) + evmScriptRegBase = await EVMScriptRegistry.at(await regFact.baseReg()) const evmScriptRegConstants = await EVMScriptRegistryConstantsMock.new() APP_BASES_NAMESPACE = await kernelBase.APP_BASES_NAMESPACE() @@ -46,10 +45,10 @@ contract('EVM Script Factory', ([permissionsRoot]) => { beforeEach(async () => { const receipt = await daoFact.newDAO(permissionsRoot) - dao = Kernel.at(getEventArgument(receipt, 'DeployDAO', 'dao')) - evmScriptReg = EVMScriptRegistry.at(getEventArgument(receipt, 'DeployEVMScriptRegistry', 'reg')) + dao = await Kernel.at(getEventArgument(receipt, 'DeployDAO', 'dao')) + evmScriptReg = await EVMScriptRegistry.at(getEventArgument(receipt, 'DeployEVMScriptRegistry', 'reg')) - acl = ACL.at(await dao.acl()) + acl = await ACL.at(await dao.acl()) }) it('factory installed EVMScriptRegistry correctly', async () => { @@ -59,9 +58,9 @@ contract('EVM Script Factory', ([permissionsRoot]) => { }) it('factory registered just 1 script executor', async () => { - assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(0)), ZERO_ADDR, 'spec ID 0 should always be empty') + assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(0)), ZERO_ADDRESS, 'spec ID 0 should always be empty') assert.notEqual(await evmScriptReg.getScriptExecutor(createExecutorId(1)), callsScriptBase.address, 'spec ID 1 should be calls script') - assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(2)), ZERO_ADDR, 'spec ID 2 and higher should be empty') + assert.equal(await evmScriptReg.getScriptExecutor(createExecutorId(2)), ZERO_ADDRESS, 'spec ID 2 and higher should be empty') }) it('factory cleaned up permissions', async () => { @@ -70,8 +69,8 @@ contract('EVM Script Factory', ([permissionsRoot]) => { assert.isFalse(await acl.hasPermission(regFact.address, evmScriptReg.address, REGISTRY_ADD_EXECUTOR_ROLE), 'EVMScriptRegistryFactory should not have REGISTRY_ADD_EXECUTOR_ROLE for created EVMScriptRegistry') assert.isFalse(await acl.hasPermission(regFact.address, evmScriptReg.address, REGISTRY_MANAGER_ROLE), 'EVMScriptRegistryFactory should not have REGISTRY_MANAGER_ROLE for created EVMScriptRegistry') - assert.equal(await acl.getPermissionManager(evmScriptReg.address, REGISTRY_ADD_EXECUTOR_ROLE), ZERO_ADDR, 'created EVMScriptRegistry should not have manager for REGISTRY_ADD_EXECUTOR_ROLE') - assert.equal(await acl.getPermissionManager(evmScriptReg.address, REGISTRY_MANAGER_ROLE), ZERO_ADDR, 'created EVMScriptRegistry should not have manager for REGISTRY_MANAGER_ROLE') + assert.equal(await acl.getPermissionManager(evmScriptReg.address, REGISTRY_ADD_EXECUTOR_ROLE), ZERO_ADDRESS, 'created EVMScriptRegistry should not have manager for REGISTRY_ADD_EXECUTOR_ROLE') + assert.equal(await acl.getPermissionManager(evmScriptReg.address, REGISTRY_MANAGER_ROLE), ZERO_ADDRESS, 'created EVMScriptRegistry should not have manager for REGISTRY_MANAGER_ROLE') }) context('> Executor app', () => { @@ -86,7 +85,7 @@ contract('EVM Script Factory', ([permissionsRoot]) => { await acl.createPermission(permissionsRoot, dao.address, APP_MANAGER_ROLE, permissionsRoot) const receipt = await dao.newAppInstance(SCRIPT_RUNNER_APP_ID, scriptRunnerAppBase.address, EMPTY_BYTES, false) - scriptRunnerApp = AppStubScriptRunner.at(getNewProxyAddress(receipt)) + scriptRunnerApp = await AppStubScriptRunner.at(getInstalledApp(receipt)) await scriptRunnerApp.initialize() executionTarget = await ExecutionTarget.new() }) @@ -105,7 +104,7 @@ contract('EVM Script Factory', ([permissionsRoot]) => { }) it('can execute calls script (spec ID 1)', async () => { - const action = { to: executionTarget.address, calldata: executionTarget.contract.execute.getData() } + const action = { to: executionTarget.address, calldata: executionTarget.contract.methods.execute().encodeABI() } const script = encodeCallScript([action], 1) const receipt = await scriptRunnerApp.runScript(script) @@ -114,7 +113,7 @@ contract('EVM Script Factory', ([permissionsRoot]) => { // The executor always uses 0x for the input and callscripts always have 0x returns const expectedExecutor = await evmScriptReg.getScriptExecutor(createExecutorId(1)) - assertEvent(receipt, 'ScriptResult', { executor: expectedExecutor, script, input: EMPTY_BYTES, returnData: EMPTY_BYTES }) + assertEvent(receipt, 'ScriptResult', { expectedArgs: { executor: expectedExecutor, script, input: null, returnData: null } }) }) }) }) diff --git a/test/contracts/forwarding/forwarding.js b/test/contracts/forwarding/forwarding.js index 2f89722ba..8eedde7a3 100644 --- a/test/contracts/forwarding/forwarding.js +++ b/test/contracts/forwarding/forwarding.js @@ -1,4 +1,5 @@ -const { assertRevert } = require('../../helpers/assertThrow') +const { EMPTY_BYTES } = require('@aragon/contract-helpers-test') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') // Mocks const ForwarderMock = artifacts.require('ForwarderMock') @@ -6,7 +7,6 @@ const ForwarderPayableMock = artifacts.require('ForwarderPayableMock') const ForwarderWithContextMock = artifacts.require('ForwarderWithContextMock') const ForwarderWithContextPayableMock = artifacts.require('ForwarderWithContextPayableMock') -const EMPTY_BYTES = '0x' const ForwarderType = { NOT_IMPLEMENTED: 0, NO_CONTEXT: 1, @@ -35,7 +35,7 @@ contract('Forwarders', () => { it('cannot forward with ETH payment', async () => { // Override the contract ABI to let us attempt sending value into this non-payable forwarder - const payableForwarder = ForwarderPayableMock.at(forwarder.address) + const payableForwarder = await ForwarderPayableMock.at(forwarder.address) await assertRevert(payableForwarder.forward(EMPTY_BYTES, { value: 1 })) }) }) @@ -85,7 +85,7 @@ contract('Forwarders', () => { it('cannot forward with ETH payment', async () => { // Override the contract ABI to let us attempt sending value into this non-payable forwarder - const payableForwarder = ForwarderWithContextPayableMock.at(forwarder.address) + const payableForwarder = await ForwarderWithContextPayableMock.at(forwarder.address) await assertRevert(payableForwarder.forward(EMPTY_BYTES, EMPTY_BYTES, { value: 1 })) }) }) diff --git a/test/contracts/kernel/kernel_acl.js b/test/contracts/kernel/kernel_acl.js index e9f2fa97d..fbbb41acf 100644 --- a/test/contracts/kernel/kernel_acl.js +++ b/test/contracts/kernel/kernel_acl.js @@ -1,9 +1,8 @@ const { hash } = require('eth-ens-namehash') -const { keccak_256 } = require('js-sha3') -const { soliditySha3 } = require('web3-utils') -const { assertRevert } = require('../../helpers/assertThrow') -const { assertAmountOfEvents, assertEvent } = require('../../helpers/assertEvent')(web3) -const { getEventArgument, getNewProxyAddress } = require('../../helpers/events') +const { sha3, soliditySha3 } = require('web3-utils') +const { bn, getEventArgument, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { getInstalledApp, ANY_ENTITY } = require('@aragon/contract-helpers-test/src/aragon-os') +const { assertAmountOfEvents, assertEvent, assertRevert } = require('@aragon/contract-helpers-test/src/asserts') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -13,14 +12,11 @@ const KernelProxy = artifacts.require('KernelProxy') const AppStub = artifacts.require('AppStub') const EMPTY_BYTES = '0x' -const ZERO_ADDR = '0x0000000000000000000000000000000000000000' - const APP_ID = hash('stub.aragonpm.test') -const keccak256 = name => `0x${keccak_256(name)}` contract('Kernel ACL', accounts => { let aclBase, appBase - let APP_MANAGER_ROLE, APP_BASES_NAMESPACE, DEFAULT_ACL_APP_ID, ANY_ENTITY + let APP_MANAGER_ROLE, APP_BASES_NAMESPACE, DEFAULT_ACL_APP_ID const permissionsRoot = accounts[0] const granted = accounts[1] @@ -37,7 +33,6 @@ contract('Kernel ACL', accounts => { APP_BASES_NAMESPACE = await kernel.APP_BASES_NAMESPACE() APP_MANAGER_ROLE = await kernel.APP_MANAGER_ROLE() DEFAULT_ACL_APP_ID = await kernel.DEFAULT_ACL_APP_ID() - ANY_ENTITY = await aclBase.ANY_ENTITY() }) // Test both the Kernel itself and the KernelProxy to make sure their behaviours are the same @@ -56,11 +51,11 @@ contract('Kernel ACL', accounts => { if (kernelType === 'Kernel') { kernel = await Kernel.new(false) // don't petrify so it can be used } else if (kernelType === 'KernelProxy') { - kernel = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + kernel = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) } await kernel.initialize(aclBase.address, permissionsRoot) - acl = ACL.at(await kernel.acl()) + acl = await ACL.at(await kernel.acl()) kernelAddr = kernel.address }) @@ -74,7 +69,7 @@ contract('Kernel ACL', accounts => { // Set up ACL proxy await acl.createPermission(permissionsRoot, kernelAddr, APP_MANAGER_ROLE, permissionsRoot) const receipt = await kernel.newAppInstance(DEFAULT_ACL_APP_ID, aclBase.address, EMPTY_BYTES, false) - const newAcl = ACL.at(getNewProxyAddress(receipt)) + const newAcl = await ACL.at(getInstalledApp(receipt)) await assertRevert(newAcl.initialize(permissionsRoot)) }) @@ -100,7 +95,7 @@ contract('Kernel ACL', accounts => { beforeEach(async () => { const receipt = await acl.createPermission(granted, kernelAddr, APP_MANAGER_ROLE, granted, { from: permissionsRoot }) assertAmountOfEvents(receipt, 'SetPermission') - assertAmountOfEvents(receipt, 'SetPermissionParams', 0) // should not have emitted this + assertAmountOfEvents(receipt, 'SetPermissionParams', { expectedAmount: 0 }) // should not have emitted this assertAmountOfEvents(receipt, 'ChangePermissionManager') }) @@ -122,7 +117,7 @@ contract('Kernel ACL', accounts => { const argId = '0x00' // arg 0 const op = '02' // not equal const value = '000000000000000000000000000000000000000000000000000000000000' // namespace 0 - const param = new web3.BigNumber(`${argId}${op}${value}`) + const param = bn(`${argId}${op}${value}`) const grantChildReceipt = await acl.grantPermissionP(child, kernelAddr, APP_MANAGER_ROLE, [param], { from: granted }) @@ -168,7 +163,7 @@ contract('Kernel ACL', accounts => { it('can grant a public permission', async () => { const receipt = await acl.grantPermission(ANY_ENTITY, kernelAddr, APP_MANAGER_ROLE, { from: granted }) assertAmountOfEvents(receipt, 'SetPermission') - assertAmountOfEvents(receipt, 'SetPermissionParams', 0) // should not have emitted this + assertAmountOfEvents(receipt, 'SetPermissionParams', { expectedAmount: 0 }) // should not have emitted this // Any entity can succesfully perform action for (const granteeIndex of [4, 5, 6]) { @@ -241,7 +236,7 @@ contract('Kernel ACL', accounts => { it('removes manager', async () => { const noManager = await acl.getPermissionManager(kernelAddr, APP_MANAGER_ROLE) - assert.equal(ZERO_ADDR, noManager, 'manager should have been removed') + assert.equal(ZERO_ADDRESS, noManager, 'manager should have been removed') }) it('old manager lost power', async () => { @@ -307,7 +302,7 @@ contract('Kernel ACL', accounts => { }) context('> burning permission manager', () => { - const MOCK_ROLE = keccak256("MOCK_ROLE") + const MOCK_ROLE = sha3("MOCK_ROLE") let BURN_ENTITY before(async () => { @@ -321,7 +316,7 @@ contract('Kernel ACL', accounts => { // burn it const receipt = await acl.burnPermissionManager(kernelAddr, MOCK_ROLE, { from: granted }) assertAmountOfEvents(receipt, 'ChangePermissionManager') - assertEvent(receipt, 'ChangePermissionManager', { app: kernelAddr, role: MOCK_ROLE, manager: BURN_ENTITY }) + assertEvent(receipt, 'ChangePermissionManager', { expectedArgs: { app: kernelAddr, role: MOCK_ROLE, manager: BURN_ENTITY } }) assert.equal(await acl.getPermissionManager(kernelAddr, MOCK_ROLE), BURN_ENTITY) // check that nothing else can be done from now on @@ -336,7 +331,7 @@ contract('Kernel ACL', accounts => { // burn it const receipt = await acl.createBurnedPermission(kernelAddr, MOCK_ROLE, { from: permissionsRoot }) assertAmountOfEvents(receipt, 'ChangePermissionManager') - assertEvent(receipt, 'ChangePermissionManager', { app: kernelAddr, role: MOCK_ROLE, manager: BURN_ENTITY }) + assertEvent(receipt, 'ChangePermissionManager', { expectedArgs: { app: kernelAddr, role: MOCK_ROLE, manager: BURN_ENTITY } }) assert.equal(await acl.getPermissionManager(kernelAddr, MOCK_ROLE), BURN_ENTITY) // check that nothing else can be done from now on diff --git a/test/contracts/kernel/kernel_apps.js b/test/contracts/kernel/kernel_apps.js index 49fea658b..755406514 100644 --- a/test/contracts/kernel/kernel_apps.js +++ b/test/contracts/kernel/kernel_apps.js @@ -1,8 +1,7 @@ const { hash } = require('eth-ens-namehash') -const { onlyIf } = require('../../helpers/onlyIf') -const { assertRevert } = require('../../helpers/assertThrow') -const { getNewProxyAddress } = require('../../helpers/events') -const { assertAmountOfEvents } = require('../../helpers/assertEvent')(web3) +const { getInstalledApp } = require('@aragon/contract-helpers-test/src/aragon-os') +const { onlyIf, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { assertAmountOfEvents, assertRevert } = require('@aragon/contract-helpers-test/src/asserts') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -16,11 +15,10 @@ const AppStub2 = artifacts.require('AppStub2') const ERCProxyMock = artifacts.require('ERCProxyMock') const KernelOverloadMock = artifacts.require('KernelOverloadMock') -const APP_ID = hash('stub.aragonpm.test') const EMPTY_BYTES = '0x' -const ZERO_ADDR = '0x0000000000000000000000000000000000000000' +const APP_ID = hash('stub.aragonpm.test') -contract('Kernel apps', ([permissionsRoot]) => { +contract('Kernel apps', ([permissionsRoot, nonContract]) => { let aclBase, appBase1, appBase2 let APP_BASES_NAMESPACE, APP_ADDR_NAMESPACE, APP_MANAGER_ROLE let UPGRADEABLE, FORWARDING @@ -58,11 +56,11 @@ contract('Kernel apps', ([permissionsRoot]) => { if (kernelType === 'Kernel') { kernel = await Kernel.new(false) // don't petrify so it can be used } else if (kernelType === 'KernelProxy') { - kernel = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + kernel = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) } await kernel.initialize(aclBase.address, permissionsRoot) - acl = ACL.at(await kernel.acl()) + acl = await ACL.at(await kernel.acl()) await acl.createPermission(permissionsRoot, kernel.address, APP_MANAGER_ROLE, permissionsRoot) }) @@ -70,11 +68,11 @@ contract('Kernel apps', ([permissionsRoot]) => { * TESTS * *********/ it('fails if setting app to 0 address', async () => { - await assertRevert(kernel.setApp(APP_BASES_NAMESPACE, APP_ID, ZERO_ADDR)) + await assertRevert(kernel.setApp(APP_BASES_NAMESPACE, APP_ID, ZERO_ADDRESS)) }) it('fails if setting app to non-contract address', async () => { - await assertRevert(kernel.setApp(APP_BASES_NAMESPACE, APP_ID, '0x1234')) + await assertRevert(kernel.setApp(APP_BASES_NAMESPACE, APP_ID, nonContract)) }) const newAppProxyMapping = { @@ -97,7 +95,7 @@ contract('Kernel apps', ([permissionsRoot]) => { onlyAppProxy(() => it('creates a new upgradeable app proxy instance', async () => { const receipt = await kernel.newAppInstance(APP_ID, appBase1.address, EMPTY_BYTES, false) - const appProxy = AppProxyUpgradeable.at(getNewProxyAddress(receipt)) + const appProxy = await AppProxyUpgradeable.at(getInstalledApp(receipt)) assert.equal(await appProxy.kernel(), kernel.address, "new appProxy instance's kernel should be set to the originating kernel") // Checks ERC897 functionality @@ -109,7 +107,7 @@ contract('Kernel apps', ([permissionsRoot]) => { onlyAppProxyPinned(() => it('creates a new non upgradeable app proxy instance', async () => { const receipt = await kernel.newPinnedAppInstance(APP_ID, appBase1.address) - const appProxy = AppProxyPinned.at(getNewProxyAddress(receipt)) + const appProxy = await AppProxyPinned.at(getInstalledApp(receipt)) assert.equal(await appProxy.kernel(), kernel.address, "new appProxy instance's kernel should be set to the originating kernel") // Checks ERC897 functionality @@ -130,7 +128,7 @@ contract('Kernel apps', ([permissionsRoot]) => { }) it('sets the app base when not previously registered', async() => { - assert.equal(ZERO_ADDR, await kernel.getApp(APP_BASES_NAMESPACE, APP_ID)) + assert.equal(ZERO_ADDRESS, await kernel.getApp(APP_BASES_NAMESPACE, APP_ID)) await kernelOverload[newInstanceFn](APP_ID, appBase1.address, EMPTY_BYTES, false) assert.equal(appBase1.address, await kernel.getApp(APP_BASES_NAMESPACE, APP_ID)) @@ -139,36 +137,36 @@ contract('Kernel apps', ([permissionsRoot]) => { it("doesn't set the app base when already set", async() => { await kernel.setApp(APP_BASES_NAMESPACE, APP_ID, appBase1.address) const receipt = await kernelOverload[newInstanceFn](APP_ID, appBase1.address, EMPTY_BYTES, false) - assertAmountOfEvents(receipt, 'SetApp', 0) + assertAmountOfEvents(receipt, 'SetApp', { expectedAmount: 0 }) }) it("also sets the default app", async () => { const receipt = await kernelOverload[newInstanceFn](APP_ID, appBase1.address, EMPTY_BYTES, true) - const appProxyAddr = getNewProxyAddress(receipt) + const appProxyAddr = getInstalledApp(receipt) // Check that both the app base and default app are set assert.equal(await kernel.getApp(APP_BASES_NAMESPACE, APP_ID), appBase1.address, 'App base should be set') - assert.equal(await kernel.getApp(APP_ADDR_NAMESPACE, APP_ID), appProxyAddr, 'Default app should be set') + assert.equal((await kernel.getApp(APP_ADDR_NAMESPACE, APP_ID)).toLowerCase(), appProxyAddr, 'Default app should be set') // Make sure app is not initialized - assert.isFalse(await AppStub.at(appProxyAddr).hasInitialized(), "App shouldn't have been initialized") + assert.isFalse(await (await AppStub.at(appProxyAddr)).hasInitialized(), "App shouldn't have been initialized") }) it("allows initializing proxy", async () => { - const initData = appBase1.initialize.request().params[0].data + const initData = appBase1.contract.methods.initialize().encodeABI() // Make sure app was initialized const receipt = await kernelOverload[newInstanceFn](APP_ID, appBase1.address, initData, false) - const appProxyAddr = getNewProxyAddress(receipt) - assert.isTrue(await AppStub.at(appProxyAddr).hasInitialized(), 'App should have been initialized') + const appProxyAddr = getInstalledApp(receipt, APP_ID) + assert.isTrue(await (await AppStub.at(appProxyAddr)).hasInitialized(), 'App should have been initialized') // Check that the app base has been set, but the app isn't the default app assert.equal(await kernel.getApp(APP_BASES_NAMESPACE, APP_ID), appBase1.address, 'App base should be set') - assert.equal(await kernel.getApp(APP_ADDR_NAMESPACE, APP_ID), ZERO_ADDR, "Default app shouldn't be set") + assert.equal(await kernel.getApp(APP_ADDR_NAMESPACE, APP_ID), ZERO_ADDRESS, "Default app shouldn't be set") }) it("fails if the app base is not given", async() => { - await assertRevert(kernelOverload[newInstanceFn](APP_ID, ZERO_ADDR, EMPTY_BYTES, false)) + await assertRevert(kernelOverload[newInstanceFn](APP_ID, ZERO_ADDRESS, EMPTY_BYTES, false)) }) it('fails if the given app base is different than the existing one', async() => { @@ -193,7 +191,7 @@ contract('Kernel apps', ([permissionsRoot]) => { }) it('sets the app base when not previously registered', async() => { - assert.equal(ZERO_ADDR, await kernel.getApp(APP_BASES_NAMESPACE, APP_ID)) + assert.equal(ZERO_ADDRESS, await kernel.getApp(APP_BASES_NAMESPACE, APP_ID)) await kernelOverload[newInstanceFn](APP_ID, appBase1.address) assert.equal(appBase1.address, await kernel.getApp(APP_BASES_NAMESPACE, APP_ID)) @@ -202,35 +200,35 @@ contract('Kernel apps', ([permissionsRoot]) => { it("doesn't set the app base when already set", async() => { await kernel.setApp(APP_BASES_NAMESPACE, APP_ID, appBase1.address) const receipt = await kernelOverload[newInstanceFn](APP_ID, appBase1.address) - assertAmountOfEvents(receipt, 'SetApp', 0) + assertAmountOfEvents(receipt, 'SetApp', { expectedAmount: 0 }) }) it("does not set the default app", async () => { const receipt = await kernelOverload[newInstanceFn](APP_ID, appBase1.address) - const appProxyAddr = getNewProxyAddress(receipt) + const appProxyAddr = getInstalledApp(receipt) // Check that only the app base is set assert.equal(await kernel.getApp(APP_BASES_NAMESPACE, APP_ID), appBase1.address, 'App base should be set') - assert.equal(await kernel.getApp(APP_ADDR_NAMESPACE, APP_ID), ZERO_ADDR, "Default app shouldn't be set") + assert.equal(await kernel.getApp(APP_ADDR_NAMESPACE, APP_ID), ZERO_ADDRESS, "Default app shouldn't be set") // Make sure app is not initialized - assert.isFalse(await AppStub.at(appProxyAddr).hasInitialized(), "App shouldn't have been initialized") + assert.isFalse(await (await AppStub.at(appProxyAddr)).hasInitialized(), "App shouldn't have been initialized") }) it("does not allow initializing proxy", async () => { const receipt = await kernelOverload[newInstanceFn](APP_ID, appBase1.address) - const appProxyAddr = getNewProxyAddress(receipt) + const appProxyAddr = getInstalledApp(receipt) // Make sure app was not initialized - assert.isFalse(await AppStub.at(appProxyAddr).hasInitialized(), 'App should have been initialized') + assert.isFalse(await (await AppStub.at(appProxyAddr)).hasInitialized(), 'App should have been initialized') // Check that the app base has been set, but the app isn't the default app assert.equal(await kernel.getApp(APP_BASES_NAMESPACE, APP_ID), appBase1.address, 'App base should be set') - assert.equal(await kernel.getApp(APP_ADDR_NAMESPACE, APP_ID), ZERO_ADDR, "Default app shouldn't be set") + assert.equal(await kernel.getApp(APP_ADDR_NAMESPACE, APP_ID), ZERO_ADDRESS, "Default app shouldn't be set") }) it("fails if the app base is not given", async() => { - await assertRevert(kernelOverload[newInstanceFn](APP_ID, ZERO_ADDR)) + await assertRevert(kernelOverload[newInstanceFn](APP_ID, ZERO_ADDRESS)) }) it('fails if the given app base is different than the existing one', async() => { diff --git a/test/contracts/kernel/kernel_funds.js b/test/contracts/kernel/kernel_funds.js index e6e4065fb..7e310d0ed 100644 --- a/test/contracts/kernel/kernel_funds.js +++ b/test/contracts/kernel/kernel_funds.js @@ -1,12 +1,9 @@ -const { assertRevert } = require('../../helpers/assertThrow') -const { onlyIf } = require('../../helpers/onlyIf') -const { getBalance } = require('../../helpers/web3') +const { bn, onlyIf } = require('@aragon/contract-helpers-test') +const { assertBn, assertRevert } = require('@aragon/contract-helpers-test/src/asserts') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') const KernelProxy = artifacts.require('KernelProxy') - -// Mocks const KernelDepositableMock = artifacts.require('KernelDepositableMock') const TX_BASE_GAS = 21000 @@ -40,7 +37,7 @@ contract('Kernel funds', ([permissionsRoot]) => { if (kernelType === 'Base') { kernel = await kernelBaseType.new(false) // don't petrify so it can be used } else if (kernelType === 'Proxy') { - kernel = kernelBaseType.at((await KernelProxy.new(kernelBase.address)).address) + kernel = await kernelBaseType.at((await KernelProxy.new(kernelBase.address)).address) } }) @@ -70,16 +67,16 @@ contract('Kernel funds', ([permissionsRoot]) => { }) it('can receive ETH after being enabled', async () => { - const amount = 1 - const initialBalance = await getBalance(kernel.address) + const amount = bn(1) + const initialBalance = bn(await web3.eth.getBalance(kernel.address)) await kernel.initialize(aclBase.address, permissionsRoot) await kernel.enableDeposits() assert.isTrue(await kernel.hasInitialized(), 'should have been initialized') assert.isTrue(await kernel.isDepositable(), 'should be depositable') - await kernel.sendTransaction({ value: 1, gas: SEND_ETH_GAS }) - assert.equal((await getBalance(kernel.address)).valueOf(), initialBalance.plus(amount)) + await kernel.sendTransaction({ value: amount, gas: SEND_ETH_GAS }) + assertBn(bn(await web3.eth.getBalance(kernel.address)), initialBalance.add(amount)) }) }) }) diff --git a/test/contracts/kernel/kernel_lifecycle.js b/test/contracts/kernel/kernel_lifecycle.js index 832a05295..8e142ff75 100644 --- a/test/contracts/kernel/kernel_lifecycle.js +++ b/test/contracts/kernel/kernel_lifecycle.js @@ -1,17 +1,14 @@ const { hash } = require('eth-ens-namehash') -const { assertRevert } = require('../../helpers/assertThrow') -const { getBlockNumber } = require('../../helpers/web3') -const { assertEvent, assertAmountOfEvents } = require('../../helpers/assertEvent')(web3) +const { assertEvent, assertAmountOfEvents, assertRevert } = require('@aragon/contract-helpers-test/src/asserts') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') const KernelProxy = artifacts.require('KernelProxy') - -// Mocks const AppStub = artifacts.require('AppStub') + +const EMPTY_BYTES = '0x' const APP_ID = hash('stub.aragonpm.test') const VAULT_ID = hash('vault.aragonpm.test') -const EMPTY_BYTES = '0x' contract('Kernel lifecycle', ([root, someone]) => { let aclBase, appBase @@ -34,7 +31,7 @@ contract('Kernel lifecycle', ([root, someone]) => { assert.isFalse(await kernel.hasPermission(someone, kernel.address, APP_MANAGER_ROLE, EMPTY_BYTES)) // Then set the required permission - const acl = ACL.at(await kernel.acl()) + const acl = await ACL.at(await kernel.acl()) await acl.createPermission(root, kernel.address, APP_MANAGER_ROLE, root) assert.isTrue(await kernel.hasPermission(root, kernel.address, APP_MANAGER_ROLE, EMPTY_BYTES)) assert.isFalse(await kernel.hasPermission(someone, kernel.address, APP_MANAGER_ROLE, EMPTY_BYTES)) @@ -115,7 +112,7 @@ contract('Kernel lifecycle', ([root, someone]) => { beforeEach(async () => { const kernelProxy = await KernelProxy.new(kernelBase.address) - kernel = Kernel.at(kernelProxy.address) + kernel = await Kernel.at(kernelProxy.address) }) it('is not initialized by default', async () => { @@ -135,11 +132,11 @@ contract('Kernel lifecycle', ([root, someone]) => { beforeEach(async () => { initReceipt = await kernel.initialize(aclBase.address, root) - acl = ACL.at(await kernel.acl()) + acl = await ACL.at(await kernel.acl()) }) it('set the ACL correctly', async () => { - assertAmountOfEvents(initReceipt, 'SetApp', 2) + assertAmountOfEvents(initReceipt, 'SetApp', { expectedAmount: 2 }) assertEvent(initReceipt, 'SetApp', { namespace: APP_BASES_NAMESPACE, appId: DEFAULT_ACL_APP_ID, app: aclBase.address }, 0) assertEvent(initReceipt, 'SetApp', { namespace: APP_ADDR_NAMESPACE, appId: DEFAULT_ACL_APP_ID, app: acl.address }, 1) }) @@ -153,7 +150,7 @@ contract('Kernel lifecycle', ([root, someone]) => { }) it('has correct initialization block', async () => { - assert.equal(await kernel.getInitializationBlock(), await getBlockNumber(), 'initialization block should be correct') + assert.equal(await kernel.getInitializationBlock(), await web3.eth.getBlockNumber(), 'initialization block should be correct') }) it('throws on reinitialization', async () => { diff --git a/test/contracts/kernel/kernel_upgrade.js b/test/contracts/kernel/kernel_upgrade.js index 04df67a20..dd4469825 100644 --- a/test/contracts/kernel/kernel_upgrade.js +++ b/test/contracts/kernel/kernel_upgrade.js @@ -1,5 +1,5 @@ -const { assertRevert } = require('../../helpers/assertThrow') -const { decodeEventsOfType } = require('../../helpers/decodeEvent') +const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { assertEvent, assertRevert } = require('@aragon/contract-helpers-test/src/asserts') const ACL = artifacts.require('ACL') const Kernel = artifacts.require('Kernel') @@ -9,15 +9,11 @@ const UpgradedKernel = artifacts.require('UpgradedKernel') // Mocks const ERCProxyMock = artifacts.require('ERCProxyMock') -const ZERO_ADDR = '0x0000000000000000000000000000000000000000' - // Only applicable to KernelProxy instances -contract('Kernel upgrade', accounts => { +contract('Kernel upgrade', ([permissionsRoot, someone]) => { let aclBase, kernelBase, upgradedBase, kernelAddr, kernel, acl let APP_MANAGER_ROLE, CORE_NAMESPACE, KERNEL_APP_ID, UPGRADEABLE - const permissionsRoot = accounts[0] - before(async () => { kernelBase = await Kernel.new(true) // petrify immediately upgradedBase = await UpgradedKernel.new(true) // petrify immediately @@ -34,14 +30,14 @@ contract('Kernel upgrade', accounts => { }) beforeEach(async () => { - kernel = Kernel.at((await KernelProxy.new(kernelBase.address)).address) + kernel = await Kernel.at((await KernelProxy.new(kernelBase.address)).address) await kernel.initialize(aclBase.address, permissionsRoot) - acl = ACL.at(await kernel.acl()) + acl = await ACL.at(await kernel.acl()) kernelAddr = kernel.address }) it('checks ERC897 functions', async () => { - const kernelProxy = KernelProxy.at(kernelAddr) + const kernelProxy = await KernelProxy.at(kernelAddr) const implementation = await kernelProxy.implementation() assert.equal(implementation, kernelBase.address, "App address should match") const proxyType = (await kernelProxy.proxyType()).toString() @@ -50,31 +46,25 @@ contract('Kernel upgrade', accounts => { it('emits SetApp event', async () => { const kernelProxy = await KernelProxy.new(kernelBase.address) - const receipt = web3.eth.getTransactionReceipt(kernelProxy.transactionHash) - - const setAppLogs = decodeEventsOfType(receipt, kernelProxy.abi, 'SetApp') - assert.equal(setAppLogs.length, 1) + const { logs } = await web3.eth.getTransactionReceipt(kernelProxy.transactionHash) - const setAppArgs = setAppLogs[0].args - assert.equal(setAppArgs.namespace, CORE_NAMESPACE, 'Kernel namespace should match') - assert.equal(setAppArgs.appId, KERNEL_APP_ID, 'Kernel app id should match') - assert.equal(setAppArgs.app.toLowerCase(), kernelBase.address.toLowerCase(), 'Kernel base address should match') + assertEvent({ rawLogs: logs }, 'SetApp', { decodeForAbi: KernelProxy.abi, expectedArgs: { namespace: CORE_NAMESPACE, appId: KERNEL_APP_ID, app: kernelBase.address } }) }) it('fails to create a KernelProxy if the base is 0', async () => { - await assertRevert(KernelProxy.new(ZERO_ADDR)) + await assertRevert(KernelProxy.new(ZERO_ADDRESS)) }) it('fails to create a KernelProxy if the base is not a contract', async () => { - await assertRevert(KernelProxy.new('0x1234')) + await assertRevert(KernelProxy.new(someone)) }) it('fails to upgrade kernel without permission', async () => { - await assertRevert(kernel.setApp(CORE_NAMESPACE, KERNEL_APP_ID, accounts[0])) + await assertRevert(kernel.setApp(CORE_NAMESPACE, KERNEL_APP_ID, permissionsRoot)) }) it('fails when calling upgraded functionality on old version', async () => { - await assertRevert(UpgradedKernel.at(kernelAddr).isUpgraded()) + await assertRevert((await UpgradedKernel.at(kernelAddr)).isUpgraded()) }) it('successfully upgrades kernel', async () => { @@ -82,12 +72,12 @@ contract('Kernel upgrade', accounts => { await kernel.setApp(CORE_NAMESPACE, KERNEL_APP_ID, upgradedBase.address) - assert.isTrue(await UpgradedKernel.at(kernelAddr).isUpgraded(), 'kernel should have been upgraded') + assert.isTrue(await (await UpgradedKernel.at(kernelAddr)).isUpgraded(), 'kernel should have been upgraded') }) it('fails if upgrading to kernel that is not a contract', async () => { await acl.createPermission(permissionsRoot, kernelAddr, APP_MANAGER_ROLE, permissionsRoot, { from: permissionsRoot }) - await assertRevert(kernel.setApp(CORE_NAMESPACE, KERNEL_APP_ID, '0x1234')) + await assertRevert(kernel.setApp(CORE_NAMESPACE, KERNEL_APP_ID, someone)) }) }) diff --git a/test/contracts/lib/math/lib_safemath64.js b/test/contracts/lib/math/lib_safemath64.js index d6619ff2e..e485a92ee 100644 --- a/test/contracts/lib/math/lib_safemath64.js +++ b/test/contracts/lib/math/lib_safemath64.js @@ -1,4 +1,5 @@ -const { assertRevert } = require('../../../helpers/assertThrow') +const { bn } = require('@aragon/contract-helpers-test') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') contract('SafeMath64 lib test', () => { let safeMath64Mock @@ -15,7 +16,7 @@ contract('SafeMath64 lib test', () => { }) it('fails if multplication overflows', async () => { - const a = new web3.BigNumber(2).pow(63) + const a = bn(2).pow(bn(63)) const b = 2 await assertRevert(safeMath64Mock.mulExt(a, b)) }) @@ -54,8 +55,8 @@ contract('SafeMath64 lib test', () => { }) it('fails if addition overflows', async () => { - const a = new web3.BigNumber(2).pow(63) - const b = new web3.BigNumber(2).pow(63) + const a = bn(2).pow(bn(63)) + const b = bn(2).pow(bn(63)) await assertRevert(safeMath64Mock.addExt(a, b)) }) diff --git a/test/contracts/lib/math/lib_safemath8.js b/test/contracts/lib/math/lib_safemath8.js index e56869516..1d91edc45 100644 --- a/test/contracts/lib/math/lib_safemath8.js +++ b/test/contracts/lib/math/lib_safemath8.js @@ -1,4 +1,4 @@ -const { assertRevert } = require('../../../helpers/assertThrow') +const { assertRevert } = require('@aragon/contract-helpers-test/src/asserts') contract('SafeMath8 lib test', () => { let safeMath8Mock diff --git a/test/helpers/assertEvent.js b/test/helpers/assertEvent.js deleted file mode 100644 index e8cabaf39..000000000 --- a/test/helpers/assertEvent.js +++ /dev/null @@ -1,28 +0,0 @@ -const { getEventAt, getEvents } = require('./events') - -module.exports = web3 => { - const assertEvent = (receipt, eventName, expectedArgs = {}, index = 0) => { - const event = getEventAt(receipt, eventName, index) - assert(typeof event === 'object', `could not find an emitted ${eventName} event ${index === 0 ? '' : `at index ${index}`}`) - - for (const arg of Object.keys(expectedArgs)) { - let foundArg = event.args[arg] - if (foundArg instanceof web3.BigNumber) foundArg = foundArg.toString() - - let expectedArg = expectedArgs[arg] - if (expectedArg instanceof web3.BigNumber) expectedArg = expectedArg.toString() - - assert.equal(foundArg, expectedArg, `${eventName} event ${arg} value does not match`) - } - } - - const assertAmountOfEvents = (receipt, eventName, expectedAmount = 1) => { - const events = getEvents(receipt, eventName) - assert.equal(events.length, expectedAmount, `number of ${eventName} events does not match`) - } - - return { - assertEvent, - assertAmountOfEvents - } -} diff --git a/test/helpers/assertThrow.js b/test/helpers/assertThrow.js deleted file mode 100644 index d13dc842a..000000000 --- a/test/helpers/assertThrow.js +++ /dev/null @@ -1,42 +0,0 @@ -const THROW_ERROR_PREFIX = 'VM Exception while processing transaction:' - -function assertError(error, expectedErrorCode) { - assert(error.message.search(expectedErrorCode) > -1, `Expected error code "${expectedErrorCode}" but failed with "${error}" instead.`) -} - -async function assertThrows(blockOrPromise, expectedErrorCode, expectedReason) { - try { - (typeof blockOrPromise === 'function') ? await blockOrPromise() : await blockOrPromise - } catch (error) { - assertError(error, expectedErrorCode) - return error - } - // assert.fail() for some reason does not have its error string printed 🤷 - assert(0, `Expected "${expectedErrorCode}"${expectedReason ? ` (with reason: "${expectedReason}")` : ''} but it did not fail`) -} - -module.exports = { - async assertJump(blockOrPromise) { - return assertThrows(blockOrPromise, 'invalid JUMP') - }, - - async assertInvalidOpcode(blockOrPromise) { - return assertThrows(blockOrPromise, 'invalid opcode') - }, - - async assertOutOfGas(blockOrPromise) { - return assertThrows(blockOrPromise, 'out of gas') - }, - - async assertRevert(blockOrPromise, reason) { - const error = await assertThrows(blockOrPromise, 'revert', reason) - const errorPrefix = `${THROW_ERROR_PREFIX} revert` - if (error.message.includes(errorPrefix)) { - error.reason = error.message.replace(errorPrefix, '').trim() - } - - if (reason) { - assert.equal(error.reason, reason, `Expected revert reason "${reason}" but failed with "${error.reason || 'no reason'}" instead.`) - } - }, -} diff --git a/test/helpers/decodeEvent.js b/test/helpers/decodeEvent.js deleted file mode 100644 index 8e974a15b..000000000 --- a/test/helpers/decodeEvent.js +++ /dev/null @@ -1,14 +0,0 @@ -const abi = require('web3-eth-abi') - -module.exports = { - decodeEventsOfType: (receipt, contractAbi, eventName) => { - const eventAbi = contractAbi.filter(abi => abi.name === eventName && abi.type === 'event')[0] - const eventSignature = abi.encodeEventSignature(eventAbi) - const eventLogs = receipt.logs.filter(l => l.topics[0] === eventSignature) - return eventLogs.map(log => { - log.event = eventAbi.name - log.args = abi.decodeLog(eventAbi.inputs, log.data, log.topics.slice(1)) - return log - }) - } -} diff --git a/test/helpers/errors.js b/test/helpers/errors.js new file mode 100644 index 000000000..8e4bcbe0a --- /dev/null +++ b/test/helpers/errors.js @@ -0,0 +1,18 @@ +const { makeErrorMappingProxy } = require('@aragon/contract-helpers-test') + +module.exports = makeErrorMappingProxy({ + // aragonOS errors + APP_AUTH_FAILED: 'APP_AUTH_FAILED', + INIT_ALREADY_INITIALIZED: 'INIT_ALREADY_INITIALIZED', + INIT_NOT_INITIALIZED: 'INIT_NOT_INITIALIZED', + RECOVER_DISALLOWED: 'RECOVER_DISALLOWED', + EVMCALLS_CALL_REVERTED: 'EVMCALLS_CALL_REVERTED', + EVMCALLS_INVALID_LENGTH: 'EVMCALLS_INVALID_LENGTH', + EVMREG_EXECUTOR_ENABLED: 'EVMREG_EXECUTOR_ENABLED', + EVMREG_EXECUTOR_DISABLED: 'EVMREG_EXECUTOR_DISABLED', + EVMCALLS_BLACKLISTED_CALL: 'EVMCALLS_BLACKLISTED_CALL', + EVMREG_INEXISTENT_EXECUTOR: 'EVMREG_INEXISTENT_EXECUTOR', + EVMRUN_EXECUTOR_UNAVAILABLE: 'EVMRUN_EXECUTOR_UNAVAILABLE', + EVMREG_SCRIPT_LENGTH_TOO_SHORT: 'EVMREG_SCRIPT_LENGTH_TOO_SHORT', + EVMRUN_EXECUTOR_INVALID_RETURN: 'EVMRUN_EXECUTOR_INVALID_RETURN', +}) diff --git a/test/helpers/events.js b/test/helpers/events.js deleted file mode 100644 index aa13b1a90..000000000 --- a/test/helpers/events.js +++ /dev/null @@ -1,11 +0,0 @@ -const getEvents = ({ logs = [] }, event) => logs.filter(l => l.event === event) -const getEventAt = (receipt, event, index = 0) => getEvents(receipt, event)[index] -const getEventArgument = (receipt, event, arg, index = 0) => getEventAt(receipt, event, index).args[arg] -const getNewProxyAddress = (receipt) => getEventArgument(receipt, 'NewAppProxy', 'proxy') - -module.exports = { - getEvents, - getEventAt, - getEventArgument, - getNewProxyAddress -} diff --git a/test/helpers/evmScript.js b/test/helpers/evmScript.js deleted file mode 100644 index 8b44f110b..000000000 --- a/test/helpers/evmScript.js +++ /dev/null @@ -1,21 +0,0 @@ -const abi = require('ethereumjs-abi') - -const createExecutorId = id => `0x${String(id).padStart(8, '0')}` - -module.exports = { - createExecutorId, - - // Encodes an array of actions ({ to: address, calldata: bytes }) into the EVM call script format - // Sets spec id and concatenates per call - // [ 20 bytes (address) ] + [ 4 bytes (uint32: calldata length) ] + [ calldataLength bytes (payload) ] - // Defaults spec id to 1 - encodeCallScript: (actions, specId = 1) => { - return actions.reduce((script, { to, calldata }) => { - const addr = abi.rawEncode(['address'], [to]).toString('hex') - const length = abi.rawEncode(['uint256'], [(calldata.length - 2) / 2]).toString('hex') - - // Remove 12 first 0s of padding for addr and 28 0s for uint32 - return script + addr.slice(24) + length.slice(56) + calldata.slice(2) - }, createExecutorId(specId)) - }, -} diff --git a/test/helpers/onlyIf.js b/test/helpers/onlyIf.js deleted file mode 100644 index 006f58589..000000000 --- a/test/helpers/onlyIf.js +++ /dev/null @@ -1,12 +0,0 @@ -// Only runs given test block when the condition passes -const onlyIf = condition => { - return testBlock => { - if (condition()) { - return testBlock() - } - } -} - -module.exports = { - onlyIf -} diff --git a/test/helpers/permissionParams.js b/test/helpers/permissionParams.js index 92ca90193..bbf327e47 100644 --- a/test/helpers/permissionParams.js +++ b/test/helpers/permissionParams.js @@ -1,9 +1,11 @@ +const { bn } = require('@aragon/contract-helpers-test') + const permissionParamEqOracle = (oracleAddress) => { // Set role such that the Oracle canPerform() function is used to determine the permission const argId = '0xCB' // arg 203 - Oracle ID const op = '01' // equal const value = oracleAddress.slice(2).padStart(60, 0) // 60 as params are uint240 - return new web3.BigNumber(`${argId}${op}${value}`) + return bn(`${argId}${op}${value}`) } module.exports = { diff --git a/test/helpers/revertStrings.js b/test/helpers/revertStrings.js deleted file mode 100644 index ee2177102..000000000 --- a/test/helpers/revertStrings.js +++ /dev/null @@ -1,61 +0,0 @@ -function makeErrorMappingProxy (target) { - return new Proxy(target, { - get (target, property) { - if (property in target) { - return target[property] - } - - throw new Error(`Could not find error ${property} in error mapping`) - }, - set () { - throw new Error('Unexpected set to error mapping') - } - }) -} - -module.exports = makeErrorMappingProxy({ - // acl/ACL.sol - ACL_AUTH_INIT_KERNEL: 'ACL_AUTH_INIT_KERNEL', - ACL_AUTH_NO_MANAGER: 'ACL_AUTH_NO_MANAGER', - ACL_EXISTENT_MANAGER: 'ACL_EXISTENT_MANAGER', - - // apps/AragonApp.sol - APP_AUTH_FAILED: 'APP_AUTH_FAILED', - - // common/Initializable.sol - INIT_ALREADY_INITIALIZED: 'INIT_ALREADY_INITIALIZED', - INIT_NOT_INITIALIZED: 'INIT_NOT_INITIALIZED', - - // common/SafeERC20.sol - SAFE_ERC_20_BALANCE_REVERTED: 'SAFE_ERC_20_BALANCE_REVERTED', - SAFE_ERC_20_ALLOWANCE_REVERTED: 'SAFE_ERC_20_ALLOWANCE_REVERTED', - - // common/Uint256Helpers.sol - UINT64_NUMBER_TOO_BIG: 'UINT64_NUMBER_TOO_BIG', - - // common/VaultRecoverable.sol - RECOVER_DISALLOWED: 'RECOVER_DISALLOWED', - RECOVER_VAULT_NOT_CONTRACT: 'RECOVER_VAULT_NOT_CONTRACT', - RECOVER_TOKEN_TRANSFER_FAILED: 'RECOVER_TOKEN_TRANSFER_FAILED', - - // evmscript/EVMScriptRegistry.sol - EVMREG_INEXISTENT_EXECUTOR: 'EVMREG_INEXISTENT_EXECUTOR', - EVMREG_EXECUTOR_ENABLED: 'EVMREG_EXECUTOR_ENABLED', - EVMREG_EXECUTOR_DISABLED: 'EVMREG_EXECUTOR_DISABLED', - EVMREG_SCRIPT_LENGTH_TOO_SHORT: 'EVMREG_SCRIPT_LENGTH_TOO_SHORT', - - // evmscript/EVMScriptRunner.sol - EVMRUN_EXECUTOR_UNAVAILABLE: 'EVMRUN_EXECUTOR_UNAVAILABLE', - EVMRUN_PROTECTED_STATE_MODIFIED: 'EVMRUN_PROTECTED_STATE_MODIFIED', - EVMRUN_EXECUTOR_INVALID_RETURN: 'EVMRUN_EXECUTOR_INVALID_RETURN', - - // evmscript/executors/CallsScript.sol - EVMCALLS_BLACKLISTED_CALL: 'EVMCALLS_BLACKLISTED_CALL', - EVMCALLS_INVALID_LENGTH: 'EVMCALLS_INVALID_LENGTH', - EVMCALLS_CALL_REVERTED: 'EVMCALLS_CALL_REVERTED', - - // kernel/Kernel.sol - KERNEL_APP_NOT_CONTRACT: 'KERNEL_APP_NOT_CONTRACT', - KERNEL_INVALID_APP_CHANGE: 'KERNEL_INVALID_APP_CHANGE', - KERNEL_AUTH_FAILED: 'KERNEL_AUTH_FAILED', -}) diff --git a/test/helpers/runSolidityTest.js b/test/helpers/runSolidityTest.js index adbb74197..01e9e4725 100644 --- a/test/helpers/runSolidityTest.js +++ b/test/helpers/runSolidityTest.js @@ -1,4 +1,4 @@ -const { decodeEventsOfType } = require('./decodeEvent') +const { decodeEvents } = require('@aragon/contract-helpers-test') const ASSERT_LIB_EVENTS_ABI = [ { @@ -31,7 +31,7 @@ const processResult = (txReceipt, mustAssert) => { if (!txReceipt || !txReceipt.receipt) { return } - const decodedLogs = decodeEventsOfType(txReceipt.receipt, ASSERT_LIB_EVENTS_ABI, 'TestEvent') + const decodedLogs = decodeEvents(txReceipt.receipt, ASSERT_LIB_EVENTS_ABI, 'TestEvent') decodedLogs.forEach(log => { if (log.event === 'TestEvent' && log.args.result !== true) { throw new Error(log.args.message) diff --git a/test/helpers/web3.js b/test/helpers/web3.js deleted file mode 100644 index 4d0084709..000000000 --- a/test/helpers/web3.js +++ /dev/null @@ -1,84 +0,0 @@ -// TODO: pls abstract promisification over web3 - -module.exports = { - signatures(contract, exclude, web3, names = false, excludeConstant = false) { - const flatten = x => [].concat.apply([], x) - const sig = f => `${f.name}(${f.inputs.map(x=>x.type).join(',')})` - - const excludedSigs = flatten(exclude.map(x => x.abi)).map(sig) - - let signatures = contract.abi - .filter(x => x.type == 'function') - .filter(s => !excludeConstant || !s.constant) - .map(sig) - .filter(s => excludedSigs.indexOf(s) < 0) - - let bs = signatures.map(s => web3.sha3(s).slice(0, 10)).sort() - if (names) - return bs.map((b, i) => ({ name: signatures[i], bytes: b })) - - return bs - }, - - getBalance(addr) { - return new Promise((resolve, reject) => { - web3.eth.getBalance(addr, async (err, res) => { - if (err || !res) return reject(err) - resolve(res) - }) - }) - }, - - getBlockNumber() { - return new Promise((resolve, reject) => { - web3.eth.getBlockNumber(async (err, res) => { - if (err || !res) return reject(err) - resolve(res) - }) - }) - }, - - getBlock(n) { - return new Promise(async (resolve, reject) => { - web3.eth.getBlock(n, (err, res) => { - if (err || !res) return reject(err) - resolve(res) - }) - }) - }, - - sendTransaction(payload) { - return new Promise((resolve, reject) => { - web3.eth.sendTransaction(payload, async (err, res) => { - if (err || !res) return reject(err) - resolve(res) - }) - }) - }, - - getNonce(web3) { - return new Promise((resolve, reject) => { - web3.eth.getAccounts((err, acc) => { - if (err) return reject(err) - web3.eth.getTransactionCount(acc[0], (err, n) => { - if (err) return reject(err) - resolve(n) - }) - }) - }) - }, - - sign(payload, address) { - return new Promise((resolve, reject) => { - web3.eth.sign(address, payload, async (err, signedPayload) => { - if (err || !signedPayload) return reject(err) - const adding0x = x => '0x'.concat(x) - resolve({ - r: adding0x(signedPayload.substr(2, 64)), - s: adding0x(signedPayload.substr(66, 64)), - v: signedPayload.substr(130, 2) == '00' ? 27 : 28, - }) - }) - }) - } -} diff --git a/truffle-config.js b/truffle-config.js index 31f7ad982..c33efc8bc 100644 --- a/truffle-config.js +++ b/truffle-config.js @@ -1 +1,6 @@ -module.exports = require('@aragon/truffle-config-v4') +const TruffleConfig = require('@aragon/truffle-config-v5/truffle-config') + +TruffleConfig.compilers.solc.version = '0.4.24' +TruffleConfig.plugins = ["solidity-coverage"] + +module.exports = TruffleConfig