diff --git a/contracts/modules/Wallet/IWallet.sol b/contracts/modules/Wallet/IWallet.sol new file mode 100644 index 000000000..194a4a77b --- /dev/null +++ b/contracts/modules/Wallet/IWallet.sol @@ -0,0 +1,19 @@ +pragma solidity ^0.4.24; + +import "../../Pausable.sol"; +import "../Module.sol"; + +/** + * @title Interface to be implemented by all Wallet Manager modules + */ +contract IWallet is Pausable, Module { + + function unpause() onlyOwner public { + super._unpause(); + } + + function pause() onlyOwner public { + super._pause(); + } + +} diff --git a/contracts/modules/Wallet/VestingEscrowWallet.sol b/contracts/modules/Wallet/VestingEscrowWallet.sol new file mode 100644 index 000000000..fb6e33aa0 --- /dev/null +++ b/contracts/modules/Wallet/VestingEscrowWallet.sol @@ -0,0 +1,462 @@ +pragma solidity ^0.4.24; + +import "./IWallet.sol"; +import "openzeppelin-solidity/contracts/math/SafeMath.sol"; +import "../../interfaces/ISecurityToken.sol"; + +/** + * @title Escrow wallet for distributing tokens on a vesting schedule + */ +contract VestingEscrowWallet is IWallet { + using SafeMath for uint; + + bytes32 public constant ISSUER = "ISSUER"; + address public treasury; + uint256 public numExcessTokens; + uint256 public templateCount; + + struct VestingSchedule { + // ID of the vesting schedule + bytes32 vestingId; + // Total number of vesting tokens at start of vesting period + uint256 totalAllocation; + // Length of the vesting period + uint256 vestingDuration; + // Start date of vesting schedule + uint256 startDate; + // Vesting frequency of the tokens + uint256 vestingFrequency; + // Total number of vested tokens + uint256 numVestedTokens; + // Total number of unvested tokens + uint256 numUnvestedTokens; + // Total number of claimed vested tokens + uint256 numClaimedVestedTokens; + // Total number of unclaimed vested tokens + uint256 numUnclaimedVestedTokens; + // Number of tokens to release to the target per tranche + uint256 tokensPerTranche; + } + + struct VestingTemplate { + // Total number of vesting tokens at start of vesting period + uint256 totalAllocation; + // Length of the vesting period + uint256 vestingDuration; + // Vesting frequency of the tokens + uint256 vestingFrequency; + } + + mapping(bytes32 => uint256) vestingScheduleIndex; + mapping(address => VestingSchedule[]) userToVestingSchedules; + mapping(uint256 => VestingTemplate) public vestingTemplates; + + + + /* Events */ + event VestingStarted( + address indexed target, + bytes32 indexed vestingId, + uint256 indexed totalAllocation, + uint256 vestingDuration, + uint256 startDate, + uint256 vestingFrequency, + uint256 numClaimedVestedTokens, + uint256 tokensPerTranche + ); + + event AddTemplate( + uint256 indexed templateNumber, + uint256 totalAllocation, + uint256 vestingDuration, + uint256 vestingFrequency + ); + + event VestingCancelled( + address indexed target, + uint256 indexed whichVestingShedule, + bytes32 indexed vestingId, + uint256 tokensCollected, + bool tokensReclaimed, + uint256 cancellationTime + ); + + event TokensCollected( + address indexed target, + uint256 indexed whichVestingShedule, + bytes32 indexed vestingId, + uint256 numberTokensCollected + ); + + /** + * @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 Function used to initialize the different variables + * @param _treasury Treasury wallet to send excess funds + */ + function configure(address _treasury) public onlyFactory { + require(_treasury != address(0), "Treasury should not be 0"); + treasury = _treasury; + } + + /** + * @notice This function returns the signature of the configure function + */ + function getInitFunction() public pure returns (bytes4) { + return bytes4(keccak256("configure(address)")); + } + + /** + * @notice Return the permissions flag that are associated with VotingEscrowWallet + */ + function getPermissions() public view returns(bytes32[]) { + bytes32[] memory allPermissions = new bytes32[](1); + allPermissions[0] = ISSUER; + return allPermissions; + } + + /** + * @notice Create a template to be used for the creation of new vesting schedules + * @param _totalAllocation Total number of tokens allocated for the target + * @param _vestingDuration Total duration of the vesting schedule + * @param _vestingFrequency Frequency of release of tokens + */ + function createTemplate( + uint256 _totalAllocation, + uint256 _vestingDuration, + uint256 _vestingFrequency + ) + public + onlyOwner + { + require(_totalAllocation != 0, "Total allocation was initialized to 0"); + require(_vestingDuration != 0, "Vesting duration was initialized to 0"); + require(_vestingFrequency != 0, "Vesting frequency was initialized to 0"); + + vestingTemplates[templateCount] = VestingTemplate(_totalAllocation, _vestingDuration, _vestingFrequency); + + templateCount = templateCount == 0 ? 0 : templateCount +1; + + emit AddTemplate( + templateCount, + _totalAllocation, + _vestingDuration, + _vestingFrequency); + } + + /** + * @notice Initiate a vesting schedule for any number of employees or affiliates + * @param _target Address of the employee or the affiliate + * @param _totalAllocation Total number of tokens allocated for the target + * @param _vestingDuration Total duration of the vesting schedule + * @param _startDate Start date of the vesting schedule + * @param _vestingFrequency Frequency of release of tokens + */ + function initiateVestingSchedule( + address[] _target, + uint256[] _totalAllocation, + uint256[] _vestingDuration, + uint256[] _startDate, + uint256[] _vestingFrequency + ) + public + onlyOwner + withPerm(ISSUER) + { + require(_target.length == _totalAllocation.length && + _target.length == _vestingDuration.length && + _target.length == _startDate.length && + _target.length == _vestingFrequency.length); + + for (uint i = 0; i < _target.length; i++) { + initiateVestingScheduleIterate(_target[i], + _totalAllocation[i], + _vestingDuration[i], + _startDate[i], + _vestingFrequency[i]); + } + } + + /** + * @notice Initiate a vesting schedule for any number of employees from a template + * @param _target Address of the employee or the affiliate + * @param _templateNumber Template number to use + * @param _startDate Start date of the vesting schedule + */ + function initiateVestingScheduleFromTemplate( + address[] _target, + uint256 _templateNumber, + uint256 _startDate + ) + public + onlyOwner + withPerm(ISSUER) + { + VestingTemplate memory _vestingTemplate = vestingTemplates[_templateNumber]; + + for (uint i = 0; i < _target.length; i++) { + require(_target[i] != address(0)); + initiateVestingScheduleIterate(_target[i], + _vestingTemplate.totalAllocation, + _vestingTemplate.vestingDuration, + _startDate, + _vestingTemplate.vestingFrequency); + } + } + + /** + * @notice Cancel a vesting schedule for an employee or affiliate + * @param _target Address of the employee or the affiliate + * @param _vestingScheduleIndex Index of the vesting schedule for the target + * @param _revokeVestingSchedule True if the issuer is reclaiming the tokens out of the contract + */ + function cancelVestingSchedule(address _target, uint256 _vestingScheduleIndex, bool _revokeVestingSchedule) + public + onlyOwner + { + VestingSchedule memory _vestingSchedule = userToVestingSchedules[_target]; + + require(_vestingSchedule.vestingId != 0, "Schedule not initialized"); + + bytes32 _vestingId = _vestingSchedule.vestingId; + uint256 _currentTranche = _calculateCurrentTranche(_vestingSchedule.startDate, _vestingSchedule.vestingDuration); + uint256 _tokensToDistribute = _calculateTokensToDistribute(_currentTranche, _vestingSchedule.tokensPerTranche, _vestingSchedule.numClaimedVestedTokens); + uint256 _numUnvestedTokens = _vestingSchedule.numUnvestedTokens.sub(_tokensToDistribute); + delete userToVestingSchedules[_target]; + + // Send vested, unclaimed tokens to the target + if (_tokensToDistribute != 0) { + require(ISecurityToken(securityToken).transfer( + _target, + _tokensToDistribute), "Unable to transfer tokens"); + } + + // Send extra tokens to the treasury or hold them in the contract + if (_numUnvestedTokens != 0) { + if (_revokeVestingSchedule) { + require(ISecurityToken(securityToken).transfer( + // treasury, + msg.sender, + _numUnvestedTokens), "Unable to transfer tokens"); + } else { + numExcessTokens = numExcessTokens.add(_numUnvestedTokens); + } + } + + emit VestingCancelled( + _target, + _vestingScheduleIndex, + _vestingId, + _tokensToDistribute, + _revokeVestingSchedule, + block.timestamp + ); + } + + /** + * @notice Collect vested tokens + * @param _vestingScheduleIndex Index of the vesting schedule for the target + */ + function collectVestedTokens(uint256 _vestingScheduleIndex) + public + { + _distributeVestedTokens(msg.sender, _vestingScheduleIndex); + } + + /** + * @notice Push vested tokens + * @param _target Address of the employee or the affiliate + * @param _vestingScheduleIndex Index of the vesting schedule for the target + */ + function pushVestedTokens(address _target, uint256 _vestingScheduleIndex) + public + onlyOwner + { + _distributeVestedTokens(_target, _vestingScheduleIndex); + } + + /** + * @notice Distribute vested tokens + * @param _target Address of the employee or the affiliate + * @param _vestingScheduleIndex Index of the vesting schedule for the target + */ + function _distributeVestedTokens(address _target, uint256 _vestingScheduleIndex) + internal + { + VestingSchedule memory _vestingSchedule = userToVestingSchedules[_target]; + + require(_vestingSchedule.vestingId != 0, "Schedule not initialized"); + + uint256 _currentTranche = _calculateCurrentTranche(_vestingSchedule.startDate, _vestingSchedule.vestingDuration); + uint256 _tokensToDistribute = _calculateTokensToDistribute(_currentTranche, _vestingSchedule.tokensPerTranche, _vestingSchedule.numClaimedVestedTokens); + + require(_tokensToDistribute != 0, "No tokens remain"); + + _vestingSchedule.numClaimedVestedTokens = _vestingSchedule.numClaimedVestedTokens.add(_tokensToDistribute); + + require(ISecurityToken(securityToken).transfer( + _target, + _tokensToDistribute), "Unable to transfer tokens"); + + emit TokensCollected( + _target, + _vestingScheduleIndex, + _vestingSchedule.vestingId, + _tokensToDistribute + ); + } + + /** + * @notice Initiate a vesting schedule for an employee or affiliate + * @param _target Address of the employee or the affiliate + * @param _totalAllocation Total number of tokens allocated for the target + * @param _vestingDuration Total duration of the vesting schedule + * @param _startDate Start date of the vesting schedule + * @param _vestingFrequency Frequency of release of tokens + */ + function initiateVestingScheduleIterate( + address _target, + uint256 _totalAllocation, + uint256 _vestingDuration, + uint256 _startDate, + uint256 _vestingFrequency + ) + public + withPerm(ISSUER) + { + require(_target != address(0), "The target should be a valid addrss"); + require(_totalAllocation != 0, "The total allocation should not be 0"); + require(_vestingDuration != 0, "The vestingDuration should not be 0"); + require(_startDate >= now, "The starting date should be after now"); + require( + _vestingFrequency != 0 && _vestingFrequency <= _vestingDuration, + "The vestingFrequency should not be 0 and it should be less than the duration"); + require(_vestingDuration % _vestingFrequency == 0, "The vesting frequency should be a multiple of the vesting duration"); + + uint256 _numTranches = _vestingDuration.div(_vestingFrequency); + uint256 _tokensPerTranche = _totalAllocation.div(_numTranches); + + bytes32 _vestingId = keccak256( + abi.encodePacked( + block.timestamp, + _target, + _totalAllocation, + _vestingDuration, + _startDate, + _vestingFrequency + ) + ); + + uint256 _vestingScheduleIndex = vestingScheduleIndex[_target]; + vestingScheduleIndex[_target] += 1; + + uint256 _numUnvestedTokens = _totalAllocation; + + userToVestingSchedules[_target] = VestingSchedule({ + vestingId: _vestingId, + totalAllocation: _totalAllocation, + vestingDuration: _vestingDuration, + startDate: _startDate, + vestingFrequency: _vestingFrequency, + numVestedTokens: 0, + numUnvestedTokens: _numUnvestedTokens, + numClaimedVestedTokens: 0, + numUnclaimedVestedTokens: 0, + tokensPerTranche: _tokensPerTranche + }); + + uint256 _tokensToSend = _calculateTokensToSend(_totalAllocation); + + // Remove tokens from the excess token count if existing tokens are used + if (_tokensToSend != _totalAllocation) { + numExcessTokens = numExcessTokens.sub(_totalAllocation.sub(_tokensToSend)); + } + + if (_tokensToSend != 0) { + require(ISecurityToken(securityToken).transferFrom( + msg.sender, + address(this), + _tokensToSend), "Unable to transfer tokens"); + } + + emit VestingStarted( + _target, + _vestingId, + _totalAllocation, + _vestingDuration, + _startDate, + _vestingFrequency, + _numUnvestedTokens, + _tokensPerTranche + ); + } + + /** + * @notice Calculate the current tranche the user is on + * @param _startDate Start date of the vesting period + * @param _vestingDuration Total duration of the vesting schedule + */ + function _calculateCurrentTranche( + uint256 _startDate, + uint256 _vestingDuration + ) + internal + view + returns (uint256) + { + return now < _startDate + ? 0 + : (now.sub(_startDate)).div(_vestingDuration); + } + + /** + * @notice Calculate the number of tokens to distribute per transaction + * @param _currentTranche Current tranche of the vesting schedule + * @param _tokensPerTranche Number of tokens to distribute in each tranche + * @param _numClaimedVestedTokens Number of vested tokens claimed thus far + */ + function _calculateTokensToDistribute( + uint256 _currentTranche, + uint256 _tokensPerTranche, + uint256 _numClaimedVestedTokens + ) + internal + pure + returns (uint256) + { + uint256 _tokensToDistribute = _currentTranche.mul(_tokensPerTranche); + return _tokensToDistribute.sub(_numClaimedVestedTokens); + } + + /** + * @notice Calculate the number of tokens the issuer must send to the contract + * @param _totalAllocation Total allocation being used for this instance + */ + function _calculateTokensToSend( + uint256 _totalAllocation + ) + internal + view + returns (uint256) + { + if (numExcessTokens > 0){ + if (numExcessTokens >= _totalAllocation) { + return 0; + } else { + return _totalAllocation.sub(numExcessTokens); + } + } else { + return _totalAllocation; + } + } + +} diff --git a/contracts/modules/Wallet/VestingEscrowWalletFactory.sol b/contracts/modules/Wallet/VestingEscrowWalletFactory.sol new file mode 100644 index 000000000..8e0bc0f6a --- /dev/null +++ b/contracts/modules/Wallet/VestingEscrowWalletFactory.sol @@ -0,0 +1,97 @@ +pragma solidity ^0.4.24; + +import "./VestingEscrowWallet.sol"; +import "../ModuleFactory.sol"; +import "../../libraries/Util.sol"; + +/** + * @title Factory for deploying VestingEscrowWallet + */ +contract VestingEscrowWalletFactory is ModuleFactory { + + /** + * @notice Constructor + * @param _polyAddress Address of the polytoken + */ + constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public + ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) + { + version = "1.0.0"; + name = "VestingEscrowWallet"; + title = "Vesting Escrow Wallet"; + description = "Allows Issuer to program an automated token vesting schedule for employees and/or affiliates so that Tokens get delivered to their wallets as contractually defined."; + 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 vestingEscrwoWallet = new VestingEscrowWallet(msg.sender, address(polyToken)); + return vestingEscrwoWallet; + } + + /** + * @notice Type of the Module factory + */ + function getTypes() public view returns(uint8) { + return 5; + } + + /** + * @notice Get the name of the Module + */ + function getName() public view returns(bytes32) { + return name; + } + + /** + * @notice Get the description of the Module + */ + function getDescription() public view returns(string) { + return description; + } + + /** + * @notice Get the title of the Module + */ + function getTitle() public 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 Get the Instructions that helped to used the module + */ + function getInstructions() public view returns(string) { + return "Configure and track vesting allocations"; + } + + /** + * @notice Get the tags related to the module factory + */ + function getTags() public view returns(bytes32[]) { + bytes32[] memory availableTags = new bytes32[](1); + availableTags[0] = "Vested Wallet"; + availableTags[1] = "Escrow"; + return availableTags; + } + +} diff --git a/migrations/2_deploy_contracts.js b/migrations/2_deploy_contracts.js index 7b1feeece..c5f6aa517 100644 --- a/migrations/2_deploy_contracts.js +++ b/migrations/2_deploy_contracts.js @@ -6,8 +6,7 @@ const USDTieredSTOProxyFactory = artifacts.require('./USDTieredSTOProxyFactory.s const CountTransferManagerFactory = artifacts.require('./CountTransferManagerFactory.sol') const EtherDividendCheckpointFactory = artifacts.require('./EtherDividendCheckpointFactory.sol') const ERC20DividendCheckpointFactory = artifacts.require('./ERC20DividendCheckpointFactory.sol') -const ModuleRegistry = artifacts.require('./ModuleRegistry.sol'); -const ModuleRegistryProxy = artifacts.require('./ModuleRegistryProxy.sol'); +const VestingEscrowWalletFactory = artifacts.require('./VestingEscrowWalletFactory.sol') const ManualApprovalTransferManagerFactory = artifacts.require('./ManualApprovalTransferManagerFactory.sol') const CappedSTOFactory = artifacts.require('./CappedSTOFactory.sol') const USDTieredSTOFactory = artifacts.require('./USDTieredSTOFactory.sol') @@ -123,183 +122,182 @@ module.exports = function (deployer, network, accounts) { // POLYMATH NETWORK Configuration :: DO THIS ONLY ONCE // A) Deploy the PolymathRegistry contract return deployer.deploy(PolymathRegistry, {from: PolymathAccount}).then(() => { - return PolymathRegistry.deployed(); - }).then((_polymathRegistry) => { - polymathRegistry = _polymathRegistry; - return polymathRegistry.changeAddress("PolyToken", PolyToken, {from: PolymathAccount}); - }).then(() => { - // Deploy libraries - return deployer.deploy(TokenLib, {from: PolymathAccount}); - }).then(() => { - // Link libraries - return deployer.link(TokenLib, STFactory); - }).then(() => { - // A) Deploy the ModuleRegistry Contract (It contains the list of verified ModuleFactory) - return deployer.deploy(ModuleRegistry, {from: PolymathAccount}); - }).then(() => { - return deployer.deploy(ModuleRegistryProxy, {from: PolymathAccount}); - }).then(() => { - let bytesProxyMR = web3.eth.abi.encodeFunctionCall(functionSignatureProxyMR, [polymathRegistry.address, PolymathAccount]); - ModuleRegistryProxy.at(ModuleRegistryProxy.address).upgradeToAndCall("1.0.0", ModuleRegistry.address, bytesProxyMR, {from: PolymathAccount}); - }).then(() => { - moduleRegistry = ModuleRegistry.at(ModuleRegistryProxy.address); - // Add module registry to polymath registry - return polymathRegistry.changeAddress("ModuleRegistry", ModuleRegistryProxy.address, {from: PolymathAccount}); - }).then(() => { - // B) Deploy the GeneralTransferManagerFactory Contract (Factory used to generate the GeneralTransferManager contract and this - // manager attach with the securityToken contract at the time of deployment) - return deployer.deploy(GeneralTransferManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); - }).then(() => { - // C) Deploy the GeneralPermissionManagerFactory Contract (Factory used to generate the GeneralPermissionManager contract and - // this manager attach with the securityToken contract at the time of deployment) - return deployer.deploy(GeneralPermissionManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); - }).then(() => { - // D) Deploy the CountTransferManagerFactory Contract (Factory used to generate the CountTransferManager contract use - // to track the counts of the investors of the security token) - return deployer.deploy(CountTransferManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); - }).then(() => { - // 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 EtherDividendCheckpointFactory Contract (Factory used to generate the EtherDividendCheckpoint contract use - // to provide the functionality of the dividend in terms of ETH) - return deployer.deploy(EtherDividendCheckpointFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); - }).then(() => { - // D) Deploy the ERC20DividendCheckpointFactory Contract (Factory used to generate the ERC20DividendCheckpoint contract use - // to provide the functionality of the dividend in terms of ERC20 token) - return deployer.deploy(ERC20DividendCheckpointFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); - }).then(() => { - // D) Deploy the ManualApprovalTransferManagerFactory Contract (Factory used to generate the ManualApprovalTransferManager contract use - // to manual approve the transfer that will overcome the other transfer restrictions) - return deployer.deploy(ManualApprovalTransferManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); - }).then(() => { - // H) Deploy the STVersionProxy001 Contract which contains the logic of deployment of securityToken. - return deployer.deploy(STFactory, GeneralTransferManagerFactory.address, {from: PolymathAccount}); - }).then(() => { - // K) Deploy the FeatureRegistry contract to control feature switches - return deployer.deploy(FeatureRegistry, PolymathRegistry.address, {from: PolymathAccount}); - }).then(() => { - // Assign the address into the FeatureRegistry key - return polymathRegistry.changeAddress("FeatureRegistry", FeatureRegistry.address, {from: PolymathAccount}); - }).then(() => { - // J) Deploy the SecurityTokenRegistry contract (Used to hold the deployed secuirtyToken details. It also act as the interface to deploy the SecurityToken) - return deployer.deploy(SecurityTokenRegistry, {from: PolymathAccount}) - }).then(()=> { - return deployer.deploy(SecurityTokenRegistryProxy, {from: PolymathAccount}); - }).then(() => { - let bytesProxy = web3.eth.abi.encodeFunctionCall(functionSignatureProxy, [PolymathRegistry.address, STFactory.address, initRegFee, initRegFee, PolyToken, PolymathAccount]); - SecurityTokenRegistryProxy.at(SecurityTokenRegistryProxy.address).upgradeToAndCall("1.0.0", SecurityTokenRegistry.address, bytesProxy, {from: PolymathAccount}); - }).then(() => { - // Assign the address into the SecurityTokenRegistry key - return polymathRegistry.changeAddress("SecurityTokenRegistry", SecurityTokenRegistryProxy.address, {from: PolymathAccount}); - }).then(() => { - // Update all addresses into the registry contract by calling the function updateFromregistry - return moduleRegistry.updateFromRegistry({from: PolymathAccount}); - }).then(() => { - // 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 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. - return moduleRegistry.registerModule(CountTransferManagerFactory.address, {from: PolymathAccount}); - }).then(() => { - // D) Register the GeneralTransferManagerFactory in the ModuleRegistry to make the factory available at the protocol level. - // So any securityToken can use that factory to generate the GeneralTransferManager contract. - return moduleRegistry.registerModule(GeneralTransferManagerFactory.address, {from: PolymathAccount}); - }).then(() => { - // E) Register the GeneralPermissionManagerFactory in the ModuleRegistry to make the factory available at the protocol level. - // So any securityToken can use that factory to generate the GeneralPermissionManager contract. - return moduleRegistry.registerModule(GeneralPermissionManagerFactory.address, {from: PolymathAccount}); - }).then(() => { - // E) Register the GeneralPermissionManagerFactory in the ModuleRegistry to make the factory available at the protocol level. - // So any securityToken can use that factory to generate the GeneralPermissionManager contract. - return moduleRegistry.registerModule(EtherDividendCheckpointFactory.address, {from: PolymathAccount}); - }).then(() => { - // D) Register the ManualApprovalTransferManagerFactory in the ModuleRegistry to make the factory available at the protocol level. - // So any securityToken can use that factory to generate the ManualApprovalTransferManager contract. - return moduleRegistry.registerModule(ManualApprovalTransferManagerFactory.address, {from: PolymathAccount}); - }).then(() => { - // E) Register the ERC20DividendCheckpointFactory in the ModuleRegistry to make the factory available at the protocol level. - // So any securityToken can use that factory to generate the ERC20DividendCheckpoint contract. - return moduleRegistry.registerModule(ERC20DividendCheckpointFactory.address, {from: PolymathAccount}); - }).then(() => { - // F) Once the GeneralTransferManagerFactory 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(GeneralTransferManagerFactory.address, true, {from: PolymathAccount}); - }).then(() => { - // G) Once the CountTransferManagerFactory 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(CountTransferManagerFactory.address, true, {from: PolymathAccount}); - }).then(() => { - // G) Once the PercentageTransferManagerFactory 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(PercentageTransferManagerFactory.address, true, {from: PolymathAccount}); - }).then(() => { - // G) Once the GeneralPermissionManagerFactory 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(GeneralPermissionManagerFactory.address, true, {from: PolymathAccount}) - }).then(() => { - // G) Once the EtherDividendCheckpointFactory 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(EtherDividendCheckpointFactory.address, true, {from: PolymathAccount}); - }).then(() => { - // G) Once the ERC20DividendCheckpointFactory 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(ERC20DividendCheckpointFactory.address, true, {from: PolymathAccount}); - }).then(() => { - // G) Once the ManualApprovalTransferManagerFactory 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(ManualApprovalTransferManagerFactory.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}) - }).then(() => { - // N) Register the CappedSTOFactory in the ModuleRegistry to make the factory available at the protocol level. - // So any securityToken can use that factory to generate the CappedSTOFactory contract. - return moduleRegistry.registerModule(CappedSTOFactory.address, {from: PolymathAccount}) - }).then(()=>{ - // G) Once the CappedSTOFactory 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(CappedSTOFactory.address, true, {from: PolymathAccount}) - }).then(() => { - // Deploy the proxy factory - return deployer.deploy(USDTieredSTOProxyFactory, {from: PolymathAccount}); - }).then(() => { - // H) Deploy the USDTieredSTOFactory (Use to generate the USDTieredSTOFactory contract which will used to collect the funds ). - return deployer.deploy(USDTieredSTOFactory, PolyToken, usdTieredSTOSetupCost, 0, 0, USDTieredSTOProxyFactory.address, {from: PolymathAccount}) - }).then(() => { - // I) Register the USDTieredSTOFactory in the ModuleRegistry to make the factory available at the protocol level. - // So any securityToken can use that factory to generate the USDTieredSTOFactory contract. - return moduleRegistry.registerModule(USDTieredSTOFactory.address, {from: PolymathAccount}) - }).then(()=>{ - // J) Once the USDTieredSTOFactory 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(USDTieredSTOFactory.address, true, {from: PolymathAccount}) - }).then(() => { - return polymathRegistry.changeAddress("PolyUsdOracle", POLYOracle, {from: PolymathAccount}); - }).then(() => { - return polymathRegistry.changeAddress("EthUsdOracle", ETHOracle, {from: PolymathAccount}); - }).then(() => { - console.log('\n'); - console.log(` - --------------------- Polymath Network Smart Contracts: --------------------- - PolymathRegistry: ${PolymathRegistry.address} - SecurityTokenRegistryProxy: ${SecurityTokenRegistryProxy.address} - SecurityTokenRegistry: ${SecurityTokenRegistry.address} - ModuleRegistry: ${ModuleRegistry.address} - ModuleRegistryProxy: ${ModuleRegistryProxy.address} - FeatureRegistry: ${FeatureRegistry.address} + return PolymathRegistry.deployed().then((polymathRegistry) => { + + return polymathRegistry.changeAddress("PolyToken", PolyToken, {from: PolymathAccount}) + .then(() => { + // A) Deploy the ModuleRegistry Contract (It contains the list of verified ModuleFactory) + // console.log("test" + PolymathRegistry.address); + return deployer.deploy(ModuleRegistry, polymathRegistry.address, {from: PolymathAccount}); + }).then(() => { + return ModuleRegistry.deployed().then((_moduleRegistry) => { + moduleRegistry = _moduleRegistry; + // Add module registry to polymath registry + return polymathRegistry.changeAddress("ModuleRegistry", ModuleRegistry.address, {from: PolymathAccount}); + }).then(() => { + // B) Deploy the GeneralTransferManagerFactory Contract (Factory used to generate the GeneralTransferManager contract and this + // manager attach with the securityToken contract at the time of deployment) + return deployer.deploy(GeneralTransferManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); + }).then(() => { + // C) Deploy the GeneralPermissionManagerFactory Contract (Factory used to generate the GeneralPermissionManager contract and + // this manager attach with the securityToken contract at the time of deployment) + return deployer.deploy(GeneralPermissionManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); + }).then(() => { + // D) Deploy the CountTransferManagerFactory Contract (Factory used to generate the CountTransferManager contract use + // to track the counts of the investors of the security token) + return deployer.deploy(CountTransferManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); + }).then(() => { + // 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 EtherDividendCheckpointFactory Contract (Factory used to generate the EtherDividendCheckpoint contract use + // to provide the functionality of the dividend in terms of ETH) + return deployer.deploy(EtherDividendCheckpointFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); + }).then(() => { + // D) Deploy the ERC20DividendCheckpointFactory Contract (Factory used to generate the ERC20DividendCheckpoint contract use + // to provide the functionality of the dividend in terms of ERC20 token) + return deployer.deploy(ERC20DividendCheckpointFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); + }).then(() => { + // D) Deploy the VestingEscrowWalletFactory Contract (Factory used to generate the VestingEscrowWallet contract use + // to provide the functionality of a vesting wallet) + return deployer.deploy(VestingEscrowWalletFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); + }).then(() => { + // D) Deploy the ManualApprovalTransferManagerFactory Contract (Factory used to generate the ManualApprovalTransferManager contract use + // to manual approve the transfer that will overcome the other transfer restrictions) + return deployer.deploy(ManualApprovalTransferManagerFactory, PolyToken, 0, 0, 0, {from: PolymathAccount}); + }).then(() => { + // 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 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. + return moduleRegistry.registerModule(CountTransferManagerFactory.address, {from: PolymathAccount}); + }).then(() => { + // D) Register the GeneralTransferManagerFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the GeneralTransferManager contract. + return moduleRegistry.registerModule(GeneralTransferManagerFactory.address, {from: PolymathAccount}); + }).then(() => { + // E) Register the GeneralPermissionManagerFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the GeneralPermissionManager contract. + return moduleRegistry.registerModule(GeneralPermissionManagerFactory.address, {from: PolymathAccount}); + }).then(() => { + // E) Register the GeneralPermissionManagerFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the GeneralPermissionManager contract. + return moduleRegistry.registerModule(EtherDividendCheckpointFactory.address, {from: PolymathAccount}); + }).then(() => { + // D) Register the ManualApprovalTransferManagerFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the ManualApprovalTransferManager contract. + return moduleRegistry.registerModule(ManualApprovalTransferManagerFactory.address, {from: PolymathAccount}); + }).then(() => { + // E) Register the ERC20DividendCheckpointFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the ERC20DividendCheckpoint contract. + return moduleRegistry.registerModule(ERC20DividendCheckpointFactory.address, {from: PolymathAccount}); + }).then(() => { + // E) Register the VestingEscrowWalletFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the VestingEscrowWallet contract. + return moduleRegistry.registerModule(VestingEscrowWalletFactory.address, {from: PolymathAccount}); + }).then(() => { + // F) Once the GeneralTransferManagerFactory 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(GeneralTransferManagerFactory.address, true, {from: PolymathAccount}); + }).then(() => { + // G) Once the CountTransferManagerFactory 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(CountTransferManagerFactory.address, true, {from: PolymathAccount}); + }).then(() => { + // G) Once the PercentageTransferManagerFactory 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(PercentageTransferManagerFactory.address, true, {from: PolymathAccount}); + }).then(() => { + // G) Once the GeneralPermissionManagerFactory 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(GeneralPermissionManagerFactory.address, true, {from: PolymathAccount}) + }).then(() => { + // G) Once the EtherDividendCheckpointFactory 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(EtherDividendCheckpointFactory.address, true, {from: PolymathAccount}); + }).then(() => { + // G) Once the ERC20DividendCheckpointFactory 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(ERC20DividendCheckpointFactory.address, true, {from: PolymathAccount}); + }).then(() => { + // G) Once the VestingEscrowWalletFactory 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(VestingEscrowWalletFactory.address, true, {from: PolymathAccount}); + }).then(() => { + // G) Once the ManualApprovalTransferManagerFactory 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(ManualApprovalTransferManagerFactory.address, true, {from: PolymathAccount}); + }).then(() => { + // H) Deploy the STVersionProxy001 Contract which contains the logic of deployment of securityToken. + return deployer.deploy(STFactory, GeneralTransferManagerFactory.address, {from: PolymathAccount}); + }).then(() => { + // K) Deploy the FeatureRegistry contract to control feature switches + return deployer.deploy(FeatureRegistry, PolymathRegistry.address, {from: PolymathAccount}); + }).then(() => { + // Assign the address into the FeatureRegistry key + return polymathRegistry.changeAddress("FeatureRegistry", FeatureRegistry.address, {from: PolymathAccount}); + }).then(() => { + // J) Deploy the SecurityTokenRegistry contract (Used to hold the deployed secuirtyToken details. It also act as the interface to deploy the SecurityToken) + return deployer.deploy(SecurityTokenRegistry, {from: PolymathAccount}) + }).then(()=> { + return deployer.deploy(SecurityTokenRegistryProxy, {from: PolymathAccount}); + }).then(() => { + let bytesProxy = web3.eth.abi.encodeFunctionCall(functionSignatureProxy, [PolymathRegistry.address, STFactory.address, initRegFee, initRegFee, PolyToken, PolymathAccount]); + SecurityTokenRegistryProxy.at(SecurityTokenRegistryProxy.address).upgradeToAndCall("1.0.0", SecurityTokenRegistry.address, bytesProxy, {from: PolymathAccount}); + }).then(() => { + // Assign the address into the SecurityTokenRegistry key + return polymathRegistry.changeAddress("SecurityTokenRegistry", SecurityTokenRegistryProxy.address, {from: PolymathAccount}); + }).then(() => { + // Update all addresses into the registry contract by calling the function updateFromregistry + return ModuleRegistry.at(ModuleRegistry.address).updateFromRegistry({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}) + }).then(() => { + // N) Register the CappedSTOFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the CappedSTOFactory contract. + return moduleRegistry.registerModule(CappedSTOFactory.address, {from: PolymathAccount}) + }).then(()=>{ + // G) Once the CappedSTOFactory 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(CappedSTOFactory.address, true, {from: PolymathAccount}) + }).then(() => { + // H) Deploy the USDTieredSTOFactory (Use to generate the USDTieredSTOFactory contract which will used to collect the funds ). + return deployer.deploy(USDTieredSTOFactory, PolyToken, usdTieredSTOSetupCost, 0, 0, {from: PolymathAccount}) + }).then(() => { + // I) Register the USDTieredSTOFactory in the ModuleRegistry to make the factory available at the protocol level. + // So any securityToken can use that factory to generate the USDTieredSTOFactory contract. + return moduleRegistry.registerModule(USDTieredSTOFactory.address, {from: PolymathAccount}) + }).then(()=>{ + // J) Once the USDTieredSTOFactory 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(USDTieredSTOFactory.address, true, {from: PolymathAccount}) + }).then(() => { + return polymathRegistry.changeAddress("PolyUsdOracle", POLYOracle, {from: PolymathAccount}); + }).then(() => { + return polymathRegistry.changeAddress("EthUsdOracle", ETHOracle, {from: PolymathAccount}); + }).then(() => { + console.log('\n'); + console.log(` + --------------------- Polymath Network Smart Contracts: --------------------- + PolymathRegistry: ${PolymathRegistry.address} + SecurityTokenRegistryProxy: ${SecurityTokenRegistryProxy.address} + SecurityTokenRegistry: ${SecurityTokenRegistry.address} + ModuleRegistry: ${ModuleRegistry.address} + FeatureRegistry: ${FeatureRegistry.address} ETHOracle: ${ETHOracle} POLYOracle: ${POLYOracle} @@ -317,11 +315,14 @@ module.exports = function (deployer, network, accounts) { ManualApprovalTransferManagerFactory: ${ManualApprovalTransferManagerFactory.address} - EtherDividendCheckpointFactory: ${EtherDividendCheckpointFactory.address} - ERC20DividendCheckpointFactory: ${ERC20DividendCheckpointFactory.address} - ----------------------------------------------------------------------------- - `); - console.log('\n'); - // -------- END OF POLYMATH NETWORK Configuration -------// + EtherDividendCheckpointFactory: ${EtherDividendCheckpointFactory.address} + ERC20DividendCheckpointFactory: ${ERC20DividendCheckpointFactory.address} + + VestingEscrowWalletFactory: ${VestingEscrowWalletFactory.address} + ----------------------------------------------------------------------------- + `); + console.log('\n'); + // -------- END OF POLYMATH NETWORK Configuration -------// + }); }); } diff --git a/test/u_vesting_escrow_wallet.js b/test/u_vesting_escrow_wallet.js new file mode 100644 index 000000000..8460676df --- /dev/null +++ b/test/u_vesting_escrow_wallet.js @@ -0,0 +1,903 @@ +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'; + +const PolymathRegistry = artifacts.require('./PolymathRegistry.sol') +const ModuleRegistry = artifacts.require('./ModuleRegistry.sol'); +const ModuleRegistryProxy = artifacts.require('./ModuleRegistryProxy.sol'); +const SecurityToken = artifacts.require('./SecurityToken.sol'); +const SecurityTokenRegistry = artifacts.require('./SecurityTokenRegistry.sol'); +const SecurityTokenRegistryProxy = artifacts.require('./SecurityTokenRegistryProxy.sol'); +const FeatureRegistry = artifacts.require('./FeatureRegistry.sol'); +const STFactory = artifacts.require('./STFactory.sol'); +const GeneralPermissionManagerFactory = artifacts.require('./GeneralPermissionManagerFactory.sol'); +const GeneralTransferManagerFactory = artifacts.require('./GeneralTransferManagerFactory.sol'); +const GeneralTransferManager = artifacts.require('./GeneralTransferManager'); +const TrackedRedemptionFactory = artifacts.require('./TrackedRedemptionFactory.sol'); +const TrackedRedemption = artifacts.require('./TrackedRedemption'); +const GeneralPermissionManager = artifacts.require('./GeneralPermissionManager'); +const PolyTokenFaucet = artifacts.require('./PolyTokenFaucet.sol'); +const VestingEscrowWalletFactory = artifacts.require('./VestingEscrowWalletFactory.sol'); +const VestingEscrowWallet = artifacts.require('./VestingEscrowWallet.sol'); + +const Web3 = require('web3'); +const BigNumber = require('bignumber.js'); +const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")) // Hardcoded development port + +contract('VestingEscrowWallet', accounts => { + + // Accounts Variable declaration + let account_polymath; + let account_issuer; + let token_owner; + let employee1; + let employee2; + let employee3; + let account_temp; + + // 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_VestingEscrowWalletFactory; + let P_VestingEscrowWalletFactory; + let P_VestingEscrowWallet; + let I_GeneralPermissionManager; + let I_VestingEscrowWallet; + let I_GeneralTransferManager; + let I_ExchangeTransferManager; + let I_ModuleRegistry; + let I_STRProxied; + let I_FeatureRegistry; + let I_SecurityTokenRegistry; + 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"; + let snapId; + // Module key + const delegateManagerKey = 1; + const transferManagerKey = 2; + const stoKey = 3; + const checkpointKey = 4; + const walletKey = 5; + + // Initial fee for ticker registry and security token registry + const initRegFee = web3.utils.toWei("250"); + + let treasury = accounts[9]; + + let bytesSTO = web3.eth.abi.encodeFunctionCall({ + name: 'configure', + type: 'function', + inputs: [{ + type: 'address', + name: '_treasury' + } + ] + }, [treasury]); + + before(async() => { + // Accounts setup + account_polymath = accounts[0]; + account_issuer = accounts[1]; + + token_owner = account_issuer; + + employee1 = accounts[6]; + employee2 = accounts[7]; + employee3 = accounts[8]; + account_temp = accounts[2]; + + + // ----------- POLYMATH NETWORK Configuration ------------ + + // Step 0: Deploy the PolymathRegistry + I_PolymathRegistry = await PolymathRegistry.new({from: account_polymath}); + + // Step 1: Deploy the token Faucet and Mint tokens for token_owner + I_PolyToken = await PolyTokenFaucet.new(); + await I_PolyToken.getTokens((10000 * Math.pow(10, 18)), token_owner); + await I_PolymathRegistry.changeAddress("PolyToken", I_PolyToken.address, {from: account_polymath}) + + // STEP 2: Deploy the ModuleRegistry + I_ModuleRegistry = await ModuleRegistry.new(I_PolymathRegistry.address, {from:account_polymath}); + await I_PolymathRegistry.changeAddress("ModuleRegistry", I_ModuleRegistry.address, {from: account_polymath}); + + assert.notEqual( + I_ModuleRegistry.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "ModuleRegistry contract was not deployed" + ); + + // STEP 2: Deploy the GeneralTransferManagerFactory + I_GeneralTransferManagerFactory = await GeneralTransferManagerFactory.new(I_PolyToken.address, 0, 0, 0, {from:account_polymath}); + + assert.notEqual( + I_GeneralTransferManagerFactory.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "GeneralTransferManagerFactory contract was not deployed" + ); + + // STEP 3: Deploy the GeneralDelegateManagerFactory + I_GeneralPermissionManagerFactory = await GeneralPermissionManagerFactory.new(I_PolyToken.address, 0, 0, 0, {from:account_polymath}); + + assert.notEqual( + I_GeneralPermissionManagerFactory.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "GeneralDelegateManagerFactory contract was not deployed" + ); + + // STEP 4: Deploy the VestingWallet + P_VestingEscrowWalletFactory = await VestingEscrowWalletFactory.new(I_PolyToken.address, web3.utils.toWei("500","ether"), 0, 0, {from:account_polymath}); + assert.notEqual( + P_VestingEscrowWalletFactory.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "VestingEscrowWalletFactory contract was not deployed" + ); + + // STEP 4: Deploy the VestingWallet + I_VestingEscrowWalletFactory = await VestingEscrowWalletFactory.new(I_PolyToken.address, 0, 0, 0, {from:account_polymath}); + assert.notEqual( + I_VestingEscrowWalletFactory.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "VestingEscrowWalletFactory contract was not deployed" + ); + + // STEP 5: Register the Modules with the ModuleRegistry contract + // (A) : Register the GeneralTransferManagerFactory + await I_ModuleRegistry.registerModule(I_GeneralTransferManagerFactory.address, { from: account_polymath }); + await I_ModuleRegistry.verifyModule(I_GeneralTransferManagerFactory.address, true, { from: account_polymath }); + + // (B) : Register the GeneralDelegateManagerFactory + await I_ModuleRegistry.registerModule(I_GeneralPermissionManagerFactory.address, { from: account_polymath }); + await I_ModuleRegistry.verifyModule(I_GeneralPermissionManagerFactory.address, true, { from: account_polymath }); + + // (C) : Register the VestingEscrowWalletFactory + await I_ModuleRegistry.registerModule(I_VestingEscrowWalletFactory.address, { from: account_polymath }); + await I_ModuleRegistry.verifyModule(I_VestingEscrowWalletFactory.address, true, { from: account_polymath }); + + // (C) : Register the Paid VestingEscrowWalletFactory + await I_ModuleRegistry.registerModule(P_VestingEscrowWalletFactory.address, { from: account_polymath }); + await I_ModuleRegistry.verifyModule(P_VestingEscrowWalletFactory.address, true, { from: account_polymath }); + + // Step 7: Deploy the STFactory contract + I_STFactory = await STFactory.new(I_GeneralTransferManagerFactory.address); + + assert.notEqual( + I_STFactory.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "STFactory contract was not deployed", + ); + + // Step 9: Deploy the SecurityTokenRegistry + // Deploy the SecurityTokenregistry + I_SecurityTokenRegistry = await SecurityTokenRegistry.new({from: account_polymath }); + + assert.notEqual( + I_SecurityTokenRegistry.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "SecurityTokenRegistry contract was not deployed", + ); + + // Step 10: update the registries addresses from the PolymathRegistry contract + I_SecurityTokenRegistryProxy = await SecurityTokenRegistryProxy.new({from: account_polymath}); + let bytesProxy = encodeProxyCall([I_PolymathRegistry.address, I_STFactory.address, initRegFee, initRegFee, I_PolyToken.address, account_polymath]); + await I_SecurityTokenRegistryProxy.upgradeToAndCall("1.0.0", I_SecurityTokenRegistry.address, bytesProxy, {from: account_polymath}); + I_STRProxied = await SecurityTokenRegistry.at(I_SecurityTokenRegistryProxy.address); + + // Step 10: Deploy the FeatureRegistry + I_FeatureRegistry = await FeatureRegistry.new( + I_PolymathRegistry.address, + { + from: account_polymath + }); + await I_PolymathRegistry.changeAddress("FeatureRegistry", I_FeatureRegistry.address, {from: account_polymath}); + + assert.notEqual( + I_FeatureRegistry.address.valueOf(), + "0x0000000000000000000000000000000000000000", + "FeatureRegistry contract was not deployed", + ); + + // Step 11: update the registries addresses from the PolymathRegistry contract + await I_PolymathRegistry.changeAddress("SecurityTokenRegistry", I_STRProxied.address, {from: account_polymath}); + await I_ModuleRegistry.updateFromRegistry({from: account_polymath}); + + // Printing all the contract addresses + console.log(` + --------------------- Polymath Network Smart Contracts: --------------------- + PolymathRegistry: ${PolymathRegistry.address} + SecurityTokenRegistryProxy: ${SecurityTokenRegistryProxy.address} + SecurityTokenRegistry: ${SecurityTokenRegistry.address} + ModuleRegistry: ${ModuleRegistry.address} + FeatureRegistry: ${FeatureRegistry.address} + + STFactory: ${STFactory.address} + GeneralTransferManagerFactory: ${GeneralTransferManagerFactory.address} + GeneralPermissionManagerFactory: ${GeneralPermissionManagerFactory.address} + + VestingEscrowWalletFactory: ${I_VestingEscrowWalletFactory.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, gas: 85000000 }); + + // 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.LogModuleAdded({from: _blockNo}), 1); + // Verify that 0 module get added successfully or not + assert.equal(log.args._type.toNumber(), 2); + assert.equal( + web3.utils.toAscii(log.args._name) + .replace(/\u0000/g, ''), + "GeneralTransferManager" + ); + }); + + it("Should intialize the auto attached modules", async () => { + let moduleData = await I_SecurityToken.modules(2, 0); + I_GeneralTransferManager = GeneralTransferManager.at(moduleData); + + }); + + it("Should successfully attach the VestingEscrowWallet with the security token", async () => { + let errorThrown = false; + try { + const tx = await I_SecurityToken.addModule(P_VestingEscrowWalletFactory.address, bytesSTO, web3.utils.toWei("500", "ether"), 0, { from: token_owner }); + } catch(error) { + console.log(` tx -> failed because Token is not paid`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("Should successfully attach the VestingEscrowWallet with the security token", async () => { + let snapId = await takeSnapshot() + await I_PolyToken.getTokens(web3.utils.toWei("500", "ether"), token_owner); + await I_PolyToken.transfer(I_SecurityToken.address, web3.utils.toWei("500", "ether"), {from: token_owner}); + const tx = await I_SecurityToken.addModule(P_VestingEscrowWalletFactory.address, bytesSTO, web3.utils.toWei("500", "ether"), 0, { from: token_owner }); + assert.equal(tx.logs[3].args._type.toNumber(), walletKey, "VestingEscrowWallet doesn't get deployed"); + assert.equal( + web3.utils.toAscii(tx.logs[3].args._name) + .replace(/\u0000/g, ''), + "VestingEscrowWallet", + "VestingEscrowWallet module was not added" + ); + P_VestingEscrowWallet = VestingEscrowWallet.at(tx.logs[3].args._module); + await revertToSnapshot(snapId); + }); + + it("Should successfully attach the VestingEscrowWallet with the security token", async () => { + const tx = await I_SecurityToken.addModule(I_VestingEscrowWalletFactory.address, bytesSTO, 0, 0, { from: token_owner }); + assert.equal(tx.logs[2].args._type.toNumber(), walletKey, "VestingEscrowWallet doesn't get deployed"); + assert.equal( + web3.utils.toAscii(tx.logs[2].args._name) + .replace(/\u0000/g, ''), + "VestingEscrowWallet", + "VestingEscrowWallet module was not added" + ); + I_VestingEscrowWallet = VestingEscrowWallet.at(tx.logs[2].args._module); + }); + }); + + describe("Check Escrow Wallet", async() => { + context("Create Template", async() => { + it("Should fail to create a vesting schedule template", async() => { + let totalAllocation = '10'; + let errorThrown = false; + let vestingDuration = latestTime() + duration.years(4); + let vestingFrequency = (duration.years(1)/4); + try { + let tx = await I_VestingEscrowWallet.createTemplate(web3.utils.toWei(totalAllocation, 'ether'), vestingDuration, vestingFrequency, {from: employee1}); + } catch(error) { + console.log(` tx -> failed because caller is not the issuer`.grey); + ensureException(error); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Create a vesting schedule template", async() => { + let totalAllocation = '10'; + let vestingDuration = duration.years(4); + let vestingFrequency = (duration.years(1)/4); + let tx = await I_VestingEscrowWallet.createTemplate(web3.utils.toWei(totalAllocation, 'ether'), vestingDuration, vestingFrequency, {from: token_owner}); + + assert.equal(tx.logs[0].args.templateNumber.toNumber(), 0, "Template should be created at number 0"); + }); + it("Create two more vesting schdule templates", async() => { + let totalAllocation = ['25', '50']; + let vestingDuration = duration.years(4); + let vestingFrequency = (duration.years(1)/4); + let tx = await I_VestingEscrowWallet.createTemplate(web3.utils.toWei(totalAllocation[0], 'ether'), vestingDuration, vestingFrequency, {from: token_owner}); + assert.equal(tx.logs[0].args.templateNumber.toNumber(), 1, "Template should be created at number 1"); + tx = await I_VestingEscrowWallet.createTemplate(web3.utils.toWei(totalAllocation[1], 'ether'), vestingDuration, vestingFrequency, {from: token_owner}); + assert.equal(tx.logs[0].args.templateNumber.toNumber(), 2, "Template should be created at number 2"); + }); + it("Increment the templateCount", async() => { + let totalAllocation = '10'; + let vestingDuration = duration.years(4); + let vestingFrequency = (duration.years(1)/4); + let count = await I_VestingEscrowWallet.templateCount.call(); + assert.equal(count.toNumber(), 3, "Template count should be 3"); + }); + }) + context("Initiate Vesting Schedule", async() => { + it("Should whitelist all relevant parties", async() => { + let tx = await I_GeneralTransferManager.modifyWhitelistMulti( + [token_owner, employee1, employee2, employee3, I_VestingEscrowWallet.address, treasury], + [latestTime(),latestTime(),latestTime(),latestTime(),latestTime(),latestTime()], + [latestTime(),latestTime(),latestTime(),latestTime(),latestTime(),latestTime()], + [latestTime() + duration.years(20),latestTime() + duration.years(20),latestTime() + duration.years(20),latestTime() + duration.years(20),latestTime() + duration.years(20),latestTime() + duration.years(20)], + [true, true, true, true, true, true], + { + from: token_owner, + gas: 6000000 + }); + + assert.equal(tx.logs[0].args._investor, token_owner); + assert.equal(tx.logs[1].args._investor, employee1); + assert.equal(tx.logs[2].args._investor, employee2); + assert.equal(tx.logs[3].args._investor, employee3); + assert.equal(tx.logs[4].args._investor, I_VestingEscrowWallet.address); + assert.equal(tx.logs[5].args._investor, treasury); + + }); + + it("Should mint tokens for the token_owner and approve the contract address", async() => { + let tokenOwnerInitialBalance = await I_SecurityToken.balanceOf(token_owner); + + await I_SecurityToken.mint(token_owner, web3.utils.toWei('500', 'ether'), { from: token_owner }); + await I_SecurityToken.approve(I_VestingEscrowWallet.address, web3.utils.toWei('500', 'ether'), {from: token_owner}); + + let tokenOwnerNewBalance = await I_SecurityToken.balanceOf(token_owner); + + assert.equal(tokenOwnerNewBalance.toNumber() - web3.utils.toWei('500', 'ether'), tokenOwnerInitialBalance.toNumber(), "Template should be created at number 2"); + }); + it("Should fail to initiate a vesting schedule because the caller is not the owner", async() => { + let errorThrown = false; + let target = [employee1, employee2, employee3] + let totalAllocation = ['10000', '25000', '50000']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [latestTime() + duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(1)/4),(duration.years(1)/2), (duration.years(1)/2)]; + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: employee1}); + } catch(error) { + console.log(` tx -> failed because caller is not the issuer`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to initiate a vesting schedule because the the input arrays are not of equal length", async() => { + let errorThrown = false; + let target = [employee1, employee2] + let totalAllocation = ['10000', '25000', '50000']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [latestTime() + duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(1)/4), (duration.years(1)/2), (duration.years(1)/2)]; + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because arrays are unequal`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + + it("Should fail to initiate a vesting schedule because a target input was 0", async() => { + let errorThrown = false; + let target = [0, employee2, employee3] + let totalAllocation = ['16', '20', '24']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [latestTime() + duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(1)/4), (duration.years(1)/2), (duration.years(1)/2)]; + + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because a target input was 0`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to initiate a vesting schedule because a totalAllocation input was 0", async() => { + let errorThrown = false; + let target = [employee1, employee2, employee3] + let totalAllocation = ['16', '20', '24']; + totalAllocation = [0, web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [latestTime() + duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(1)/4), (duration.years(1)/2), (duration.years(1)/2)]; + + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because a totalAllocation input was 0`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to initiate a vesting schedule because a vestingDuration input was 0", async() => { + let errorThrown = false; + let target = [employee1, employee2, employee3] + let totalAllocation = ['16', '20', '24']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [0, duration.years(4), duration.years(4)]; + let startDate = [latestTime() + duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(1)/4), (duration.years(1)/2), (duration.years(1)/2)]; + + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because a vestingDuration input was 0`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to initiate a vesting schedule because a startDate was input was before now", async() => { + let errorThrown = false; + let target = [employee1, employee2, employee3] + let totalAllocation = ['16', '20', '24']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [latestTime() - duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(1)/4), (duration.years(1)/2), (duration.years(1)/2)]; + + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because a startDate input was 0`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to initiate a vesting schedule because a vestingFrequency input was 0", async() => { + let errorThrown = false; + let target = [employee1, employee2, employee3] + let totalAllocation = ['10000', '25000', '50000']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [0, latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [0, (duration.years(1)/2), (duration.years(1)/2)]; + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because a vestingFrequency input was 0`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to initiate a vesting schedule because a vestingFrequency was greater than the associated vestingDuration", async() => { + let errorThrown = false; + let target = [employee1, employee2, employee3] + let totalAllocation = ['16', '20', '24']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [latestTime() + duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(5)), (duration.years(1)/2), (duration.years(1)/2)]; + + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because a vestingFrequency was greater than the associated vestingDuration`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to initiate a vesting schedule because a vestingFrequency was not a whole factor of the associated vestingDuration", async() => { + let errorThrown = false; + let target = [employee1, employee2, employee3] + let totalAllocation = ['16', '20', '24']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [latestTime() + duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(3)/4), (duration.years(1)/2), (duration.years(1)/2)]; + + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + try { + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because a vestingFrequency was not a whole factor of the associated vestingDuration`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Create a vesting schedule for each of the employees", async() => { + let target = [employee1, employee2, employee3] + let totalAllocation = ['16', '20', '24']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether'), web3.utils.toWei(totalAllocation[1], 'ether'), web3.utils.toWei(totalAllocation[2], 'ether')] + let vestingDuration = [duration.years(4), duration.years(4), duration.years(4)]; + let startDate = [latestTime() + duration.days(1), latestTime() + duration.days(2), latestTime() + duration.days(3)] + let vestingFrequency = [(duration.years(1)/4), (duration.years(1)/2), (duration.years(1)/2)]; + + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + + let employee1VestingCount = await I_VestingEscrowWallet.individualVestingCount(employee1) + let employee2VestingCount = await I_VestingEscrowWallet.individualVestingCount(employee2) + let employee3VestingCount = await I_VestingEscrowWallet.individualVestingCount(employee3) + + assert.equal(employee1VestingCount.toNumber(), 1, "Did not receive a vesting schedule.") + assert.equal(employee2VestingCount.toNumber(), 1, "Did not receive a vesting schedule.") + assert.equal(employee3VestingCount.toNumber(), 1, "Did not receive a vesting schedule.") + }); + it("Increment the vesting schedule for a specific employee", async() => { + let target = [employee1] + let totalAllocation = ['20']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether')] + let vestingDuration = [duration.years(4)]; + let startDate = [latestTime() + duration.days(1)] + let vestingFrequency = [(duration.years(1)/4)]; + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + + let employee1VestingCount = await I_VestingEscrowWallet.individualVestingCount(employee1) + + assert.equal(employee1VestingCount.toNumber(), 2, "Did not receive a vesting schedule.") + }); + it("Save vesting schedule for a specific employee in individualVestingDetails", async() => { + let txOne = await I_VestingEscrowWallet.individualVestingDetails(employee1, 0); + let totalAllocationOne = txOne[1].toNumber(); + let txTwo = await I_VestingEscrowWallet.individualVestingDetails(employee1, 1); + let totalAllocationTwo = txTwo[1].toNumber(); + + assert.equal(totalAllocationOne, web3.utils.toWei('16', 'ether'), "Schedule did not get stored"); + assert.equal(totalAllocationTwo, web3.utils.toWei('20', 'ether'), "Schedule did not get stored") + }); + it("Issuer should send all tokens if no tokens available exist in the contract upon vesting schedule creation", async() => { + let tokenOwnerBalanceBefore = await I_SecurityToken.balanceOf(token_owner); + + let target = [employee1] + let totalAllocation = ['20']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether')] + let vestingDuration = [duration.years(4)]; + let startDate = [latestTime() + duration.days(1)] + let vestingFrequency = [(duration.years(1)/4)]; + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + let tx = await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + + let tokenOwnerBalanceAfter = await I_SecurityToken.balanceOf(token_owner); + + assert.equal(tokenOwnerBalanceAfter.add(totalAllocation).toNumber(), tokenOwnerBalanceBefore.toNumber(), "Tokens did not get transferred.") + }); + it("Issuer should send partial tokens if some of the required tokens already exist and are available in the contract upon vesting schedule creation", async() => { + let tokenOwnerBalanceBefore = await I_SecurityToken.balanceOf(token_owner); + + // Create a vesting schedule + let target = [employee1] + let totalAllocation = ['20']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether')] + let vestingDuration = [duration.years(4)]; + let startDate = [latestTime() + duration.days(1)] + let vestingFrequency = [(duration.years(1)/4)]; + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + + // Cancel schedule and leave tokens + // This is the 4th schedule creation for employee1 + await I_VestingEscrowWallet.cancelVestingSchedule(employee1, 3, false, {from: token_owner}); + + let tokenOwnerBalanceMiddle = await I_SecurityToken.balanceOf(token_owner); + + assert.equal(tokenOwnerBalanceMiddle.add(totalAllocation).toNumber(), tokenOwnerBalanceBefore.toNumber(), "Tokens did not get left in the contract.") + + // Create schedule with double the amount of tokens. Owner should only send 20, since there are 20 in the contract already + let newTotalAllocation = ['40']; + newTotalAllocation = [web3.utils.toWei(newTotalAllocation[0], 'ether')] + + params = [target, newTotalAllocation, vestingDuration, startDate, vestingFrequency]; + await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + + let tokenOwnerBalanceAfter = await I_SecurityToken.balanceOf(token_owner); + + assert.equal(tokenOwnerBalanceAfter.add(totalAllocation).toNumber(), tokenOwnerBalanceMiddle.toNumber(), "Tokens did not get transferred.") + }); + it("Issuer should send no tokens if the all of the required tokens already exist and are available in the contract upon vesting schedule creation", async() => { + let tokenOwnerBalanceBefore = await I_SecurityToken.balanceOf(token_owner); + + // Create a vesting schedule + let target = [employee1] + let totalAllocation = ['40']; + totalAllocation = [web3.utils.toWei(totalAllocation[0], 'ether')] + let vestingDuration = [duration.years(4)]; + let startDate = [latestTime() + duration.days(1)] + let vestingFrequency = [(duration.years(1)/4)]; + let params = [target, totalAllocation, vestingDuration, startDate, vestingFrequency]; + + await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + + // Cancel schedule and leave tokens + // This is the 6th schedule creation for employee1 + await I_VestingEscrowWallet.cancelVestingSchedule(employee1, 5, false, {from: token_owner}); + + let tokenOwnerBalanceMiddle = await I_SecurityToken.balanceOf(token_owner); + + assert.equal(tokenOwnerBalanceMiddle.add(totalAllocation).toNumber(), tokenOwnerBalanceBefore.toNumber(), "Tokens did not get left in the contract.") + + // Create schedule with double the amount of tokens. Owner should only send 20, since there are 20 in the contract already + let newTotalAllocation = ['20']; + newTotalAllocation = [web3.utils.toWei(newTotalAllocation[0], 'ether')] + + params = [target, newTotalAllocation, vestingDuration, startDate, vestingFrequency]; + await I_VestingEscrowWallet.initiateVestingSchedule(params[0], params[1], params[2], params[3], params[4], {from: token_owner}); + + let tokenOwnerBalanceAfter = await I_SecurityToken.balanceOf(token_owner); + + assert.equal(tokenOwnerBalanceAfter.toNumber(), tokenOwnerBalanceMiddle.toNumber(), "Tokens did not get transferred.") + }); + }) + context("Initiate Vesting Schedule From Template", async() => { + it("Should fail to initiate a vesting schedule from template because the caller is not the owner", async() => { + let errorThrown = false; + let target = [employee1, employee2, employee3] + let templateNumber = 0; + let startDate = latestTime() + duration.days(1) + + try { + let tx = await I_VestingEscrowWallet.initiateVestingScheduleFromTemplate(target, templateNumber, startDate, {from: employee1}); + } catch(error) { + console.log(` tx -> failed because caller is not the issuer`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to initiate a vesting schedule from template because an input target is 0", async() => { + let errorThrown = false; + let target = [0, employee2, employee3] + let templateNumber = 0; + let startDate = latestTime() + duration.days(1) + + try { + let tx = await I_VestingEscrowWallet.initiateVestingScheduleFromTemplate(target, templateNumber, startDate, {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because a target input was 0`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Create a vesting schedule for an employee based on a template", async() => { + let currentScheduleCount = await I_VestingEscrowWallet.individualVestingCount(employee1); + let target = [employee1, employee2, employee3] + let templateNumber = 0; + let startDate = latestTime() + duration.days(1) + + let tx = await I_VestingEscrowWallet.initiateVestingScheduleFromTemplate(target, templateNumber, startDate, {from: token_owner}); + let newScheduleCount = await I_VestingEscrowWallet.individualVestingCount(employee1); + + assert.equal(currentScheduleCount.add(1).toNumber(), newScheduleCount.toNumber(), "Schedule count did not get updated") + }); + it("Create a vesting schedule for multiple employees based on a template", async() => { + let currentScheduleCountOne = await I_VestingEscrowWallet.individualVestingCount(employee1); + let currentScheduleCountTwo = await I_VestingEscrowWallet.individualVestingCount(employee2); + let currentScheduleCountThree = await I_VestingEscrowWallet.individualVestingCount(employee3); + + let target = [employee1, employee2, employee3] + let templateNumber = 0; + let startDate = latestTime() + duration.days(1) + + let tx = await I_VestingEscrowWallet.initiateVestingScheduleFromTemplate(target, templateNumber, startDate, {from: token_owner}); + let newScheduleCountOne = await I_VestingEscrowWallet.individualVestingCount(employee1); + let newScheduleCountTwo = await I_VestingEscrowWallet.individualVestingCount(employee2); + let newScheduleCountThree = await I_VestingEscrowWallet.individualVestingCount(employee3); + + assert.equal(currentScheduleCountOne.add(1).toNumber(), newScheduleCountOne.toNumber(), "Schedule count did not get updated") + assert.equal(currentScheduleCountTwo.add(1).toNumber(), newScheduleCountTwo.toNumber(), "Schedule count did not get updated") + assert.equal(currentScheduleCountThree.add(1).toNumber(), newScheduleCountThree.toNumber(), "Schedule count did not get updated") + }); + it("Save vesting schedule for a specific employee in individualVestingDetails", async() => { + let currentScheduleCount = await I_VestingEscrowWallet.individualVestingCount(employee1); + + let tx = await I_VestingEscrowWallet.individualVestingDetails(employee1, currentScheduleCount.sub(1)); + let totalAllocation = tx[1].toNumber(); + + assert.equal(totalAllocation, web3.utils.toWei('10', 'ether'), "Schedule did not get stored"); + }); + }); + context("Cancel Vesting Scheduel", async() => { + it("Should fail to cancel a vesting schedule because the caller is not the owner", async() => { + let errorThrown = false; + let currentScheduleCount = await I_VestingEscrowWallet.individualVestingCount(employee1); + currentScheduleCount = currentScheduleCount.sub(1); + try { + await I_VestingEscrowWallet.cancelVestingSchedule(employee1, currentScheduleCount, false, {from: employee1}); + } catch(error) { + console.log(` tx -> failed because caller is not the issuer`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Should fail to cancel a vesting schedule because it does not exist", async() => { + let errorThrown = false; + let nonexistentScheduleCount = await I_VestingEscrowWallet.individualVestingCount(employee1); + nonexistentScheduleCount = nonexistentScheduleCount.add(1); + try { + await I_VestingEscrowWallet.cancelVestingSchedule(employee1, nonexistentScheduleCount, false, {from: token_owner}); + } catch(error) { + console.log(` tx -> failed because veasting schedule does not exist`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Delete the individualVestingDetails from storage", async() => { + let currentScheduleCount = await I_VestingEscrowWallet.individualVestingCount(employee1); + currentScheduleCount = currentScheduleCount.sub(1); + + let tx = await I_VestingEscrowWallet.individualVestingDetails(employee1, currentScheduleCount); + let totalAllocation = tx[1].toNumber(); + + assert.equal(totalAllocation, web3.utils.toWei('10', 'ether'), "Schedule did not get stored"); + + await I_VestingEscrowWallet.cancelVestingSchedule(employee1, currentScheduleCount, false, {from: token_owner}); + + tx = await I_VestingEscrowWallet.individualVestingDetails(employee1, currentScheduleCount); + totalAllocation = tx[1].toNumber(); + + assert.equal(totalAllocation, 0, "Schedule did not get deleted") + }); + it("Send unvested tokens to the treasury if the issuer wants to reclaim them", async() => { + await increaseTime(duration.years(10)); + + let employee1InitialBalance = await I_SecurityToken.balanceOf(employee1); + let treasuryInitialBalance = await I_SecurityToken.balanceOf(token_owner); + + await I_VestingEscrowWallet.cancelVestingSchedule(employee1, 4, true, {from: token_owner}); + + let employee1NewBalance = await I_SecurityToken.balanceOf(employee1); + let treasuryNewBalance = await I_SecurityToken.balanceOf(token_owner); + + // Send 5 vested tokens to the employee and the remaining 35 to the treasury + let expectedEmployeeTokens = new BigNumber(5e18); + let expectedTreasuryTokens = new BigNumber(35e18); + + assert.equal(employee1NewBalance.sub(employee1InitialBalance).valueOf(), expectedEmployeeTokens.valueOf(), "Employee did not get their tokens.") + assert.equal(treasuryNewBalance.sub(treasuryInitialBalance).valueOf(), expectedTreasuryTokens.valueOf(), "Treasury did not get their tokens."); + }); + it("Keep tokens in the contract if the issuer sets _isReclaiming false", async() => { + let employee3InitialBalance = await I_SecurityToken.balanceOf(employee3); + let contractInitialBalance = await I_SecurityToken.balanceOf(I_VestingEscrowWallet.address); + + await I_VestingEscrowWallet.cancelVestingSchedule(employee3, 2, false, {from: token_owner}); + + let employee3NewBalance = await I_SecurityToken.balanceOf(employee3); + let contractNewBalance = await I_SecurityToken.balanceOf(I_VestingEscrowWallet.address); + + let expectedEmployeeTokens = new BigNumber(5e18); + assert.equal(employee3NewBalance.sub(employee3InitialBalance).valueOf(), expectedEmployeeTokens.valueOf(), "Employee did not get their tokens.") + assert.equal(contractNewBalance.valueOf(), contractInitialBalance.valueOf(), "Contract did not keep its tokens"); + }); + }) + context("Collect Vested Tokens", async() => { + it("Should fail to collect because a vesting schedule does not exist", async() => { + let errorThrown = false; + + try { + await I_VestingEscrowWallet.collectVestedTokens(1000, {from: employee2}); + } catch(error) { + console.log(` tx -> failed because a vestingFrequency was not a whole factor of the associated vestingDuration`.grey); + Object.keys(error).forEach(function (key){ + ensureException(error[key]); + }); + errorThrown = true; + } + assert.ok(errorThrown, message); + }); + it("Send vested tokens to the employee", async() => { + let employee2InitialBalance = await I_SecurityToken.balanceOf(employee2); + + await I_VestingEscrowWallet.collectVestedTokens(0, {from: employee2}); + + let employee2NewBalance = await I_SecurityToken.balanceOf(employee2); + + let expectedGains = new BigNumber(5e18); + + assert.equal(employee2InitialBalance.plus(expectedGains).valueOf(), employee2NewBalance.valueOf(), "Tokens did not get claimed") + }); + }) + context("Push Vested Tokens", async() => { + it("Should function in the exact same manner as collectVestedTokens, except they are pushed by the owner", async() => { + let employee3InitialBalance = await I_SecurityToken.balanceOf(employee3); + + await I_VestingEscrowWallet.pushVestedTokens(employee3, 0, {from: token_owner}); + + let employee3NewBalance = await I_SecurityToken.balanceOf(employee3); + + let expectedGains = new BigNumber(6e18); + + assert.equal(employee3InitialBalance.plus(expectedGains).valueOf(), employee3NewBalance.valueOf(), "Tokens did not get claimed") + }); + }); + }); +});