From 9722fe41a4fa3e94c8747b0435b85fbc3b85c3c8 Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Mon, 15 Oct 2018 22:14:47 +0530 Subject: [PATCH 01/10] tests added --- .../MaximumVolumeTransferManager.sol | 290 ++++++ .../MaximumVolumeTransferManagerFactory.sol | 98 ++ migrations/2_deploy_contracts.js | 15 + scripts/test.sh | 2 +- test/helpers/createInstances.js | 14 + test/z_maximum_volume_transfer_manager.js | 839 ++++++++++++++++++ 6 files changed, 1257 insertions(+), 1 deletion(-) create mode 100644 contracts/modules/TransferManager/MaximumVolumeTransferManager.sol create mode 100644 contracts/modules/TransferManager/MaximumVolumeTransferManagerFactory.sol create mode 100644 test/z_maximum_volume_transfer_manager.js diff --git a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol new file mode 100644 index 000000000..a029f5872 --- /dev/null +++ b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol @@ -0,0 +1,290 @@ +pragma solidity ^0.4.24; + +import "./ITransferManager.sol"; +import "openzeppelin-solidity/contracts/math/SafeMath.sol"; + +/** + * @title Transfer Manager module for capping the amount of token transfers within a period + */ +contract MaximumVolumeTransferManager is ITransferManager { + + using SafeMath for uint256; + + bytes32 public constant ADMIN = "ADMIN"; + + enum RollingIntervals { Daily, Weekly, Quarterly, Biannually, Annually } + + struct MaximumVolumeRestriction{ + uint256 maximumVolumeAllowed; + uint256 startTime; + uint256 endTime; + RollingIntervals rollingPeriodInterval; + } + + MaximumVolumeRestriction[] public maximumVolumeRestrictions; + + // mapping from address to RollingIntervals to periodIds to tokens transfered + mapping(address => mapping(uint256 => mapping(uint256 => uint256))) volumeTally; + + // Emit whenever a new maximum volume restriction gets added + event MaximumVolumeRestrictionAdded( + address indexed from, + uint256 timestamp, + uint256 _maximumVolume, + uint256 _startTime, + uint256 _endTime, + uint256 _rollingPeriodInterval + ); + + // Emit whenever a new maximum volume restriction gets modified + event MaximumVolumeRestrictionModified( + address indexed from, + uint256 timestamp, + uint256 idx, + uint256 _maximumVolume, + uint256 _startTime, + uint256 _endTime, + uint256 _rollingPeriodInterval + ); + + // Emit whenever a new maximum volume restriction gets removed + event MaximumVolumeRestrictionRemoved( + address indexed from, + uint256 timestamp + ); + + /** + * @notice Constructor + * @param _securityToken Address of the security token + * @param _polyAddress Address of the polytoken + */ + constructor (address _securityToken, address _polyAddress) + public + Module(_securityToken, _polyAddress) + { + } + + /** + * @notice This function returns the signature of configure function + */ + function getInitFunction() public pure returns (bytes4) { + return bytes4(0); + } + + /// @notice Used to verify the transfer transaction according to the rule implemented in the trnasfer managers + function verifyTransfer(address _from, address /*_to*/, uint256 _amount, bytes /* _data */, bool _isTransfer) public returns(Result) { + // function must only be called by the associated security token if _isTransfer == true + require(_isTransfer == false || msg.sender == securityToken, "Sender is not owner"); + + if (!paused) { + for(uint256 i = 0; i < maximumVolumeRestrictions.length; i++){ + MaximumVolumeRestriction memory restriction = maximumVolumeRestrictions[i]; + if(now >= restriction.startTime && now <= restriction.endTime){ + uint256 period = _getPeriod(restriction.rollingPeriodInterval); + uint256 periodId = now.div(period); + if(_amount.add(volumeTally[_from][uint256(restriction.rollingPeriodInterval)][periodId]) > restriction.maximumVolumeAllowed){ + return Result.INVALID; + }else{ + volumeTally[_from][uint256(restriction.rollingPeriodInterval)][periodId] = _amount.add(volumeTally[_from][uint256(restriction.rollingPeriodInterval)][periodId]); + } + } + } + return Result.VALID; + } + return Result.NA; + } + + /** + * @notice allows admin to add new maximum volume transfer restrictions + * @param _maximumVolume maximum token volume that can be transfered + * @param _startTime timestamp representing when this maximum volume restriction starts + * @param _endTime timestamp representing when this maximum volume restriction ends + * @param _rollingPeriodInterval interval period representing one of five RollingIntervals + */ + function addMaximumVolumeRestriction( + uint256 _maximumVolume, + uint256 _startTime, + uint256 _endTime, + uint256 _rollingPeriodInterval) + public withPerm(ADMIN) { + _checkRestrictionParams(_startTime, _endTime, _rollingPeriodInterval); + + if(_startTime == 0) { + _startTime = now; + require(_endTime > _startTime, "end time must be greater than start time"); + } + + emit MaximumVolumeRestrictionAdded( + msg.sender, + now, + _maximumVolume, + _startTime, + _endTime, + _rollingPeriodInterval + ); + + maximumVolumeRestrictions.push( + MaximumVolumeRestriction( + _maximumVolume, + _startTime, + _endTime, + RollingIntervals(_rollingPeriodInterval) + ) + ); + } + + /** + * @notice allows admin to add multiple new maximum volume transfer restrictions + * @param _maximumVolumes maximum token volumes that can be transfered + * @param _startTimes timestamps representing when these maximum volume restrictions start + * @param _endTimes timestamps representing when these maximum volume restrictions end + * @param _rollingPeriodIntervals interval periods representing one of five RollingIntervals + */ + function addMultipleMaximumVolumeRestrictions( + uint256[] _maximumVolumes, + uint256[] _startTimes, + uint256[] _endTimes, + uint256[] _rollingPeriodIntervals) + public withPerm(ADMIN) { + require(_maximumVolumes.length >= 1, "No restrictions provided"); + require( + _maximumVolumes.length == _startTimes.length && + _maximumVolumes.length == _endTimes.length && + _maximumVolumes.length == _rollingPeriodIntervals.length, + "Input array length mismatch" + ); + + for(uint256 i = 0; i < _maximumVolumes.length; i++){ + addMaximumVolumeRestriction( + _maximumVolumes[i], + _startTimes[i], + _endTimes[i], + _rollingPeriodIntervals[i] + ); + } + } + + /** + * @notice allows admin to modify a maximum volume transfer restriction + * @param idx representing the array index of the maximum volume transfer restriction + * @param _maximumVolume maximum token volume that can be transfered + * @param _startTime timestamp representing when this maximum volume restriction starts + * @param _endTime timestamp representing when this maximum volume restriction ends + * @param _rollingPeriodInterval interval period representing one of five RollingIntervals + */ + function modifyMaximumTransferRestriction( + uint256 idx, + uint256 _maximumVolume, + uint256 _startTime, + uint256 _endTime, + uint256 _rollingPeriodInterval) + public withPerm(ADMIN) { + require(idx < maximumVolumeRestrictions.length, "invalid index"); + require(now < maximumVolumeRestrictions[idx].endTime, "restriction is no longer active"); + _checkRestrictionParams(_startTime, _endTime, _rollingPeriodInterval); + + if(_startTime == 0) { + _startTime = now; + require(_endTime > _startTime, "end time must be greater than start time"); + } + + MaximumVolumeRestriction memory restriction = MaximumVolumeRestriction( + _maximumVolume, + _startTime, + _endTime, + RollingIntervals(_rollingPeriodInterval) + ); + maximumVolumeRestrictions[idx] = restriction; + + emit MaximumVolumeRestrictionModified( + msg.sender, + now, + idx, + _maximumVolume, + _startTime, + _endTime, + _rollingPeriodInterval + ); + } + + /** + * @notice allows admin to delete a maximum volume transfer restriction + * @param idx representing the array index of the maximum volume transfer restriction + */ + function removeMaximumTransferRestriction(uint256 idx) public withPerm(ADMIN){ + require (maximumVolumeRestrictions.length != 0, "no existing restrictions"); + require (maximumVolumeRestrictions.length > idx, "invalid index"); + + if(idx < (maximumVolumeRestrictions.length - 1)){ + MaximumVolumeRestriction memory lastRestriction = maximumVolumeRestrictions[maximumVolumeRestrictions.length - 1]; + maximumVolumeRestrictions[idx] = lastRestriction; + } + + maximumVolumeRestrictions.length = (maximumVolumeRestrictions.length).sub(1); + + emit MaximumVolumeRestrictionRemoved( + msg.sender, + now + ); + } + + /** + * @notice Return the permissions flag that are associated with MaximumVolumeTransferManager + */ + function getPermissions() public view returns(bytes32[]) { + bytes32[] memory allPermissions = new bytes32[](1); + allPermissions[0] = ADMIN; + return allPermissions; + } + + /** + * @notice returns a count of all the added maximum volume restrictions + */ + function getMaximumVolumeRestrictionsCount() public view returns(uint) { + return maximumVolumeRestrictions.length; + } + + /** + * @notice gets rolling interval period value in seconds + * @param _rollingPeriodInterval one of five RollingIntervals enum value + */ + function _getPeriod(RollingIntervals _rollingPeriodInterval) internal pure returns(uint256){ + uint256 period; + if(_rollingPeriodInterval == RollingIntervals.Daily){ + period = 24 hours; + }else if(_rollingPeriodInterval == RollingIntervals.Weekly){ + period = 168 hours; + }else if(_rollingPeriodInterval == RollingIntervals.Quarterly){ + period = 2920 hours; + }else if(_rollingPeriodInterval == RollingIntervals.Biannually){ + period = 4380 hours; + }else{ + period = 8760 hours; + } + return period; + } + + /** + * @notice internal function for checking restriction parameters + * @param _startTime timestamp representing when this maximum volume restriction starts + * @param _endTime timestamp representing when this maximum volume restriction ends + * @param _rollingPeriodInterval interval period representing one of five RollingIntervals + */ + function _checkRestrictionParams( + uint256 _startTime, + uint256 _endTime, + uint256 _rollingPeriodInterval + ) internal view { + require( + uint256(RollingIntervals.Annually) >= _rollingPeriodInterval, + "invalid rolling period interval - should be < 5" + ); + require(_startTime == 0 || _startTime >= now, 'invalid startTime'); + require(_endTime > 0 && _endTime > _startTime, 'invalid endTime'); + require( + _getPeriod(RollingIntervals(_rollingPeriodInterval)) <= _endTime.sub(_startTime), + "rolling interval must be less than or equal to the difference between endTime and startTime" + ); + } + +} diff --git a/contracts/modules/TransferManager/MaximumVolumeTransferManagerFactory.sol b/contracts/modules/TransferManager/MaximumVolumeTransferManagerFactory.sol new file mode 100644 index 000000000..19c6aaeb6 --- /dev/null +++ b/contracts/modules/TransferManager/MaximumVolumeTransferManagerFactory.sol @@ -0,0 +1,98 @@ +pragma solidity ^0.4.24; + +import "./MaximumVolumeTransferManager.sol"; +import "../ModuleFactory.sol"; + +contract MaximumVolumeTransferManagerFactory is ModuleFactory{ + + /** + * @notice Constructor + * @param _polyAddress Address of the polytoken + * @param _setupCost Setup cost of the module + * @param _usageCost Usage cost of the module + * @param _subscriptionCost Subscription cost of the module + */ + constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public + ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) + { + version = "1.0.0"; + name = "MaximumVolumeTransferManager"; + title = "Maximum Volume Transfer Manager"; + description = "limit the volume of transferable tokens within a rolling time interval"; + compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); + compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); + } + + /** + * @notice used to launch the Module with the help of factory + * @return address Contract address of the Module + */ + function deploy(bytes /* _data */) external returns(address) { + if (setupCost > 0) + require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom because of sufficent Allowance is not provided"); + address maximumVolumeTransferManager = new MaximumVolumeTransferManager(msg.sender, address(polyToken)); + emit GenerateModuleFromFactory(address(maximumVolumeTransferManager), getName(), address(this), msg.sender, setupCost, now); + return address(maximumVolumeTransferManager); + } + + /** + * @notice Type of the Module factory + */ + function getTypes() external view returns(uint8[]) { + uint8[] memory res = new uint8[](1); + res[0] = 2; + return res; + } + + /** + * @notice Get the name of the Module + */ + function getName() public view returns(bytes32) { + return name; + } + + /** + * @notice Get the description of the Module + */ + function getDescription() external view returns(string) { + return description; + } + + /** + * @notice Get the title of the Module + */ + function getTitle() external view returns(string) { + return title; + } + + /** + * @notice Get the version of the Module + */ + function getVersion() external view returns(string) { + return version; + } + + /** + * @notice Get the setup cost of the module + */ + function getSetupCost() external view returns (uint256) { + return setupCost; + } + + /** + * @notice Returns the instructions associated with the module + */ + function getInstructions() external view returns(string) { + return "Allows an issuer to restrict the total volume of tokens that can be transfered within a rolling time interval."; + } + + /** + * @notice Get the tags related to the module factory + */ + function getTags() external view returns(bytes32[]) { + bytes32[] memory availableTags = new bytes32[](2); + availableTags[0] = "MaximumVolume"; + availableTags[1] = "Transfer Restriction"; + return availableTags; + } +} diff --git a/migrations/2_deploy_contracts.js b/migrations/2_deploy_contracts.js index 0994e249e..002ba91b4 100644 --- a/migrations/2_deploy_contracts.js +++ b/migrations/2_deploy_contracts.js @@ -4,6 +4,7 @@ const GeneralPermissionManagerFactory = artifacts.require('./GeneralPermissionMa const PercentageTransferManagerFactory = artifacts.require('./PercentageTransferManagerFactory.sol') const USDTieredSTOProxyFactory = artifacts.require('./USDTieredSTOProxyFactory.sol'); const CountTransferManagerFactory = artifacts.require('./CountTransferManagerFactory.sol') +const MaximumVolumeTransferManagerFactory = artifacts.require('./MaximumVolumeTransferManagerFactory.sol') const EtherDividendCheckpointFactory = artifacts.require('./EtherDividendCheckpointFactory.sol') const ERC20DividendCheckpointFactory = artifacts.require('./ERC20DividendCheckpointFactory.sol') const ModuleRegistry = artifacts.require('./ModuleRegistry.sol'); @@ -161,6 +162,10 @@ module.exports = function (deployer, network, accounts) { // D) Deploy the PercentageTransferManagerFactory Contract (Factory used to generate the PercentageTransferManager contract use // to track the percentage of investment the investors could do for a particular security token) return deployer.deploy(PercentageTransferManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); + }).then(() => { + // D) Deploy the MaximumVolumeTransferManagerFactory Contract (Factory used to generate the MaximumVolumeTransferManager contract use + // to restrict the maximum volume of tokens which can be transfered within a rolling time interval) + return deployer.deploy(MaximumVolumeTransferManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); }).then(() => { // D) Deploy the EtherDividendCheckpointFactory Contract (Factory used to generate the EtherDividendCheckpoint contract use // to provide the functionality of the dividend in terms of ETH) @@ -200,6 +205,10 @@ module.exports = function (deployer, network, accounts) { // D) Register the PercentageTransferManagerFactory in the ModuleRegistry to make the factory available at the protocol level. // So any securityToken can use that factory to generate the PercentageTransferManager contract. return moduleRegistry.registerModule(PercentageTransferManagerFactory.address, {from: PolymathAccount}); + }).then(() => { + // D) Register the MaximumVolumeTransferManagerFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the MaximumVolumeTransferManager contract. + return moduleRegistry.registerModule(MaximumVolumeTransferManagerFactory.address, {from: PolymathAccount}); }).then(() => { // D) Register the CountTransferManagerFactory in the ModuleRegistry to make the factory available at the protocol level. // So any securityToken can use that factory to generate the CountTransferManager contract. @@ -259,6 +268,11 @@ module.exports = function (deployer, network, accounts) { // contract, Factory should comes under the verified list of factories or those factories deployed by the securityToken issuers only. // Here it gets verified because it is deployed by the third party account (Polymath Account) not with the issuer accounts. return moduleRegistry.verifyModule(ManualApprovalTransferManagerFactory.address, true, {from: PolymathAccount}); + }).then(() => { + // G) Once the MaximumVolumeTransferManagerFactory registered with the ModuleRegistry contract then for making them accessble to the securityToken + // contract, Factory should comes under the verified list of factories or those factories deployed by the securityToken issuers only. + // Here it gets verified because it is deployed by the third party account (Polymath Account) not with the issuer accounts. + return moduleRegistry.verifyModule(MaximumVolumeTransferManagerFactory.address, true, {from: PolymathAccount}); }).then(() => { // M) Deploy the CappedSTOFactory (Use to generate the CappedSTO contract which will used to collect the funds ). return deployer.deploy(CappedSTOFactory, PolyToken, cappedSTOSetupCost, 0, 0, {from: PolymathAccount}) @@ -313,6 +327,7 @@ module.exports = function (deployer, network, accounts) { CountTransferManagerFactory: ${CountTransferManagerFactory.address} PercentageTransferManagerFactory: ${PercentageTransferManagerFactory.address} ManualApprovalTransferManagerFactory: ${ManualApprovalTransferManagerFactory.address} + MaximumVolumeTransferManagerFactory: ${MaximumVolumeTransferManagerFactory.address} EtherDividendCheckpointFactory: ${EtherDividendCheckpointFactory.address} ERC20DividendCheckpointFactory: ${ERC20DividendCheckpointFactory.address} --------------------------------------------------------------------------------- diff --git a/scripts/test.sh b/scripts/test.sh index 6dd3ce95a..053bd5f03 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -63,7 +63,7 @@ start_testrpc() { if ! [ -z "${TRAVIS_PULL_REQUEST+x}" ] && [ "$TRAVIS_PULL_REQUEST" != false ]; then node_modules/.bin/testrpc-sc --gasLimit 0xfffffffffff --port "$testrpc_port" "${accounts[@]}" > /dev/null & else - node_modules/.bin/ganache-cli --gasLimit 8000000 "${accounts[@]}" > /dev/null & + node_modules/.bin/ganache-cli --gasLimit 0xfffffffffff "${accounts[@]}" > /dev/null & fi diff --git a/test/helpers/createInstances.js b/test/helpers/createInstances.js index 82a77e42a..bf5e632e9 100644 --- a/test/helpers/createInstances.js +++ b/test/helpers/createInstances.js @@ -11,6 +11,7 @@ const SecurityTokenRegistryMock = artifacts.require("./SecurityTokenRegistryMock const ERC20DividendCheckpointFactory = artifacts.require("./ERC20DividendCheckpointFactory.sol"); const EtherDividendCheckpointFactory = artifacts.require("./EtherDividendCheckpointFactory.sol"); const ManualApprovalTransferManagerFactory = artifacts.require("./ManualApprovalTransferManagerFactory.sol"); +const MaximumVolumeTransferManagerFactory = artifacts.require("./MaximumVolumeTransferManagerFactory.sol"); const SingleTradeVolumeRestrictionManagerFactory = artifacts.require('./SingleTradeVolumeRestrictionTMFactory.sol'); const TrackedRedemptionFactory = artifacts.require("./TrackedRedemptionFactory.sol"); const PercentageTransferManagerFactory = artifacts.require("./PercentageTransferManagerFactory.sol"); @@ -37,6 +38,7 @@ let I_USDTieredSTOFactory; let I_TrackedRedemptionFactory; let I_SingleTradeVolumeRestrictionManagerFactory; let I_ManualApprovalTransferManagerFactory; +let I_MaximumVolumeTransferManagerFactory; let I_VolumeRestrictionTransferManagerFactory; let I_PercentageTransferManagerFactory; let I_EtherDividendCheckpointFactory; @@ -225,6 +227,18 @@ export async function deployManualApprovalTMAndVerifyed(accountPolymath, MRProxy return new Array(I_ManualApprovalTransferManagerFactory); } +export async function deployMaximumVolumeTMAndVerifyed(accountPolymath, MRProxyInstance, polyToken, setupCost) { + I_MaximumVolumeTransferManagerFactory = await MaximumVolumeTransferManagerFactory.new(polyToken, setupCost, 0, 0, { from: accountPolymath }); + assert.notEqual( + I_MaximumVolumeTransferManagerFactory.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "MaximumVolumeTransferManagerFactory contract was not deployed" + ); + + await registerAndVerifyByMR(I_MaximumVolumeTransferManagerFactory.address, accountPolymath, MRProxyInstance); + return new Array(I_MaximumVolumeTransferManagerFactory); +} + export async function deployPercentageTMAndVerified(accountPolymath, MRProxyInstance, polyToken, setupCost) { I_PercentageTransferManagerFactory = await PercentageTransferManagerFactory.new(polyToken, setupCost, 0, 0, { from: accountPolymath }); assert.notEqual( diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js new file mode 100644 index 000000000..06241d0d4 --- /dev/null +++ b/test/z_maximum_volume_transfer_manager.js @@ -0,0 +1,839 @@ +import latestTime from "./helpers/latestTime"; +import { duration, ensureException, promisifyLogWatch, latestBlock } from "./helpers/utils"; +import takeSnapshot, { increaseTime, revertToSnapshot } from "./helpers/time"; +import { encodeProxyCall } from "./helpers/encodeCall"; +import { catchRevert } from "./helpers/exceptions"; +import { setUpPolymathNetwork, deployMaximumVolumeTMAndVerifyed, deployGPMAndVerifyed, deployCountTMAndVerifyed } from "./helpers/createInstances"; + +const SecurityToken = artifacts.require("./SecurityToken.sol"); +const GeneralTransferManager = artifacts.require("./GeneralTransferManager"); +const MaximumVolumeTransferManager = artifacts.require("./MaximumVolumeTransferManager"); +const CountTransferManager = artifacts.require("./CountTransferManager"); +const GeneralPermissionManager = artifacts.require("./GeneralPermissionManager"); + +const Web3 = require("web3"); +const BigNumber = require("bignumber.js"); +const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); // Hardcoded development port + +contract("MaximumVolumeTransferManager", accounts => { + // Accounts Variable declaration + let account_polymath; + let account_issuer; + let token_owner; + let account_investor1; + let account_investor2; + let account_investor3; + let account_investor4; + let account_investor5; + + // investor Details + let fromTime = latestTime(); + let toTime = latestTime(); + let expiryTime = toTime + duration.days(15); + + let message = "Transaction Should Fail!"; + + // Contract Instance Declaration + let I_GeneralPermissionManagerFactory; + let I_GeneralTransferManagerFactory; + let I_SecurityTokenRegistryProxy; + let I_MaximumVolumeTransferManagerFactory; + let P_MaximumVolumeTransferManagerFactory; + let P_MaximumVolumeTransferManager; + let I_CountTransferManagerFactory; + let I_GeneralPermissionManager; + let I_MaximumVolumeTransferManager; + let I_CountTransferManager; + let I_GeneralTransferManager; + let I_ModuleRegistryProxy; + let I_ModuleRegistry; + let I_FeatureRegistry; + let I_SecurityTokenRegistry; + let I_MRProxied; + let I_STRProxied; + let I_STFactory; + let I_SecurityToken; + let I_PolyToken; + let I_PolymathRegistry; + + // SecurityToken Details + const name = "Team"; + const symbol = "sap"; + const tokenDetails = "This is equity type of issuance"; + const decimals = 18; + const contact = "team@polymath.network"; + + // Module key + const delegateManagerKey = 1; + const transferManagerKey = 2; + const stoKey = 3; + + // Initial fee for ticker registry and security token registry + const initRegFee = web3.utils.toWei("250"); + + const STOParameters = ["uint256", "uint256", "uint256", "uint256", "uint8[]", "address"]; + + before(async () => { + // Accounts setup + account_polymath = accounts[0]; + account_issuer = accounts[1]; + + token_owner = account_issuer; + + account_investor1 = accounts[6]; + account_investor2 = accounts[7]; + account_investor3 = accounts[8]; + account_investor4 = accounts[9]; + account_investor5 = accounts[5]; + + // Step 1: Deploy the genral PM ecosystem + let instances = await setUpPolymathNetwork(account_polymath, token_owner); + + [ + I_PolymathRegistry, + I_PolyToken, + I_FeatureRegistry, + I_ModuleRegistry, + I_ModuleRegistryProxy, + I_MRProxied, + I_GeneralTransferManagerFactory, + I_STFactory, + I_SecurityTokenRegistry, + I_SecurityTokenRegistryProxy, + I_STRProxied + ] = instances; + + // STEP 2: Deploy the GeneralDelegateManagerFactory + [I_GeneralPermissionManagerFactory] = await deployGPMAndVerifyed(account_polymath, I_MRProxied, I_PolyToken.address, 0); + // STEP 3: Deploy the MaximumVolumeTransferManagerFactory + [I_MaximumVolumeTransferManagerFactory] = await deployMaximumVolumeTMAndVerifyed(account_polymath, I_MRProxied, I_PolyToken.address, 0); + // STEP 4: Deploy the Paid MaximumVolumeTransferManagerFactory + [P_MaximumVolumeTransferManagerFactory] = await deployMaximumVolumeTMAndVerifyed(account_polymath, I_MRProxied, I_PolyToken.address, web3.utils.toWei("500", "ether")); + // STEP 5: Deploy the CountTransferManagerFactory + [I_CountTransferManagerFactory] = await deployCountTMAndVerifyed(account_polymath, I_MRProxied, I_PolyToken.address, 0); + + // Printing all the contract addresses + console.log(` + --------------------- Polymath Network Smart Contracts: --------------------- + PolymathRegistry: ${I_PolymathRegistry.address} + SecurityTokenRegistryProxy: ${I_SecurityTokenRegistryProxy.address} + SecurityTokenRegistry: ${I_SecurityTokenRegistry.address} + ModuleRegistry: ${I_ModuleRegistry.address} + FeatureRegistry: ${I_FeatureRegistry.address} + + STFactory: ${I_STFactory.address} + GeneralTransferManagerFactory: ${I_GeneralTransferManagerFactory.address} + GeneralPermissionManagerFactory: ${I_GeneralPermissionManagerFactory.address} + + MaximumVolumeTransferManagerFactory: ${I_MaximumVolumeTransferManagerFactory.address} + CountTransferManagerFactory: ${I_CountTransferManagerFactory.address} + ----------------------------------------------------------------------------- + `); + }); + + describe("Generate the SecurityToken", async () => { + it("Should register the ticker before the generation of the security token", async () => { + await I_PolyToken.approve(I_STRProxied.address, initRegFee, { from: token_owner }); + let tx = await I_STRProxied.registerTicker(token_owner, symbol, contact, { from: token_owner }); + assert.equal(tx.logs[0].args._owner, token_owner); + assert.equal(tx.logs[0].args._ticker, symbol.toUpperCase()); + }); + + it("Should generate the new security token with the same symbol as registered above", async () => { + await I_PolyToken.approve(I_STRProxied.address, initRegFee, { from: token_owner }); + let _blockNo = latestBlock(); + let tx = await I_STRProxied.generateSecurityToken(name, symbol, tokenDetails, false, { from: token_owner }); + + // Verify the successful generation of the security token + assert.equal(tx.logs[1].args._ticker, symbol.toUpperCase(), "SecurityToken doesn't get deployed"); + + I_SecurityToken = SecurityToken.at(tx.logs[1].args._securityTokenAddress); + + const log = await promisifyLogWatch(I_SecurityToken.ModuleAdded({ from: _blockNo }), 1); + + // Verify that GeneralTransferManager module get added successfully or not + assert.equal(log.args._types[0].toNumber(), 2); + assert.equal(web3.utils.toUtf8(log.args._name), "GeneralTransferManager"); + }); + + it("Should intialize the auto attached modules", async () => { + let moduleData = (await I_SecurityToken.getModulesByType(2))[0]; + I_GeneralTransferManager = GeneralTransferManager.at(moduleData); + }); + }); + + describe("Buy tokens using whitelist & manual approvals", async () => { + it("Should Buy the tokens", async () => { + // Add the Investor in to the whitelist + + let tx = await I_GeneralTransferManager.modifyWhitelist( + account_investor1, + latestTime(), + latestTime(), + latestTime() + duration.days(10), + true, + { + from: account_issuer, + gas: 6000000 + } + ); + + assert.equal( + tx.logs[0].args._investor.toLowerCase(), + account_investor1.toLowerCase(), + "Failed in adding the investor in whitelist" + ); + + // Jump time + await increaseTime(5000); + + // Mint some tokens + await I_SecurityToken.mint(account_investor1, web3.utils.toWei("4", "ether"), { from: token_owner }); + + assert.equal((await I_SecurityToken.balanceOf(account_investor1)).toNumber(), web3.utils.toWei("4", "ether")); + }); + + it("Should Buy some more tokens", async () => { + // Add the Investor in to the whitelist + + let tx = await I_GeneralTransferManager.modifyWhitelist( + account_investor2, + latestTime(), + latestTime(), + latestTime() + duration.days(10), + true, + { + from: account_issuer, + gas: 6000000 + } + ); + + assert.equal( + tx.logs[0].args._investor.toLowerCase(), + account_investor2.toLowerCase(), + "Failed in adding the investor in whitelist" + ); + + // Mint some tokens + await I_SecurityToken.mint(account_investor2, web3.utils.toWei("1", "ether"), { from: token_owner }); + + assert.equal((await I_SecurityToken.balanceOf(account_investor2)).toNumber(), web3.utils.toWei("1", "ether")); + }); + + it("Should successfully attach the MaximumVolumeTransferManager with the security token", async () => { + await I_PolyToken.getTokens(web3.utils.toWei("500", "ether"), token_owner); + await catchRevert( + I_SecurityToken.addModule(P_MaximumVolumeTransferManagerFactory.address, "0x", web3.utils.toWei("500", "ether"), 0, { + from: token_owner + }) + ); + }); + + it("Should successfully attach the General permission manager factory with the security token", async () => { + let snapId = await takeSnapshot(); + await I_PolyToken.transfer(I_SecurityToken.address, web3.utils.toWei("500", "ether"), { from: token_owner }); + const tx = await I_SecurityToken.addModule( + P_MaximumVolumeTransferManagerFactory.address, + "0x", + web3.utils.toWei("500", "ether"), + 0, + { from: token_owner } + ); + assert.equal(tx.logs[3].args._types[0].toNumber(), transferManagerKey, "Maximum Volume Transfer Manager doesn't get deployed"); + assert.equal( + web3.utils.toAscii(tx.logs[3].args._name).replace(/\u0000/g, ""), + "MaximumVolumeTransferManager", + "MaximumVolumeTransferManagerFactory module was not added" + ); + P_MaximumVolumeTransferManagerFactory = MaximumVolumeTransferManager.at(tx.logs[3].args._module); + await revertToSnapshot(snapId); + }); + + it("Should successfully attach the MaximumVolumeTransferManager with the security token", async () => { + const tx = await I_SecurityToken.addModule(I_MaximumVolumeTransferManagerFactory.address, "", 0, 0, { from: token_owner }); + assert.equal(tx.logs[2].args._types[0].toNumber(), transferManagerKey, "MaximumVolumeTransferManager doesn't get deployed"); + assert.equal( + web3.utils.toUtf8(tx.logs[2].args._name), + "MaximumVolumeTransferManager", + "MaximumVolumeTransferManager module was not added" + ); + I_MaximumVolumeTransferManager = MaximumVolumeTransferManager.at(tx.logs[2].args._module); + }); + //function verifyTransfer(address _from, address _to, uint256 _amount, bool _isTransfer) public returns(Result) { + it("Cannot call verifyTransfer on the TM directly if _isTransfer == true", async () => { + await catchRevert( + I_MaximumVolumeTransferManager.verifyTransfer( + account_investor4, + account_investor4, + web3.utils.toWei("2", "ether"), + "", + true, + { from: token_owner } + ) + ); + }); + + it("Can call verifyTransfer on the TM directly if _isTransfer == false", async () => { + await I_MaximumVolumeTransferManager.verifyTransfer( + account_investor4, + account_investor4, + web3.utils.toWei("2", "ether"), + "", + false, + { from: token_owner } + ); + }); + + it("Add a new token holder", async () => { + let tx = await I_GeneralTransferManager.modifyWhitelist( + account_investor3, + latestTime(), + latestTime(), + latestTime() + duration.days(10), + true, + { + from: account_issuer, + gas: 6000000 + } + ); + + assert.equal( + tx.logs[0].args._investor.toLowerCase(), + account_investor3.toLowerCase(), + "Failed in adding the investor in whitelist" + ); + + // Add the Investor in to the whitelist + // Mint some tokens + await I_SecurityToken.mint(account_investor3, web3.utils.toWei("1", "ether"), { from: token_owner }); + + assert.equal((await I_SecurityToken.balanceOf(account_investor3)).toNumber(), web3.utils.toWei("1", "ether")); + }); + + it("Should pause the tranfers at transferManager level", async() => { + let tx = await I_MaximumVolumeTransferManager.pause({from: token_owner}); + }); + + it("Should still be able to transfer between existing token holders", async () => { + // Add the Investor in to the whitelist + // Mint some tokens + await I_SecurityToken.transfer(account_investor1, web3.utils.toWei("1", "ether"), { from: account_investor2 }); + + assert.equal((await I_SecurityToken.balanceOf(account_investor1)).toNumber(), web3.utils.toWei("5", "ether")); + }); + + it("Should unpause the tranfers at transferManager level", async() => { + await I_MaximumVolumeTransferManager.unpause({from: token_owner}); + }); + + let max_vol = web3.utils.toWei('1', 'ether'); + let startTime = 0; //now + let endTime = latestTime() + duration.years(2); + let rollingInterval = 1; //weekly + + it("should not allow creation of a maximum volume restriction if endTime is set to 0", async() => { + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + max_vol, + startTime, + 0, + rollingInterval, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> invalid end time`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should not allow creation of a maximum volume restriction if rolling interval is not recognized", async() => { + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + max_vol, + startTime, + endTime, + 6, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> invalid rolling interval enum`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should not allow creation of a maximum volume restriction if startTime is equal to endTime", async() => { + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + max_vol, + endTime, + endTime, + rollingInterval, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> invalid startTime and endTime`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should not allow creation of a maximum volume restriction if endTime is less than startTime", async() => { + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + max_vol, + endTime, + startTime, + rollingInterval, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> invalid startTime and endTime`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should not allow creation of a maximum volume restriction if startTime is in the past", async() => { + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + max_vol, + latestTime() - 1000, + endTime, + rollingInterval, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> startTime is in the past`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should not allow creation of a maximum volume restriction if rolling interval is greater than the restriction period", async() => { + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + max_vol, + startTime, + startTime + 10, + rollingInterval, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> rolling interval is bigger than the restriction period`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should create a Maximum Volume Transfer Restriction", async()=>{ + await I_SecurityToken.changeGranularity(Math.pow(10, 5), { from: token_owner }); + const tx = await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + max_vol, + startTime, + endTime, + rollingInterval, + { from: token_owner } + ); + const logs = tx.logs[0]; + const currentStartTime = (await web3.eth.getBlock('latest')).timestamp; + + assert.equal( + 1, + await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(), + "Restriction not added to the array" + ); + assert.equal("MaximumVolumeRestrictionAdded", logs['event'], "Invalid event"); + assert.equal(currentStartTime, logs['args']['_startTime'], "Invalid start time"); + assert.equal(endTime, logs['args']['_endTime'], "Invalid end time"); + assert.equal(rollingInterval , logs['args']['_rollingPeriodInterval'], "Invalid rolling interval"); + }); + + it("Should not be able to transfer between existing token holders over maximum limit", async() => { + let errorThrown = false; + try { + await I_SecurityToken.transfer(account_investor3, web3.utils.toWei('1.1', 'ether'), { from: account_investor1 }); + } catch(error) { + console.log(` tx revert -> Transfer value exceeds maximum limit`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should allow all token transfers upto the limit and then reject further transfers until the next period starts", async () => { + const initialBalance = await I_SecurityToken.balanceOf(account_investor3); + assert.equal(initialBalance.toNumber(), web3.utils.toWei('1', 'ether')); + + await I_SecurityToken.transfer(account_investor3, web3.utils.toWei('0.4', 'ether'), { from: account_investor1 }); + await I_SecurityToken.transfer(account_investor3, web3.utils.toWei('0.2', 'ether'), { from: account_investor1 }); + await I_SecurityToken.transfer(account_investor3, web3.utils.toWei('0.4', 'ether'), { from: account_investor1 }); + + let finalBalance = await I_SecurityToken.balanceOf(account_investor3); + assert.equal(finalBalance.toNumber(), web3.utils.toWei('2', 'ether')); + + let errorThrown = false; + try { + await I_SecurityToken.transfer(account_investor3, web3.utils.toWei('1', 'ether'), { from: account_investor1 }); + } catch(error) { + console.log(` tx revert -> maximum transfer limit exceeded`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + + // increase evm time by one week/604800 seconds + await increaseTime(604800); + + await I_SecurityToken.transfer(account_investor3, web3.utils.toWei('1', 'ether'), { from: account_investor1 }); + + finalBalance = await I_SecurityToken.balanceOf(account_investor3); + assert.equal(finalBalance.toNumber(), web3.utils.toWei('3', 'ether')); + }); + + it("should allow for modification of an existing maximum volume transfer restriction", async()=>{ + const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); + const idx = nRestrictions - 1; + + const newMaxVolume = web3.utils.toWei('0.5', 'ether'); + const newStartTime = 0; + const newEndTime = latestTime() + duration.years(1); + const newRollingInterval = 0; + + const tx = await I_MaximumVolumeTransferManager.modifyMaximumTransferRestriction( + idx, + newMaxVolume, + newStartTime, + newEndTime, + newRollingInterval, + { from: token_owner } + ); + const logs = tx.logs[0]; + const currentStartTime = (await web3.eth.getBlock('latest')).timestamp; + + assert.equal("MaximumVolumeRestrictionModified", logs['event'], "Invalid event"); + assert.equal(currentStartTime, logs['args']['_startTime'], "Invalid start time"); + assert.equal(newEndTime, logs['args']['_endTime'], "Invalid end time"); + assert.equal(newRollingInterval , logs['args']['_rollingPeriodInterval'], "Invalid rolling interval"); + }); + + it("should not allow for modification of an expired restriction", async()=>{ + // increase evm time by 3 years + await increaseTime(94608000); + + let errorThrown = false; + try { + await I_MaximumVolumeTransferManager.modifyMaximumTransferRestriction( + 0, + web3.utils.toWei('5', 'ether'), + 0, + latestTime() + duration.years(1), + 3, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> Transfer restriction has already expired`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should allow for addition of multiple maximum volume restrictions", async()=>{ + const maxVolumes = [100000000, 500000000, 6000000000]; + const startTimes = [0, 0, 0]; + const endTimes = [latestTime() + duration.years(1), latestTime() + duration.years(2), latestTime() + duration.years(3)]; + const rollingIntervals = [0, 2, 4]; + + await I_MaximumVolumeTransferManager.addMultipleMaximumVolumeRestrictions( + maxVolumes, + startTimes, + endTimes, + rollingIntervals, + { from: token_owner } + ); + + assert.equal( + 4, + await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(), + "Failed to add multiple restrictions" + ); + }); + + it("should fail if input array lengths mismatch for mutiple maximum volume transfer restrictions", async()=>{ + const maxVolumes = [100000000, 6000000000]; + const startTimes = [0, 0, 0]; + const endTimes = [latestTime() + duration.years(1)]; + const rollingIntervals = [0, 2, 4]; + + let errorThrown = false; + try { + await I_MaximumVolumeTransferManager.addMultipleMaximumVolumeRestrictions( + maxVolumes, + startTimes, + endTimes, + rollingIntervals, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> Array lengths mis-match`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should allow for deletion of a maximum volume transfer restriction", async () => { + const tx = await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction(1, { from: token_owner }); + const logs = tx.logs[0]; + assert.equal("MaximumVolumeRestrictionRemoved", logs['event'], "Invalid event"); + }); + + // it("Should fail to add a manual approval because invalid _from address", async () => { + // await catchRevert( + // I_ManualApprovalTransferManager.addManualApproval( + // "", + // account_investor4, + // web3.utils.toWei("2", "ether"), + // latestTime() + duration.days(1), + // { from: token_owner } + // ) + // ); + // }); + + // it("Should fail to add a manual approval because invalid _to address", async () => { + // await catchRevert( + // I_ManualApprovalTransferManager.addManualApproval( + // account_investor1, + // "", + // web3.utils.toWei("2", "ether"), + // latestTime() + duration.days(1), + // { from: token_owner } + // ) + // ); + // }); + + // it("Should fail to add a manual approval because invalid expiry time", async () => { + // await catchRevert( + // I_ManualApprovalTransferManager.addManualApproval( + // account_investor1, + // account_investor4, + // web3.utils.toWei("2", "ether"), + // 99999, + // { from: token_owner } + // ) + // ); + // }); + + // it("Add a manual approval for a 4th investor", async () => { + // await I_ManualApprovalTransferManager.addManualApproval( + // account_investor1, + // account_investor4, + // web3.utils.toWei("2", "ether"), + // latestTime() + duration.days(1), + // { from: token_owner } + // ); + // }); + + // it("Should fail to revoke manual approval because invalid _from address", async () => { + // await catchRevert(I_ManualApprovalTransferManager.revokeManualApproval("", account_investor4, { from: token_owner })); + // }); + + // it("Should fail to revoke manual approval because invalid _to address", async () => { + // await catchRevert(I_ManualApprovalTransferManager.revokeManualApproval(account_investor1, "", { from: token_owner })); + // }); + + // it("Should revoke manual approval", async () => { + // let tx = await I_ManualApprovalTransferManager.revokeManualApproval(account_investor1, account_investor4, { + // from: token_owner + // }); + // assert.equal(tx.logs[0].args._from, account_investor1); + // assert.equal(tx.logs[0].args._to, account_investor4); + // assert.equal(tx.logs[0].args._addedBy, token_owner); + // await I_ManualApprovalTransferManager.addManualApproval( + // account_investor1, + // account_investor4, + // web3.utils.toWei("2", "ether"), + // latestTime() + duration.days(1), + // { from: token_owner } + // ); + // }); + + // it("Use 50% of manual approval for transfer", async () => { + // await I_SecurityToken.transfer(account_investor4, web3.utils.toWei("1", "ether"), { from: account_investor1 }); + + // assert.equal((await I_SecurityToken.balanceOf(account_investor4)).toNumber(), web3.utils.toWei("1", "ether")); + // }); + + // it("Check verifyTransfer without actually transferring", async () => { + // let verified = await I_SecurityToken.verifyTransfer.call( + // account_investor1, + // account_investor4, + // web3.utils.toWei("1", "ether"), + // "" + // ); + // console.log(JSON.stringify(verified)); + // assert.equal(verified, true); + + // verified = await I_SecurityToken.verifyTransfer.call(account_investor1, account_investor4, web3.utils.toWei("2", "ether"), ""); + // assert.equal(verified, false); + + // verified = await I_SecurityToken.verifyTransfer.call(account_investor1, account_investor4, web3.utils.toWei("1", "ether"), ""); + // assert.equal(verified, true); + // }); + + // it("Use remaining 50% of manual approval for transfer", async () => { + // await I_SecurityToken.transfer(account_investor4, web3.utils.toWei("1", "ether"), { from: account_investor1 }); + + // assert.equal((await I_SecurityToken.balanceOf(account_investor4)).toNumber(), web3.utils.toWei("2", "ether")); + // }); + + // it("Check further transfers fail", async () => { + // await catchRevert(I_SecurityToken.transfer(account_investor4, web3.utils.toWei("1", "ether"), { from: account_investor1 })); + + // //Check that other transfers are still valid + // await I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 }); + // }); + + // it("Should fail to add a manual block because invalid _from address", async () => { + // await catchRevert( + // I_ManualApprovalTransferManager.addManualBlocking("", account_investor2, latestTime() + duration.days(1), { + // from: token_owner + // }) + // ); + // }); + + // it("Should fail to add a manual block because invalid _to address", async () => { + // await catchRevert( + // I_ManualApprovalTransferManager.addManualBlocking(account_investor1, "", latestTime() + duration.days(1), { + // from: token_owner + // }) + // ); + // }); + + // it("Should fail to add a manual block because invalid expiry time", async () => { + // await catchRevert( + // I_ManualApprovalTransferManager.addManualBlocking(account_investor1, account_investor2, 99999, { from: token_owner }) + // ); + // }); + + // it("Add a manual block for a 2nd investor", async () => { + // await I_ManualApprovalTransferManager.addManualBlocking(account_investor1, account_investor2, latestTime() + duration.days(1), { + // from: token_owner + // }); + // }); + + // it("Check manual block causes failure", async () => { + // await catchRevert(I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 })); + // }); + + // it("Should fail to revoke manual block because invalid _from address", async () => { + // await catchRevert(I_ManualApprovalTransferManager.revokeManualBlocking("0x0", account_investor2, { from: token_owner })); + // }); + + // it("Should fail to revoke manual block because invalid _to address", async () => { + // await catchRevert(I_ManualApprovalTransferManager.revokeManualBlocking(account_investor1, "0x0", { from: token_owner })); + // }); + + // it("Revoke manual block and check transfer works", async () => { + // await I_ManualApprovalTransferManager.revokeManualBlocking(account_investor1, account_investor2, { from: token_owner }); + // await I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 }); + // assert.equal((await I_SecurityToken.balanceOf(account_investor2)).toNumber(), web3.utils.toWei("2", "ether")); + // }); + + // it("Check manual block ignored after expiry", async () => { + // await I_ManualApprovalTransferManager.addManualBlocking(account_investor1, account_investor2, latestTime() + duration.days(1), { + // from: token_owner + // }); + + // await catchRevert(I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 })); + // await increaseTime(1 + 24 * 60 * 60); + // await I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 }); + // }); + + it("Should successfully attach the CountTransferManager with the security token (count of 1)", async () => { + let bytesCountTM = web3.eth.abi.encodeFunctionCall( + { + name: "configure", + type: "function", + inputs: [ + { + type: "uint256", + name: "_maxHolderCount" + } + ] + }, + [1] + ); + + const tx = await I_SecurityToken.addModule(I_CountTransferManagerFactory.address, bytesCountTM, 0, 0, { from: token_owner }); + assert.equal(tx.logs[2].args._types[0].toNumber(), transferManagerKey, "CountTransferManager doesn't get deployed"); + let name = web3.utils.toUtf8(tx.logs[2].args._name); + assert.equal(name, "CountTransferManager", "CountTransferManager module was not added"); + I_CountTransferManager = CountTransferManager.at(tx.logs[2].args._module); + }); + + it("Should get the permission list", async () => { + let perm = await I_MaximumVolumeTransferManager.getPermissions.call(); + assert.equal(perm.length, 1); + }); + + // it("Check manual approval has a higher priority than an INVALID result from another TM", async() => { + // //Should fail initial transfer + // + // try { + // await I_SecurityToken.transfer(account_investor5, web3.utils.toWei('1', 'ether'), { from: account_investor2 }); + // } catch(error) { + // console.log(`Failed due to to count block`); + // ensureException(error); + // errorThrown = true; + // } + // //Add a manual approval - transfer should now work + // await I_ManualApprovalTransferManager.addManualApproval(account_investor2, account_investor5, web3.utils.toWei('1', 'ether'), latestTime() + duration.days(1), { from: token_owner }); + // await I_SecurityToken.transfer(account_investor5, web3.utils.toWei('1', 'ether'), { from: account_investor2 }); + // }); + + it("Should get the init function", async () => { + let byte = await I_MaximumVolumeTransferManager.getInitFunction.call(); + assert.equal(web3.utils.toAscii(byte).replace(/\u0000/g, ""), 0); + }); + }); + + describe("MaximumVolume Transfer Manager Factory test cases", async () => { + it("Should get the exact details of the factory", async () => { + assert.equal(await I_MaximumVolumeTransferManagerFactory.setupCost.call(), 0); + assert.equal((await I_MaximumVolumeTransferManagerFactory.getTypes.call())[0], 2); + let name = web3.utils.toUtf8(await I_MaximumVolumeTransferManagerFactory.getName.call()); + assert.equal(name, "MaximumVolumeTransferManager", "Wrong Module added"); + let desc = await I_MaximumVolumeTransferManagerFactory.getDescription.call(); + assert.equal(desc, "limit the volume of transferable tokens within a rolling time interval", "Wrong Module added"); + let title = await I_MaximumVolumeTransferManagerFactory.getTitle.call(); + assert.equal(title, "Maximum Volume Transfer Manager", "Wrong Module added"); + let inst = await I_MaximumVolumeTransferManagerFactory.getInstructions.call(); + assert.equal( + inst, + "Allows an issuer to restrict the total volume of tokens that can be transfered within a rolling time interval.", + "Wrong Module added" + ); + }); + + it("Should get the tags of the factory", async () => { + let tags = await I_MaximumVolumeTransferManagerFactory.getTags.call(); + assert.equal(web3.utils.toUtf8(tags[0]), "MaximumVolume"); + }); + }); +}); + From 6c3490518640be116040a88dee8a3b23d8ef4d16 Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Mon, 15 Oct 2018 23:47:34 +0530 Subject: [PATCH 02/10] cleanup test --- test/z_maximum_volume_transfer_manager.js | 177 ---------------------- 1 file changed, 177 deletions(-) diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js index 06241d0d4..500753be5 100644 --- a/test/z_maximum_volume_transfer_manager.js +++ b/test/z_maximum_volume_transfer_manager.js @@ -602,168 +602,6 @@ contract("MaximumVolumeTransferManager", accounts => { assert.equal("MaximumVolumeRestrictionRemoved", logs['event'], "Invalid event"); }); - // it("Should fail to add a manual approval because invalid _from address", async () => { - // await catchRevert( - // I_ManualApprovalTransferManager.addManualApproval( - // "", - // account_investor4, - // web3.utils.toWei("2", "ether"), - // latestTime() + duration.days(1), - // { from: token_owner } - // ) - // ); - // }); - - // it("Should fail to add a manual approval because invalid _to address", async () => { - // await catchRevert( - // I_ManualApprovalTransferManager.addManualApproval( - // account_investor1, - // "", - // web3.utils.toWei("2", "ether"), - // latestTime() + duration.days(1), - // { from: token_owner } - // ) - // ); - // }); - - // it("Should fail to add a manual approval because invalid expiry time", async () => { - // await catchRevert( - // I_ManualApprovalTransferManager.addManualApproval( - // account_investor1, - // account_investor4, - // web3.utils.toWei("2", "ether"), - // 99999, - // { from: token_owner } - // ) - // ); - // }); - - // it("Add a manual approval for a 4th investor", async () => { - // await I_ManualApprovalTransferManager.addManualApproval( - // account_investor1, - // account_investor4, - // web3.utils.toWei("2", "ether"), - // latestTime() + duration.days(1), - // { from: token_owner } - // ); - // }); - - // it("Should fail to revoke manual approval because invalid _from address", async () => { - // await catchRevert(I_ManualApprovalTransferManager.revokeManualApproval("", account_investor4, { from: token_owner })); - // }); - - // it("Should fail to revoke manual approval because invalid _to address", async () => { - // await catchRevert(I_ManualApprovalTransferManager.revokeManualApproval(account_investor1, "", { from: token_owner })); - // }); - - // it("Should revoke manual approval", async () => { - // let tx = await I_ManualApprovalTransferManager.revokeManualApproval(account_investor1, account_investor4, { - // from: token_owner - // }); - // assert.equal(tx.logs[0].args._from, account_investor1); - // assert.equal(tx.logs[0].args._to, account_investor4); - // assert.equal(tx.logs[0].args._addedBy, token_owner); - // await I_ManualApprovalTransferManager.addManualApproval( - // account_investor1, - // account_investor4, - // web3.utils.toWei("2", "ether"), - // latestTime() + duration.days(1), - // { from: token_owner } - // ); - // }); - - // it("Use 50% of manual approval for transfer", async () => { - // await I_SecurityToken.transfer(account_investor4, web3.utils.toWei("1", "ether"), { from: account_investor1 }); - - // assert.equal((await I_SecurityToken.balanceOf(account_investor4)).toNumber(), web3.utils.toWei("1", "ether")); - // }); - - // it("Check verifyTransfer without actually transferring", async () => { - // let verified = await I_SecurityToken.verifyTransfer.call( - // account_investor1, - // account_investor4, - // web3.utils.toWei("1", "ether"), - // "" - // ); - // console.log(JSON.stringify(verified)); - // assert.equal(verified, true); - - // verified = await I_SecurityToken.verifyTransfer.call(account_investor1, account_investor4, web3.utils.toWei("2", "ether"), ""); - // assert.equal(verified, false); - - // verified = await I_SecurityToken.verifyTransfer.call(account_investor1, account_investor4, web3.utils.toWei("1", "ether"), ""); - // assert.equal(verified, true); - // }); - - // it("Use remaining 50% of manual approval for transfer", async () => { - // await I_SecurityToken.transfer(account_investor4, web3.utils.toWei("1", "ether"), { from: account_investor1 }); - - // assert.equal((await I_SecurityToken.balanceOf(account_investor4)).toNumber(), web3.utils.toWei("2", "ether")); - // }); - - // it("Check further transfers fail", async () => { - // await catchRevert(I_SecurityToken.transfer(account_investor4, web3.utils.toWei("1", "ether"), { from: account_investor1 })); - - // //Check that other transfers are still valid - // await I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 }); - // }); - - // it("Should fail to add a manual block because invalid _from address", async () => { - // await catchRevert( - // I_ManualApprovalTransferManager.addManualBlocking("", account_investor2, latestTime() + duration.days(1), { - // from: token_owner - // }) - // ); - // }); - - // it("Should fail to add a manual block because invalid _to address", async () => { - // await catchRevert( - // I_ManualApprovalTransferManager.addManualBlocking(account_investor1, "", latestTime() + duration.days(1), { - // from: token_owner - // }) - // ); - // }); - - // it("Should fail to add a manual block because invalid expiry time", async () => { - // await catchRevert( - // I_ManualApprovalTransferManager.addManualBlocking(account_investor1, account_investor2, 99999, { from: token_owner }) - // ); - // }); - - // it("Add a manual block for a 2nd investor", async () => { - // await I_ManualApprovalTransferManager.addManualBlocking(account_investor1, account_investor2, latestTime() + duration.days(1), { - // from: token_owner - // }); - // }); - - // it("Check manual block causes failure", async () => { - // await catchRevert(I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 })); - // }); - - // it("Should fail to revoke manual block because invalid _from address", async () => { - // await catchRevert(I_ManualApprovalTransferManager.revokeManualBlocking("0x0", account_investor2, { from: token_owner })); - // }); - - // it("Should fail to revoke manual block because invalid _to address", async () => { - // await catchRevert(I_ManualApprovalTransferManager.revokeManualBlocking(account_investor1, "0x0", { from: token_owner })); - // }); - - // it("Revoke manual block and check transfer works", async () => { - // await I_ManualApprovalTransferManager.revokeManualBlocking(account_investor1, account_investor2, { from: token_owner }); - // await I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 }); - // assert.equal((await I_SecurityToken.balanceOf(account_investor2)).toNumber(), web3.utils.toWei("2", "ether")); - // }); - - // it("Check manual block ignored after expiry", async () => { - // await I_ManualApprovalTransferManager.addManualBlocking(account_investor1, account_investor2, latestTime() + duration.days(1), { - // from: token_owner - // }); - - // await catchRevert(I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 })); - // await increaseTime(1 + 24 * 60 * 60); - // await I_SecurityToken.transfer(account_investor2, web3.utils.toWei("1", "ether"), { from: account_investor1 }); - // }); - it("Should successfully attach the CountTransferManager with the security token (count of 1)", async () => { let bytesCountTM = web3.eth.abi.encodeFunctionCall( { @@ -791,21 +629,6 @@ contract("MaximumVolumeTransferManager", accounts => { assert.equal(perm.length, 1); }); - // it("Check manual approval has a higher priority than an INVALID result from another TM", async() => { - // //Should fail initial transfer - // - // try { - // await I_SecurityToken.transfer(account_investor5, web3.utils.toWei('1', 'ether'), { from: account_investor2 }); - // } catch(error) { - // console.log(`Failed due to to count block`); - // ensureException(error); - // errorThrown = true; - // } - // //Add a manual approval - transfer should now work - // await I_ManualApprovalTransferManager.addManualApproval(account_investor2, account_investor5, web3.utils.toWei('1', 'ether'), latestTime() + duration.days(1), { from: token_owner }); - // await I_SecurityToken.transfer(account_investor5, web3.utils.toWei('1', 'ether'), { from: account_investor2 }); - // }); - it("Should get the init function", async () => { let byte = await I_MaximumVolumeTransferManager.getInitFunction.call(); assert.equal(web3.utils.toAscii(byte).replace(/\u0000/g, ""), 0); From b391fd6f589fb7989760f277ca982b8f49bf7254 Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Tue, 16 Oct 2018 00:01:19 +0530 Subject: [PATCH 03/10] test file updated --- test/z_maximum_volume_transfer_manager.js | 36 +++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js index 500753be5..270218976 100644 --- a/test/z_maximum_volume_transfer_manager.js +++ b/test/z_maximum_volume_transfer_manager.js @@ -552,6 +552,26 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); + it("should fail to modify any restriction if idx provided is wrong", async() =>{ + let errorThrown = false; + const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); + try { + await I_MaximumVolumeTransferManager.modifyMaximumTransferRestriction( + nRestrictions, + web3.utils.toWei('5', 'ether'), + 0, + latestTime() + duration.years(1), + 1, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> Index out of bounds`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("should allow for addition of multiple maximum volume restrictions", async()=>{ const maxVolumes = [100000000, 500000000, 6000000000]; const startTimes = [0, 0, 0]; @@ -602,6 +622,22 @@ contract("MaximumVolumeTransferManager", accounts => { assert.equal("MaximumVolumeRestrictionRemoved", logs['event'], "Invalid event"); }); + it("should fail to delete any restriction if idx provided is wrong", async() =>{ + let errorThrown = false; + const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); + try { + await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction( + nRestrictions, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> Index out of bounds`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should successfully attach the CountTransferManager with the security token (count of 1)", async () => { let bytesCountTM = web3.eth.abi.encodeFunctionCall( { From ae9303a532a82d6b026e6aa0a93dc2dcbe592165 Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Thu, 18 Oct 2018 00:24:05 +0530 Subject: [PATCH 04/10] modifed event params & fixed errors --- .../ManualApprovalTransferManager.sol | 2 +- .../MaximumVolumeTransferManager.sol | 72 ++++++++++--------- test/z_maximum_volume_transfer_manager.js | 32 ++++----- 3 files changed, 56 insertions(+), 50 deletions(-) diff --git a/contracts/modules/TransferManager/ManualApprovalTransferManager.sol b/contracts/modules/TransferManager/ManualApprovalTransferManager.sol index 1dcc9f4cd..02a3c584c 100644 --- a/contracts/modules/TransferManager/ManualApprovalTransferManager.sol +++ b/contracts/modules/TransferManager/ManualApprovalTransferManager.sol @@ -83,7 +83,7 @@ contract ManualApprovalTransferManager is ITransferManager { * @param _from Address of the sender * @param _to Address of the receiver * @param _amount The amount of tokens to transfer - * @param _isTransfer Whether or not this is an actual transfer or just a test to see if the tokens would be transferrable + * @param _isTransfer Whether or not this is an actual transfer or just a test to see if the tokens would be transferable */ function verifyTransfer(address _from, address _to, uint256 _amount, bytes /* _data */, bool _isTransfer) public returns(Result) { // function must only be called by the associated security token if _isTransfer == true diff --git a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol index a029f5872..1271213c4 100644 --- a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol +++ b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol @@ -27,8 +27,8 @@ contract MaximumVolumeTransferManager is ITransferManager { mapping(address => mapping(uint256 => mapping(uint256 => uint256))) volumeTally; // Emit whenever a new maximum volume restriction gets added - event MaximumVolumeRestrictionAdded( - address indexed from, + event AddNewMaximumVolumeRestriction( + uint256 _index, uint256 timestamp, uint256 _maximumVolume, uint256 _startTime, @@ -37,10 +37,9 @@ contract MaximumVolumeTransferManager is ITransferManager { ); // Emit whenever a new maximum volume restriction gets modified - event MaximumVolumeRestrictionModified( - address indexed from, - uint256 timestamp, - uint256 idx, + event ModifyMaximumVolumeRestriction( + uint256 _index, + uint256 timestamp, uint256 _maximumVolume, uint256 _startTime, uint256 _endTime, @@ -48,8 +47,8 @@ contract MaximumVolumeTransferManager is ITransferManager { ); // Emit whenever a new maximum volume restriction gets removed - event MaximumVolumeRestrictionRemoved( - address indexed from, + event RemoveMaximumVolumeRestricion( + address indexed _from, uint256 timestamp ); @@ -71,17 +70,25 @@ contract MaximumVolumeTransferManager is ITransferManager { return bytes4(0); } - /// @notice Used to verify the transfer transaction according to the rule implemented in the trnasfer managers + /** + * @notice used to verify a transfer transaction and restrict the amount of tokens that can be transfered within a rolling time interval + * @param _from Address of the sender + * @param _amount The amount of tokens to transfer + * @param _isTransfer Whether or not this is an actual transfer or just a test to see if the tokens would be transferable + */ function verifyTransfer(address _from, address /*_to*/, uint256 _amount, bytes /* _data */, bool _isTransfer) public returns(Result) { // function must only be called by the associated security token if _isTransfer == true require(_isTransfer == false || msg.sender == securityToken, "Sender is not owner"); + // loop over every existing max transfer restriction to check if current transaction falls under their activity interval if (!paused) { for(uint256 i = 0; i < maximumVolumeRestrictions.length; i++){ MaximumVolumeRestriction memory restriction = maximumVolumeRestrictions[i]; if(now >= restriction.startTime && now <= restriction.endTime){ uint256 period = _getPeriod(restriction.rollingPeriodInterval); - uint256 periodId = now.div(period); + uint256 periodId = (now.sub(restriction.startTime)).div(period); + + // if the transfer amount causes the total period volume to exceed the maximum value, transfer is invalid if(_amount.add(volumeTally[_from][uint256(restriction.rollingPeriodInterval)][periodId]) > restriction.maximumVolumeAllowed){ return Result.INVALID; }else{ @@ -101,7 +108,7 @@ contract MaximumVolumeTransferManager is ITransferManager { * @param _endTime timestamp representing when this maximum volume restriction ends * @param _rollingPeriodInterval interval period representing one of five RollingIntervals */ - function addMaximumVolumeRestriction( + function addMaxVolumeRestricion( uint256 _maximumVolume, uint256 _startTime, uint256 _endTime, @@ -114,8 +121,8 @@ contract MaximumVolumeTransferManager is ITransferManager { require(_endTime > _startTime, "end time must be greater than start time"); } - emit MaximumVolumeRestrictionAdded( - msg.sender, + emit AddNewMaximumVolumeRestriction( + maximumVolumeRestrictions.length, now, _maximumVolume, _startTime, @@ -140,7 +147,7 @@ contract MaximumVolumeTransferManager is ITransferManager { * @param _endTimes timestamps representing when these maximum volume restrictions end * @param _rollingPeriodIntervals interval periods representing one of five RollingIntervals */ - function addMultipleMaximumVolumeRestrictions( + function addMaxVolumeRestricionsMulti( uint256[] _maximumVolumes, uint256[] _startTimes, uint256[] _endTimes, @@ -155,7 +162,7 @@ contract MaximumVolumeTransferManager is ITransferManager { ); for(uint256 i = 0; i < _maximumVolumes.length; i++){ - addMaximumVolumeRestriction( + addMaxVolumeRestricion( _maximumVolumes[i], _startTimes[i], _endTimes[i], @@ -166,21 +173,21 @@ contract MaximumVolumeTransferManager is ITransferManager { /** * @notice allows admin to modify a maximum volume transfer restriction - * @param idx representing the array index of the maximum volume transfer restriction + * @param _index representing the array index of the maximum volume transfer restriction * @param _maximumVolume maximum token volume that can be transfered * @param _startTime timestamp representing when this maximum volume restriction starts * @param _endTime timestamp representing when this maximum volume restriction ends * @param _rollingPeriodInterval interval period representing one of five RollingIntervals */ function modifyMaximumTransferRestriction( - uint256 idx, + uint256 _index, uint256 _maximumVolume, uint256 _startTime, uint256 _endTime, uint256 _rollingPeriodInterval) public withPerm(ADMIN) { - require(idx < maximumVolumeRestrictions.length, "invalid index"); - require(now < maximumVolumeRestrictions[idx].endTime, "restriction is no longer active"); + require(_index < maximumVolumeRestrictions.length, "invalid index"); + require(now < maximumVolumeRestrictions[_index].endTime, "restriction is no longer active"); _checkRestrictionParams(_startTime, _endTime, _rollingPeriodInterval); if(_startTime == 0) { @@ -194,12 +201,11 @@ contract MaximumVolumeTransferManager is ITransferManager { _endTime, RollingIntervals(_rollingPeriodInterval) ); - maximumVolumeRestrictions[idx] = restriction; + maximumVolumeRestrictions[_index] = restriction; - emit MaximumVolumeRestrictionModified( - msg.sender, + emit ModifyMaximumVolumeRestriction( + _index, now, - idx, _maximumVolume, _startTime, _endTime, @@ -209,20 +215,20 @@ contract MaximumVolumeTransferManager is ITransferManager { /** * @notice allows admin to delete a maximum volume transfer restriction - * @param idx representing the array index of the maximum volume transfer restriction + * @param _index representing the array index of the maximum volume transfer restriction */ - function removeMaximumTransferRestriction(uint256 idx) public withPerm(ADMIN){ + function removeMaximumTransferRestriction(uint256 _index) public withPerm(ADMIN){ require (maximumVolumeRestrictions.length != 0, "no existing restrictions"); - require (maximumVolumeRestrictions.length > idx, "invalid index"); + require (maximumVolumeRestrictions.length > _index, "invalid index"); - if(idx < (maximumVolumeRestrictions.length - 1)){ + if(_index < (maximumVolumeRestrictions.length - 1)){ MaximumVolumeRestriction memory lastRestriction = maximumVolumeRestrictions[maximumVolumeRestrictions.length - 1]; - maximumVolumeRestrictions[idx] = lastRestriction; + maximumVolumeRestrictions[_index] = lastRestriction; } maximumVolumeRestrictions.length = (maximumVolumeRestrictions.length).sub(1); - emit MaximumVolumeRestrictionRemoved( + emit RemoveMaximumVolumeRestricion( msg.sender, now ); @@ -253,13 +259,13 @@ contract MaximumVolumeTransferManager is ITransferManager { if(_rollingPeriodInterval == RollingIntervals.Daily){ period = 24 hours; }else if(_rollingPeriodInterval == RollingIntervals.Weekly){ - period = 168 hours; + period = 7 * 24 hours; }else if(_rollingPeriodInterval == RollingIntervals.Quarterly){ - period = 2920 hours; + period = 3 * 30 * 24 hours; }else if(_rollingPeriodInterval == RollingIntervals.Biannually){ - period = 4380 hours; + period = 6 * 30 * 24 hours; }else{ - period = 8760 hours; + period = 365 * 24 hours; } return period; } diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js index 270218976..88cea49d3 100644 --- a/test/z_maximum_volume_transfer_manager.js +++ b/test/z_maximum_volume_transfer_manager.js @@ -334,7 +334,7 @@ contract("MaximumVolumeTransferManager", accounts => { it("should not allow creation of a maximum volume restriction if endTime is set to 0", async() => { let errorThrown = false; try{ - await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, startTime, 0, @@ -352,7 +352,7 @@ contract("MaximumVolumeTransferManager", accounts => { it("should not allow creation of a maximum volume restriction if rolling interval is not recognized", async() => { let errorThrown = false; try{ - await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, startTime, endTime, @@ -370,7 +370,7 @@ contract("MaximumVolumeTransferManager", accounts => { it("should not allow creation of a maximum volume restriction if startTime is equal to endTime", async() => { let errorThrown = false; try{ - await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, endTime, endTime, @@ -388,7 +388,7 @@ contract("MaximumVolumeTransferManager", accounts => { it("should not allow creation of a maximum volume restriction if endTime is less than startTime", async() => { let errorThrown = false; try{ - await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, endTime, startTime, @@ -406,7 +406,7 @@ contract("MaximumVolumeTransferManager", accounts => { it("should not allow creation of a maximum volume restriction if startTime is in the past", async() => { let errorThrown = false; try{ - await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, latestTime() - 1000, endTime, @@ -424,7 +424,7 @@ contract("MaximumVolumeTransferManager", accounts => { it("should not allow creation of a maximum volume restriction if rolling interval is greater than the restriction period", async() => { let errorThrown = false; try{ - await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, startTime, startTime + 10, @@ -441,7 +441,7 @@ contract("MaximumVolumeTransferManager", accounts => { it("should create a Maximum Volume Transfer Restriction", async()=>{ await I_SecurityToken.changeGranularity(Math.pow(10, 5), { from: token_owner }); - const tx = await I_MaximumVolumeTransferManager.addMaximumVolumeRestriction( + const tx = await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, startTime, endTime, @@ -456,7 +456,7 @@ contract("MaximumVolumeTransferManager", accounts => { await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(), "Restriction not added to the array" ); - assert.equal("MaximumVolumeRestrictionAdded", logs['event'], "Invalid event"); + assert.equal("AddNewMaximumVolumeRestriction", logs['event'], "Invalid event"); assert.equal(currentStartTime, logs['args']['_startTime'], "Invalid start time"); assert.equal(endTime, logs['args']['_endTime'], "Invalid end time"); assert.equal(rollingInterval , logs['args']['_rollingPeriodInterval'], "Invalid rolling interval"); @@ -506,7 +506,7 @@ contract("MaximumVolumeTransferManager", accounts => { it("should allow for modification of an existing maximum volume transfer restriction", async()=>{ const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); - const idx = nRestrictions - 1; + const index = nRestrictions - 1; const newMaxVolume = web3.utils.toWei('0.5', 'ether'); const newStartTime = 0; @@ -514,7 +514,7 @@ contract("MaximumVolumeTransferManager", accounts => { const newRollingInterval = 0; const tx = await I_MaximumVolumeTransferManager.modifyMaximumTransferRestriction( - idx, + index, newMaxVolume, newStartTime, newEndTime, @@ -524,7 +524,7 @@ contract("MaximumVolumeTransferManager", accounts => { const logs = tx.logs[0]; const currentStartTime = (await web3.eth.getBlock('latest')).timestamp; - assert.equal("MaximumVolumeRestrictionModified", logs['event'], "Invalid event"); + assert.equal("ModifyMaximumVolumeRestriction", logs['event'], "Invalid event"); assert.equal(currentStartTime, logs['args']['_startTime'], "Invalid start time"); assert.equal(newEndTime, logs['args']['_endTime'], "Invalid end time"); assert.equal(newRollingInterval , logs['args']['_rollingPeriodInterval'], "Invalid rolling interval"); @@ -552,7 +552,7 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); - it("should fail to modify any restriction if idx provided is wrong", async() =>{ + it("should fail to modify any restriction if index provided is wrong", async() =>{ let errorThrown = false; const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); try { @@ -578,7 +578,7 @@ contract("MaximumVolumeTransferManager", accounts => { const endTimes = [latestTime() + duration.years(1), latestTime() + duration.years(2), latestTime() + duration.years(3)]; const rollingIntervals = [0, 2, 4]; - await I_MaximumVolumeTransferManager.addMultipleMaximumVolumeRestrictions( + await I_MaximumVolumeTransferManager.addMaxVolumeRestricionsMulti( maxVolumes, startTimes, endTimes, @@ -601,7 +601,7 @@ contract("MaximumVolumeTransferManager", accounts => { let errorThrown = false; try { - await I_MaximumVolumeTransferManager.addMultipleMaximumVolumeRestrictions( + await I_MaximumVolumeTransferManager.addMaxVolumeRestricionsMulti( maxVolumes, startTimes, endTimes, @@ -619,10 +619,10 @@ contract("MaximumVolumeTransferManager", accounts => { it("should allow for deletion of a maximum volume transfer restriction", async () => { const tx = await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction(1, { from: token_owner }); const logs = tx.logs[0]; - assert.equal("MaximumVolumeRestrictionRemoved", logs['event'], "Invalid event"); + assert.equal("RemoveMaximumVolumeRestricion", logs['event'], "Invalid event"); }); - it("should fail to delete any restriction if idx provided is wrong", async() =>{ + it("should fail to delete any restriction if index provided is wrong", async() =>{ let errorThrown = false; const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); try { From 0f54e625de22cb6fc7235dfb504c42cf874e2d7f Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Fri, 19 Oct 2018 23:20:07 +0530 Subject: [PATCH 05/10] updated TM --- .../MaximumVolumeTransferManager.sol | 72 +++++++++++-------- scripts/test.sh | 2 +- test/z_maximum_volume_transfer_manager.js | 61 +++++++++++----- 3 files changed, 85 insertions(+), 50 deletions(-) diff --git a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol index 1271213c4..dd67a20a9 100644 --- a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol +++ b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol @@ -7,7 +7,6 @@ import "openzeppelin-solidity/contracts/math/SafeMath.sol"; * @title Transfer Manager module for capping the amount of token transfers within a period */ contract MaximumVolumeTransferManager is ITransferManager { - using SafeMath for uint256; bytes32 public constant ADMIN = "ADMIN"; @@ -114,30 +113,12 @@ contract MaximumVolumeTransferManager is ITransferManager { uint256 _endTime, uint256 _rollingPeriodInterval) public withPerm(ADMIN) { - _checkRestrictionParams(_startTime, _endTime, _rollingPeriodInterval); - if(_startTime == 0) { _startTime = now; - require(_endTime > _startTime, "end time must be greater than start time"); } + _checkRestrictionParams(_startTime, _endTime, _rollingPeriodInterval); - emit AddNewMaximumVolumeRestriction( - maximumVolumeRestrictions.length, - now, - _maximumVolume, - _startTime, - _endTime, - _rollingPeriodInterval - ); - - maximumVolumeRestrictions.push( - MaximumVolumeRestriction( - _maximumVolume, - _startTime, - _endTime, - RollingIntervals(_rollingPeriodInterval) - ) - ); + _addMaxVolumeRestricion(_maximumVolume, _startTime, _endTime, _rollingPeriodInterval); } /** @@ -162,7 +143,7 @@ contract MaximumVolumeTransferManager is ITransferManager { ); for(uint256 i = 0; i < _maximumVolumes.length; i++){ - addMaxVolumeRestricion( + _addMaxVolumeRestricion( _maximumVolumes[i], _startTimes[i], _endTimes[i], @@ -188,13 +169,13 @@ contract MaximumVolumeTransferManager is ITransferManager { public withPerm(ADMIN) { require(_index < maximumVolumeRestrictions.length, "invalid index"); require(now < maximumVolumeRestrictions[_index].endTime, "restriction is no longer active"); - _checkRestrictionParams(_startTime, _endTime, _rollingPeriodInterval); if(_startTime == 0) { _startTime = now; - require(_endTime > _startTime, "end time must be greater than start time"); } + _checkRestrictionParams(_startTime, _endTime, _rollingPeriodInterval); + MaximumVolumeRestriction memory restriction = MaximumVolumeRestriction( _maximumVolume, _startTime, @@ -218,15 +199,13 @@ contract MaximumVolumeTransferManager is ITransferManager { * @param _index representing the array index of the maximum volume transfer restriction */ function removeMaximumTransferRestriction(uint256 _index) public withPerm(ADMIN){ - require (maximumVolumeRestrictions.length != 0, "no existing restrictions"); require (maximumVolumeRestrictions.length > _index, "invalid index"); if(_index < (maximumVolumeRestrictions.length - 1)){ - MaximumVolumeRestriction memory lastRestriction = maximumVolumeRestrictions[maximumVolumeRestrictions.length - 1]; - maximumVolumeRestrictions[_index] = lastRestriction; + maximumVolumeRestrictions[_index] = maximumVolumeRestrictions[maximumVolumeRestrictions.length - 1]; } - maximumVolumeRestrictions.length = (maximumVolumeRestrictions.length).sub(1); + maximumVolumeRestrictions.length = maximumVolumeRestrictions.length - 1; emit RemoveMaximumVolumeRestricion( msg.sender, @@ -250,6 +229,39 @@ contract MaximumVolumeTransferManager is ITransferManager { return maximumVolumeRestrictions.length; } + /** + * @notice internal function to create new maximum volume transfer restrictions + * @param _maximumVolume maximum token volume that can be transfered + * @param _startTime timestamp representing when this maximum volume restriction starts + * @param _endTime timestamp representing when this maximum volume restriction ends + * @param _rollingPeriodInterval interval period representing one of five RollingIntervals + */ + function _addMaxVolumeRestricion( + uint256 _maximumVolume, + uint256 _startTime, + uint256 _endTime, + uint256 _rollingPeriodInterval) + internal { + emit AddNewMaximumVolumeRestriction( + maximumVolumeRestrictions.length, + now, + _maximumVolume, + _startTime, + _endTime, + _rollingPeriodInterval + ); + + maximumVolumeRestrictions.push( + MaximumVolumeRestriction( + _maximumVolume, + _startTime, + _endTime, + RollingIntervals(_rollingPeriodInterval) + ) + ); + } + + /** * @notice gets rolling interval period value in seconds * @param _rollingPeriodInterval one of five RollingIntervals enum value @@ -285,8 +297,8 @@ contract MaximumVolumeTransferManager is ITransferManager { uint256(RollingIntervals.Annually) >= _rollingPeriodInterval, "invalid rolling period interval - should be < 5" ); - require(_startTime == 0 || _startTime >= now, 'invalid startTime'); - require(_endTime > 0 && _endTime > _startTime, 'invalid endTime'); + require(_startTime != 0, 'invalid startTime'); + require(_endTime > _startTime && _endTime > now, 'invalid endTime'); require( _getPeriod(RollingIntervals(_rollingPeriodInterval)) <= _endTime.sub(_startTime), "rolling interval must be less than or equal to the difference between endTime and startTime" diff --git a/scripts/test.sh b/scripts/test.sh index 053bd5f03..6dd3ce95a 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -63,7 +63,7 @@ start_testrpc() { if ! [ -z "${TRAVIS_PULL_REQUEST+x}" ] && [ "$TRAVIS_PULL_REQUEST" != false ]; then node_modules/.bin/testrpc-sc --gasLimit 0xfffffffffff --port "$testrpc_port" "${accounts[@]}" > /dev/null & else - node_modules/.bin/ganache-cli --gasLimit 0xfffffffffff "${accounts[@]}" > /dev/null & + node_modules/.bin/ganache-cli --gasLimit 8000000 "${accounts[@]}" > /dev/null & fi diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js index 88cea49d3..b7f4dd9c4 100644 --- a/test/z_maximum_volume_transfer_manager.js +++ b/test/z_maximum_volume_transfer_manager.js @@ -259,7 +259,7 @@ contract("MaximumVolumeTransferManager", accounts => { ); I_MaximumVolumeTransferManager = MaximumVolumeTransferManager.at(tx.logs[2].args._module); }); - //function verifyTransfer(address _from, address _to, uint256 _amount, bool _isTransfer) public returns(Result) { + it("Cannot call verifyTransfer on the TM directly if _isTransfer == true", async () => { await catchRevert( I_MaximumVolumeTransferManager.verifyTransfer( @@ -331,67 +331,67 @@ contract("MaximumVolumeTransferManager", accounts => { let endTime = latestTime() + duration.years(2); let rollingInterval = 1; //weekly - it("should not allow creation of a maximum volume restriction if endTime is set to 0", async() => { + it("should fail to add a new max volume restriction when called by a non-admin account", async() => { let errorThrown = false; try{ await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, startTime, - 0, + endTime, rollingInterval, - { from: token_owner } + { from: account_investor1 } ); } catch(error) { - console.log(` tx revert -> invalid end time`.grey); + console.log(` tx revert -> not an admin`.grey); ensureException(error); errorThrown = true; } assert.ok(errorThrown, message); }); - it("should not allow creation of a maximum volume restriction if rolling interval is not recognized", async() => { + it("should not allow creation of a maximum volume restriction if endTime is set to 0", async() => { let errorThrown = false; try{ await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, startTime, - endTime, - 6, + 0, + rollingInterval, { from: token_owner } ); } catch(error) { - console.log(` tx revert -> invalid rolling interval enum`.grey); + console.log(` tx revert -> invalid end time`.grey); ensureException(error); errorThrown = true; } assert.ok(errorThrown, message); }); - it("should not allow creation of a maximum volume restriction if startTime is equal to endTime", async() => { + it("should not allow creation of a maximum volume restriction if rolling interval is not recognized", async() => { let errorThrown = false; try{ await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, + startTime, endTime, - endTime, - rollingInterval, + 6, { from: token_owner } ); } catch(error) { - console.log(` tx revert -> invalid startTime and endTime`.grey); + console.log(` tx revert -> invalid rolling interval enum`.grey); ensureException(error); errorThrown = true; } assert.ok(errorThrown, message); }); - it("should not allow creation of a maximum volume restriction if endTime is less than startTime", async() => { + it("should not allow creation of a maximum volume restriction if startTime is equal to endTime", async() => { let errorThrown = false; try{ await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, endTime, - startTime, + endTime, rollingInterval, { from: token_owner } ); @@ -403,18 +403,18 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); - it("should not allow creation of a maximum volume restriction if startTime is in the past", async() => { + it("should not allow creation of a maximum volume restriction if endTime is less than startTime", async() => { let errorThrown = false; try{ await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, - latestTime() - 1000, endTime, + startTime, rollingInterval, { from: token_owner } ); } catch(error) { - console.log(` tx revert -> startTime is in the past`.grey); + console.log(` tx revert -> invalid startTime and endTime`.grey); ensureException(error); errorThrown = true; } @@ -572,6 +572,29 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); + it("should fail to add to add multiple new max volume restrictions when called by a non-admin account", async() => { + const maxVolumes = [100000000, 500000000, 6000000000]; + const startTimes = [0, 0, 0]; + const endTimes = [latestTime() + duration.years(1), latestTime() + duration.years(2), latestTime() + duration.years(3)]; + const rollingIntervals = [0, 2, 4]; + + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaxVolumeRestricionsMulti( + maxVolumes, + startTimes, + endTimes, + rollingIntervals, + { from: account_investor1 } + ); + } catch(error) { + console.log(` tx revert -> not an admin`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("should allow for addition of multiple maximum volume restrictions", async()=>{ const maxVolumes = [100000000, 500000000, 6000000000]; const startTimes = [0, 0, 0]; @@ -637,7 +660,7 @@ contract("MaximumVolumeTransferManager", accounts => { } assert.ok(errorThrown, message); }); - + it("Should successfully attach the CountTransferManager with the security token (count of 1)", async () => { let bytesCountTM = web3.eth.abi.encodeFunctionCall( { From 53781c2fd80accbfc4a36009277cfdcbeff8a1a0 Mon Sep 17 00:00:00 2001 From: Mudit Gupta Date: Fri, 19 Oct 2018 23:24:07 +0530 Subject: [PATCH 06/10] fix lint error Co-Authored-By: vyomshm --- .../modules/TransferManager/MaximumVolumeTransferManager.sol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol index dd67a20a9..a0b4c3909 100644 --- a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol +++ b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol @@ -7,7 +7,7 @@ import "openzeppelin-solidity/contracts/math/SafeMath.sol"; * @title Transfer Manager module for capping the amount of token transfers within a period */ contract MaximumVolumeTransferManager is ITransferManager { - using SafeMath for uint256; + using SafeMath for uint256; bytes32 public constant ADMIN = "ADMIN"; From 0751c87074eeeb888d0abcca8b7eee9757574af4 Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Sat, 20 Oct 2018 02:30:23 +0530 Subject: [PATCH 07/10] updated test files --- test/z_maximum_volume_transfer_manager.js | 86 ++++++++++++++++++++--- 1 file changed, 78 insertions(+), 8 deletions(-) diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js index b7f4dd9c4..e82a5f018 100644 --- a/test/z_maximum_volume_transfer_manager.js +++ b/test/z_maximum_volume_transfer_manager.js @@ -504,14 +504,14 @@ contract("MaximumVolumeTransferManager", accounts => { assert.equal(finalBalance.toNumber(), web3.utils.toWei('3', 'ether')); }); - it("should allow for modification of an existing maximum volume transfer restriction", async()=>{ + it("should allow for modification of an existing maximum volume transfer restriction with new startTime is set to zero", async()=>{ const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); const index = nRestrictions - 1; const newMaxVolume = web3.utils.toWei('0.5', 'ether'); const newStartTime = 0; const newEndTime = latestTime() + duration.years(1); - const newRollingInterval = 0; + const newRollingInterval = 4; const tx = await I_MaximumVolumeTransferManager.modifyMaximumTransferRestriction( index, @@ -530,6 +530,32 @@ contract("MaximumVolumeTransferManager", accounts => { assert.equal(newRollingInterval , logs['args']['_rollingPeriodInterval'], "Invalid rolling interval"); }); + it("should allow for modification of an existing maximum volume transfer restriction", async()=>{ + const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); + const index = nRestrictions - 1; + + const newMaxVolume = web3.utils.toWei('0.5', 'ether'); + const newStartTime = latestTime() - duration.years(1); + const newEndTime = latestTime() + duration.years(1); + const newRollingInterval = 3; + + const tx = await I_MaximumVolumeTransferManager.modifyMaximumTransferRestriction( + index, + newMaxVolume, + newStartTime, + newEndTime, + newRollingInterval, + { from: token_owner } + ); + const logs = tx.logs[0]; + const currentStartTime = (await web3.eth.getBlock('latest')).timestamp; + + assert.equal("ModifyMaximumVolumeRestriction", logs['event'], "Invalid event"); + assert.equal(newStartTime, logs['args']['_startTime'], "Invalid start time"); + assert.equal(newEndTime, logs['args']['_endTime'], "Invalid end time"); + assert.equal(newRollingInterval , logs['args']['_rollingPeriodInterval'], "Invalid rolling interval"); + }); + it("should not allow for modification of an expired restriction", async()=>{ // increase evm time by 3 years await increaseTime(94608000); @@ -595,12 +621,35 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); - it("should allow for addition of multiple maximum volume restrictions", async()=>{ - const maxVolumes = [100000000, 500000000, 6000000000]; + it("should fail to add to add multiple new max volume restrictions when max volumes array is empty", async() => { + const maxVolumes = []; const startTimes = [0, 0, 0]; const endTimes = [latestTime() + duration.years(1), latestTime() + duration.years(2), latestTime() + duration.years(3)]; const rollingIntervals = [0, 2, 4]; + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaxVolumeRestricionsMulti( + maxVolumes, + startTimes, + endTimes, + rollingIntervals, + { from: account_investor1 } + ); + } catch(error) { + console.log(` tx revert -> max volumes array is empty`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("should allow for addition of multiple maximum volume restrictions", async()=>{ + const maxVolumes = [100000000, 200000000, 300000000, 400000000, 500000000]; + const startTimes = [0, 0, 0, latestTime() - 10000, latestTime() + 10000]; + const endTimes = [latestTime() + duration.weeks(1), latestTime() + duration.weeks(2), latestTime() + duration.years(1), latestTime() + duration.years(2), latestTime() + duration.years(3)]; + const rollingIntervals = [0, 1, 2, 3 ,4]; + await I_MaximumVolumeTransferManager.addMaxVolumeRestricionsMulti( maxVolumes, startTimes, @@ -610,7 +659,7 @@ contract("MaximumVolumeTransferManager", accounts => { ); assert.equal( - 4, + 6, await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(), "Failed to add multiple restrictions" ); @@ -639,9 +688,14 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); - it("should allow for deletion of a maximum volume transfer restriction", async () => { - const tx = await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction(1, { from: token_owner }); - const logs = tx.logs[0]; + it("should allow for successful deletion of maximum volume transfer restrictions", async () => { + let tx = await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction(1, { from: token_owner }); + let logs = tx.logs[0]; + assert.equal("RemoveMaximumVolumeRestricion", logs['event'], "Invalid event"); + + const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); + tx = await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction(nRestrictions - 1, { from: token_owner }); + logs = tx.logs[0]; assert.equal("RemoveMaximumVolumeRestricion", logs['event'], "Invalid event"); }); @@ -660,6 +714,22 @@ contract("MaximumVolumeTransferManager", accounts => { } assert.ok(errorThrown, message); }); + + it("should fail to delete any restriction if called by a non-admin account", async() =>{ + let errorThrown = false; + const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); + try { + await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction( + nRestrictions, + { from: account_investor1 } + ); + } catch(error) { + console.log(` tx revert -> account not an admin`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); it("Should successfully attach the CountTransferManager with the security token (count of 1)", async () => { let bytesCountTM = web3.eth.abi.encodeFunctionCall( From 12eb7c6b45b7f30e7abb92b72c6c7df582cf860d Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Sun, 21 Oct 2018 03:34:26 +0530 Subject: [PATCH 08/10] increasing test coverage --- test/z_maximum_volume_transfer_manager.js | 110 ++++++++++++++-------- 1 file changed, 73 insertions(+), 37 deletions(-) diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js index e82a5f018..3d5067767 100644 --- a/test/z_maximum_volume_transfer_manager.js +++ b/test/z_maximum_volume_transfer_manager.js @@ -504,23 +504,24 @@ contract("MaximumVolumeTransferManager", accounts => { assert.equal(finalBalance.toNumber(), web3.utils.toWei('3', 'ether')); }); - it("should allow for modification of an existing maximum volume transfer restriction with new startTime is set to zero", async()=>{ + it("should allow for modification of an existing maximum volume transfer restriction with new startTime set to zero", async()=>{ const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); const index = nRestrictions - 1; const newMaxVolume = web3.utils.toWei('0.5', 'ether'); const newStartTime = 0; - const newEndTime = latestTime() + duration.years(1); + const newEndTime = latestTime() + duration.years(3); const newRollingInterval = 4; const tx = await I_MaximumVolumeTransferManager.modifyMaximumTransferRestriction( - index, - newMaxVolume, - newStartTime, - newEndTime, - newRollingInterval, - { from: token_owner } + index, + newMaxVolume, + newStartTime, + newEndTime, + newRollingInterval, + { from: token_owner } ); + const logs = tx.logs[0]; const currentStartTime = (await web3.eth.getBlock('latest')).timestamp; @@ -644,27 +645,6 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); - it("should allow for addition of multiple maximum volume restrictions", async()=>{ - const maxVolumes = [100000000, 200000000, 300000000, 400000000, 500000000]; - const startTimes = [0, 0, 0, latestTime() - 10000, latestTime() + 10000]; - const endTimes = [latestTime() + duration.weeks(1), latestTime() + duration.weeks(2), latestTime() + duration.years(1), latestTime() + duration.years(2), latestTime() + duration.years(3)]; - const rollingIntervals = [0, 1, 2, 3 ,4]; - - await I_MaximumVolumeTransferManager.addMaxVolumeRestricionsMulti( - maxVolumes, - startTimes, - endTimes, - rollingIntervals, - { from: token_owner } - ); - - assert.equal( - 6, - await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(), - "Failed to add multiple restrictions" - ); - }); - it("should fail if input array lengths mismatch for mutiple maximum volume transfer restrictions", async()=>{ const maxVolumes = [100000000, 6000000000]; const startTimes = [0, 0, 0]; @@ -688,15 +668,54 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); - it("should allow for successful deletion of maximum volume transfer restrictions", async () => { - let tx = await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction(1, { from: token_owner }); - let logs = tx.logs[0]; - assert.equal("RemoveMaximumVolumeRestricion", logs['event'], "Invalid event"); + it("should allow for addition of multiple maximum volume restrictions", async()=>{ + const maxVolumes = [100000, 200000, 300000, 400000, 500000]; + const startTimes = [0, 0, 0, latestTime() - 10000, latestTime() + 10000]; + const endTimes = [latestTime() + duration.weeks(1), latestTime() + duration.weeks(2), latestTime() + duration.years(1), latestTime() + duration.years(2), latestTime() + duration.years(3)]; + const rollingIntervals = [0, 1, 2, 3 ,4]; - const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); - tx = await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction(nRestrictions - 1, { from: token_owner }); - logs = tx.logs[0]; - assert.equal("RemoveMaximumVolumeRestricion", logs['event'], "Invalid event"); + await I_MaximumVolumeTransferManager.addMaxVolumeRestricionsMulti( + maxVolumes, + startTimes, + endTimes, + rollingIntervals, + { from: token_owner } + ); + + assert.equal( + 6, + await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(), + "Failed to add multiple restrictions" + ); + }); + + it("should restrict transfers to their set maximum limits", async()=>{ + await I_SecurityToken.transfer(account_investor4, 100000, { from: account_investor1 }); + await catchRevert( + I_SecurityToken.transfer(account_investor4, 1, { from: account_investor1 }) + ); + + await increaseTime(duration.days(1)); + await I_SecurityToken.transfer(account_investor4, 100000, { from: account_investor1 }); + await catchRevert( + I_SecurityToken.transfer(account_investor4, 1, { from: account_investor1 }) + ); + + await increaseTime(duration.days(1)); + await catchRevert( + I_SecurityToken.transfer(account_investor4, 1, { from: account_investor1 }) + ); + + await increaseTime(duration.weeks(1)); + await I_SecurityToken.transfer(account_investor4, 100000, { from: account_investor1 }); + await catchRevert( + I_SecurityToken.transfer(account_investor4, 1, { from: account_investor1 }) + ); + + await increaseTime(duration.weeks(1)); + await catchRevert( + I_SecurityToken.transfer(account_investor4, 1, { from: account_investor1 }) + ); }); it("should fail to delete any restriction if index provided is wrong", async() =>{ @@ -730,6 +749,22 @@ contract("MaximumVolumeTransferManager", accounts => { } assert.ok(errorThrown, message); }); + + it("should allow for successful deletion of maximum volume transfer restrictions", async () => { + let tx; + let logs; + const nRestrictions = await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(); + for (let i = 0; i < nRestrictions; i++) { + tx = await I_MaximumVolumeTransferManager.removeMaximumTransferRestriction(0, { from: token_owner }); + logs = tx.logs[0]; + assert.equal("RemoveMaximumVolumeRestricion", logs['event'], "Invalid event"); + } + assert.equal( + 0, + await I_MaximumVolumeTransferManager.getMaximumVolumeRestrictionsCount.call(), + "Failed to remove all max volume restrictions" + ); + }); it("Should successfully attach the CountTransferManager with the security token (count of 1)", async () => { let bytesCountTM = web3.eth.abi.encodeFunctionCall( @@ -780,6 +815,7 @@ contract("MaximumVolumeTransferManager", accounts => { "Allows an issuer to restrict the total volume of tokens that can be transfered within a rolling time interval.", "Wrong Module added" ); + assert(await I_MaximumVolumeTransferManagerFactory.getVersion.call(), '1.0.0'); }); it("Should get the tags of the factory", async () => { From f55f56c35c060f83693cca880bc1d5e5a6300944 Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Sun, 21 Oct 2018 21:01:57 +0530 Subject: [PATCH 09/10] boosted branch coverage --- .../MaximumVolumeTransferManager.sol | 2 -- test/z_maximum_volume_transfer_manager.js | 22 +++++++++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol index a0b4c3909..57fd2761f 100644 --- a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol +++ b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol @@ -134,7 +134,6 @@ contract MaximumVolumeTransferManager is ITransferManager { uint256[] _endTimes, uint256[] _rollingPeriodIntervals) public withPerm(ADMIN) { - require(_maximumVolumes.length >= 1, "No restrictions provided"); require( _maximumVolumes.length == _startTimes.length && _maximumVolumes.length == _endTimes.length && @@ -297,7 +296,6 @@ contract MaximumVolumeTransferManager is ITransferManager { uint256(RollingIntervals.Annually) >= _rollingPeriodInterval, "invalid rolling period interval - should be < 5" ); - require(_startTime != 0, 'invalid startTime'); require(_endTime > _startTime && _endTime > now, 'invalid endTime'); require( _getPeriod(RollingIntervals(_rollingPeriodInterval)) <= _endTime.sub(_startTime), diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js index 3d5067767..5c1d289a8 100644 --- a/test/z_maximum_volume_transfer_manager.js +++ b/test/z_maximum_volume_transfer_manager.js @@ -421,14 +421,32 @@ contract("MaximumVolumeTransferManager", accounts => { assert.ok(errorThrown, message); }); + it("should not allow creation of a maximum volume restriction if endTime is less than current time", async() => { + let errorThrown = false; + try{ + await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( + max_vol, + latestTime() - 100000, + latestTime() - 100, + rollingInterval, + { from: token_owner } + ); + } catch(error) { + console.log(` tx revert -> endTime is in the past`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("should not allow creation of a maximum volume restriction if rolling interval is greater than the restriction period", async() => { let errorThrown = false; try{ await I_MaximumVolumeTransferManager.addMaxVolumeRestricion( max_vol, startTime, - startTime + 10, - rollingInterval, + latestTime() + 10, + 0, { from: token_owner } ); } catch(error) { From bd57f0ee499a6bc5dda1a9b6a05359a042675ada Mon Sep 17 00:00:00 2001 From: Vyom Sharma Date: Sun, 21 Oct 2018 23:22:43 +0530 Subject: [PATCH 10/10] added sanity check + bug fixes --- .../modules/TransferManager/MaximumVolumeTransferManager.sol | 1 + test/z_maximum_volume_transfer_manager.js | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol index 57fd2761f..cf8b9fe59 100644 --- a/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol +++ b/contracts/modules/TransferManager/MaximumVolumeTransferManager.sol @@ -134,6 +134,7 @@ contract MaximumVolumeTransferManager is ITransferManager { uint256[] _endTimes, uint256[] _rollingPeriodIntervals) public withPerm(ADMIN) { + require(_maximumVolumes.length >= 1, "No restrictions provided"); require( _maximumVolumes.length == _startTimes.length && _maximumVolumes.length == _endTimes.length && diff --git a/test/z_maximum_volume_transfer_manager.js b/test/z_maximum_volume_transfer_manager.js index 5c1d289a8..deb420d76 100644 --- a/test/z_maximum_volume_transfer_manager.js +++ b/test/z_maximum_volume_transfer_manager.js @@ -653,7 +653,7 @@ contract("MaximumVolumeTransferManager", accounts => { startTimes, endTimes, rollingIntervals, - { from: account_investor1 } + { from: token_owner } ); } catch(error) { console.log(` tx revert -> max volumes array is empty`.grey);