From bc56f9770039ec8540522e4e5216de0d763c7495 Mon Sep 17 00:00:00 2001 From: Ravindra Kumar Date: Tue, 23 Oct 2018 13:22:31 +0530 Subject: [PATCH] Initial Commit --- .babelrc | 3 + .circleci/config.yml | 37 +++++ .env.sample | 2 + .eslintignore | 4 + .eslintrc.js | 102 ++++++++++++++ .gitattributes | 1 + .github/ISSUE_TEMPLATE/bug_report.md | 35 +++++ .github/ISSUE_TEMPLATE/feature_request.md | 17 +++ .gitignore | 106 +++++++++++++++ .prettierignore | 1 + .prettierrc | 5 + .solcover.js | 6 + .soliumignore | 2 + .soliumrc.json | 27 ++++ .travis.yml | 21 +++ CODE_OF_CONDUCT.md | 46 +++++++ CONTRIBUTING.md | 1 + LICENSE | 21 +++ PULL_REQUEST_TEMPLATE.md | 1 + README.md | 67 +++++++++ contracts/Migrations.sol | 30 ++++ contracts/Ownable.sol | 39 ++++++ migrations/1_initial_migration.js | 5 + migrations/2_contract_migrations.js | 5 + mocha-smart-contracts-config.json | 10 ++ package.json | 65 +++++++++ test/Ownable.test.js | 36 +++++ test/helpers/general.js | 158 ++++++++++++++++++++++ truffle.js | 57 ++++++++ 29 files changed, 910 insertions(+) create mode 100644 .babelrc create mode 100644 .circleci/config.yml create mode 100644 .env.sample create mode 100644 .eslintignore create mode 100644 .eslintrc.js create mode 100644 .gitattributes create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .gitignore create mode 100644 .prettierignore create mode 100644 .prettierrc create mode 100644 .solcover.js create mode 100644 .soliumignore create mode 100644 .soliumrc.json create mode 100644 .travis.yml create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 PULL_REQUEST_TEMPLATE.md create mode 100644 README.md create mode 100644 contracts/Migrations.sol create mode 100644 contracts/Ownable.sol create mode 100644 migrations/1_initial_migration.js create mode 100644 migrations/2_contract_migrations.js create mode 100644 mocha-smart-contracts-config.json create mode 100644 package.json create mode 100644 test/Ownable.test.js create mode 100644 test/helpers/general.js create mode 100644 truffle.js diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..3ea7a2d --- /dev/null +++ b/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["env","es2015", "stage-2", "stage-3"] +} diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..46f98bb --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,37 @@ +# Javascript Node CircleCI 2.0 configuration file +# +# Check https://circleci.com/docs/2.0/language-javascript/ for more details +# +version: 2 +jobs: + build: + docker: + # specify the version you desire here + - image: circleci/node:8.4.0 + + # Specify service dependencies here if necessary + # CircleCI maintains a library of pre-built images + # documented at https://circleci.com/docs/2.0/circleci-images/ + # - image: circleci/mongo:3.4.4 + + working_directory: ~/repo + + steps: + - checkout + + # Download and cache dependencies + - restore_cache: + keys: + - v1-dependencies-{{ checksum "package.json" }} + # fallback to using the latest cache if no exact match is found + - v1-dependencies- + + - run: npm install + + - save_cache: + paths: + - node_modules + key: v1-dependencies-{{ checksum "package.json" }} + + # run tests! + - run: npm run test-ci \ No newline at end of file diff --git a/.env.sample b/.env.sample new file mode 100644 index 0000000..98aee42 --- /dev/null +++ b/.env.sample @@ -0,0 +1,2 @@ +RINKEBY_PRIVATE_KEY="df7ebe6c9601adf4e911faac9da547686e6453a11cf13264d895fc2979a6bec2" +ROPSTEN_PRIVATE_KEY="192f175c2f5e5a9437fdbc12043404763f96ccbcd6fc32b1d61dbb61e14e6f34" \ No newline at end of file diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..47d952c --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +tmp/** +build/** +node_modules/** +contracts/** diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..6d2fc1d --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,102 @@ +module.exports = { + parser: 'babel-eslint', + parserOptions: { + ecmaFeatures: { + generators: true, + experimentalObjectRestSpread: true + }, + sourceType: 'module', + allowImportExportEverywhere: false + }, + extends: [ + 'eslint:recommended', + 'plugin:import/errors', + 'plugin:import/warnings', + 'plugin:promise/recommended', + 'plugin:security/recommended' + ], + plugins: [ + 'compat', + 'prettier', + 'promise', + 'security' + ], + settings: { + 'import/resolver': { + node: { + extensions: ['.js', '.jsx', '.json', '.css'], + paths: './src' + } + }, + polyfills: ['fetch', 'promises'] + }, + env: { + node: true, + }, + globals: { + __DEV__: true, + __dirname: true, + after: true, + afterAll: true, + afterEach: true, + artifacts: true, + assert: true, + before: true, + beforeAll: true, + beforeEach: true, + console: true, + contract: true, + describe: true, + expect: true, + fetch: true, + global: true, + it: true, + module: true, + process: true, + Promise: true, + require: true, + setTimeout: true, + test: true, + xdescribe: true, + xit: true, + web3: true + }, + rules: { + 'compat/compat': 'error', + 'import/first': 'error', + 'import/no-anonymous-default-export': 'error', + 'import/no-unassigned-import': 'error', + 'import/prefer-default-export': 'error', + 'import/no-named-as-default': 'off', + 'import/no-unresolved': 'error', + 'prettier/prettier': [ + 'error', + { + semi: false, + singleQuote: true, + trailingComma: 'none' + } + ], + 'promise/avoid-new': 'off', + 'security/detect-object-injection': 'off', + 'arrow-body-style': 'off', + 'lines-between-class-members': ['error', 'always'], + 'no-console': ['warn', { allow: ['assert'] }], + 'no-shadow': 'error', + 'no-var': 'error', + + 'padding-line-between-statements': [ + 'error', + { blankLine: 'always', prev: 'class', next: '*' }, + { blankLine: 'always', prev: 'do', next: '*' }, + { blankLine: 'always', prev: '*', next: 'export' }, + { blankLine: 'always', prev: 'for', next: '*' }, + { blankLine: 'always', prev: 'if', next: '*' }, + { blankLine: 'always', prev: 'switch', next: '*' }, + { blankLine: 'always', prev: 'try', next: '*' }, + { blankLine: 'always', prev: 'while', next: '*' }, + { blankLine: 'always', prev: 'with', next: '*' } + ], + 'prefer-const': 'error' + } +} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..7cc88f0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sol linguist-language=Solidity \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..b735373 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,35 @@ +--- +name: Bug report +about: Create a report to help us improve + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..066b2d9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b8f79c9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,106 @@ + +# Created by https://www.gitignore.io/api/solidity,soliditytruffle + +### Solidity ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +# parcel-bundler cache (https://parceljs.org/) +.cache + +# next.js build output +.next + +# nuxt.js build output +.nuxt + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless + +### SolidityTruffle ### +# depedencies +node_modules + +# testing + +# production +build +build_webpack + +# misc +.DS_Store +npm-debug.log +.truffle-solidity-loader +.vagrant/** +blockchain/geth/** +blockchain/keystore/** +blockchain/history + +#truffle +.tern-port +yarn.lock +package-lock.json + + +# End of https://www.gitignore.io/api/solidity,soliditytruffle + +test-results/ \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..ec6d3cd --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +package.json diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..49955e2 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,5 @@ +{ + "semi": false, + "singleQuote": true, + "trailingComma": "none" +} diff --git a/.solcover.js b/.solcover.js new file mode 100644 index 0000000..669e290 --- /dev/null +++ b/.solcover.js @@ -0,0 +1,6 @@ +module.exports = { + port: 9545, + testrpcOptions: + '-p 9545 -m "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat"', + copyNodeModules: false +} diff --git a/.soliumignore b/.soliumignore new file mode 100644 index 0000000..3394412 --- /dev/null +++ b/.soliumignore @@ -0,0 +1,2 @@ +node_modules +contracts/Migrations.sol \ No newline at end of file diff --git a/.soliumrc.json b/.soliumrc.json new file mode 100644 index 0000000..6313fb8 --- /dev/null +++ b/.soliumrc.json @@ -0,0 +1,27 @@ +{ + "extends": "solium:all", + "plugins": ["security"], + "rules": { + "arg-overflow": "error", + "array-declarations": "error", + "blank-lines": "error", + "camelcase": "error", + "comma-whitespace": "error", + "deprecated-suicide": "error", + "function-whitespace": "error", + "imports-on-top": "error", + "indentation": ["error", 4], + "lbrace": "error", + "mixedcase": "error", + "no-empty-blocks": "error", + "no-unused-vars": "error", + "operator-whitespace": "error", + "pragma-on-top": "error", + "quotes": ["error", "double"], + "security/no-inline-assembly": "off", + "semicolon-whitespace": "error", + "uppercase": "off", + "variable-declarations": "error", + "whitespace": "error" + } +} diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..a530aa4 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,21 @@ +sudo: required +language: node_js +node_js: + - "9" +cache: + directories: + - node_modules +install: + - npm install -g truffle@beta + - npm install -g ganache-cli + - npm install +script: + - npm run lint + - npm run solium + - npm run ganache + - sleep 5 + - truffle migrate --network test + - truffle test + - npm run stop +after_script: + - npm run coverage && cat coverage/lcov.info | coveralls diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..e441bc1 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ravindrakumar8088@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..dfb6aea --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1 @@ +Contributors Guide diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5f83974 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Ravindra Kumar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1 @@ + diff --git a/README.md b/README.md new file mode 100644 index 0000000..bcb69e4 --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# Moat Contract + +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/MoatNetwork/MoatContract/blob/master/LICENSE) +[![Build Status](https://travis-ci.org/MoatNetwork/MoatContract.svg?branch=master)](https://travis-ci.org/MoatNetwork/MoatContract) +[![Coverage Status](https://coveralls.io/repos/github/MoatNetwork/MoatContract/badge.svg?branch=master)](https://coveralls.io/github/MoatNetwork/MoatContract?branch=master) +[![CircleCI](https://circleci.com/gh/MoatNetwork/MoatContract.svg?style=svg)](https://circleci.com/gh/MoatNetwork/MoatContract) + +> Smart Contracts powering Moat Fund + +### Show some :heart: +[![GitHub stars](https://img.shields.io/github/stars/MoatNetwork/MoatContract.svg?style=social&label=Star)](https://github.com/MoatNetwork/MoatContract) [![GitHub forks](https://img.shields.io/github/forks/MoatNetwork/MoatContract.svg?style=social&label=Fork)](https://github.com/MoatNetwork/MoatContract/fork) [![GitHub watchers](https://img.shields.io/github/watchers/MoatNetwork/MoatContract.svg?style=social&label=Watch)](https://github.com/MoatNetwork/MoatContract) [![GitHub followers](https://img.shields.io/github/followers/ravidsrk.svg?style=social&label=Follow)](https://github.com/MoatNetwork/MoatContract) + +## This project uses: +- [Truffle v5](https://truffleframework.com/) +- [Ganache](https://truffleframework.com/ganache) +- [Solium](https://github.com/duaraghav8/Solium) +- [OpenZeppelin](https://github.com/OpenZeppelin/openzeppelin-solidity) +- [Travis CI](https://travis-ci.org/MoatNetwork/MoatContract) and [Circle CI](https://circleci.com/gh/MoatNetwork/MoatContract) +- [Coveralls](https://coveralls.io/github/MoatNetwork/MoatContract?branch=master) + +## Installation + +1. Install Truffle and Ganache CLI globally. + +```javascript +npm install -g truffle@beta +npm install -g ganache-cli +``` + +2. Create a `.env` file in the root directory and add your private key. + +## Commands: + +``` +Compile contracts: truffle compile +Migrate contracts: truffle migrate +Test contracts: truffle test +Run eslint: npm run lint +Run solium: npm run solium +Run solidity-coverage: npm run coverage +Run lint, solium, and truffle test: npm run test +``` + +## License +``` +MIT License + +Copyright (c) 2018 Moat Network + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/contracts/Migrations.sol b/contracts/Migrations.sol new file mode 100644 index 0000000..319b77b --- /dev/null +++ b/contracts/Migrations.sol @@ -0,0 +1,30 @@ +pragma solidity 0.4.24; + + +/* solium-disable mixedcase */ +contract Migrations { + address public owner; + uint public last_completed_migration; + + modifier restricted() { + if (msg.sender == owner) + _; + } + + constructor() + public + { + owner = msg.sender; + } + + function setCompleted(uint completed) public restricted { + last_completed_migration = completed; + } + + function upgrade(address _newAddress) public restricted { + Migrations upgraded = Migrations(_newAddress); + upgraded.setCompleted(last_completed_migration); + } +} + +/* solium-enable mixedcase */ diff --git a/contracts/Ownable.sol b/contracts/Ownable.sol new file mode 100644 index 0000000..18dfea2 --- /dev/null +++ b/contracts/Ownable.sol @@ -0,0 +1,39 @@ +pragma solidity 0.4.24; + + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner, "Only owner accessible"); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0), "Address not equal to zero"); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } +} \ No newline at end of file diff --git a/migrations/1_initial_migration.js b/migrations/1_initial_migration.js new file mode 100644 index 0000000..100bd2c --- /dev/null +++ b/migrations/1_initial_migration.js @@ -0,0 +1,5 @@ +const Migrations = artifacts.require('./Migrations.sol') + +module.exports = async deployer => { + await deployer.deploy(Migrations) +} diff --git a/migrations/2_contract_migrations.js b/migrations/2_contract_migrations.js new file mode 100644 index 0000000..a3be069 --- /dev/null +++ b/migrations/2_contract_migrations.js @@ -0,0 +1,5 @@ +const ownableFactory = artifacts.require('Ownable.sol') + +module.exports = async deployer => { + await deployer.deploy(ownableFactory) +} diff --git a/mocha-smart-contracts-config.json b/mocha-smart-contracts-config.json new file mode 100644 index 0000000..8e7acad --- /dev/null +++ b/mocha-smart-contracts-config.json @@ -0,0 +1,10 @@ +{ + "reporterEnabled": "mocha-junit-reporter, eth-gas-reporter", + "mochaJunitReporterReporterOptions": { + "mochaFile": "./test-results/test-contract-results.xml" + }, + "reporterOptions": { + "currency": "USD", + "gasPrice": 21 + } +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..2e3edb0 --- /dev/null +++ b/package.json @@ -0,0 +1,65 @@ +{ + "name": "smart-contract-starter", + "description": "Boilerplate for your next Smart Contract, made simple.", + "version": "0.0.1", + "author": "Ravindra Kumar ", + "license": "MIT", + "main": "truffle.js", + "directories": { + "test": "test" + }, + "scripts": { + "ganache": "ganache-cli -e 300 -p 9545 -m 'candy maple cake sugar pudding cream honey rich smooth crumble sweet treat' --accounts 30 > /dev/null &", + "stop": "sudo kill `sudo lsof -t -i:9545`", + "test": "npm run ganache sleep 5 && npm run lint ./ && npm run solium && truffle test && npm run stop", + "test:gas-reporter": "GAS_REPORTER=true npm run test", + "test-ci": "GAS_REPORTER=true npm run ganache sleep 5 && npm run lint ./ && npm run solium && truffle test", + "coverage": "./node_modules/.bin/solidity-coverage", + "lint": "eslint ./test", + "lint:fix": "eslint ./ --fix", + "solium": "solium -d contracts/", + "solium:fix": "solium -d contracts/ --fix", + "build": "npm run clean:contracts && truffle compile" + }, + "dependencies": { + "web3": "^1.0.0-beta.36", + "bn.js": "^4.11.8", + "dotenv": "^6.1.0", + "openzeppelin-solidity": "^2.0.0", + "prettier": "^1.14.3", + "truffle": "^5.0.0-beta.0", + "webpack": "^4.22.0", + "truffle-hdwallet-provider": "^1.0.0-web3one.0" + }, + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-eslint": "10.0.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "^1.7.0", + "babel-preset-es2015": "6.24.1", + "babel-preset-stage-2": "6.24.1", + "babel-preset-stage-3": "6.24.1", + "babel-register": "6.26.0", + "chai": "4.2.0", + "chai-as-promised": "7.1.1", + "chai-bignumber": "2.0.2", + "coveralls": "3.0.2", + "eslint": "5.7.0", + "eslint-config-prettier": "^3.1.0", + "eslint-config-standard": "^12.0.0", + "eslint-plugin-babel": "^5.2.1", + "eslint-plugin-compat": "^2.6.2", + "eslint-plugin-import": "2.14.0", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-prettier": "^3.0.0", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-security": "^1.4.0", + "eslint-plugin-standard": "^4.0.0", + "eth-gas-reporter": "^0.1.12", + "ganache-cli": "^6.1.8", + "mocha-junit-reporter": "^1.18.0", + "mocha-multi-reporters": "^1.1.7", + "solidity-coverage": "0.5.11", + "solium": "1.1.8" + } +} diff --git a/test/Ownable.test.js b/test/Ownable.test.js new file mode 100644 index 0000000..414a9c1 --- /dev/null +++ b/test/Ownable.test.js @@ -0,0 +1,36 @@ +const { assertRevert } = require('./helpers/general') + +const Ownable = artifacts.require('Ownable') + +contract('Ownable', accounts => { + let ownable + + beforeEach(async () => { + ownable = await Ownable.new() + }) + + it('should have an owner', async () => { + const owner = await ownable.owner() + assert.isTrue(owner !== 0) + }) + + it('changes owner after transfer', async () => { + const other = accounts[1] + await ownable.transferOwnership(other) + const owner = await ownable.owner() + + assert.isTrue(owner === other) + }) + + it('should prevent non-owners from transfering', async () => { + const other = accounts[2] + const owner = await ownable.owner.call() + assert.isTrue(owner !== other) + await assertRevert(ownable.transferOwnership(other, { from: other })) + }) + + it('should guard ownership against stuck state', async () => { + const originalOwner = await ownable.owner() + await assertRevert(ownable.transferOwnership(null, { from: originalOwner })) + }) +}) diff --git a/test/helpers/general.js b/test/helpers/general.js new file mode 100644 index 0000000..57cba27 --- /dev/null +++ b/test/helpers/general.js @@ -0,0 +1,158 @@ +const { BN } = web3.utils + +const decimals18 = new BN(10).pow(new BN(18)) +const bigZero = new BN(0) +const addressZero = `0x${'0'.repeat(40)}` +const bytes32Zero = '0x' + '00'.repeat(32) +const gasPrice = new BN(5e9) + +const assertRevert = async promise => { + try { + await promise + assert.fail('Expected revert not received') + } catch (error) { + const revertFound = error.message.search('revert') >= 0 + assert(revertFound, `Expected "revert", got ${error} instead`) + } +} + +const assertJump = async promise => { + try { + await promise + assert.fail('Expected invalid opcode not received') + } catch (error) { + const invalidOpcodeReceived = error.message.search('invalid opcode') >= 0 + assert( + invalidOpcodeReceived, + `Expected "invalid opcode", got ${error} instead` + ) + } +} + +const assertThrow = async promise => { + try { + await promise + } catch (error) { + // TODO: Check jump destination to destinguish between a throw + // and an actual invalid jump. + const invalidOpcode = error.message.search('invalid opcode') >= 0 + // TODO: When we contract A calls contract B, and B throws, instead + // of an 'invalid jump', we get an 'out of gas' error. How do + // we distinguish this from an actual out of gas event? (The + // testrpc log actually show an 'invalid jump' event.) + const outOfGas = error.message.search('out of gas') >= 0 + const revert = error.message.search('revert') >= 0 + const exception = + error.message.search( + 'VM Exception while processing transaction: revert' + ) >= 0 + assert( + invalidOpcode || exception || outOfGas || revert, + "Expected throw, got '" + error + "' instead" + ) + return + } + + assert.fail('Expected throw not received') +} + +const waitForEvent = (contract, event, optTimeout) => + new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + clearTimeout(timeout) + return reject(new Error('Timeout waiting for contractEvent')) + }, optTimeout || 5000) + + const eventEmitter = contract.contract.events[event]() + eventEmitter + .on('data', data => { + eventEmitter.unsubscribe() + clearTimeout(timeout) + resolve(data) + }) + .on('changed', data => { + clearTimeout() + eventEmitter.unsubscribe() + resolve(data) + }) + .on('error', err => { + eventEmitter.unsubscribe() + reject(err) + }) + }) + +const areInRange = (num1, num2, range) => { + const bigNum1 = new BN(num1.toString()) + const bigNum2 = new BN(num2.toString()) + const bigRange = new BN(range.toString()) + + if (bigNum1.equals(bigNum2)) { + return true + } + + const larger = bigNum1.gt(bigNum2) ? bigNum1 : bigNum2 + const smaller = bigNum1.lt(bigNum2) ? bigNum1 : bigNum2 + + return larger.sub(smaller).lt(bigRange) +} + +const getNowInSeconds = () => new BN(Date.now()).div(1000).floor(0) + +const trimBytes32Array = bytes32Array => + bytes32Array.filter(bytes32 => bytes32 != bytes32Zero) + +const getEtherBalance = address => { + return new Promise((resolve, reject) => { + web3.eth.getBalance(address, (err, res) => { + if (err) reject(err) + + resolve(res) + }) + }) +} + +const getTxInfo = txHash => { + if (typeof txHash === 'object') { + return txHash.receipt + } + + return new Promise((resolve, reject) => { + web3.eth.getTransactionReceipt(txHash, (err, res) => { + if (err) { + reject(err) + } + + resolve(res) + }) + }) +} + +const sendTransaction = args => { + return new Promise(function(resolve, reject) { + web3.eth.sendTransaction(args, (err, res) => { + if (err) { + reject(err) + } else { + resolve(res) + } + }) + }) +} + +module.exports = { + decimals18, + bigZero, + addressZero, + bytes32Zero, + gasPrice, + assertRevert, + assertJump, + assertThrow, + waitForEvent, + areInRange, + getNowInSeconds, + trimBytes32Array, + getEtherBalance, + getTxInfo, + sendTransaction +} diff --git a/truffle.js b/truffle.js new file mode 100644 index 0000000..f555f32 --- /dev/null +++ b/truffle.js @@ -0,0 +1,57 @@ +require('dotenv').config() +const HDWalletProvider = require('truffle-hdwallet-provider') +const Wallet = require('ethereumjs-wallet') + +const rinkebyPrivateKey = new Buffer(process.env['RINKEBY_PRIVATE_KEY'], 'hex') +const rinkebyWallet = Wallet.fromPrivateKey(rinkebyPrivateKey) +const rinkebyProvider = new HDWalletProvider( + rinkebyWallet, + 'https://rinkeby.infura.io/' +) + +const ropstenPrivateKey = new Buffer(process.env['ROPSTEN_PRIVATE_KEY'], 'hex') +const ropstenWallet = Wallet.fromPrivateKey(ropstenPrivateKey) +const ropstenProvider = new HDWalletProvider( + ropstenWallet, + 'https://ropsten.infura.io/' +) + +module.exports = { + migrations_directory: './migrations', + networks: { + test: { + host: 'localhost', + port: 9545, + network_id: '*', + gas: 6.5e6, + gasPrice: 5e9, + websockets: true + }, + ropsten: { + network_id: 3, + gas: 6.5e6, + gasPrice: 5e9, + provider: () => ropstenProvider + }, + rinkeby: { + network_id: 4, + gas: 6.5e6, + gasPrice: 5e9, + provider: () => rinkebyProvider + } + }, + solc: { + optimizer: { + enabled: true, + runs: 500 + } + }, + mocha: { + reporter: 'mocha-multi-reporters', + useColors: true, + enableTimeouts: false, + reporterOptions: { + configFile: './mocha-smart-contracts-config.json' + } + } +}