├── .editorconfig ├── .env.example ├── .gitattributes ├── .github ├── actions │ └── setup │ │ └── action.yml └── workflows │ └── ci.yml ├── .gitignore ├── .nvmrc ├── .prettierrc ├── .solcover.js ├── LICENSE ├── README.md ├── analysis ├── .gitkeep ├── control-flow │ ├── .gitkeep │ └── SampleContract.png ├── description-table │ ├── .gitkeep │ └── SampleContract.md ├── inheritance-tree │ ├── .gitkeep │ └── SampleContract.png └── uml │ ├── .gitkeep │ └── SampleContract.svg ├── bs-config.json ├── contracts ├── SampleContract.sol └── mocks │ ├── ERC20Mock.sol │ └── ERC721Mock.sol ├── dist ├── .gitkeep └── SampleContract.dist.sol ├── docs ├── .gitkeep └── index.md ├── eslint.config.mjs ├── hardhat.config.js ├── migrations └── .gitkeep ├── package-lock.json ├── package.json ├── pages ├── .vitepress │ ├── config.mjs │ └── theme │ │ ├── custom.css │ │ └── index.js ├── deploy │ └── deploy.sh ├── index.md └── public │ ├── favicon.ico │ └── images │ └── solidity-toolkit.png ├── scripts ├── analyze.sh ├── checks │ └── inheritance-ordering.js ├── flat.sh └── solhint-custom │ ├── index.js │ └── package.json ├── slither.config.json ├── solhint.config.js ├── test ├── SampleContract.test.js └── helpers │ └── customError.js └── web-console ├── README.md ├── index.html └── js └── app.js /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | [*] 7 | charset = utf-8 8 | end_of_line = lf 9 | indent_style = space 10 | insert_final_newline = true 11 | trim_trailing_whitespace = false 12 | max_line_length = 120 13 | 14 | [*.sol] 15 | indent_size = 4 16 | 17 | [*.js] 18 | indent_size = 2 19 | 20 | [*.{adoc,md}] 21 | max_line_length = 0 22 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # vitepress deploy 2 | GIT_DEPLOY_DIR=pages/.vitepress/dist 3 | GIT_DEPLOY_BRANCH=gh-pages 4 | GIT_DEPLOY_REPO=origin 5 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /.github/actions/setup/action.yml: -------------------------------------------------------------------------------- 1 | name: Setup 2 | 3 | runs: 4 | using: composite 5 | steps: 6 | - name: Setup Node 7 | uses: actions/setup-node@v4 8 | with: 9 | node-version: 22 10 | 11 | - name: Setup Cache 12 | uses: actions/cache@v4 13 | id: cache 14 | with: 15 | path: '**/node_modules' 16 | key: npm-${{ hashFiles('**/package-lock.json') }} 17 | 18 | - name: Install dependencies 19 | run: npm ci 20 | shell: bash 21 | if: steps.cache.outputs.cache-hit != 'true' 22 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: {} 8 | release: 9 | types: 10 | - created 11 | 12 | jobs: 13 | lint: 14 | name: Lint 15 | runs-on: ubuntu-latest 16 | env: 17 | FORCE_COLOR: 1 18 | steps: 19 | - name: Setup Code 20 | uses: actions/checkout@v4 21 | 22 | - name: Setup Environment 23 | uses: ./.github/actions/setup 24 | 25 | - name: Run Linter 26 | run: npm run lint 27 | 28 | test: 29 | name: Test 30 | runs-on: ubuntu-latest 31 | env: 32 | FORCE_COLOR: 1 33 | steps: 34 | - name: Setup Code 35 | uses: actions/checkout@v4 36 | 37 | - name: Setup Environment 38 | uses: ./.github/actions/setup 39 | 40 | - name: Run Test 41 | run: npm test 42 | 43 | - name: Check Linearisation 44 | run: npm run check:inheritance 45 | 46 | coverage: 47 | name: Coverage 48 | runs-on: ubuntu-latest 49 | env: 50 | FORCE_COLOR: 1 51 | steps: 52 | - name: Setup Code 53 | uses: actions/checkout@v4 54 | 55 | - name: Setup Environment 56 | uses: ./.github/actions/setup 57 | 58 | - name: Run Coverage 59 | run: npm run coverage 60 | 61 | - name: Post to Codecov 62 | uses: codecov/codecov-action@v5 63 | env: 64 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 65 | 66 | slither: 67 | name: Slither 68 | runs-on: ubuntu-latest 69 | env: 70 | FORCE_COLOR: 1 71 | steps: 72 | - name: Setup Code 73 | uses: actions/checkout@v4 74 | 75 | - name: Setup Environment 76 | uses: ./.github/actions/setup 77 | 78 | - name: Run Slither 79 | uses: crytic/slither-action@v0.4.0 80 | with: 81 | node-version: 22 82 | solc-version: 0.8.28 83 | 84 | codespell: 85 | name: Codespell 86 | runs-on: ubuntu-latest 87 | env: 88 | FORCE_COLOR: 1 89 | steps: 90 | - name: Setup Code 91 | uses: actions/checkout@v4 92 | 93 | - name: Run CodeSpell 94 | uses: codespell-project/actions-codespell@v2 95 | with: 96 | check_hidden: true 97 | check_filenames: true 98 | skip: .git,package-lock.json 99 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.swo 3 | 4 | # Logs 5 | logs 6 | *.log 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | scTopics 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | coverage.json 17 | coverageEnv 18 | 19 | # temporary artifact from solidity-coverage 20 | allFiredEvents 21 | .coverage_artifacts 22 | .coverage_cache 23 | .coverage_contracts 24 | 25 | # node-waf configuration 26 | .lock-wscript 27 | 28 | # Dependency directory 29 | node_modules 30 | 31 | # Debug log from npm 32 | npm-debug.log 33 | 34 | # local env variables 35 | .env 36 | 37 | # truffle build directory 38 | /build 39 | 40 | # hardat-exposed 41 | contracts-exposed 42 | 43 | # Hardhat files 44 | /artifacts 45 | /cache 46 | 47 | # macOS 48 | .DS_Store 49 | 50 | # truffle 51 | .node-xmlhttprequest-* 52 | 53 | # IntelliJ IDE 54 | .idea 55 | 56 | # vuepress 57 | pages/.vuepress/dist 58 | pages/.vuepress/.env.json 59 | 60 | # vitepress 61 | pages/.vitepress/cache 62 | pages/.vitepress/dist 63 | pages/.vitepress/.env.json 64 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 22 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 120, 3 | "singleQuote": true, 4 | "trailingComma": "all", 5 | "arrowParens": "avoid", 6 | "overrides": [ 7 | { 8 | "files": "*.sol", 9 | "options": { 10 | "singleQuote": false 11 | } 12 | } 13 | ], 14 | "plugins": ["prettier-plugin-solidity"] 15 | } 16 | -------------------------------------------------------------------------------- /.solcover.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | norpc: true, 3 | testCommand: 'npm test', 4 | compileCommand: 'npm run compile', 5 | skipFiles: ['mocks'], 6 | }; 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 NONCEPT S.R.L. (https://noncept.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solidity Toolkit 2 | 3 | [![CI](https://github.com/noncept/solidity-toolkit/actions/workflows/ci.yml/badge.svg)](https://github.com/noncept/solidity-toolkit/actions/workflows/ci.yml) 4 | [![Coverage Status](https://codecov.io/gh/noncept/solidity-toolkit/graph/badge.svg)](https://codecov.io/gh/noncept/solidity-toolkit) 5 | [![MIT licensed](https://img.shields.io/github/license/noncept/solidity-toolkit.svg)](https://github.com/noncept/solidity-toolkit/blob/master/LICENSE) 6 | 7 | 8 | A toolkit for Solidity Smart Contracts development. 9 | 10 | ## Install 11 | 12 | ```bash 13 | git clone https://github.com/noncept/solidity-toolkit.git 14 | ``` 15 | 16 | ## Development 17 | 18 | ### Install dependencies 19 | 20 | ```bash 21 | npm install 22 | ``` 23 | 24 | ### Compile 25 | 26 | ```bash 27 | npm run compile 28 | ``` 29 | 30 | ### Test 31 | 32 | ```bash 33 | npm test 34 | ``` 35 | 36 | ### Code Coverage 37 | 38 | ```bash 39 | npm run coverage 40 | ``` 41 | 42 | ### Linter 43 | 44 | Check Solidity files. 45 | 46 | ```bash 47 | npm run lint:sol 48 | ``` 49 | 50 | Check JS/TS files. 51 | 52 | ```bash 53 | npm run lint:js 54 | ``` 55 | 56 | Fix JS and Solidity files. 57 | 58 | ```bash 59 | npm run lint:fix 60 | ``` 61 | 62 | ## Create Documentation 63 | 64 | ```bash 65 | npm run docs 66 | ``` 67 | 68 | - [Example Documentation](https://github.com/noncept/solidity-toolkit/blob/master/docs/index.md) 69 | 70 | ## Use web3 console in your browser (i.e. to use MetaMask) 71 | 72 | ```bash 73 | npm run dev 74 | ``` 75 | 76 | Read how to interact with your Smart Contracts [here](https://github.com/noncept/solidity-toolkit/blob/master/web-console/README.md). 77 | 78 | ## Flattener 79 | 80 | This allows to flatten the code into a single file. 81 | 82 | Edit `scripts/flat.sh` to add your contracts. 83 | 84 | ```bash 85 | npm run flat 86 | ``` 87 | 88 | - [Example flattened code](https://github.com/noncept/solidity-toolkit/blob/master/dist/SampleContract.dist.sol) 89 | 90 | ## Analysis 91 | 92 | > [!IMPORTANT] 93 | > It is better to analyze the flattened code to have a bigger overview on the entire codebase. So run the flattener first. 94 | 95 | ### Describe 96 | 97 | The `describe` command shows a summary of the contracts and methods in the files provided 98 | 99 | ```bash 100 | surya describe dist/SampleContract.dist.sol 101 | ``` 102 | 103 | ### Dependencies 104 | 105 | The `dependencies` command outputs the c3-linearization of a given contract's inheirtance graph. Contracts will be listed starting with most-derived, ie. if the same function is defined in more than one contract, the solidity compiler will use the definition in whichever contract is listed first. 106 | 107 | ```bash 108 | surya dependencies SampleContract dist/SampleContract.dist.sol 109 | ``` 110 | ### Generate Report 111 | 112 | Edit `scripts/analyze.sh` to add your contracts 113 | 114 | ```bash 115 | npm run analyze 116 | ``` 117 | 118 | The `inheritance` command outputs a DOT-formatted graph of the inheritance tree. 119 | 120 | - [Example inheritance graph](https://github.com/noncept/solidity-toolkit/blob/master/analysis/inheritance-tree/SampleContract.png) 121 | 122 | The `graph` command outputs a DOT-formatted graph of the control flow. 123 | 124 | - [Example control flow](https://github.com/noncept/solidity-toolkit/blob/master/analysis/control-flow/SampleContract.png) 125 | 126 | The `mdreport` command creates a markdown description report with tables comprising information about the system's files, contracts and their functions. 127 | 128 | - [Example description table](https://github.com/noncept/solidity-toolkit/blob/master/analysis/description-table/SampleContract.md) 129 | 130 | The `sol2uml` generates UML class diagram from Solidity contracts. 131 | 132 | - [Example UML diagram](https://github.com/noncept/solidity-toolkit/blob/master/analysis/uml/SampleContract.svg) 133 | 134 | ## License 135 | 136 | Code released under the [MIT License](https://github.com/noncept/solidity-toolkit/blob/master/LICENSE). 137 | -------------------------------------------------------------------------------- /analysis/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/analysis/.gitkeep -------------------------------------------------------------------------------- /analysis/control-flow/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/analysis/control-flow/.gitkeep -------------------------------------------------------------------------------- /analysis/control-flow/SampleContract.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/analysis/control-flow/SampleContract.png -------------------------------------------------------------------------------- /analysis/description-table/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/analysis/description-table/.gitkeep -------------------------------------------------------------------------------- /analysis/description-table/SampleContract.md: -------------------------------------------------------------------------------- 1 | ## Sūrya's Description Report 2 | 3 | ### Files Description Table 4 | 5 | 6 | | File Name | SHA-1 Hash | 7 | |-------------|--------------| 8 | | dist/SampleContract.dist.sol | 08d7b69ad35c44ffb058b10b6120dd389ac55e4b | 9 | 10 | 11 | ### Contracts Description Table 12 | 13 | 14 | | Contract | Type | Bases | | | 15 | |:----------:|:-------------------:|:----------------:|:----------------:|:---------------:| 16 | | └ | **Function Name** | **Visibility** | **Mutability** | **Modifiers** | 17 | |||||| 18 | | **Context** | Implementation | ||| 19 | | └ | _msgSender | Internal 🔒 | | | 20 | | └ | _msgData | Internal 🔒 | | | 21 | | └ | _contextSuffixLength | Internal 🔒 | | | 22 | |||||| 23 | | **Ownable** | Implementation | Context ||| 24 | | └ | | Public ❗️ | 🛑 |NO❗️ | 25 | | └ | owner | Public ❗️ | |NO❗️ | 26 | | └ | _checkOwner | Internal 🔒 | | | 27 | | └ | renounceOwnership | Public ❗️ | 🛑 | onlyOwner | 28 | | └ | transferOwnership | Public ❗️ | 🛑 | onlyOwner | 29 | | └ | _transferOwnership | Internal 🔒 | 🛑 | | 30 | |||||| 31 | | **IERC165** | Interface | ||| 32 | | └ | supportsInterface | External ❗️ | |NO❗️ | 33 | |||||| 34 | | **IERC721** | Interface | IERC165 ||| 35 | | └ | balanceOf | External ❗️ | |NO❗️ | 36 | | └ | ownerOf | External ❗️ | |NO❗️ | 37 | | └ | safeTransferFrom | External ❗️ | 🛑 |NO❗️ | 38 | | └ | safeTransferFrom | External ❗️ | 🛑 |NO❗️ | 39 | | └ | transferFrom | External ❗️ | 🛑 |NO❗️ | 40 | | └ | approve | External ❗️ | 🛑 |NO❗️ | 41 | | └ | setApprovalForAll | External ❗️ | 🛑 |NO❗️ | 42 | | └ | getApproved | External ❗️ | |NO❗️ | 43 | | └ | isApprovedForAll | External ❗️ | |NO❗️ | 44 | |||||| 45 | | **IERC20** | Interface | ||| 46 | | └ | totalSupply | External ❗️ | |NO❗️ | 47 | | └ | balanceOf | External ❗️ | |NO❗️ | 48 | | └ | transfer | External ❗️ | 🛑 |NO❗️ | 49 | | └ | allowance | External ❗️ | |NO❗️ | 50 | | └ | approve | External ❗️ | 🛑 |NO❗️ | 51 | | └ | transferFrom | External ❗️ | 🛑 |NO❗️ | 52 | |||||| 53 | | **RecoverERC20** | Implementation | ||| 54 | | └ | _recoverERC20 | Internal 🔒 | 🛑 | | 55 | |||||| 56 | | **RecoverERC721** | Implementation | ||| 57 | | └ | _recoverERC721 | Internal 🔒 | 🛑 | | 58 | |||||| 59 | | **TokenRecover** | Implementation | Ownable, RecoverERC20, RecoverERC721 ||| 60 | | └ | | Public ❗️ | 🛑 | Ownable | 61 | | └ | recoverERC20 | Public ❗️ | 🛑 | onlyOwner | 62 | | └ | recoverERC721 | Public ❗️ | 🛑 | onlyOwner | 63 | |||||| 64 | | **SampleContract** | Implementation | TokenRecover ||| 65 | | └ | | Public ❗️ | 🛑 | TokenRecover | 66 | | └ | managerDoesWork | External ❗️ | 🛑 | onlyManager | 67 | | └ | ownerDoesWork | External ❗️ | 🛑 | onlyOwner | 68 | | └ | manager | Public ❗️ | |NO❗️ | 69 | | └ | _internalWork | Internal 🔒 | 🛑 | | 70 | 71 | 72 | ### Legend 73 | 74 | | Symbol | Meaning | 75 | |:--------:|-----------| 76 | | 🛑 | Function can modify state | 77 | | 💵 | Function is payable | 78 | -------------------------------------------------------------------------------- /analysis/inheritance-tree/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/analysis/inheritance-tree/.gitkeep -------------------------------------------------------------------------------- /analysis/inheritance-tree/SampleContract.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/analysis/inheritance-tree/SampleContract.png -------------------------------------------------------------------------------- /analysis/uml/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/analysis/uml/.gitkeep -------------------------------------------------------------------------------- /analysis/uml/SampleContract.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | UmlClassDiagram 11 | 12 | 13 | 14 | 0 15 | 16 | <<Abstract>> 17 | Context 18 | 19 | Internal: 20 |    _msgSender(): address 21 |    _msgData(): bytes 22 |    _contextSuffixLength(): uint256 23 | 24 | 25 | 26 | 1 27 | 28 | <<Abstract>> 29 | Ownable 30 | 31 | Private: 32 |   _owner: address 33 | 34 | Internal: 35 |    _checkOwner() 36 |    _transferOwnership(newOwner: address) 37 | Public: 38 |    <<event>> OwnershipTransferred(previousOwner: address, newOwner: address) 39 |    <<modifier>> onlyOwner() 40 |    constructor(initialOwner: address) 41 |    owner(): address 42 |    renounceOwnership() <<onlyOwner>> 43 |    transferOwnership(newOwner: address) <<onlyOwner>> 44 | 45 | 46 | 47 | 1->0 48 | 49 | 50 | 51 | 52 | 53 | 2 54 | 55 | <<Interface>> 56 | IERC165 57 | 58 | External: 59 |     supportsInterface(interfaceId: bytes4): bool 60 | 61 | 62 | 63 | 3 64 | 65 | <<Interface>> 66 | IERC721 67 | 68 | External: 69 |     balanceOf(owner: address): (balance: uint256) 70 |     ownerOf(tokenId: uint256): (owner: address) 71 |     safeTransferFrom(from: address, to: address, tokenId: uint256, data: bytes) 72 |     safeTransferFrom(from: address, to: address, tokenId: uint256) 73 |     transferFrom(from: address, to: address, tokenId: uint256) 74 |     approve(to: address, tokenId: uint256) 75 |     setApprovalForAll(operator: address, approved: bool) 76 |     getApproved(tokenId: uint256): (operator: address) 77 |     isApprovedForAll(owner: address, operator: address): bool 78 | Public: 79 |    <<event>> Transfer(from: address, to: address, tokenId: uint256) 80 |    <<event>> Approval(owner: address, approved: address, tokenId: uint256) 81 |    <<event>> ApprovalForAll(owner: address, operator: address, approved: bool) 82 | 83 | 84 | 85 | 3->2 86 | 87 | 88 | 89 | 90 | 91 | 4 92 | 93 | <<Interface>> 94 | IERC20 95 | 96 | External: 97 |     totalSupply(): uint256 98 |     balanceOf(account: address): uint256 99 |     transfer(to: address, value: uint256): bool 100 |     allowance(owner: address, spender: address): uint256 101 |     approve(spender: address, value: uint256): bool 102 |     transferFrom(from: address, to: address, value: uint256): bool 103 | Public: 104 |    <<event>> Transfer(from: address, to: address, value: uint256) 105 |    <<event>> Approval(owner: address, spender: address, value: uint256) 106 | 107 | 108 | 109 | 5 110 | 111 | <<Abstract>> 112 | RecoverERC20 113 | 114 | Internal: 115 |    _recoverERC20(tokenAddress: address, tokenReceiver: address, tokenAmount: uint256) 116 | 117 | 118 | 119 | 5->4 120 | 121 | 122 | 123 | 124 | 125 | 6 126 | 127 | <<Abstract>> 128 | RecoverERC721 129 | 130 | Internal: 131 |    _recoverERC721(tokenAddress: address, tokenReceiver: address, tokenId: uint256, data: bytes) 132 | 133 | 134 | 135 | 6->3 136 | 137 | 138 | 139 | 140 | 141 | 7 142 | 143 | <<Abstract>> 144 | TokenRecover 145 | 146 | Public: 147 |    constructor(initialOwner: address) 148 |    recoverERC20(tokenAddress: address, tokenReceiver: address, tokenAmount: uint256) <<onlyOwner>> 149 |    recoverERC721(tokenAddress: address, tokenReceiver: address, tokenId: uint256, data: bytes) <<onlyOwner>> 150 | 151 | 152 | 153 | 7->1 154 | 155 | 156 | 157 | 158 | 159 | 7->5 160 | 161 | 162 | 163 | 164 | 165 | 7->6 166 | 167 | 168 | 169 | 170 | 171 | 8 172 | 173 | SampleContract 174 | 175 | Private: 176 |   _manager: address 177 | 178 | Internal: 179 |    _internalWork(value: uint256) 180 | External: 181 |    managerDoesWork(value: uint256) <<onlyManager>> 182 |    ownerDoesWork(value: uint256) <<onlyOwner>> 183 | Public: 184 |    <<event>> WorkDone(value: uint256) 185 |    <<modifier>> onlyManager() 186 |    constructor(manager_: address) 187 |    manager(): address 188 | 189 | 190 | 191 | 8->7 192 | 193 | 194 | 195 | 196 | 197 | -------------------------------------------------------------------------------- /bs-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "server": { 3 | "baseDir": [ 4 | "./web-console", 5 | "./artifacts/contracts", 6 | "./node_modules/web3/dist" 7 | ] 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /contracts/SampleContract.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.20; 4 | 5 | import {TokenRecover} from "eth-token-recover/contracts/TokenRecover.sol"; 6 | 7 | /** 8 | * @title SampleContract 9 | * @dev Implementation of a Sample Contract 10 | * @author Vittorio Minacori 11 | */ 12 | contract SampleContract is TokenRecover { 13 | // store the manager address 14 | address private immutable _manager; 15 | 16 | /** 17 | * @dev Emitted after a work done. 18 | * @param value An amount to be emitted. 19 | */ 20 | event WorkDone(uint256 value); 21 | 22 | /** 23 | * @dev The caller account is not authorized to perform an operation. 24 | * @param account The caller account. 25 | */ 26 | error SampleContractUnauthorizedAccount(address account); 27 | 28 | /** 29 | * @dev The manager is not a valid manager account. (eg. `address(0)`) 30 | */ 31 | error SampleContractInvalidManager(address manager); 32 | 33 | /** 34 | * @dev Requires that sender is the contract manager. 35 | */ 36 | modifier onlyManager() { 37 | if (manager() != _msgSender()) { 38 | revert SampleContractUnauthorizedAccount(_msgSender()); 39 | } 40 | _; 41 | } 42 | 43 | /** 44 | * @dev Create a new contract assigning provided `manager` and assigning `owner` to deployer. 45 | */ 46 | constructor(address manager_) TokenRecover(_msgSender()) { 47 | if (manager_ == address(0)) { 48 | revert SampleContractInvalidManager(manager_); 49 | } 50 | 51 | _manager = manager_; 52 | } 53 | 54 | /** 55 | * @dev Does work for manager. 56 | * Emits a 'WorkDone' event. 57 | * @param value Just an amount to be emitted. 58 | */ 59 | function managerDoesWork(uint256 value) external onlyManager { 60 | _internalWork(value); 61 | } 62 | 63 | /** 64 | * @dev Does work for owner. 65 | * Emits a 'WorkDone' event. 66 | * @param value Just an amount to be emitted. 67 | */ 68 | function ownerDoesWork(uint256 value) external onlyOwner { 69 | _internalWork(value); 70 | } 71 | 72 | /** 73 | * @dev Return the contract manager. 74 | * @return An address indicating the manager. 75 | */ 76 | function manager() public view returns (address) { 77 | return _manager; 78 | } 79 | 80 | /** 81 | * @dev Low level work method. 82 | * Emits a 'WorkDone' event. 83 | * @param value Just an amount to be emitted. 84 | */ 85 | function _internalWork(uint256 value) internal { 86 | emit WorkDone(value); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /contracts/mocks/ERC20Mock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.20; 4 | 5 | import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 6 | 7 | // mock class using ERC20 8 | contract ERC20Mock is ERC20 { 9 | constructor() ERC20("TEST", "TEST") {} 10 | } 11 | -------------------------------------------------------------------------------- /contracts/mocks/ERC721Mock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.20; 4 | 5 | import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; 6 | 7 | // mock class using ERC721 8 | contract ERC721Mock is ERC721 { 9 | constructor() ERC721("TEST", "TEST") {} 10 | } 11 | -------------------------------------------------------------------------------- /dist/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/dist/.gitkeep -------------------------------------------------------------------------------- /dist/SampleContract.dist.sol: -------------------------------------------------------------------------------- 1 | // Sources flattened with hardhat v2.22.19 https://hardhat.org 2 | 3 | // SPDX-License-Identifier: MIT 4 | 5 | // File @openzeppelin/contracts/utils/Context.sol@v5.2.0 6 | 7 | // Original license: SPDX_License_Identifier: MIT 8 | // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) 9 | 10 | pragma solidity ^0.8.20; 11 | 12 | /** 13 | * @dev Provides information about the current execution context, including the 14 | * sender of the transaction and its data. While these are generally available 15 | * via msg.sender and msg.data, they should not be accessed in such a direct 16 | * manner, since when dealing with meta-transactions the account sending and 17 | * paying for execution may not be the actual sender (as far as an application 18 | * is concerned). 19 | * 20 | * This contract is only required for intermediate, library-like contracts. 21 | */ 22 | abstract contract Context { 23 | function _msgSender() internal view virtual returns (address) { 24 | return msg.sender; 25 | } 26 | 27 | function _msgData() internal view virtual returns (bytes calldata) { 28 | return msg.data; 29 | } 30 | 31 | function _contextSuffixLength() internal view virtual returns (uint256) { 32 | return 0; 33 | } 34 | } 35 | 36 | 37 | // File @openzeppelin/contracts/access/Ownable.sol@v5.2.0 38 | 39 | // Original license: SPDX_License_Identifier: MIT 40 | // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) 41 | 42 | pragma solidity ^0.8.20; 43 | 44 | /** 45 | * @dev Contract module which provides a basic access control mechanism, where 46 | * there is an account (an owner) that can be granted exclusive access to 47 | * specific functions. 48 | * 49 | * The initial owner is set to the address provided by the deployer. This can 50 | * later be changed with {transferOwnership}. 51 | * 52 | * This module is used through inheritance. It will make available the modifier 53 | * `onlyOwner`, which can be applied to your functions to restrict their use to 54 | * the owner. 55 | */ 56 | abstract contract Ownable is Context { 57 | address private _owner; 58 | 59 | /** 60 | * @dev The caller account is not authorized to perform an operation. 61 | */ 62 | error OwnableUnauthorizedAccount(address account); 63 | 64 | /** 65 | * @dev The owner is not a valid owner account. (eg. `address(0)`) 66 | */ 67 | error OwnableInvalidOwner(address owner); 68 | 69 | event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); 70 | 71 | /** 72 | * @dev Initializes the contract setting the address provided by the deployer as the initial owner. 73 | */ 74 | constructor(address initialOwner) { 75 | if (initialOwner == address(0)) { 76 | revert OwnableInvalidOwner(address(0)); 77 | } 78 | _transferOwnership(initialOwner); 79 | } 80 | 81 | /** 82 | * @dev Throws if called by any account other than the owner. 83 | */ 84 | modifier onlyOwner() { 85 | _checkOwner(); 86 | _; 87 | } 88 | 89 | /** 90 | * @dev Returns the address of the current owner. 91 | */ 92 | function owner() public view virtual returns (address) { 93 | return _owner; 94 | } 95 | 96 | /** 97 | * @dev Throws if the sender is not the owner. 98 | */ 99 | function _checkOwner() internal view virtual { 100 | if (owner() != _msgSender()) { 101 | revert OwnableUnauthorizedAccount(_msgSender()); 102 | } 103 | } 104 | 105 | /** 106 | * @dev Leaves the contract without owner. It will not be possible to call 107 | * `onlyOwner` functions. Can only be called by the current owner. 108 | * 109 | * NOTE: Renouncing ownership will leave the contract without an owner, 110 | * thereby disabling any functionality that is only available to the owner. 111 | */ 112 | function renounceOwnership() public virtual onlyOwner { 113 | _transferOwnership(address(0)); 114 | } 115 | 116 | /** 117 | * @dev Transfers ownership of the contract to a new account (`newOwner`). 118 | * Can only be called by the current owner. 119 | */ 120 | function transferOwnership(address newOwner) public virtual onlyOwner { 121 | if (newOwner == address(0)) { 122 | revert OwnableInvalidOwner(address(0)); 123 | } 124 | _transferOwnership(newOwner); 125 | } 126 | 127 | /** 128 | * @dev Transfers ownership of the contract to a new account (`newOwner`). 129 | * Internal function without access restriction. 130 | */ 131 | function _transferOwnership(address newOwner) internal virtual { 132 | address oldOwner = _owner; 133 | _owner = newOwner; 134 | emit OwnershipTransferred(oldOwner, newOwner); 135 | } 136 | } 137 | 138 | 139 | // File @openzeppelin/contracts/utils/introspection/IERC165.sol@v5.2.0 140 | 141 | // Original license: SPDX_License_Identifier: MIT 142 | // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol) 143 | 144 | pragma solidity ^0.8.20; 145 | 146 | /** 147 | * @dev Interface of the ERC-165 standard, as defined in the 148 | * https://eips.ethereum.org/EIPS/eip-165[ERC]. 149 | * 150 | * Implementers can declare support of contract interfaces, which can then be 151 | * queried by others ({ERC165Checker}). 152 | * 153 | * For an implementation, see {ERC165}. 154 | */ 155 | interface IERC165 { 156 | /** 157 | * @dev Returns true if this contract implements the interface defined by 158 | * `interfaceId`. See the corresponding 159 | * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section] 160 | * to learn more about how these ids are created. 161 | * 162 | * This function call must use less than 30 000 gas. 163 | */ 164 | function supportsInterface(bytes4 interfaceId) external view returns (bool); 165 | } 166 | 167 | 168 | // File @openzeppelin/contracts/token/ERC721/IERC721.sol@v5.2.0 169 | 170 | // Original license: SPDX_License_Identifier: MIT 171 | // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol) 172 | 173 | pragma solidity ^0.8.20; 174 | 175 | /** 176 | * @dev Required interface of an ERC-721 compliant contract. 177 | */ 178 | interface IERC721 is IERC165 { 179 | /** 180 | * @dev Emitted when `tokenId` token is transferred from `from` to `to`. 181 | */ 182 | event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); 183 | 184 | /** 185 | * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. 186 | */ 187 | event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); 188 | 189 | /** 190 | * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. 191 | */ 192 | event ApprovalForAll(address indexed owner, address indexed operator, bool approved); 193 | 194 | /** 195 | * @dev Returns the number of tokens in ``owner``'s account. 196 | */ 197 | function balanceOf(address owner) external view returns (uint256 balance); 198 | 199 | /** 200 | * @dev Returns the owner of the `tokenId` token. 201 | * 202 | * Requirements: 203 | * 204 | * - `tokenId` must exist. 205 | */ 206 | function ownerOf(uint256 tokenId) external view returns (address owner); 207 | 208 | /** 209 | * @dev Safely transfers `tokenId` token from `from` to `to`. 210 | * 211 | * Requirements: 212 | * 213 | * - `from` cannot be the zero address. 214 | * - `to` cannot be the zero address. 215 | * - `tokenId` token must exist and be owned by `from`. 216 | * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. 217 | * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon 218 | * a safe transfer. 219 | * 220 | * Emits a {Transfer} event. 221 | */ 222 | function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; 223 | 224 | /** 225 | * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients 226 | * are aware of the ERC-721 protocol to prevent tokens from being forever locked. 227 | * 228 | * Requirements: 229 | * 230 | * - `from` cannot be the zero address. 231 | * - `to` cannot be the zero address. 232 | * - `tokenId` token must exist and be owned by `from`. 233 | * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or 234 | * {setApprovalForAll}. 235 | * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon 236 | * a safe transfer. 237 | * 238 | * Emits a {Transfer} event. 239 | */ 240 | function safeTransferFrom(address from, address to, uint256 tokenId) external; 241 | 242 | /** 243 | * @dev Transfers `tokenId` token from `from` to `to`. 244 | * 245 | * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721 246 | * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must 247 | * understand this adds an external call which potentially creates a reentrancy vulnerability. 248 | * 249 | * Requirements: 250 | * 251 | * - `from` cannot be the zero address. 252 | * - `to` cannot be the zero address. 253 | * - `tokenId` token must be owned by `from`. 254 | * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. 255 | * 256 | * Emits a {Transfer} event. 257 | */ 258 | function transferFrom(address from, address to, uint256 tokenId) external; 259 | 260 | /** 261 | * @dev Gives permission to `to` to transfer `tokenId` token to another account. 262 | * The approval is cleared when the token is transferred. 263 | * 264 | * Only a single account can be approved at a time, so approving the zero address clears previous approvals. 265 | * 266 | * Requirements: 267 | * 268 | * - The caller must own the token or be an approved operator. 269 | * - `tokenId` must exist. 270 | * 271 | * Emits an {Approval} event. 272 | */ 273 | function approve(address to, uint256 tokenId) external; 274 | 275 | /** 276 | * @dev Approve or remove `operator` as an operator for the caller. 277 | * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. 278 | * 279 | * Requirements: 280 | * 281 | * - The `operator` cannot be the address zero. 282 | * 283 | * Emits an {ApprovalForAll} event. 284 | */ 285 | function setApprovalForAll(address operator, bool approved) external; 286 | 287 | /** 288 | * @dev Returns the account approved for `tokenId` token. 289 | * 290 | * Requirements: 291 | * 292 | * - `tokenId` must exist. 293 | */ 294 | function getApproved(uint256 tokenId) external view returns (address operator); 295 | 296 | /** 297 | * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. 298 | * 299 | * See {setApprovalForAll} 300 | */ 301 | function isApprovedForAll(address owner, address operator) external view returns (bool); 302 | } 303 | 304 | 305 | // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v5.2.0 306 | 307 | // Original license: SPDX_License_Identifier: MIT 308 | // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol) 309 | 310 | pragma solidity ^0.8.20; 311 | 312 | /** 313 | * @dev Interface of the ERC-20 standard as defined in the ERC. 314 | */ 315 | interface IERC20 { 316 | /** 317 | * @dev Emitted when `value` tokens are moved from one account (`from`) to 318 | * another (`to`). 319 | * 320 | * Note that `value` may be zero. 321 | */ 322 | event Transfer(address indexed from, address indexed to, uint256 value); 323 | 324 | /** 325 | * @dev Emitted when the allowance of a `spender` for an `owner` is set by 326 | * a call to {approve}. `value` is the new allowance. 327 | */ 328 | event Approval(address indexed owner, address indexed spender, uint256 value); 329 | 330 | /** 331 | * @dev Returns the value of tokens in existence. 332 | */ 333 | function totalSupply() external view returns (uint256); 334 | 335 | /** 336 | * @dev Returns the value of tokens owned by `account`. 337 | */ 338 | function balanceOf(address account) external view returns (uint256); 339 | 340 | /** 341 | * @dev Moves a `value` amount of tokens from the caller's account to `to`. 342 | * 343 | * Returns a boolean value indicating whether the operation succeeded. 344 | * 345 | * Emits a {Transfer} event. 346 | */ 347 | function transfer(address to, uint256 value) external returns (bool); 348 | 349 | /** 350 | * @dev Returns the remaining number of tokens that `spender` will be 351 | * allowed to spend on behalf of `owner` through {transferFrom}. This is 352 | * zero by default. 353 | * 354 | * This value changes when {approve} or {transferFrom} are called. 355 | */ 356 | function allowance(address owner, address spender) external view returns (uint256); 357 | 358 | /** 359 | * @dev Sets a `value` amount of tokens as the allowance of `spender` over the 360 | * caller's tokens. 361 | * 362 | * Returns a boolean value indicating whether the operation succeeded. 363 | * 364 | * IMPORTANT: Beware that changing an allowance with this method brings the risk 365 | * that someone may use both the old and the new allowance by unfortunate 366 | * transaction ordering. One possible solution to mitigate this race 367 | * condition is to first reduce the spender's allowance to 0 and set the 368 | * desired value afterwards: 369 | * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 370 | * 371 | * Emits an {Approval} event. 372 | */ 373 | function approve(address spender, uint256 value) external returns (bool); 374 | 375 | /** 376 | * @dev Moves a `value` amount of tokens from `from` to `to` using the 377 | * allowance mechanism. `value` is then deducted from the caller's 378 | * allowance. 379 | * 380 | * Returns a boolean value indicating whether the operation succeeded. 381 | * 382 | * Emits a {Transfer} event. 383 | */ 384 | function transferFrom(address from, address to, uint256 value) external returns (bool); 385 | } 386 | 387 | 388 | // File eth-token-recover/contracts/recover/RecoverERC20.sol@v6.5.0 389 | 390 | // Original license: SPDX_License_Identifier: MIT 391 | 392 | pragma solidity ^0.8.20; 393 | 394 | /** 395 | * @title RecoverERC20 396 | * @dev Allows to recover any ERC-20 token sent into the contract and sends them to a receiver. 397 | */ 398 | abstract contract RecoverERC20 { 399 | /** 400 | * @dev Recovers a `tokenAmount` of the ERC-20 `tokenAddress` locked into this contract 401 | * and sends them to the `tokenReceiver` address. 402 | * 403 | * WARNING: it allows everyone to recover tokens. Access controls MUST be defined in derived contracts. 404 | * 405 | * @param tokenAddress The contract address of the token to recover. 406 | * @param tokenReceiver The address that will receive the recovered tokens. 407 | * @param tokenAmount Number of tokens to be recovered. 408 | */ 409 | function _recoverERC20(address tokenAddress, address tokenReceiver, uint256 tokenAmount) internal virtual { 410 | // slither-disable-next-line unchecked-transfer 411 | IERC20(tokenAddress).transfer(tokenReceiver, tokenAmount); 412 | } 413 | } 414 | 415 | 416 | // File eth-token-recover/contracts/recover/RecoverERC721.sol@v6.5.0 417 | 418 | // Original license: SPDX_License_Identifier: MIT 419 | 420 | pragma solidity ^0.8.20; 421 | 422 | /** 423 | * @title RecoverERC721 424 | * @dev Allows to recover any ERC-721 token sent into the contract and sends them to a receiver. 425 | */ 426 | abstract contract RecoverERC721 { 427 | /** 428 | * @dev Recovers the `tokenId` of the ERC-721 `tokenAddress` locked into this contract 429 | * and sends it to the `tokenReceiver` address. 430 | * 431 | * WARNING: it allows everyone to recover tokens. Access controls MUST be defined in derived contracts. 432 | * 433 | * @param tokenAddress The contract address of the token to recover. 434 | * @param tokenReceiver The address that will receive the recovered token. 435 | * @param tokenId The identifier for the NFT to be recovered. 436 | * @param data Additional data with no specified format. 437 | */ 438 | function _recoverERC721( 439 | address tokenAddress, 440 | address tokenReceiver, 441 | uint256 tokenId, 442 | bytes memory data 443 | ) internal virtual { 444 | IERC721(tokenAddress).safeTransferFrom(address(this), tokenReceiver, tokenId, data); 445 | } 446 | } 447 | 448 | 449 | // File eth-token-recover/contracts/TokenRecover.sol@v6.5.0 450 | 451 | // Original license: SPDX_License_Identifier: MIT 452 | 453 | pragma solidity ^0.8.20; 454 | 455 | 456 | /** 457 | * @title TokenRecover 458 | * @dev Allows the contract owner to recover any ERC-20 or ERC-721 token sent into the contract 459 | * and sends them to a receiver. 460 | */ 461 | abstract contract TokenRecover is Ownable, RecoverERC20, RecoverERC721 { 462 | /** 463 | * @dev Initializes the contract setting the address provided by the deployer as the initial owner. 464 | */ 465 | constructor(address initialOwner) Ownable(initialOwner) {} 466 | 467 | /** 468 | * @dev Recovers a `tokenAmount` of the ERC-20 `tokenAddress` locked into this contract 469 | * and sends them to the `tokenReceiver` address. 470 | * 471 | * NOTE: restricting access to owner only. See `RecoverERC20::_recoverERC20`. 472 | * 473 | * @param tokenAddress The contract address of the token to recover. 474 | * @param tokenReceiver The address that will receive the recovered tokens. 475 | * @param tokenAmount Number of tokens to be recovered. 476 | */ 477 | function recoverERC20(address tokenAddress, address tokenReceiver, uint256 tokenAmount) public virtual onlyOwner { 478 | _recoverERC20(tokenAddress, tokenReceiver, tokenAmount); 479 | } 480 | 481 | /** 482 | * @dev Recovers the `tokenId` of the ERC-721 `tokenAddress` locked into this contract 483 | * and sends it to the `tokenReceiver` address. 484 | * 485 | * NOTE: restricting access to owner only. See `RecoverERC721::_recoverERC721`. 486 | * 487 | * @param tokenAddress The contract address of the token to recover. 488 | * @param tokenReceiver The address that will receive the recovered token. 489 | * @param tokenId The identifier for the NFT to be recovered. 490 | * @param data Additional data with no specified format. 491 | */ 492 | function recoverERC721( 493 | address tokenAddress, 494 | address tokenReceiver, 495 | uint256 tokenId, 496 | bytes memory data 497 | ) public virtual onlyOwner { 498 | _recoverERC721(tokenAddress, tokenReceiver, tokenId, data); 499 | } 500 | } 501 | 502 | 503 | // File contracts/SampleContract.sol 504 | 505 | // Original license: SPDX_License_Identifier: MIT 506 | 507 | pragma solidity ^0.8.20; 508 | 509 | /** 510 | * @title SampleContract 511 | * @dev Implementation of a Sample Contract 512 | * @author Vittorio Minacori 513 | */ 514 | contract SampleContract is TokenRecover { 515 | // store the manager address 516 | address private immutable _manager; 517 | 518 | /** 519 | * @dev Emitted after a work done. 520 | * @param value An amount to be emitted. 521 | */ 522 | event WorkDone(uint256 value); 523 | 524 | /** 525 | * @dev The caller account is not authorized to perform an operation. 526 | * @param account The caller account. 527 | */ 528 | error SampleContractUnauthorizedAccount(address account); 529 | 530 | /** 531 | * @dev The manager is not a valid manager account. (eg. `address(0)`) 532 | */ 533 | error SampleContractInvalidManager(address manager); 534 | 535 | /** 536 | * @dev Requires that sender is the contract manager. 537 | */ 538 | modifier onlyManager() { 539 | if (manager() != _msgSender()) { 540 | revert SampleContractUnauthorizedAccount(_msgSender()); 541 | } 542 | _; 543 | } 544 | 545 | /** 546 | * @dev Create a new contract assigning provided `manager` and assigning `owner` to deployer. 547 | */ 548 | constructor(address manager_) TokenRecover(_msgSender()) { 549 | if (manager_ == address(0)) { 550 | revert SampleContractInvalidManager(manager_); 551 | } 552 | 553 | _manager = manager_; 554 | } 555 | 556 | /** 557 | * @dev Does work for manager. 558 | * Emits a 'WorkDone' event. 559 | * @param value Just an amount to be emitted. 560 | */ 561 | function managerDoesWork(uint256 value) external onlyManager { 562 | _internalWork(value); 563 | } 564 | 565 | /** 566 | * @dev Does work for owner. 567 | * Emits a 'WorkDone' event. 568 | * @param value Just an amount to be emitted. 569 | */ 570 | function ownerDoesWork(uint256 value) external onlyOwner { 571 | _internalWork(value); 572 | } 573 | 574 | /** 575 | * @dev Return the contract manager. 576 | * @return An address indicating the manager. 577 | */ 578 | function manager() public view returns (address) { 579 | return _manager; 580 | } 581 | 582 | /** 583 | * @dev Low level work method. 584 | * Emits a 'WorkDone' event. 585 | * @param value Just an amount to be emitted. 586 | */ 587 | function _internalWork(uint256 value) internal { 588 | emit WorkDone(value); 589 | } 590 | } 591 | -------------------------------------------------------------------------------- /docs/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/docs/.gitkeep -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # Solidity API 2 | 3 | ## SampleContract 4 | 5 | _Implementation of a Sample Contract_ 6 | 7 | ### WorkDone 8 | 9 | ```solidity 10 | event WorkDone(uint256 value) 11 | ``` 12 | 13 | _Emitted after a work done._ 14 | 15 | #### Parameters 16 | 17 | | Name | Type | Description | 18 | | ---- | ---- | ----------- | 19 | | value | uint256 | An amount to be emitted. | 20 | 21 | ### SampleContractUnauthorizedAccount 22 | 23 | ```solidity 24 | error SampleContractUnauthorizedAccount(address account) 25 | ``` 26 | 27 | _The caller account is not authorized to perform an operation._ 28 | 29 | #### Parameters 30 | 31 | | Name | Type | Description | 32 | | ---- | ---- | ----------- | 33 | | account | address | The caller account. | 34 | 35 | ### SampleContractInvalidManager 36 | 37 | ```solidity 38 | error SampleContractInvalidManager(address manager) 39 | ``` 40 | 41 | _The manager is not a valid manager account. (eg. `address(0)`)_ 42 | 43 | ### onlyManager 44 | 45 | ```solidity 46 | modifier onlyManager() 47 | ``` 48 | 49 | _Requires that sender is the contract manager._ 50 | 51 | ### constructor 52 | 53 | ```solidity 54 | constructor(address manager_) public 55 | ``` 56 | 57 | _Create a new contract assigning provided `manager` and assigning `owner` to deployer._ 58 | 59 | ### managerDoesWork 60 | 61 | ```solidity 62 | function managerDoesWork(uint256 value) external 63 | ``` 64 | 65 | _Does work for manager. 66 | Emits a 'WorkDone' event._ 67 | 68 | #### Parameters 69 | 70 | | Name | Type | Description | 71 | | ---- | ---- | ----------- | 72 | | value | uint256 | Just an amount to be emitted. | 73 | 74 | ### ownerDoesWork 75 | 76 | ```solidity 77 | function ownerDoesWork(uint256 value) external 78 | ``` 79 | 80 | _Does work for owner. 81 | Emits a 'WorkDone' event._ 82 | 83 | #### Parameters 84 | 85 | | Name | Type | Description | 86 | | ---- | ---- | ----------- | 87 | | value | uint256 | Just an amount to be emitted. | 88 | 89 | ### manager 90 | 91 | ```solidity 92 | function manager() public view returns (address) 93 | ``` 94 | 95 | _Return the contract manager._ 96 | 97 | #### Return Values 98 | 99 | | Name | Type | Description | 100 | | ---- | ---- | ----------- | 101 | | [0] | address | An address indicating the manager. | 102 | 103 | ### _internalWork 104 | 105 | ```solidity 106 | function _internalWork(uint256 value) internal 107 | ``` 108 | 109 | _Low level work method. 110 | Emits a 'WorkDone' event._ 111 | 112 | #### Parameters 113 | 114 | | Name | Type | Description | 115 | | ---- | ---- | ----------- | 116 | | value | uint256 | Just an amount to be emitted. | 117 | 118 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import js from '@eslint/js'; 2 | import { includeIgnoreFile } from '@eslint/compat'; 3 | import prettier from 'eslint-config-prettier'; 4 | import mochaNoOnly from 'eslint-plugin-mocha-no-only'; 5 | import globals from 'globals'; 6 | import path from 'path'; 7 | 8 | export default [ 9 | js.configs.recommended, 10 | prettier, 11 | { 12 | plugins: { 13 | mochaNoOnly, 14 | }, 15 | languageOptions: { 16 | ecmaVersion: 2022, 17 | globals: { 18 | ...globals.browser, 19 | ...globals.mocha, 20 | ...globals.node, 21 | artifacts: 'readonly', 22 | contract: 'readonly', 23 | web3: 'readonly', 24 | extendEnvironment: 'readonly', 25 | expect: 'readonly', 26 | }, 27 | }, 28 | rules: { 'mochaNoOnly/mocha-no-only': ['error'] }, 29 | }, 30 | includeIgnoreFile(path.resolve(import.meta.dirname, '.gitignore')), 31 | ]; 32 | -------------------------------------------------------------------------------- /hardhat.config.js: -------------------------------------------------------------------------------- 1 | require('@nomiclabs/hardhat-truffle5'); 2 | require('hardhat-exposed'); 3 | require('hardhat-gas-reporter'); 4 | require('solidity-coverage'); 5 | require('solidity-docgen'); 6 | 7 | module.exports = { 8 | defaultNetwork: 'hardhat', 9 | solidity: { 10 | version: '0.8.28', 11 | settings: { 12 | evmVersion: 'cancun', 13 | optimizer: { 14 | enabled: true, 15 | runs: 200, 16 | }, 17 | }, 18 | }, 19 | docgen: { 20 | outputDir: 'docs', 21 | exclude: ['mocks', 'examples'], 22 | }, 23 | exposed: { 24 | imports: false, 25 | initializers: true, 26 | exclude: ['vendor/**/*'], 27 | }, 28 | gasReporter: { 29 | enabled: true, 30 | excludeContracts: ['mocks', 'examples', '@openzeppelin/contracts'], 31 | showMethodSig: true, 32 | trackGasDeltas: true, 33 | }, 34 | }; 35 | -------------------------------------------------------------------------------- /migrations/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/migrations/.gitkeep -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Solidity Toolkit", 3 | "name": "solidity-toolkit", 4 | "version": "1.0.0", 5 | "description": "A toolkit for Solidity Smart Contracts development.", 6 | "private": true, 7 | "files": [ 8 | "contracts", 9 | "test" 10 | ], 11 | "keywords": [ 12 | "solidity", 13 | "web3" 14 | ], 15 | "scripts": { 16 | "dev": "lite-server", 17 | "console": "hardhat console", 18 | "compile": "hardhat compile", 19 | "test": "hardhat test", 20 | "coverage": "hardhat coverage", 21 | "clean": "hardhat clean && rimraf build contracts/build coverage coverage.json", 22 | "profile": "npm run clean && npm run coverage && open coverage/index.html", 23 | "check:inheritance": "scripts/checks/inheritance-ordering.js artifacts/build-info/*", 24 | "lint": "npm run lint:js && npm run lint:sol", 25 | "lint:fix": "npm run lint:js:fix && npm run lint:sol:fix", 26 | "lint:js": "prettier --log-level warn --ignore-path .gitignore '**/*.{js,mjs,ts}' --check && eslint .", 27 | "lint:js:fix": "prettier --log-level warn --ignore-path .gitignore '**/*.{js,mjs,ts}' --write && eslint . --fix", 28 | "lint:sol": "prettier --log-level warn --ignore-path .gitignore '{contracts,test}/**/*.sol' --check && solhint '{contracts,test}/**/*.sol'", 29 | "lint:sol:fix": "prettier --log-level warn --ignore-path .gitignore '{contracts,test}/**/*.sol' --write", 30 | "flat": "scripts/flat.sh", 31 | "analyze": "scripts/analyze.sh", 32 | "docs": "hardhat docgen", 33 | "pages:dev": "vitepress dev pages", 34 | "pages:build": "vitepress build pages", 35 | "pages:deploy": "vitepress build pages && sh pages/deploy/deploy.sh" 36 | }, 37 | "repository": { 38 | "type": "git", 39 | "url": "https://github.com/noncept/solidity-toolkit.git" 40 | }, 41 | "homepage": "https://github.com/noncept/solidity-toolkit/", 42 | "bugs": { 43 | "url": "https://github.com/noncept/solidity-toolkit/issues" 44 | }, 45 | "author": "NONCEPT (https://noncept.com)", 46 | "contributors": [ 47 | { 48 | "name": "Vittorio Minacori", 49 | "url": "https://github.com/vittominacori" 50 | } 51 | ], 52 | "license": "MIT", 53 | "devDependencies": { 54 | "@eslint/compat": "^1.2.7", 55 | "@eslint/eslintrc": "^3.3.0", 56 | "@eslint/js": "^9.22.0", 57 | "@nomiclabs/hardhat-truffle5": "^2.0.7", 58 | "@nomiclabs/hardhat-web3": "^2.0.1", 59 | "@openzeppelin/test-helpers": "^0.5.16", 60 | "chai": "^4.5.0", 61 | "eslint": "^9.22.0", 62 | "eslint-config-prettier": "^10.1.1", 63 | "eslint-plugin-mocha-no-only": "^1.2.0", 64 | "eth-sig-util": "^3.0.1", 65 | "ethereumjs-util": "^7.1.5", 66 | "ethereumjs-wallet": "^1.0.2", 67 | "globals": "^16.0.0", 68 | "graphlib": "^2.1.8", 69 | "hardhat": "^2.22.19", 70 | "hardhat-exposed": "^0.3.17", 71 | "hardhat-gas-reporter": "^2.2.2", 72 | "keccak256": "^1.0.6", 73 | "lite-server": "^2.6.1", 74 | "prettier": "^3.5.3", 75 | "prettier-plugin-solidity": "^1.4.2", 76 | "rimraf": "^6.0.1", 77 | "sol2uml": "^2.5.21", 78 | "solhint": "^5.0.5", 79 | "solhint-plugin-openzeppelin": "file:scripts/solhint-custom", 80 | "solidity-coverage": "^0.8.14", 81 | "solidity-docgen": "^0.6.0-beta.36", 82 | "surya": "^0.4.12", 83 | "vitepress": "^1.6.3", 84 | "yargs": "^17.7.2" 85 | }, 86 | "dependencies": { 87 | "@openzeppelin/contracts": "5.2.0", 88 | "eth-token-recover": "6.5.0" 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /pages/.vitepress/config.mjs: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitepress'; 2 | 3 | const title = 'Solidity Toolkit | NONCEPT'; 4 | const description = 'A toolkit for Solidity Smart Contracts development.'; 5 | const url = 'https://noncept.github.io/solidity-toolkit'; 6 | const image = 'https://noncept.github.io/solidity-toolkit/images/solidity-toolkit.png'; 7 | const repo = 'https://github.com/noncept/solidity-toolkit.git'; 8 | 9 | export default defineConfig({ 10 | title: 'Solidity Toolkit', 11 | titleTemplate: 'NONCEPT', 12 | description: description, 13 | base: '/solidity-toolkit/', 14 | head: [ 15 | ['link', { rel: 'shortcut icon', href: '/solidity-toolkit/favicon.ico' }], 16 | ['meta', { name: 'title', property: 'og:title', content: title }], 17 | ['meta', { name: 'description', property: 'og:description', content: description }], 18 | ['meta', { name: 'image', property: 'og:image', content: image }], 19 | ['meta', { property: 'og:title', content: title }], 20 | ['meta', { property: 'og:description', content: description }], 21 | ['meta', { property: 'og:image', content: image }], 22 | ['meta', { property: 'og:type', content: 'website' }], 23 | ['meta', { property: 'og:url', content: url }], 24 | ['meta', { property: 'twitter:title', content: title }], 25 | ['meta', { property: 'twitter:description', content: description }], 26 | ['meta', { property: 'twitter:image', content: image }], 27 | ['meta', { property: 'twitter:card', content: 'summary_large_image' }], 28 | ], 29 | themeConfig: { 30 | siteTitle: 'Solidity Toolkit', 31 | socialLinks: [{ icon: 'github', link: repo }], 32 | search: { 33 | provider: 'local', 34 | }, 35 | }, 36 | }); 37 | -------------------------------------------------------------------------------- /pages/.vitepress/theme/custom.css: -------------------------------------------------------------------------------- 1 | .vp-doc h1 + p a img { 2 | display: inline-block; 3 | margin: 2px; 4 | } 5 | -------------------------------------------------------------------------------- /pages/.vitepress/theme/index.js: -------------------------------------------------------------------------------- 1 | import DefaultTheme from 'vitepress/theme'; 2 | import './custom.css'; 3 | 4 | export default DefaultTheme; 5 | -------------------------------------------------------------------------------- /pages/deploy/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # https://github.com/X1011/git-directory-deploy 3 | set -o errexit #abort if any command fails 4 | me=$(basename "$0") 5 | 6 | help_message="\ 7 | Usage: $me [-c FILE] [] 8 | Deploy generated files to a git branch. 9 | 10 | Options: 11 | 12 | -h, --help Show this help information. 13 | -v, --verbose Increase verbosity. Useful for debugging. 14 | -e, --allow-empty Allow deployment of an empty directory. 15 | -m, --message MESSAGE Specify the message used when committing on the 16 | deploy branch. 17 | -n, --no-hash Don't append the source commit's hash to the deploy 18 | commit's message. 19 | -c, --config-file PATH Override default & environment variables' values 20 | with those in set in the file at 'PATH'. Must be the 21 | first option specified. 22 | 23 | Variables: 24 | 25 | GIT_DEPLOY_DIR Folder path containing the files to deploy. 26 | GIT_DEPLOY_BRANCH Commit deployable files to this branch. 27 | GIT_DEPLOY_REPO Push the deploy branch to this repository. 28 | 29 | These variables have default values defined in the script. The defaults can be 30 | overridden by environment variables. Any environment variables are overridden 31 | by values set in a '.env' file (if it exists), and in turn by those set in a 32 | file specified by the '--config-file' option." 33 | 34 | parse_args() { 35 | # Set args from a local environment file. 36 | if [ -e ".env" ]; then 37 | source .env 38 | fi 39 | 40 | # Set args from file specified on the command-line. 41 | if [[ $1 = "-c" || $1 = "--config-file" ]]; then 42 | source "$2" 43 | shift 2 44 | fi 45 | 46 | # Parse arg flags 47 | # If something is exposed as an environment variable, set/overwrite it 48 | # here. Otherwise, set/overwrite the internal variable instead. 49 | while : ; do 50 | if [[ $1 = "-h" || $1 = "--help" ]]; then 51 | echo "$help_message" 52 | return 0 53 | elif [[ $1 = "-v" || $1 = "--verbose" ]]; then 54 | verbose=true 55 | shift 56 | elif [[ $1 = "-e" || $1 = "--allow-empty" ]]; then 57 | allow_empty=true 58 | shift 59 | elif [[ ( $1 = "-m" || $1 = "--message" ) && -n $2 ]]; then 60 | commit_message=$2 61 | shift 2 62 | elif [[ $1 = "-n" || $1 = "--no-hash" ]]; then 63 | GIT_DEPLOY_APPEND_HASH=false 64 | shift 65 | else 66 | break 67 | fi 68 | done 69 | 70 | # Set internal option vars from the environment and arg flags. All internal 71 | # vars should be declared here, with sane defaults if applicable. 72 | 73 | # Source directory & target branch. 74 | deploy_directory=${GIT_DEPLOY_DIR:-dist} 75 | deploy_branch=${GIT_DEPLOY_BRANCH:-gh-pages} 76 | 77 | #if no user identity is already set in the current git environment, use this: 78 | default_username=${GIT_DEPLOY_USERNAME:-deploy.sh} 79 | default_email=${GIT_DEPLOY_EMAIL:-} 80 | 81 | #repository to deploy to. must be readable and writable. 82 | repo=${GIT_DEPLOY_REPO:-origin} 83 | 84 | #append commit hash to the end of message by default 85 | append_hash=${GIT_DEPLOY_APPEND_HASH:-true} 86 | } 87 | 88 | main() { 89 | parse_args "$@" 90 | 91 | enable_expanded_output 92 | 93 | if ! git diff --exit-code --quiet --cached; then 94 | echo Aborting due to uncommitted changes in the index >&2 95 | return 1 96 | fi 97 | 98 | commit_title=`git log -n 1 --format="%s" HEAD` 99 | commit_hash=` git log -n 1 --format="%H" HEAD` 100 | 101 | #default commit message uses last title if a custom one is not supplied 102 | if [[ -z $commit_message ]]; then 103 | commit_message="publish: $commit_title" 104 | fi 105 | 106 | #append hash to commit message unless no hash flag was found 107 | if [ $append_hash = true ]; then 108 | commit_message="$commit_message"$'\n\n'"generated from commit $commit_hash" 109 | fi 110 | 111 | previous_branch=`git rev-parse --abbrev-ref HEAD` 112 | 113 | if [ ! -d "$deploy_directory" ]; then 114 | echo "Deploy directory '$deploy_directory' does not exist. Aborting." >&2 115 | return 1 116 | fi 117 | 118 | # must use short form of flag in ls for compatibility with OS X and BSD 119 | if [[ -z `ls -A "$deploy_directory" 2> /dev/null` && -z $allow_empty ]]; then 120 | echo "Deploy directory '$deploy_directory' is empty. Aborting. If you're sure you want to deploy an empty tree, use the --allow-empty / -e flag." >&2 121 | return 1 122 | fi 123 | 124 | if git ls-remote --exit-code $repo "refs/heads/$deploy_branch" ; then 125 | # deploy_branch exists in $repo; make sure we have the latest version 126 | 127 | disable_expanded_output 128 | git fetch --force $repo $deploy_branch:$deploy_branch 129 | enable_expanded_output 130 | fi 131 | 132 | # check if deploy_branch exists locally 133 | if git show-ref --verify --quiet "refs/heads/$deploy_branch" 134 | then incremental_deploy 135 | else initial_deploy 136 | fi 137 | 138 | restore_head 139 | } 140 | 141 | initial_deploy() { 142 | git --work-tree "$deploy_directory" checkout --orphan $deploy_branch 143 | git --work-tree "$deploy_directory" add --all 144 | commit_push 145 | } 146 | 147 | incremental_deploy() { 148 | #make deploy_branch the current branch 149 | git symbolic-ref HEAD refs/heads/$deploy_branch 150 | #put the previously committed contents of deploy_branch into the index 151 | git --work-tree "$deploy_directory" reset --mixed --quiet 152 | git --work-tree "$deploy_directory" add --all 153 | 154 | set +o errexit 155 | diff=$(git --work-tree "$deploy_directory" diff --exit-code --quiet HEAD --)$? 156 | set -o errexit 157 | case $diff in 158 | 0) echo No changes to files in $deploy_directory. Skipping commit.;; 159 | 1) commit_push;; 160 | *) 161 | echo git diff exited with code $diff. Aborting. Staying on branch $deploy_branch so you can debug. To switch back to develop, use: git symbolic-ref HEAD refs/heads/develop && git reset --mixed >&2 162 | return $diff 163 | ;; 164 | esac 165 | } 166 | 167 | commit_push() { 168 | set_user_id 169 | git --work-tree "$deploy_directory" commit -m "$commit_message" 170 | 171 | disable_expanded_output 172 | #--quiet is important here to avoid outputting the repo URL, which may contain a secret token 173 | git push --quiet $repo $deploy_branch 174 | enable_expanded_output 175 | } 176 | 177 | #echo expanded commands as they are executed (for debugging) 178 | enable_expanded_output() { 179 | if [ $verbose ]; then 180 | set -o xtrace 181 | set +o verbose 182 | fi 183 | } 184 | 185 | #this is used to avoid outputting the repo URL, which may contain a secret token 186 | disable_expanded_output() { 187 | if [ $verbose ]; then 188 | set +o xtrace 189 | set -o verbose 190 | fi 191 | } 192 | 193 | set_user_id() { 194 | if [[ -z `git config user.name` ]]; then 195 | git config user.name "$default_username" 196 | fi 197 | if [[ -z `git config user.email` ]]; then 198 | git config user.email "$default_email" 199 | fi 200 | } 201 | 202 | restore_head() { 203 | if [[ $previous_branch = "HEAD" ]]; then 204 | #we weren't on any branch before, so just set HEAD back to the commit it was on 205 | git update-ref --no-deref HEAD $commit_hash $deploy_branch 206 | else 207 | git symbolic-ref HEAD refs/heads/$previous_branch 208 | fi 209 | 210 | git reset --mixed 211 | } 212 | 213 | [[ $1 = --source-only ]] || main "$@" 214 | -------------------------------------------------------------------------------- /pages/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: doc 3 | --- 4 | 5 | 6 | -------------------------------------------------------------------------------- /pages/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/pages/public/favicon.ico -------------------------------------------------------------------------------- /pages/public/images/solidity-toolkit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noncept/solidity-toolkit/b3e1d680a7a698abefa8e463bd03979145d44035/pages/public/images/solidity-toolkit.png -------------------------------------------------------------------------------- /scripts/analyze.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | for contract in "SampleContract" 4 | do 5 | npx surya inheritance dist/$contract.dist.sol | dot -Tpng > analysis/inheritance-tree/$contract.png 6 | 7 | npx surya graph dist/$contract.dist.sol | dot -Tpng > analysis/control-flow/$contract.png 8 | 9 | npx surya mdreport analysis/description-table/$contract.md dist/$contract.dist.sol 10 | 11 | npx sol2uml -hn dist/$contract.dist.sol -o analysis/uml/$contract.svg 12 | done 13 | -------------------------------------------------------------------------------- /scripts/checks/inheritance-ordering.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const path = require('path'); 4 | const graphlib = require('graphlib'); 5 | const { findAll } = require('solidity-ast/utils'); 6 | const { _: artifacts } = require('yargs').argv; 7 | 8 | for (const artifact of artifacts) { 9 | const { output: solcOutput } = require(path.resolve(__dirname, '../..', artifact)); 10 | 11 | const graph = new graphlib.Graph({ directed: true }); 12 | const names = {}; 13 | const linearized = []; 14 | 15 | for (const source in solcOutput.contracts) { 16 | if (['contracts-exposed/', 'contracts/mocks/'].some(pattern => source.startsWith(pattern))) { 17 | continue; 18 | } 19 | 20 | for (const contractDef of findAll('ContractDefinition', solcOutput.sources[source].ast)) { 21 | names[contractDef.id] = contractDef.name; 22 | linearized.push(contractDef.linearizedBaseContracts); 23 | 24 | contractDef.linearizedBaseContracts.forEach((c1, i, contracts) => 25 | contracts.slice(i + 1).forEach(c2 => { 26 | graph.setEdge(c1, c2); 27 | }), 28 | ); 29 | } 30 | } 31 | 32 | /// graphlib.alg.findCycles will not find minimal cycles. 33 | /// We are only interested int cycles of lengths 2 (needs proof) 34 | graph.nodes().forEach((x, i, nodes) => 35 | nodes 36 | .slice(i + 1) 37 | .filter(y => graph.hasEdge(x, y) && graph.hasEdge(y, x)) 38 | .forEach(y => { 39 | console.log(`Conflict between ${names[x]} and ${names[y]} detected in the following dependency chains:`); 40 | linearized 41 | .filter(chain => chain.includes(parseInt(x)) && chain.includes(parseInt(y))) 42 | .forEach(chain => { 43 | const comp = chain.indexOf(parseInt(x)) < chain.indexOf(parseInt(y)) ? '>' : '<'; 44 | console.log(`- ${names[x]} ${comp} ${names[y]} in ${names[chain.find(Boolean)]}`); 45 | // console.log(`- ${names[x]} ${comp} ${names[y]}: ${chain.reverse().map(id => names[id]).join(', ')}`); 46 | }); 47 | process.exitCode = 1; 48 | }), 49 | ); 50 | } 51 | 52 | if (!process.exitCode) { 53 | console.log('Contract ordering is consistent.'); 54 | } 55 | -------------------------------------------------------------------------------- /scripts/flat.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | for contract in "SampleContract" 4 | do 5 | npx hardhat flatten contracts/$contract.sol > dist/$contract.dist.sol 6 | done 7 | -------------------------------------------------------------------------------- /scripts/solhint-custom/index.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const minimatch = require('minimatch'); 3 | 4 | // Files matching these patterns will be ignored unless a rule has `static global = true` 5 | const ignore = ['contracts/mocks/**/*', 'test/**/*']; 6 | 7 | class Base { 8 | constructor(reporter, config, source, fileName) { 9 | this.reporter = reporter; 10 | this.ignored = this.constructor.global || ignore.some(p => minimatch(path.normalize(fileName), p)); 11 | this.ruleId = this.constructor.ruleId; 12 | if (this.ruleId === undefined) { 13 | throw Error('missing ruleId static property'); 14 | } 15 | } 16 | 17 | error(node, message) { 18 | if (!this.ignored) { 19 | this.reporter.error(node, this.ruleId, message); 20 | } 21 | } 22 | } 23 | 24 | module.exports = [ 25 | class extends Base { 26 | static ruleId = 'interface-names'; 27 | 28 | ContractDefinition(node) { 29 | if (node.kind === 'interface' && !/^I[A-Z]/.test(node.name)) { 30 | this.error(node, 'Interface names should have a capital I prefix'); 31 | } 32 | } 33 | }, 34 | 35 | class extends Base { 36 | static ruleId = 'private-variables'; 37 | 38 | VariableDeclaration(node) { 39 | const constantOrImmutable = node.isDeclaredConst || node.isImmutable; 40 | if (node.isStateVar && !constantOrImmutable && node.visibility !== 'private') { 41 | this.error(node, 'State variables must be private'); 42 | } 43 | } 44 | }, 45 | 46 | class extends Base { 47 | static ruleId = 'leading-underscore'; 48 | 49 | VariableDeclaration(node) { 50 | if (node.isDeclaredConst) { 51 | // TODO: expand visibility and fix 52 | if (node.visibility === 'private' && /^_/.test(node.name)) { 53 | this.error(node, 'Constant variables should not have leading underscore'); 54 | } 55 | } else if (node.visibility === 'private' && !/^_/.test(node.name)) { 56 | this.error(node, 'Non-constant private variables must have leading underscore'); 57 | } 58 | } 59 | 60 | FunctionDefinition(node) { 61 | if (node.visibility === 'private' || (node.visibility === 'internal' && node.parent.kind !== 'library')) { 62 | if (!/^_/.test(node.name)) { 63 | this.error(node, 'Private and internal functions must have leading underscore'); 64 | } 65 | } 66 | if (node.visibility === 'internal' && node.parent.kind === 'library') { 67 | if (/^_/.test(node.name)) { 68 | this.error(node, 'Library internal functions should not have leading underscore'); 69 | } 70 | } 71 | } 72 | }, 73 | 74 | // TODO: re-enable and fix 75 | // class extends Base { 76 | // static ruleId = 'no-external-virtual'; 77 | // 78 | // FunctionDefinition(node) { 79 | // if (node.visibility == 'external' && node.isVirtual) { 80 | // this.error(node, 'Functions should not be external and virtual'); 81 | // } 82 | // } 83 | // }, 84 | ]; 85 | -------------------------------------------------------------------------------- /scripts/solhint-custom/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "solhint-plugin-openzeppelin", 3 | "version": "0.0.0", 4 | "private": true 5 | } 6 | -------------------------------------------------------------------------------- /slither.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "detectors_to_run": "arbitrary-send-erc20,array-by-reference,incorrect-shift,name-reused,rtlo,suicidal,uninitialized-state,uninitialized-storage,arbitrary-send-erc20-permit,controlled-array-length,controlled-delegatecall,delegatecall-loop,msg-value-loop,reentrancy-eth,unchecked-transfer,weak-prng,domain-separator-collision,erc20-interface,erc721-interface,locked-ether,mapping-deletion,shadowing-abstract,tautology,write-after-write,boolean-cst,reentrancy-no-eth,reused-constructor,tx-origin,unchecked-lowlevel,unchecked-send,variable-scope,void-cst,events-access,events-maths,incorrect-unary,boolean-equal,cyclomatic-complexity,deprecated-standards,erc20-indexed,function-init-state,pragma,unused-state,reentrancy-unlimited-gas,constable-states,immutable-states,var-read-using-this", 3 | "filter_paths": "contracts/mocks,contracts/vendor,contracts-exposed" 4 | } 5 | -------------------------------------------------------------------------------- /solhint.config.js: -------------------------------------------------------------------------------- 1 | const customRules = require('solhint-plugin-openzeppelin'); 2 | 3 | const rules = [ 4 | 'avoid-tx-origin', 5 | 'const-name-snakecase', 6 | 'contract-name-camelcase', 7 | 'event-name-camelcase', 8 | 'explicit-types', 9 | 'func-name-mixedcase', 10 | 'func-param-name-mixedcase', 11 | 'imports-on-top', 12 | 'modifier-name-mixedcase', 13 | 'no-console', 14 | 'no-global-import', 15 | 'no-unused-vars', 16 | 'quotes', 17 | 'use-forbidden-name', 18 | 'var-name-mixedcase', 19 | 'visibility-modifier-order', 20 | ...customRules.map(r => `openzeppelin/${r.ruleId}`), 21 | ]; 22 | 23 | module.exports = { 24 | plugins: ['openzeppelin'], 25 | rules: Object.fromEntries(rules.map(r => [r, 'error'])), 26 | }; 27 | -------------------------------------------------------------------------------- /test/SampleContract.test.js: -------------------------------------------------------------------------------- 1 | const { BN, constants, expectEvent } = require('@openzeppelin/test-helpers'); 2 | const { expectRevertCustomError } = require('./helpers/customError'); 3 | 4 | const { expect } = require('chai'); 5 | 6 | const { shouldBehaveLikeTokenRecover } = require('eth-token-recover/test/TokenRecover.behavior'); 7 | 8 | const SampleContract = artifacts.require('$SampleContract'); 9 | 10 | contract('SampleContract', function ([owner, manager, anotherAccount]) { 11 | const value = new BN(1000); 12 | 13 | describe('creating valid contract', function () { 14 | it('rejects zero address for manager', async function () { 15 | await expectRevertCustomError(SampleContract.new(constants.ZERO_ADDRESS), 'SampleContractInvalidManager', [ 16 | constants.ZERO_ADDRESS, 17 | ]); 18 | }); 19 | }); 20 | 21 | describe('once deployed', function () { 22 | beforeEach(async function () { 23 | this.contract = await SampleContract.new(manager, { from: owner }); 24 | }); 25 | 26 | it('deployer should be contract owner', async function () { 27 | expect(await this.contract.owner()).to.equal(owner); 28 | }); 29 | 30 | it('manager should be set as provided', async function () { 31 | expect(await this.contract.manager()).to.equal(manager); 32 | }); 33 | 34 | context('calling the ownerDoesWork function', function () { 35 | describe('if owner is calling', function () { 36 | it('emits a WorkDone event', async function () { 37 | const receipt = await this.contract.ownerDoesWork(value, { from: owner }); 38 | 39 | await expectEvent.inTransaction(receipt.tx, SampleContract, 'WorkDone', { 40 | value, 41 | }); 42 | }); 43 | }); 44 | 45 | describe('if another account is calling', function () { 46 | it('reverts', async function () { 47 | await expectRevertCustomError( 48 | this.contract.ownerDoesWork(value, { from: anotherAccount }), 49 | 'OwnableUnauthorizedAccount', 50 | [anotherAccount], 51 | ); 52 | }); 53 | }); 54 | }); 55 | 56 | context('calling the managerDoesWork function', function () { 57 | describe('if manager is calling', function () { 58 | it('emits a WorkDone event', async function () { 59 | const receipt = await this.contract.managerDoesWork(value, { from: manager }); 60 | 61 | await expectEvent.inTransaction(receipt.tx, SampleContract, 'WorkDone', { 62 | value, 63 | }); 64 | }); 65 | }); 66 | 67 | describe('if another account is calling', function () { 68 | it('reverts', async function () { 69 | await expectRevertCustomError( 70 | this.contract.managerDoesWork(value, { from: anotherAccount }), 71 | 'SampleContractUnauthorizedAccount', 72 | [anotherAccount], 73 | ); 74 | }); 75 | }); 76 | }); 77 | 78 | context('testing internal methods', function () { 79 | describe('calling _internalWork', function () { 80 | it('emits a WorkDone event', async function () { 81 | const receipt = await this.contract.$_internalWork(value); 82 | 83 | await expectEvent.inTransaction(receipt.tx, SampleContract, 'WorkDone', { 84 | value, 85 | }); 86 | }); 87 | }); 88 | }); 89 | 90 | context('like a TokenRecover', function () { 91 | beforeEach(async function () { 92 | this.instance = this.contract; 93 | }); 94 | 95 | shouldBehaveLikeTokenRecover(owner, anotherAccount); 96 | }); 97 | }); 98 | }); 99 | -------------------------------------------------------------------------------- /test/helpers/customError.js: -------------------------------------------------------------------------------- 1 | const { expect } = require('chai'); 2 | 3 | /** Revert handler that supports custom errors. */ 4 | async function expectRevertCustomError(promise, expectedErrorName, args) { 5 | if (!Array.isArray(args)) { 6 | expect.fail('Expected 3rd array parameter for error arguments'); 7 | } 8 | 9 | await promise.then( 10 | () => expect.fail("Expected promise to throw but it didn't"), 11 | ({ message }) => { 12 | // The revert message for custom errors looks like: 13 | // VM Exception while processing transaction: 14 | // reverted with custom error 'InvalidAccountNonce("0x70997970C51812dc3A010C7d01b50e0d17dc79C8", 0)' 15 | 16 | // Attempt to parse as a custom error 17 | const match = message.match(/custom error '(?\w+)\((?.*)\)'/); 18 | if (!match) { 19 | expect.fail(`Could not parse as custom error. ${message}`); 20 | } 21 | // Extract the error name and parameters 22 | const errorName = match.groups.name; 23 | const argMatches = [...match.groups.args.matchAll(/-?\w+/g)]; 24 | 25 | // Assert error name 26 | expect(errorName).to.be.equal( 27 | expectedErrorName, 28 | `Unexpected custom error name (with found args: [${argMatches.map(([a]) => a)}])`, 29 | ); 30 | 31 | // Coerce to string for comparison since `arg` can be either a number or hex. 32 | const sanitizedExpected = args.map(arg => arg.toString().toLowerCase()); 33 | const sanitizedActual = argMatches.map(([arg]) => arg.toString().toLowerCase()); 34 | 35 | // Assert argument equality 36 | expect(sanitizedActual).to.have.members(sanitizedExpected, `Unexpected ${errorName} arguments`); 37 | }, 38 | ); 39 | } 40 | 41 | module.exports = { 42 | expectRevertCustomError, 43 | }; 44 | -------------------------------------------------------------------------------- /web-console/README.md: -------------------------------------------------------------------------------- 1 | # Smart Contract - Console 2 | 3 | ## Usage 4 | 5 | ### Load Artifact 6 | 7 | ```javascript 8 | App.initContract('ContractName'); 9 | ``` 10 | 11 | ### Get Contract with Address 12 | 13 | ```javascript 14 | const myContract = await App.getContract('ContractName', '0x123...'); 15 | 16 | // myContract.methods.myMethod([param1[, param2[, ...]]]).call(options [, defaultBlock] [, callback]) 17 | // myContract.methods.myMethod([param1[, param2[, ...]]]).send(options[, callback]) 18 | ``` 19 | 20 | ### Deploy Contract with Arguments 21 | 22 | ```javascript 23 | App.deployContract('ContractName', ['arg1', 'arg2']); 24 | ``` 25 | -------------------------------------------------------------------------------- /web-console/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Smart Contract - Console 8 | 9 | 10 | Smart Contract - Console 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /web-console/js/app.js: -------------------------------------------------------------------------------- 1 | /* global Web3 */ 2 | 3 | const App = { 4 | coinbase: null, 5 | web3: null, 6 | web3Provider: null, 7 | artifacts: [], 8 | promisify(fn, ...args) { 9 | return new Promise((resolve, reject) => { 10 | fn(...args, (err, res) => { 11 | if (err) { 12 | reject(err); 13 | } else { 14 | resolve(res); 15 | } 16 | }); 17 | }); 18 | }, 19 | initWeb3: async function () { 20 | if (typeof window.ethereum !== 'undefined') { 21 | console.log('Injected Ethereum'); 22 | 23 | this.web3Provider = window.ethereum; 24 | 25 | this.web3 = new Web3(window.ethereum); 26 | 27 | await this.web3Provider.request({ method: 'eth_requestAccounts' }); 28 | 29 | this.coinbase = await this.promisify(this.web3.eth.getCoinbase); 30 | } else { 31 | console.log('No MetaMask found'); 32 | } 33 | }, 34 | initContract: function (contractName) { 35 | fetch(`${contractName}.json`) 36 | .then(response => response.json()) 37 | .then(contract => { 38 | this.artifacts[contractName] = contract; 39 | }) 40 | .catch(error => console.log(error)); 41 | }, 42 | getContract: function (contractName, address) { 43 | return new this.web3.eth.Contract(this.artifacts[contractName].abi, address); 44 | }, 45 | deployContract: function (contractName, args, opts) { 46 | const contract = new this.web3.eth.Contract(this.artifacts[contractName].abi); 47 | 48 | contract 49 | .deploy({ 50 | data: this.artifacts[contractName].bytecode, 51 | arguments: args, 52 | }) 53 | .send(opts || { from: this.coinbase }) 54 | .on('error', error => { 55 | console.log(error.message); 56 | }) 57 | .on('transactionHash', transactionHash => { 58 | console.log(transactionHash); 59 | }) 60 | .on('receipt', receipt => { 61 | console.log(receipt); 62 | }); 63 | }, 64 | }; 65 | 66 | App.initWeb3(); 67 | --------------------------------------------------------------------------------