├── .gitattributes ├── .soliumignore ├── scripts ├── coverage.sh └── test.sh ├── migrations ├── 1_initial_migration.js ├── 2_Lock_Token_migration.js └── 3_Lock_migration.js ├── .gitignore ├── .solcover.js ├── .soliumrc.json ├── contracts ├── Migrations.sol ├── LockToken.sol └── Lock.sol ├── package.json ├── README.md ├── truffle-config.js ├── audit_report_02.md ├── audit_report_01.md └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /.soliumignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | contracts/test 3 | contratcs/Migrations.sol 4 | -------------------------------------------------------------------------------- /scripts/coverage.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | SOLIDITY_COVERAGE=true scripts/test.sh -------------------------------------------------------------------------------- /migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | const Migrations = artifacts.require("Migrations"); 2 | 3 | module.exports = function(deployer) { 4 | deployer.deploy(Migrations); 5 | }; 6 | -------------------------------------------------------------------------------- /migrations/2_Lock_Token_migration.js: -------------------------------------------------------------------------------- 1 | const LockToken = artifacts.require("LockToken"); 2 | 3 | module.exports = function(deployer) { 4 | deployer.deploy( 5 | LockToken 6 | ); 7 | }; 8 | -------------------------------------------------------------------------------- /migrations/3_Lock_migration.js: -------------------------------------------------------------------------------- 1 | const Lock = artifacts.require("Lock"); 2 | const LockToken = artifacts.require("LockToken"); 3 | 4 | module.exports = function(deployer) { 5 | deployer.deploy( 6 | Lock, 7 | "0x284F214Df3F85526A910979F52C96e54fB228136", 8 | LockToken.address, 9 | "1000000000000000000" 10 | ); 11 | }; 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | coverage.json 4 | .env 5 | build/ 6 | flattened_contracts/ 7 | # IDEs and editors 8 | /.idea 9 | .project 10 | .classpath 11 | .c9/ 12 | *.launch 13 | .settings/ 14 | *.sublime-workspace 15 | # IDE - VSCode 16 | .vscode/* 17 | !.vscode/settings.json 18 | !.vscode/tasks.json 19 | !.vscode/launch.json 20 | !.vscode/extensions.json 21 | # System Files 22 | .DS_Store 23 | Thumbs.db -------------------------------------------------------------------------------- /.solcover.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | norpc: true, 3 | copyPackages:["openzeppelin-solidity"], 4 | port: 8555, 5 | testCommand: 'node --max-old-space-size=4096 ../node_modules/.bin/truffle test --network coverage', 6 | compileCommand: 'node --max-old-space-size=4096 ../node_modules/.bin/truffle compile --network coverage', 7 | skipFiles : ["escrow/EscrowProxy.sol", "test/TestToken.sol", "token/ITokenContract.sol"] 8 | }; -------------------------------------------------------------------------------- /.soliumrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solium:all", 3 | "plugins": ["security"], 4 | "rules": { 5 | "error-reason": "off", 6 | "indentation": ["error", 4], 7 | "lbrace": "off", 8 | "linebreak-style": ["error", "unix"], 9 | "no-constant": ["error"], 10 | "no-empty-blocks": "off", 11 | "quotes": ["error", "double"], 12 | "visibility-first": "error", 13 | "max-len": ["error", 79], 14 | "security/enforce-explicit-visibility": ["error"], 15 | "security/no-block-members": ["warning"], 16 | "security/no-inline-assembly": ["warning"] 17 | } 18 | } -------------------------------------------------------------------------------- /contracts/Migrations.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.4.21 <0.6.0; 2 | 3 | contract Migrations { 4 | address public owner; 5 | uint public last_completed_migration; 6 | 7 | constructor() public { 8 | owner = msg.sender; 9 | } 10 | 11 | modifier restricted() { 12 | if (msg.sender == owner) _; 13 | } 14 | 15 | function setCompleted(uint completed) public restricted { 16 | last_completed_migration = completed; 17 | } 18 | 19 | function upgrade(address new_address) public restricted { 20 | Migrations upgraded = Migrations(new_address); 21 | upgraded.setCompleted(last_completed_migration); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lock", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "devDependencies": { 7 | "bignumber.js": "^7.2.1", 8 | "chai": "^4.2.0", 9 | "coveralls": "^3.0.2", 10 | "dotenv": "^6.2.0", 11 | "ethlint": "^1.2.3", 12 | "ganache-cli": "^6.1.4", 13 | "ganache-cli-coverage": "github:Agusx1211/ganache-cli#c462b3fc48fe9b16756f7799885c0741114d9ed3", 14 | "husky": "^1.1.0", 15 | "lodash": "^4.17.10", 16 | "openzeppelin-solidity": "2.4", 17 | "openzeppelin-test-helpers": "0.3.2", 18 | "solidity-coverage": "github:rotcivegaf/solidity-coverage#5875f5b7bc74d447f3312c9c0e9fc7814b482477", 19 | "truffle": "5.0.30", 20 | "truffle-hdwallet-provider": "^1.0.14", 21 | "web3": "^1.2.4" 22 | }, 23 | "scripts": { 24 | "test": "scripts/test.sh", 25 | "compile": "truffle compile", 26 | "migrate": "truffle migrate", 27 | "networks": "truffle networks", 28 | "coverage": "scripts/coverage.sh", 29 | "lint:sol": "solium -d .", 30 | "lint:sol:fix": "solium -d . --fix" 31 | }, 32 | "author": "Ginete Technologies", 33 | "license": "ISC" 34 | } 35 | -------------------------------------------------------------------------------- /contracts/LockToken.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.5.15; 2 | 3 | import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; 4 | import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; 5 | 6 | 7 | contract LockToken is ERC20, Ownable { 8 | 9 | uint public initialSupply = 1000; 10 | 11 | string public name = "Lock Protocol Token"; 12 | string public symbol = "LOCK"; 13 | uint8 public decimals = 18; 14 | 15 | 16 | constructor() public { 17 | // mint totalTokensAmount times 10^decimals for operator 18 | _mint(msg.sender, initialSupply * (10 ** uint256(decimals))); 19 | } 20 | 21 | /** 22 | * @dev See {ERC20-_mint}. 23 | * 24 | * Requirements: 25 | * 26 | * - the caller must have the owner. 27 | */ 28 | function mint( 29 | address account, 30 | uint256 amount 31 | ) 32 | external 33 | onlyOwner 34 | returns(bool) 35 | { 36 | _mint(account, amount); 37 | return true; 38 | } 39 | 40 | /** 41 | * @dev Destroys `amount` tokens from the caller. 42 | * 43 | * See {ERC20-_burn}. 44 | * Only owner should call this function 45 | */ 46 | function burn(uint256 amount) external onlyOwner { 47 | _burn(_msgSender(), amount); 48 | } 49 | 50 | /** 51 | * @dev See {ERC20-_burnFrom}. 52 | * Only owner should call this function 53 | */ 54 | function burnFrom(address account, uint256 amount) external onlyOwner { 55 | _burnFrom(account, amount); 56 | } 57 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lock-SmartContracts 2 | 3 | This repository contains all Lock smart contracts 4 | 5 | ## Getting Started 6 | 7 | It integrates with [Truffle](https://github.com/ConsenSys/truffle), an Ethereum development environment. Please install Truffle. 8 | 9 | ```sh 10 | npm install -g truffle 11 | 12 | ``` 13 | Clone Lock-SmartContracts 14 | 15 | ```sh 16 | git clone https://github.com/LockFinance/contracts.git 17 | cd lock/smart-contracts 18 | npm i 19 | ``` 20 | 21 | Compile and Deploy 22 | ------------------ 23 | These commands apply to the RPC provider running on port 8545. You may want to have TestRPC running in the background. They are really wrappers around the [corresponding Truffle commands](http://truffleframework.com/docs/advanced/commands). 24 | 25 | ### Compile all contracts to obtain ABI and bytecode: 26 | 27 | ```bash 28 | npm run compile 29 | ``` 30 | 31 | ### Migrate all contracts required for the basic framework onto network associated with RPC provider: 32 | 33 | ```bash 34 | npm run migrate 35 | ``` 36 | Network Artifacts 37 | ----------------- 38 | 39 | ### Show the deployed addresses of all contracts on all networks: 40 | 41 | ```bash 42 | npm run networks 43 | ``` 44 | 45 | Testing 46 | ------------------- 47 | ### Run all tests (requires Node version >=8 for `async/await`, and will automatically run TestRPC in the background): 48 | 49 | ```bash 50 | npm test 51 | ``` 52 | 53 | Test Coverage 54 | ------------------- 55 | ### Get test coverage stats(requires Node version >=8 for `async/await`, and will automatically run TestRPC in the background): 56 | 57 | ```bash 58 | npm run coverage 59 | ``` 60 | -------------------------------------------------------------------------------- /truffle-config.js: -------------------------------------------------------------------------------- 1 | const HDWalletProvider = require("truffle-hdwallet-provider"); 2 | 3 | require('dotenv').config() // Store environment-specific variable from '.env' to process.env 4 | 5 | require('chai/register-should'); 6 | 7 | module.exports = { 8 | networks: { 9 | development: { 10 | host: "localhost", 11 | port: 8545, 12 | network_id: "*" 13 | }, 14 | rinkeby: { 15 | provider: () => new HDWalletProvider(process.env.PK, "https://rinkeby.infura.io/v3/" + process.env.INFURA_API_KEY), 16 | port: 8545, 17 | network_id: "4", 18 | gas: 7000000, 19 | gasPrice: 40000000000 20 | }, 21 | mainnet: { 22 | provider: () => new HDWalletProvider(process.env.PK, "https://mainnet.infura.io/v3/" + process.env.INFURA_API_KEY), 23 | port: 8545, 24 | network_id: "1", 25 | gas: 6000000, 26 | gasPrice: 10000000000 27 | }, 28 | ropsten: { 29 | provider: () => new HDWalletProvider(process.env.PK, "https://ropsten.infura.io/v3/" + process.env.INFURA_API_KEY), 30 | port: 8545, 31 | network_id: "3", 32 | gas: 7000000, 33 | gasPrice: 40000000000 34 | }, 35 | rinkebyLocal: { 36 | host: "localhost", 37 | port: 8545, 38 | network_id: "4", // Rinkeby network id 39 | from:"0x1e09a22f24d8fd302b2028a688658e9b29551969" 40 | }, 41 | coverage: { 42 | host: "localhost", 43 | network_id: "*", 44 | port: 8545, // <-- If you change this, also set the port option in .solcover.js. 45 | gas: 0xfffffffffff, // <-- Use this high gas value 46 | gasPrice: 0x01 // <-- Use this low gas price 47 | }, 48 | }, 49 | compilers: { 50 | solc: { 51 | version: "0.5.15", 52 | settings: { 53 | optimizer: { 54 | enabled: true, 55 | runs: 200 // Optimize for how many times you intend to run the code 56 | } 57 | } 58 | } 59 | } 60 | }; -------------------------------------------------------------------------------- /scripts/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Exit script as soon as a command fails. 4 | set -o errexit 5 | 6 | # Executes cleanup function at script exit. 7 | trap cleanup EXIT 8 | 9 | cleanup() { 10 | # Kill the ganache instance that we started (if we started one and if it's still running). 11 | if [ -n "$ganache_pid" ] && ps -p $ganache_pid > /dev/null; then 12 | kill -9 $ganache_pid 13 | fi 14 | } 15 | 16 | if [ "$SOLIDITY_COVERAGE" = true ]; then 17 | ganache_port=8545 18 | else 19 | ganache_port=8545 20 | fi 21 | 22 | ganache_running() { 23 | nc -z localhost "$ganache_port" 24 | } 25 | 26 | start_ganache() { 27 | menomic_string="dog permit example repeat gloom defy teach pumpkin library remain scorpion skull" 28 | 29 | if [ "$SOLIDITY_COVERAGE" = true ]; then 30 | echo "Running Ganache CLI Coverage" 31 | node_modules/.bin/ganache-cli-coverage --emitFreeLogs true --allowUnlimitedContractSize true --gasLimit 0xfffffffffff --port "$ganache_port" -m "$menomic_string" -e 1000 -a 100 > /dev/null & 32 | else 33 | echo "Running Ganache" 34 | node_modules/.bin/ganache-cli --gasLimit 0xfffffffffff -m "$menomic_string" -e 1000 -a 100 -p $ganache_port > /dev/null & 35 | fi 36 | 37 | ganache_pid=$! 38 | } 39 | 40 | if ganache_running; then 41 | echo "Using existing ganache instance" 42 | 43 | else 44 | echo "Starting our own ganache instance" 45 | start_ganache 46 | 47 | while : 48 | do 49 | if ganache_running 50 | then 51 | break 52 | fi 53 | done 54 | echo "Ganache up and Running" 55 | fi 56 | 57 | if [ "$SOLC_NIGHTLY" = true ]; then 58 | echo "Downloading solc nightly" 59 | wget -q https://raw.githubusercontent.com/ethereum/solc-bin/gh-pages/bin/soljson-nightly.js -O /tmp/soljson.js && find . -name soljson.js -exec cp /tmp/soljson.js {} \; 60 | fi 61 | 62 | if [ "$SOLIDITY_COVERAGE" = true ]; then 63 | node_modules/.bin/solidity-coverage 64 | 65 | if [ "$CONTINUOUS_INTEGRATION" = true ]; then 66 | cat coverage/lcov.info | node_modules/.bin/coveralls 67 | fi 68 | else 69 | node_modules/.bin/truffle test "./contracts/test" 70 | fi 71 | -------------------------------------------------------------------------------- /audit_report_02.md: -------------------------------------------------------------------------------- 1 | 2 | # Lock finance audit report. 3 | 4 | # 1. Summary 5 | 6 | This document is a security audit report performed by [danbogd](https://github.com/danbogd), where [lock.finance](https://github.com/LockFinance/contracts/blob/master/contracts/Lock.sol) has been reviewed. 7 | 8 | # 2. In scope 9 | 10 | Сommit hash 1e7210d84746d58447939440daf5de959a82666c. 11 | 12 | - [Lock.sol](https://github.com/LockFinance/contracts/blob/1e7210d84746d58447939440daf5de959a82666c/contracts/Lock.sol). 13 | 14 | 15 | # 3. Findings 16 | 17 | In total, **4 issues** were reported including: 18 | 19 | - 0 high severity issues 20 | - 1 medium severity issues 21 | - 1 low severity issues 22 | - 1 owner privileges (ability of owner to manipulate contract, may be risky for investors). 23 | - 1 notes. 24 | 25 | No critical security issues were found. 26 | 27 | ## 3.1. There is no way to remove outdated airdrops 28 | ### Severity: medium 29 | ### Description 30 | 31 | At each claim of funds there is a calculation of airdrops. This occurs in a loop and can cause the throw of transaction if array of airdrops will be huge. In case of Ethereum an amount of airdrops can be really huge. But there is no way in this contract to remove outdated airdrops from array to prevent this. This can lead to the blocking of funds without the ability to return them. 32 | 33 | ### Code snippet 34 | 35 | https://github.com/LockFinance/contracts/blob/1e7210d84746d58447939440daf5de959a82666c/contracts/Lock.sol#L816-L839 36 | 37 | 38 | ```js 39 | function _claimAirdroppedTokens( 40 | address baseToken, 41 | uint256 lockDate, 42 | uint256 amount 43 | ) 44 | private 45 | { 46 | //This loop can be very costly if number of airdropped tokens 47 | //for base token is very large. But we assume that it is not going to be the case 48 | for(uint256 i = 0; i < _baseTokenVsAirdrops[baseToken].length; i++) { 49 | 50 | Airdrop memory airdrop = _baseTokenVsAirdrops[baseToken][i]; 51 | 52 | if(airdrop.date < lockDate || airdrop.date > block.timestamp) { 53 | return; 54 | } 55 | else { 56 | uint256 airdropAmount = amount.mul(airdrop.numerator).div(airdrop.denominator); 57 | IERC20(airdrop.destToken).safeTransfer(msg.sender, airdropAmount); 58 | emit TokensAirdropped(airdrop.destToken, airdropAmount); 59 | } 60 | } 61 | 62 | } 63 | ``` 64 | ### Recommendation 65 | 66 | Add the mechanism that allows to remove outdated airdrops from the mapping `_baseTokenVsAirdrops`. 67 | 68 | 69 | ## 3.2. Owner Privileges 70 | 71 | ### Severity: owner previliges 72 | 73 | ### Description 74 | 75 | 76 | - The owner can set any value of fee up to 100%. 77 | 78 | ```js 79 | 80 | function setFee(uint256 fee) external onlyOwner { 81 | _fee = fee; 82 | emit FeeChanged(fee); 83 | } 84 | ``` 85 | 86 | ### Code snippet 87 | 88 | https://github.com/LockFinance/contracts/blob/1e7210d84746d58447939440daf5de959a82666c/contracts/Lock.sol#L479 89 | 90 | ### Recomendation 91 | 92 | I think that this owner previliges may be justified. About another owner actions as Emergency unlock of a token and manage token airdrops for any asset the client can get information from the official site [https://docs.lock.finance/](https://docs.lock.finance) under the section Administration. 93 | 94 | 95 | ## 3.3. Payable function without withdraw 96 | ### Severity: low 97 | ### Description 98 | 99 | `lock()` function allows to deposit Ether to the contract, but there is no way to withdraw these funds. In case if using lock of tokens but accidently sends ether is possible loss of funds. 100 | 101 | ### Code snippet 102 | 103 | https://github.com/LockFinance/contracts/blob/1e7210d84746d58447939440daf5de959a82666c/contracts/Lock.sol#L605-L660 104 | 105 | 106 | ## 3.4. It is required to limit the maximum of date argument. 107 | 108 | ### Severity: note 109 | 110 | ### Description 111 | 112 | For various reasons (accident), `date` or `duration` variable may have a large value which can lead to blocking tokens for many many years. We can not rely on the correct input data and should check it in this contract. 113 | 114 | ```js 115 | function lock( 116 | address tokenAddress, 117 | uint256 amount, 118 | uint256 duration, 119 | address payable beneficiary 120 | ) 121 | external 122 | payable 123 | whenNotPaused 124 | canLockAsset(tokenAddress) 125 | { 126 | require( 127 | beneficiary != address(0), 128 | "Lock: Provide valid beneficiary address!!" 129 | ); 130 | 131 | Token memory token = _tokens[_tokenVsIndex[tokenAddress].sub(1)]; 132 | 133 | require( 134 | amount >= token.minAmount, 135 | "Lock: Please provide minimum amount of tokens!!" 136 | ); 137 | 138 | uint256 endDate = block.timestamp.add(duration); 139 | uint256 fee = amount.mul(_fee).div(10000); 140 | uint256 newAmount = amount.sub(fee); 141 | 142 | if(ETH_ADDRESS == tokenAddress) { 143 | _lockETH( 144 | newAmount, 145 | fee, 146 | endDate, 147 | beneficiary 148 | ); 149 | } 150 | 151 | else { 152 | _lockERC20( 153 | tokenAddress, 154 | newAmount, 155 | fee, 156 | endDate, 157 | beneficiary 158 | ); 159 | } 160 | 161 | emit AssetLocked( 162 | tokenAddress, 163 | msg.sender, 164 | beneficiary, 165 | _lockId, 166 | newAmount, 167 | block.timestamp, 168 | endDate 169 | ); 170 | } 171 | 172 | ``` 173 | 174 | ```js 175 | function setAirdrop( 176 | address baseToken, 177 | address destToken, 178 | uint256 numerator, 179 | uint256 denominator, 180 | uint256 date 181 | ) 182 | external 183 | onlyOwner 184 | tokenExist(baseToken) 185 | { 186 | require(destToken != address(0), "Lock: Invalid destination token!!"); 187 | require(numerator > 0, "Lock: Invalid numerator!!"); 188 | require(denominator > 0, "Lock: Invalid denominator!!"); 189 | require(isActive(baseToken), "Lock: Base token is not active!!"); 190 | 191 | _baseTokenVsAirdrops[baseToken].push(Airdrop({ 192 | destToken: destToken, 193 | numerator: numerator, 194 | denominator: denominator, 195 | date: date 196 | })); 197 | 198 | emit AirdropAdded( 199 | baseToken, 200 | destToken, 201 | date 202 | ); 203 | } 204 | ``` 205 | ### Code snippet 206 | 207 | https://github.com/LockFinance/contracts/blob/1e7210d84746d58447939440daf5de959a82666c/contracts/Lock.sol#L413-L441 208 | 209 | https://github.com/LockFinance/contracts/blob/1e7210d84746d58447939440daf5de959a82666c/contracts/Lock.sol#L605-L660 210 | 211 | 212 | ## 4. Conclusion 213 | 214 | The review did not show any critical issues, some of medium and low severity issues were found. 215 | 216 | 217 | -------------------------------------------------------------------------------- /audit_report_01.md: -------------------------------------------------------------------------------- 1 | # Disclaimer 2 | 3 | THE CONTENT OF THIS AUDIT REPORT IS PROVIDED "AS IS", WITHOUT REPRESENTATIONS AND WARRANTIES OF ANY KIND. 4 | 5 | THE AUTHOR AND HIS EMPLOYER DISCLAIM ANY LIABILITY FOR DAMAGE ARISING OUT OF, OR IN CONNECTION WITH, THIS AUDIT REPORT. 6 | 7 | COPYRIGHT OF THIS REPORT REMAINS WITH THE AUTHOR. 8 | 9 | # Introduction 10 | 11 | ## Purpose of this Report 12 | 13 | Cryptonics Consulting has been engaged to perform an audit of smart contract for the Lock project ([https://lock.finance/](https://lock.finance/)). 14 | 15 | The objectives of the audit are as follows: 16 | 17 | 1. Determine correct functioning of the contract, in accordance with the project specification. 18 | 2. Determine possible vulnerabilities, which could be exploited by an attacker. 19 | 3. Determine contract bugs, which might lead to unexpected behavior. 20 | 4. Analyze, whether best practices have been applied during development. 21 | 5. Make recommendations to improve code safety and readability. 22 | 23 | This report represents the summary of the findings. 24 | 25 | As with any code audit, there is a limit to which vulnerabilities can be found, and unexpected execution paths may still be possible. The author of this report does not guarantee complete coverage (see disclaimer). 26 | 27 | ## Codebase Submitted To The audit 28 | 29 | The smart contract code has been provided by the developers in form of public GitHub repository: 30 | 31 | [https://github.com/LockFinance/contracts](https://github.com/LockFinance/contracts) 32 | 33 | The commit number reviewed for this audit was: 1e7210d84746d58447939440daf5de959a82666c 34 | 35 | ## Methodology 36 | 37 | The audit has been performed in the following steps: 38 | 39 | 1. Gaining an understanding of the contract's intended purpose by reading the available documentation. 40 | 2. Automated scanning of the contract with static code analysis tools for security vulnerabilities and use of best practice guidelines. 41 | 3. Manual line by line analysis of the contracts source code for security vulnerabilities and use of best practice guidelines, including but not limited to: 42 | - Reentrancy analysis 43 | - Race condition analysis 44 | - Front-running issues and transaction order dependencies 45 | - Time dependencies 46 | - Under- / overflow issues 47 | - Function visibility Issues 48 | - Possible denial of service attacks 49 | - Storage Layout Vulnerabilities 50 | 4. Report preparation 51 | 52 | # Smart Contract Overview 53 | 54 | The submitted smart contract implements an asset vault, that allows smart Ether and ERC-20 tokens to be timelocked into the smart contract. It also provides airdrop facilities associated with locked assets. 55 | 56 | The full functionality is documented on the project's website: [https://docs.lock.finance/](https://docs.lock.finance/). 57 | 58 | 59 | 60 | 61 | 62 | # Summary of Findings 63 | 64 | The contract provided for this audit is of very good quality. 65 | 66 | Community audited code seems to have been reused whenever possible. A safe math library is used to prevent overflow and underflow issues. 67 | 68 | No reentrancy attack vectors have been found and precautions have been taken to avoid transaction ordering issues. 69 | 70 | The overall design of the contract ensures that the only external calls that are performed are to contracts (ERC-20 tokens) explicitly authorized by the contract owner. 71 | 72 | Two minor issues have been noted (see below). 73 | 74 | Gas usage is reasonable for this type of contract. 75 | 76 | 77 | 78 | # Issues Encountered 79 | 80 | ## Critical Issues 81 | 82 | No minor issues have been found. 83 | 84 | ## Major Issues 85 | 86 | No major issues have been found. 87 | 88 | ## Minor Issues 89 | 90 | ### Use of Transfer() NOt Recommended Anymore 91 | 92 | The contract uses the **transfer()** function to transfer ETH in several places. This used to be considered good practice, in order to avoid reentrancy vulnerabilities. 93 | 94 | However, since the recent Istanbul protocol update, gas costs for certain operations have changed, meaning that the 2300 gas forwarded by transfer may not be sufficient for smart contract-based wallets to receive ETH. Using **transfer()** is therefore not recommended anymore, since it may cause transfers to revert, when smart contracts are involved. 95 | 96 | Most best practice guidelines have recently been updated in light of this change. See: 97 | 98 | [https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/](https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/) 99 | 100 | [https://consensys.github.io/smart-contract-best-practices/recommendations/#avoid-transfer-and-send](https://consensys.github.io/smart-contract-best-practices/recommendations/#avoid-transfer-and-send) 101 | 102 | It therefore recommended to replace the **transfer()** calls with **call.value()**. 103 | 104 | Note: To implement this recommendation safely, all ETH transfers should be moved to after state changes have been performed, in order to guard against reentrancy vulnerabilities. 105 | 106 | **UPDATE: The team has addressed this issue by replacing all transfer() calls with call.value().** 107 | 108 | ### AirDrop Arrays may Grow to Large and Cause Block Gas Limit Issues 109 | 110 | The functions **getAirdrops()** and **\_claimAirdroppedTokens()** loop over airdrop arrays. Should these arrays grow too large, these transactions will revert because of the block gas limit. 111 | 112 | This issue is mitigated by the fact that airdrops can only be added by the contract's owner and can therefore not be exploited for a DoS style attack. However, since there is no way to remove an airdrop, it would be impossible for the contract owner to fix the issue should the array grow too large accidentally. 113 | 114 | For extra safety, an airdrop removal method should be considered. 115 | 116 | **UPDATE: The team is aware of this issue and will ensure off-chain that these arrays don not grow too large, since there is no risk of malicious or accidental exploitation by a user.** 117 | 118 | 119 | 120 | # Security Audit Breakdown 121 | 122 | ## Reentrancy and Race Conditions REsistance 123 | 124 | ### Description 125 | 126 | Reentrancy vulnerabilities consist in unexpected behavior, if a function is called various times before execution has completed. This may happen when calls to external contracts are made. 127 | 128 | The following function, which can be used to withdraw the total balance of the caller from a contract is an example of reentrancy vulnerability: 129 | 130 | ``` 131 | mapping(address => uint) private balances; 132 | 133 | function payOut() { 134 | 135 | require(msg.sender.call.value(balances[msg.sender])()); 136 | balances[msg.sender] = 0; 137 | 138 | } 139 | ``` 140 | 141 | The _call.value() _invocation causes contract external code to be executed. If the caller is another contract, this means that the contracts fallback method is executed. This may call _payOut() _again, before the balance is set to 0, thereby obtaining more funds than available. 142 | 143 | ### Audit Result 144 | 145 | **No reentrancy issues have been found in the contract. However, care must be taken not to introduce reentrancy vulnerabilities when fixing the first minor issue reported above.** 146 | 147 | ## Under-/Overflow Protection 148 | 149 | ### Description 150 | 151 | Balances are usually represented by unsigned integers, typically 256-bit numbers in Solidity. When unsigned integers overflow or underflow, their value changes dramatically. Let's look at the following example of a more common underflow (numbers shortened for readability): 152 | 153 | 0x0003 - 0x0004 = 0xFFFF 154 | 155 | It's easy to see the issue here. Subtracting 1 more than available balance causes an underflow. The resulting balance is now a large number. 156 | 157 | Also note, that in integer arithmetic division is troublesome, due to rounding errors. 158 | 159 | ### Audit Result 160 | 161 | **The contracts avoid overflow and underflow issues by employing a safe math library for all arithmetic operations.** 162 | 163 | ## Transaction Ordering Assumptions 164 | 165 | ### Description 166 | 167 | Transactions enter a pool of unconfirmed transactions and maybe included in blocks by miners in any order, depending on the miner's transaction selection criteria, which is probably some algorithm aimed at achieving maximum earnings from transaction fees, but could be anything. Hence, the order of transactions being included can be completely different to the order in which they are generated. Therefore, contract code cannot make any assumptions on transaction order. 168 | 169 | Apart from unexpected results in contract execution, there is a possible attack vector in this, as transactions are visible in the mempool and their execution can be predicted. This maybe an issue in trading, where delaying a transaction may be used for personal advantage by a rogue miner. In fact, simply being aware of certain transactions before they are executed can be used as advantage by anyone, not just miners. 170 | 171 | ### Audit Result 172 | 173 | **Transactions are kept as simple as possible and care has been taken not to assume a specific order of invocation.** 174 | 175 | ## Timestamp Dependencies 176 | 177 | ### DEscription 178 | 179 | Timestamps are generated by the miners. Therefore, no contract should rely on the block timestamp for critical operations, such as using it as a seed for random number generation. [Consensys](https://new.consensys.net/) give a 15 seconds rule their [guidelines](https://consensys.github.io/smart-contract-best-practices/recommendations/#timestamp-dependence), which states that it is safe to use _block.timestamp,_ if your time depending code can deal with a 15 second variation. 180 | 181 | ### Audit Result 182 | 183 | **Although the block timestamp is used in various places, the specific uses are able to tolerate 15 second variations.** 184 | 185 | ## Denial of Service Attack Prevention 186 | 187 | ### Description 188 | 189 | Denial of Service attacks can occur when a transaction depends on the outcome of an external call. A typical example of this some activity to be carried out after an Ether transfer. If the receiver is another contract, it can reject the transfer causing the whole transaction to fail. 190 | 191 | ### Audit Result 192 | 193 | **The contracts avoid DoS attacks of this type.** 194 | 195 | ## Block Gas Limit 196 | 197 | ### Description 198 | 199 | Contract transactions can sometimes be forced to always fails by making them exceed the maximum amount of gas that can be included in a block. The classic example of this is explained in [this explanation](https://consensys.github.io/smart-contract-best-practices/known_attacks/#dos-with-block-gas-limit) of an auction contract. Forcing the contract to refund many small bids, which are not accepted, will bump up the gas used and, if this exceeds the block gas limit, the whole transaction will fail. 200 | 201 | The solution to this problem is avoiding situations in which many transaction calls can be caused by the same function invocation, especially if the number of calls can be influenced externally. 202 | 203 | ### Audit result 204 | 205 | **The contracts have no block gas limit issues that could be exploited for denial of service scenarios by external user. To avoid this, certain loops over various-sized arrays are broken up into smaller iterations.** 206 | 207 | **However, there may be accidental block gas limit issues with a large number of airdrops being registered by the contract owner (see issue description above).** 208 | 209 | ## Community Audited Code 210 | 211 | ### Description 212 | 213 | It always best to re-use community audited code when available, such as the [code provided by Open Zeppelin](https://github.com/OpenZeppelin/openzeppelin-contracts). 214 | 215 | ### Audit Result 216 | 217 | **The contracts uses the Open Zeppelin provided code extensively: (**[**https://github.com/OpenZeppelin/openzeppelin-contracts**](https://github.com/OpenZeppelin/openzeppelin-contracts)**).** 218 | 219 | 220 | 221 | # Gas Usage Analysis 222 | 223 | ### Description 224 | 225 | Gas usage of smart contracts is very important. Gas is charged for each operation that alters state, i.e. a write transaction. In contrast, read-only queries can be processed by local nodes and therefore do not have an associated cost. 226 | 227 | Excessive gas usage may make contracts unusable in practice, in particular in times of network congestion when the gas price has to be increased to incentivize miners to prioritize transactions. 228 | 229 | Furthermore, issues with excessive gas usage can lead to exceeding the block gas limit preventing transactions from completing. This is particularly dangerous in the case of executing code in unbounded loops, for example iterating over a variable size array. If the size of the array can be influenced by a public contract call, this can be used to create Denial of Service Attacks. 230 | 231 | For these reasons, the present smart contract audit includes a gas usage analysis performed in two steps: 232 | 233 | 1. The code has been analyzed using automated gas estimation tools that return a relatively accurate estimate of the gas usage of each function. 234 | 2. As automated, gas estimation has its limits, a manual line by line analysis for gas related issues has also been performed. 235 | 236 | ### Audit Result 237 | 238 | It is obvious that care has been taken to implement all functions as compact and gas efficiently as possible. 239 | 240 | In general, gas usage is very reasonable. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /contracts/Lock.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.5.15; 2 | 3 | import "openzeppelin-solidity/contracts/math/SafeMath.sol"; 4 | import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; 5 | import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; 6 | import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; 7 | 8 | 9 | /** 10 | * @dev This contract will hold user locked funds which will be unlocked after 11 | * lock-up period ends 12 | */ 13 | contract Lock is Ownable { 14 | using SafeERC20 for IERC20; 15 | using SafeMath for uint256; 16 | 17 | enum Status { _, OPEN, CLOSED } 18 | enum TokenStatus {_, ACTIVE, INACTIVE } 19 | 20 | struct Token { 21 | address tokenAddress; 22 | uint256 minAmount; 23 | bool emergencyUnlock; 24 | TokenStatus status; 25 | uint256[] tierAmounts; 26 | uint256[] tierFees; 27 | } 28 | 29 | Token[] private _tokens; 30 | 31 | IERC20 private _lockToken; 32 | 33 | //Fee per lock in lock token 34 | uint256 private _lockTokenFee; 35 | 36 | //Keeps track of token index in above array 37 | mapping(address => uint256) private _tokenVsIndex; 38 | 39 | //Wallet where fees will go 40 | address payable private _wallet; 41 | 42 | address constant private ETH_ADDRESS = address( 43 | 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE 44 | ); 45 | 46 | struct LockedAsset { 47 | address token;// Token address 48 | uint256 amount;// Amount locked 49 | uint256 startDate;// Start date. We can remove this later 50 | uint256 endDate; 51 | uint256 lastLocked; 52 | //Amount threshold after a locked asset can be unlocked 53 | uint256 amountThreshold; 54 | address payable beneficiary;// Beneficary who will receive funds 55 | Status status; 56 | } 57 | 58 | struct Airdrop { 59 | address destToken; 60 | //numerator and denominator will be used to calculate ratio 61 | //Example 1DAI will get you 4 SAI 62 | //which means numerator = 4 and denominator = 1 63 | uint256 numerator; 64 | uint256 denominator; 65 | uint256 date;// Date at which time this entry was made 66 | //Only those locked asset which were locked before this date will be 67 | //given airdropped tokens 68 | } 69 | 70 | //Mapping of base token versus airdropped token 71 | mapping(address => Airdrop[]) private _baseTokenVsAirdrops; 72 | 73 | //Global lockedasset id. Also give total number of lock-ups made so far 74 | uint256 private _lockId; 75 | 76 | //list of all asset ids for a user/beneficiary 77 | mapping(address => uint256[]) private _userVsLockIds; 78 | 79 | mapping(uint256 => LockedAsset) private _idVsLockedAsset; 80 | 81 | bool private _paused; 82 | 83 | event TokenAdded(address indexed token); 84 | event TokenInactivated(address indexed token); 85 | event TokenActivated(address indexed token); 86 | event WalletChanged(address indexed wallet); 87 | event AssetLocked( 88 | address indexed token, 89 | address indexed sender, 90 | address indexed beneficiary, 91 | uint256 id, 92 | uint256 amount, 93 | uint256 startDate, 94 | uint256 endDate, 95 | bool lockTokenFee, 96 | uint256 fee 97 | ); 98 | event TokenUpdated( 99 | uint256 indexed id, 100 | address indexed token, 101 | uint256 minAmount, 102 | bool emergencyUnlock, 103 | uint256[] tierAmounts, 104 | uint256[] tierFees 105 | ); 106 | event Paused(); 107 | event Unpaused(); 108 | 109 | event AssetClaimed( 110 | uint256 indexed id, 111 | address indexed beneficiary, 112 | address indexed token 113 | ); 114 | 115 | event AirdropAdded( 116 | address indexed baseToken, 117 | address indexed destToken, 118 | uint256 index, 119 | uint256 airdropDate, 120 | uint256 numerator, 121 | uint256 denominator 122 | ); 123 | 124 | event AirdropUpdated( 125 | address indexed baseToken, 126 | address indexed destToken, 127 | uint256 index, 128 | uint256 airdropDate, 129 | uint256 numerator, 130 | uint256 denominator 131 | ); 132 | 133 | event TokensAirdropped( 134 | address indexed destToken, 135 | uint256 amount 136 | ); 137 | 138 | event LockTokenUpdated(address indexed lockTokenAddress); 139 | event LockTokenFeeUpdated(uint256 fee); 140 | 141 | event AmountAdded(address indexed beneficiary, uint256 id, uint256 amount); 142 | 143 | modifier tokenExist(address token) { 144 | require(_tokenVsIndex[token] > 0, "Lock: Token does not exist!!"); 145 | _; 146 | } 147 | 148 | modifier tokenDoesNotExist(address token) { 149 | require(_tokenVsIndex[token] == 0, "Lock: Token already exist!!"); 150 | _; 151 | } 152 | 153 | modifier canLockAsset(address token) { 154 | uint256 index = _tokenVsIndex[token]; 155 | 156 | require(index > 0, "Lock: Token does not exist!!"); 157 | 158 | require( 159 | _tokens[index.sub(1)].status == TokenStatus.ACTIVE, 160 | "Lock: Token not active!!" 161 | ); 162 | 163 | require( 164 | !_tokens[index.sub(1)].emergencyUnlock, 165 | "Lock: Token is in emergency unlock state!!" 166 | ); 167 | _; 168 | } 169 | 170 | modifier canClaim(uint256 id) { 171 | 172 | require(claimable(id), "Lock: Can't claim asset"); 173 | 174 | require( 175 | _idVsLockedAsset[id].beneficiary == msg.sender, 176 | "Lock: Unauthorized access!!" 177 | ); 178 | _; 179 | } 180 | 181 | /** 182 | * @dev Modifier to make a function callable only when the contract is not paused. 183 | */ 184 | modifier whenNotPaused() { 185 | require(!_paused, "Lock: paused"); 186 | _; 187 | } 188 | 189 | /** 190 | * @dev Modifier to make a function callable only when the contract is paused. 191 | */ 192 | modifier whenPaused() { 193 | require(_paused, "Lock: not paused"); 194 | _; 195 | } 196 | 197 | /** 198 | * @dev Constructor 199 | * @param wallet Wallet address where fees will go 200 | * @param lockTokenAddress Address of the lock token 201 | * @param lockTokenFee Fee for each lock in lock token 202 | */ 203 | constructor( 204 | address payable wallet, 205 | address lockTokenAddress, 206 | uint256 lockTokenFee 207 | ) 208 | public 209 | { 210 | require( 211 | wallet != address(0), 212 | "Lock: Please provide valid wallet address!!" 213 | ); 214 | require( 215 | lockTokenAddress != address(0), 216 | "Lock: Invalid lock token address" 217 | ); 218 | _lockToken = IERC20(lockTokenAddress); 219 | _wallet = wallet; 220 | _lockTokenFee = lockTokenFee; 221 | } 222 | 223 | /** 224 | * @dev Returns true if the contract is paused, and false otherwise. 225 | */ 226 | function paused() external view returns (bool) { 227 | return _paused; 228 | } 229 | 230 | /** 231 | * @dev returns the fee receiver wallet address 232 | */ 233 | function getWallet() external view returns(address) { 234 | return _wallet; 235 | } 236 | 237 | /** 238 | * @dev Returns total token count 239 | */ 240 | function getTokenCount() external view returns(uint256) { 241 | return _tokens.length; 242 | } 243 | 244 | /** 245 | * @dev Returns lock token address 246 | */ 247 | function getLockToken() external view returns(address) { 248 | return address(_lockToken); 249 | } 250 | 251 | /** 252 | * @dev Returns fee per lock in lock token 253 | */ 254 | function getLockTokenFee() external view returns(uint256) { 255 | return _lockTokenFee; 256 | } 257 | 258 | /** 259 | * @dev Returns list of supported tokens 260 | * This will be a paginated method which will only send 15 tokens in one request 261 | * This is done to prevent infinite loops and overflow of gas limits 262 | * @param start start index for pagination 263 | * @param length Amount of tokens to fetch 264 | */ 265 | function getTokens(uint256 start, uint256 length) external view returns( 266 | address[] memory tokenAddresses, 267 | uint256[] memory minAmounts, 268 | bool[] memory emergencyUnlocks, 269 | TokenStatus[] memory statuses 270 | ) 271 | { 272 | tokenAddresses = new address[](length); 273 | minAmounts = new uint256[](length); 274 | emergencyUnlocks = new bool[](length); 275 | statuses = new TokenStatus[](length); 276 | 277 | require(start.add(length) <= _tokens.length, "Lock: Invalid input"); 278 | require(length > 0 && length <= 15, "Lock: Invalid length"); 279 | uint256 count = 0; 280 | for(uint256 i = start; i < start.add(length); i++) { 281 | tokenAddresses[count] = _tokens[i].tokenAddress; 282 | minAmounts[count] = _tokens[i].minAmount; 283 | emergencyUnlocks[count] = _tokens[i].emergencyUnlock; 284 | statuses[count] = _tokens[i].status; 285 | count = count.add(1); 286 | } 287 | 288 | return( 289 | tokenAddresses, 290 | minAmounts, 291 | emergencyUnlocks, 292 | statuses 293 | ); 294 | } 295 | 296 | /** 297 | * @dev Returns information about specific token 298 | * @dev tokenAddress Address of the token 299 | */ 300 | function getTokenInfo(address tokenAddress) external view returns( 301 | uint256 minAmount, 302 | bool emergencyUnlock, 303 | TokenStatus status, 304 | uint256[] memory tierAmounts, 305 | uint256[] memory tierFees 306 | ) 307 | { 308 | uint256 index = _tokenVsIndex[tokenAddress]; 309 | 310 | if(index > 0){ 311 | index = index.sub(1); 312 | Token memory token = _tokens[index]; 313 | return ( 314 | token.minAmount, 315 | token.emergencyUnlock, 316 | token.status, 317 | token.tierAmounts, 318 | token.tierFees 319 | ); 320 | } 321 | } 322 | 323 | /** 324 | * @dev Returns information about a locked asset 325 | * @param id Asset id 326 | */ 327 | function getLockedAsset(uint256 id) external view returns( 328 | address token, 329 | uint256 amount, 330 | uint256 startDate, 331 | uint256 endDate, 332 | uint256 lastLocked, 333 | address beneficiary, 334 | Status status, 335 | uint256 amountThreshold 336 | ) 337 | { 338 | LockedAsset memory asset = _idVsLockedAsset[id]; 339 | token = asset.token; 340 | amount = asset.amount; 341 | startDate = asset.startDate; 342 | endDate = asset.endDate; 343 | beneficiary = asset.beneficiary; 344 | status = asset.status; 345 | amountThreshold = asset.amountThreshold; 346 | lastLocked = asset.lastLocked; 347 | 348 | return( 349 | token, 350 | amount, 351 | startDate, 352 | endDate, 353 | lastLocked, 354 | beneficiary, 355 | status, 356 | amountThreshold 357 | ); 358 | } 359 | 360 | /** 361 | * @dev Returns all asset ids for a user 362 | * @param user Address of the user 363 | */ 364 | function getAssetIds( 365 | address user 366 | ) 367 | external 368 | view 369 | returns (uint256[] memory ids) 370 | { 371 | return _userVsLockIds[user]; 372 | } 373 | 374 | /** 375 | * @dev Returns airdrop info for a given token 376 | * @param token Token address 377 | */ 378 | function getAirdrops(address token) external view returns( 379 | address[] memory destTokens, 380 | uint256[] memory numerators, 381 | uint256[] memory denominators, 382 | uint256[] memory dates 383 | ) 384 | { 385 | uint256 length = _baseTokenVsAirdrops[token].length; 386 | 387 | destTokens = new address[](length); 388 | numerators = new uint256[](length); 389 | denominators = new uint256[](length); 390 | dates = new uint256[](length); 391 | 392 | //This loop can be very costly if there are very large number of airdrops for a token. 393 | //Which we presume will not be the case 394 | for(uint256 i = 0; i < length; i++){ 395 | 396 | Airdrop memory airdrop = _baseTokenVsAirdrops[token][i]; 397 | destTokens[i] = airdrop.destToken; 398 | numerators[i] = airdrop.numerator; 399 | denominators[i] = airdrop.denominator; 400 | dates[i] = airdrop.date; 401 | } 402 | 403 | return ( 404 | destTokens, 405 | numerators, 406 | denominators, 407 | dates 408 | ); 409 | } 410 | 411 | /** 412 | * @dev Returns specific airdrop for a base token 413 | * @param token Base token address 414 | * @param index Index at which this airdrop is in array 415 | */ 416 | function getAirdrop(address token, uint256 index) external view returns( 417 | address destToken, 418 | uint256 numerator, 419 | uint256 denominator, 420 | uint256 date 421 | ) 422 | { 423 | return ( 424 | _baseTokenVsAirdrops[token][index].destToken, 425 | _baseTokenVsAirdrops[token][index].numerator, 426 | _baseTokenVsAirdrops[token][index].denominator, 427 | _baseTokenVsAirdrops[token][index].date 428 | ); 429 | } 430 | 431 | /** 432 | * @dev Called by an admin to pause, triggers stopped state. 433 | */ 434 | function pause() external onlyOwner whenNotPaused { 435 | _paused = true; 436 | emit Paused(); 437 | } 438 | 439 | /** 440 | * @dev Called by an admin to unpause, returns to normal state. 441 | */ 442 | function unpause() external onlyOwner whenPaused { 443 | _paused = false; 444 | emit Unpaused(); 445 | } 446 | 447 | /** 448 | * @dev Allows admin to set airdrop token for a given base token 449 | * @param baseToken Address of the base token 450 | * @param destToken Address of the airdropped token 451 | * @param numerator Numerator to calculate ratio 452 | * @param denominator Denominator to calculate ratio 453 | * @param date Date at which airdrop happened or will happen 454 | */ 455 | function setAirdrop( 456 | address baseToken, 457 | address destToken, 458 | uint256 numerator, 459 | uint256 denominator, 460 | uint256 date 461 | ) 462 | external 463 | onlyOwner 464 | tokenExist(baseToken) 465 | { 466 | require(destToken != address(0), "Lock: Invalid destination token!!"); 467 | require(numerator > 0, "Lock: Invalid numerator!!"); 468 | require(denominator > 0, "Lock: Invalid denominator!!"); 469 | require(isActive(baseToken), "Lock: Base token is not active!!"); 470 | 471 | _baseTokenVsAirdrops[baseToken].push(Airdrop({ 472 | destToken: destToken, 473 | numerator: numerator, 474 | denominator: denominator, 475 | date: date 476 | })); 477 | 478 | emit AirdropAdded( 479 | baseToken, 480 | destToken, 481 | _baseTokenVsAirdrops[baseToken].length.sub(1), 482 | date, 483 | numerator, 484 | denominator 485 | ); 486 | } 487 | 488 | /** 489 | * @dev Update lock token address 490 | * @param lockTokenAddress New lock token address 491 | */ 492 | function updateLockToken(address lockTokenAddress) external onlyOwner { 493 | require( 494 | lockTokenAddress != address(0), 495 | "Lock: Invalid lock token address" 496 | ); 497 | _lockToken = IERC20(lockTokenAddress); 498 | emit LockTokenUpdated(lockTokenAddress); 499 | } 500 | 501 | /** 502 | * @dev Update fee in lock token 503 | * @param lockTokenFee Fee per lock in lock token 504 | */ 505 | function updateLockTokenFee(uint256 lockTokenFee) external onlyOwner { 506 | _lockTokenFee = lockTokenFee; 507 | emit LockTokenFeeUpdated(lockTokenFee); 508 | } 509 | 510 | /** 511 | * @dev Allows admin to update airdrop at given index 512 | * @param baseToken Base token address for which airdrop has to be updated 513 | * @param numerator New numerator 514 | * @param denominator New denominator 515 | * @param date New airdrop date 516 | * @param index Index at which this airdrop resides for the basetoken 517 | */ 518 | function updateAirdrop( 519 | address baseToken, 520 | uint256 numerator, 521 | uint256 denominator, 522 | uint256 date, 523 | uint256 index 524 | ) 525 | external 526 | onlyOwner 527 | { 528 | require( 529 | _baseTokenVsAirdrops[baseToken].length > index, 530 | "Lock: Invalid index value!!" 531 | ); 532 | require(numerator > 0, "Lock: Invalid numerator!!"); 533 | require(denominator > 0, "Lock: Invalid denominator!!"); 534 | 535 | Airdrop storage airdrop = _baseTokenVsAirdrops[baseToken][index]; 536 | airdrop.numerator = numerator; 537 | airdrop.denominator = denominator; 538 | airdrop.date = date; 539 | 540 | emit AirdropUpdated( 541 | baseToken, 542 | airdrop.destToken, 543 | index, 544 | date, 545 | numerator, 546 | denominator 547 | ); 548 | } 549 | 550 | /** 551 | * @dev Allows admin to set fee receiver wallet 552 | * @param wallet New wallet address 553 | */ 554 | function setWallet(address payable wallet) external onlyOwner { 555 | require( 556 | wallet != address(0), 557 | "Lock: Please provider valid wallet address!!" 558 | ); 559 | _wallet = wallet; 560 | 561 | emit WalletChanged(wallet); 562 | } 563 | 564 | /** 565 | * @dev Allows admin to update token info 566 | * @param tokenAddress Address of the token to be updated 567 | * @param minAmount Min amount of tokens required to lock 568 | * @param emergencyUnlock If token is in emergency unlock state 569 | * @param tierAmounts Threshold amount for chargin fee 570 | * @param tierFees Fees for each tier 571 | */ 572 | function updateToken( 573 | address tokenAddress, 574 | uint256 minAmount, 575 | bool emergencyUnlock, 576 | uint256[] calldata tierAmounts, 577 | uint256[] calldata tierFees 578 | ) 579 | external 580 | onlyOwner 581 | tokenExist(tokenAddress) 582 | { 583 | require( 584 | tierAmounts.length == tierFees.length, 585 | "Lock: Tiers does not match" 586 | ); 587 | 588 | uint256 index = _tokenVsIndex[tokenAddress].sub(1); 589 | Token storage token = _tokens[index]; 590 | token.minAmount = minAmount; 591 | token.emergencyUnlock = emergencyUnlock; 592 | token.tierAmounts = tierAmounts; 593 | token.tierFees = tierFees; 594 | emit TokenUpdated( 595 | index, 596 | tokenAddress, 597 | minAmount, 598 | emergencyUnlock, 599 | tierAmounts, 600 | tierFees 601 | ); 602 | } 603 | 604 | /** 605 | * @dev Allows admin to add new token to the list 606 | * @param token Address of the token 607 | * @param minAmount Minimum amount of tokens to lock for this token 608 | * @param tierAmounts Threshold amount for chargin fee 609 | * @param tierFees Fees for each tier 610 | */ 611 | function addToken( 612 | address token, 613 | uint256 minAmount, 614 | uint256[] calldata tierAmounts, 615 | uint256[] calldata tierFees 616 | ) 617 | external 618 | onlyOwner 619 | tokenDoesNotExist(token) 620 | { 621 | require( 622 | tierAmounts.length == tierFees.length, 623 | "Lock: Tiers does not match" 624 | ); 625 | 626 | _tokens.push(Token({ 627 | tokenAddress: token, 628 | minAmount: minAmount, 629 | emergencyUnlock: false, 630 | status: TokenStatus.ACTIVE, 631 | tierAmounts: tierAmounts, 632 | tierFees: tierFees 633 | })); 634 | _tokenVsIndex[token] = _tokens.length; 635 | 636 | emit TokenAdded(token); 637 | } 638 | 639 | 640 | /** 641 | * @dev Allows admin to inactivate token 642 | * @param token Address of the token to be inactivated 643 | */ 644 | function inactivateToken( 645 | address token 646 | ) 647 | external 648 | onlyOwner 649 | tokenExist(token) 650 | { 651 | uint256 index = _tokenVsIndex[token].sub(1); 652 | 653 | require( 654 | _tokens[index].status == TokenStatus.ACTIVE, 655 | "Lock: Token already inactive!!" 656 | ); 657 | 658 | _tokens[index].status = TokenStatus.INACTIVE; 659 | 660 | emit TokenInactivated(token); 661 | } 662 | 663 | /** 664 | * @dev Allows admin to activate any existing token 665 | * @param token Address of the token to be activated 666 | */ 667 | function activateToken( 668 | address token 669 | ) 670 | external 671 | onlyOwner 672 | tokenExist(token) 673 | { 674 | uint256 index = _tokenVsIndex[token].sub(1); 675 | 676 | require( 677 | _tokens[index].status == TokenStatus.INACTIVE, 678 | "Lock: Token already active!!" 679 | ); 680 | 681 | _tokens[index].status = TokenStatus.ACTIVE; 682 | 683 | emit TokenActivated(token); 684 | } 685 | 686 | /** 687 | * @dev Allows user to lock asset. In case of ERC-20 token the user will 688 | * first have to approve the contract to spend on his/her behalf 689 | * @param tokenAddress Address of the token to be locked 690 | * @param amount Amount of tokens to lock 691 | * @param duration Duration for which tokens to be locked. In seconds 692 | * @param beneficiary Address of the beneficiary 693 | * @param amountThreshold Threshold amount which is when locked in a single lock will make that lock claimable 694 | * @param lockFee Bool to check if fee to be paid in lock token or not 695 | */ 696 | function lock( 697 | address tokenAddress, 698 | uint256 amount, 699 | uint256 duration, 700 | address payable beneficiary, 701 | uint256 amountThreshold, 702 | bool lockFee 703 | ) 704 | external 705 | payable 706 | whenNotPaused 707 | canLockAsset(tokenAddress) 708 | { 709 | uint256 remValue = _lock( 710 | tokenAddress, 711 | amount, 712 | duration, 713 | beneficiary, 714 | amountThreshold, 715 | msg.value, 716 | lockFee 717 | ); 718 | 719 | require( 720 | remValue < 10000000000, 721 | "Lock: Sent more ethers then required" 722 | ); 723 | 724 | } 725 | 726 | /** 727 | * @dev Allows user to lock asset. In case of ERC-20 token the user will 728 | * first have to approve the contract to spend on his/her behalf 729 | * @param tokenAddress Address of the token to be locked 730 | * @param amounts List of amount of tokens to lock 731 | * @param durations List of duration for which tokens to be locked. In seconds 732 | * @param beneficiaries List of addresses of the beneficiaries 733 | * @param amountThresholds List of threshold amounts which is when locked in a single lock will make that lock claimable 734 | * @param lockFee Bool to check if fee to be paid in lock token or not 735 | */ 736 | function bulkLock( 737 | address tokenAddress, 738 | uint256[] calldata amounts, 739 | uint256[] calldata durations, 740 | address payable[] calldata beneficiaries, 741 | uint256[] calldata amountThresholds, 742 | bool lockFee 743 | ) 744 | external 745 | payable 746 | whenNotPaused 747 | canLockAsset(tokenAddress) 748 | { 749 | uint256 remValue = msg.value; 750 | require(amounts.length == durations.length, "Lock: Invalid input"); 751 | require(amounts.length == beneficiaries.length, "Lock: Invalid input"); 752 | require( 753 | amounts.length == amountThresholds.length, 754 | "Lock: Invalid input" 755 | ); 756 | 757 | for(uint256 i = 0; i < amounts.length; i++){ 758 | remValue = _lock( 759 | tokenAddress, 760 | amounts[i], 761 | durations[i], 762 | beneficiaries[i], 763 | amountThresholds[i], 764 | remValue, 765 | lockFee 766 | ); 767 | } 768 | 769 | require( 770 | remValue < 10000000000, 771 | "Lock: Sent more ethers then required" 772 | ); 773 | 774 | } 775 | 776 | /** 777 | * @dev Allows beneficiary of locked asset to claim asset after lock-up period ends 778 | * @param id Id of the locked asset 779 | */ 780 | function claim(uint256 id) external canClaim(id) { 781 | LockedAsset memory lockedAsset = _idVsLockedAsset[id]; 782 | if(ETH_ADDRESS == lockedAsset.token) { 783 | _claimETH( 784 | id 785 | ); 786 | } 787 | 788 | else { 789 | _claimERC20( 790 | id 791 | ); 792 | } 793 | 794 | emit AssetClaimed( 795 | id, 796 | lockedAsset.beneficiary, 797 | lockedAsset.token 798 | ); 799 | } 800 | 801 | /** 802 | * @dev Allows anyone to add more tokens in the existing lock 803 | * @param id id of the locked asset 804 | * @param amount Amount to be added 805 | * @param lockFee Bool to check if fee to be paid in lock token or not 806 | */ 807 | function addAmount( 808 | uint256 id, 809 | uint256 amount, 810 | bool lockFee 811 | ) 812 | external 813 | payable 814 | whenNotPaused 815 | { 816 | LockedAsset storage lockedAsset = _idVsLockedAsset[id]; 817 | 818 | require(lockedAsset.status == Status.OPEN, "Lock: Lock is not open"); 819 | 820 | Token memory token = _tokens[_tokenVsIndex[lockedAsset.token].sub(1)]; 821 | 822 | //At the time of addition of tokens previous aridrops will be claimed 823 | _claimAirdroppedTokens( 824 | lockedAsset.token, 825 | lockedAsset.lastLocked, 826 | lockedAsset.amount 827 | ); 828 | 829 | 830 | uint256 fee = 0; 831 | uint256 newAmount = 0; 832 | (fee, newAmount) = _calculateFee(amount, lockFee, token); 833 | 834 | if(lockFee) { 835 | _lockToken.safeTransferFrom(msg.sender, _wallet, _lockTokenFee); 836 | } 837 | if(ETH_ADDRESS == lockedAsset.token) { 838 | require(amount == msg.value, "Lock: Insufficient value sent"); 839 | 840 | if(!lockFee) { 841 | (bool success,) = _wallet.call.value(fee)(""); 842 | require(success, "Lock: Transfer of fee failed"); 843 | } 844 | } 845 | else { 846 | if(!lockFee){ 847 | IERC20(lockedAsset.token).safeTransferFrom(msg.sender, _wallet, fee); 848 | } 849 | 850 | IERC20(lockedAsset.token).safeTransferFrom(msg.sender, address(this), newAmount); 851 | } 852 | 853 | lockedAsset.amount = lockedAsset.amount.add(newAmount); 854 | lockedAsset.lastLocked = block.timestamp; 855 | 856 | emit AmountAdded(lockedAsset.beneficiary, id, newAmount); 857 | 858 | } 859 | 860 | 861 | /** 862 | * @dev Returns whether given asset can be claimed or not 863 | * @param id id of an asset 864 | */ 865 | function claimable(uint256 id) public view returns(bool){ 866 | 867 | LockedAsset memory asset = _idVsLockedAsset[id]; 868 | if( 869 | asset.status == Status.OPEN && 870 | ( 871 | asset.endDate <= block.timestamp || 872 | _tokens[_tokenVsIndex[asset.token].sub(1)].emergencyUnlock || 873 | (asset.amountThreshold > 0 && asset.amount >= asset.amountThreshold) 874 | ) 875 | ) 876 | { 877 | return true; 878 | } 879 | return false; 880 | } 881 | 882 | /** 883 | * @dev Returns whether provided token is active or not 884 | * @param token Address of the token to be checked 885 | */ 886 | function isActive(address token) public view returns(bool) { 887 | uint256 index = _tokenVsIndex[token]; 888 | 889 | if(index > 0){ 890 | return (_tokens[index.sub(1)].status == TokenStatus.ACTIVE); 891 | } 892 | return false; 893 | } 894 | 895 | /** 896 | * @dev Helper method to lock asset 897 | */ 898 | function _lock( 899 | address tokenAddress, 900 | uint256 amount, 901 | uint256 duration, 902 | address payable beneficiary, 903 | uint256 amountThreshold, 904 | uint256 value, 905 | bool lockFee 906 | ) 907 | private 908 | returns(uint256) 909 | { 910 | require( 911 | beneficiary != address(0), 912 | "Lock: Provide valid beneficiary address!!" 913 | ); 914 | 915 | Token memory token = _tokens[_tokenVsIndex[tokenAddress].sub(1)]; 916 | 917 | require( 918 | amount >= token.minAmount, 919 | "Lock: Please provide minimum amount of tokens!!" 920 | ); 921 | 922 | uint256 endDate = block.timestamp.add(duration); 923 | uint256 fee = 0; 924 | uint256 newAmount = 0; 925 | 926 | (fee, newAmount) = _calculateFee(amount, lockFee, token); 927 | 928 | uint256 remValue = value; 929 | 930 | if(ETH_ADDRESS == tokenAddress) { 931 | _lockETH( 932 | newAmount, 933 | fee, 934 | endDate, 935 | beneficiary, 936 | amountThreshold, 937 | value, 938 | lockFee 939 | ); 940 | 941 | remValue = remValue.sub(amount); 942 | } 943 | 944 | else { 945 | _lockERC20( 946 | tokenAddress, 947 | newAmount, 948 | fee, 949 | endDate, 950 | beneficiary, 951 | amountThreshold, 952 | lockFee 953 | ); 954 | } 955 | 956 | emit AssetLocked( 957 | tokenAddress, 958 | msg.sender, 959 | beneficiary, 960 | _lockId, 961 | newAmount, 962 | block.timestamp, 963 | endDate, 964 | lockFee, 965 | fee 966 | ); 967 | 968 | return remValue; 969 | } 970 | 971 | /** 972 | * @dev Helper method to lock ETH 973 | */ 974 | function _lockETH( 975 | uint256 amount, 976 | uint256 fee, 977 | uint256 endDate, 978 | address payable beneficiary, 979 | uint256 amountThreshold, 980 | uint256 value, 981 | bool lockFee 982 | ) 983 | private 984 | { 985 | 986 | //Transferring fee to the wallet 987 | 988 | if(lockFee){ 989 | require(value >= amount, "Lock: Enough ETH not sent!!"); 990 | _lockToken.safeTransferFrom(msg.sender, _wallet, fee); 991 | } 992 | else { 993 | require(value >= amount.add(fee), "Lock: Enough ETH not sent!!"); 994 | (bool success,) = _wallet.call.value(fee)(""); 995 | require(success, "Lock: Transfer of fee failed"); 996 | } 997 | 998 | 999 | _lockId = _lockId.add(1); 1000 | 1001 | _idVsLockedAsset[_lockId] = LockedAsset({ 1002 | token: ETH_ADDRESS, 1003 | amount: amount, 1004 | startDate: block.timestamp, 1005 | endDate: endDate, 1006 | lastLocked: block.timestamp, 1007 | beneficiary: beneficiary, 1008 | status: Status.OPEN, 1009 | amountThreshold: amountThreshold 1010 | }); 1011 | _userVsLockIds[beneficiary].push(_lockId); 1012 | } 1013 | 1014 | /** 1015 | * @dev Helper method to lock ERC-20 tokens 1016 | */ 1017 | function _lockERC20( 1018 | address token, 1019 | uint256 amount, 1020 | uint256 fee, 1021 | uint256 endDate, 1022 | address payable beneficiary, 1023 | uint256 amountThreshold, 1024 | bool lockFee 1025 | ) 1026 | private 1027 | { 1028 | 1029 | //Transfer fee to the wallet 1030 | if(lockFee){ 1031 | _lockToken.safeTransferFrom(msg.sender, _wallet, fee); 1032 | } 1033 | else { 1034 | IERC20(token).safeTransferFrom(msg.sender, _wallet, fee); 1035 | } 1036 | 1037 | //Transfer required amount of tokens to the contract from user balance 1038 | IERC20(token).safeTransferFrom(msg.sender, address(this), amount); 1039 | 1040 | _lockId = _lockId.add(1); 1041 | 1042 | _idVsLockedAsset[_lockId] = LockedAsset({ 1043 | token: token, 1044 | amount: amount, 1045 | startDate: block.timestamp, 1046 | endDate: endDate, 1047 | lastLocked: block.timestamp, 1048 | beneficiary: beneficiary, 1049 | status: Status.OPEN, 1050 | amountThreshold: amountThreshold 1051 | }); 1052 | _userVsLockIds[beneficiary].push(_lockId); 1053 | } 1054 | 1055 | /** 1056 | * @dev Helper method to claim ETH 1057 | */ 1058 | function _claimETH(uint256 id) private { 1059 | LockedAsset storage asset = _idVsLockedAsset[id]; 1060 | asset.status = Status.CLOSED; 1061 | (bool success,) = msg.sender.call.value(asset.amount)(""); 1062 | require(success, "Lock: Failed to transfer eth!!"); 1063 | 1064 | _claimAirdroppedTokens( 1065 | asset.token, 1066 | asset.lastLocked, 1067 | asset.amount 1068 | ); 1069 | } 1070 | 1071 | /** 1072 | * @dev Helper method to claim ERC-20 1073 | */ 1074 | function _claimERC20(uint256 id) private { 1075 | LockedAsset storage asset = _idVsLockedAsset[id]; 1076 | asset.status = Status.CLOSED; 1077 | IERC20(asset.token).safeTransfer(msg.sender, asset.amount); 1078 | _claimAirdroppedTokens( 1079 | asset.token, 1080 | asset.lastLocked, 1081 | asset.amount 1082 | ); 1083 | } 1084 | 1085 | /** 1086 | * @dev Helper method to claim airdropped tokens 1087 | * @param baseToken Base Token address 1088 | * @param lastLocked Date when base tokens were last locked 1089 | * @param amount Amount of base tokens locked 1090 | */ 1091 | function _claimAirdroppedTokens( 1092 | address baseToken, 1093 | uint256 lastLocked, 1094 | uint256 amount 1095 | ) 1096 | private 1097 | { 1098 | //This loop can be very costly if number of airdropped tokens 1099 | //for base token is very large. But we assume that it is not going to be the case 1100 | for(uint256 i = 0; i < _baseTokenVsAirdrops[baseToken].length; i++) { 1101 | 1102 | Airdrop memory airdrop = _baseTokenVsAirdrops[baseToken][i]; 1103 | 1104 | if(airdrop.date > lastLocked && airdrop.date < block.timestamp) { 1105 | uint256 airdropAmount = amount.mul(airdrop.numerator).div(airdrop.denominator); 1106 | IERC20(airdrop.destToken).safeTransfer(msg.sender, airdropAmount); 1107 | emit TokensAirdropped(airdrop.destToken, airdropAmount); 1108 | } 1109 | } 1110 | 1111 | } 1112 | 1113 | //Helper method to calculate fee 1114 | function _calculateFee( 1115 | uint256 amount, 1116 | bool lockFee, 1117 | Token memory token 1118 | ) 1119 | private 1120 | view 1121 | returns(uint256 fee, uint256 newAmount) 1122 | { 1123 | newAmount = amount; 1124 | 1125 | if(lockFee){ 1126 | fee = _lockTokenFee; 1127 | } 1128 | else{ 1129 | uint256 tempAmount = amount; 1130 | for( 1131 | uint256 i = 0; (i < token.tierAmounts.length - 1 && tempAmount > 0); i++ 1132 | ) 1133 | { 1134 | if(tempAmount >= token.tierAmounts[i]){ 1135 | tempAmount = tempAmount.sub(token.tierAmounts[i]); 1136 | fee = fee.add(token.tierAmounts[i].mul(token.tierFees[i]).div(10000)); 1137 | } 1138 | else{ 1139 | fee = fee.add(tempAmount.mul(token.tierFees[i]).div(10000)); 1140 | tempAmount = 0; 1141 | } 1142 | } 1143 | //All remaining tokens will be calculated in last tier 1144 | fee = fee.add( 1145 | tempAmount.mul(token.tierFees[token.tierAmounts.length - 1]) 1146 | .div(10000) 1147 | ); 1148 | newAmount = amount.sub(fee); 1149 | } 1150 | return(fee, newAmount); 1151 | } 1152 | } 1153 | --------------------------------------------------------------------------------