├── .dockerignore ├── .env.sample ├── .gitattributes ├── .gitignore ├── .solcover.js ├── .travis.yml ├── Dockerfile ├── LICENSE ├── README.md ├── contracts └── DelegateRegistry.sol ├── deploy.sh ├── docker-compose.deploy.yml ├── docker-compose.yml ├── docs └── guidelines.md ├── migrations ├── 1_deploy_registry.js └── utils │ ├── address_utils.js │ ├── promise_utils.js │ └── singleton_factory.js ├── networks.json ├── package.json ├── scripts ├── clean_build.js ├── generate_meta.js └── verify_deployment.js ├── test ├── check_deployment.js ├── delegate_with_eoa.js ├── delegate_with_safe.js ├── invalid_calls.js └── utils │ └── assertions.js ├── truffle-config.js └── yarn.lock /.dockerignore: -------------------------------------------------------------------------------- 1 | /build 2 | /node_modules -------------------------------------------------------------------------------- /.env.sample: -------------------------------------------------------------------------------- 1 | MNEMONIC=some mnemonic 2 | INFURA_TOKEN=12365478965412 -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | node_modules/ 3 | .DS_Store 4 | .zos.session 5 | .openzeppelin/.session 6 | env/ 7 | .env 8 | .env.deploy 9 | bin/ 10 | solc 11 | coverage.json 12 | /coverage -------------------------------------------------------------------------------- /.solcover.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | mocha: { 3 | grep: "@skip-on-coverage", // Find everything with this tag 4 | invert: true // Run the grep's inverse set. 5 | } 6 | }; -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: minimal 2 | 3 | services: 4 | - docker 5 | 6 | cache: 7 | directories: 8 | - node_modules 9 | 10 | before_script: 11 | - cp .env.sample .env 12 | - docker build -t delegate-registry . 13 | 14 | jobs: 15 | include: 16 | - script: 17 | - docker run delegate-registry yarn test 18 | - script: 19 | - docker run delegate-registry yarn coverage -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:12 2 | 3 | ENV USER=root 4 | WORKDIR "/" 5 | 6 | RUN echo "{}" > networks.json 7 | COPY package.json yarn.lock truffle-config.js ./ 8 | 9 | RUN yarn 10 | 11 | COPY . . 12 | 13 | RUN yarn compile -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Delegate Registry 2 | ================= 3 | 4 | [![Build Status](https://travis-ci.com/gnosis/delegate-registry.svg?branch=main)](https://travis-ci.com/gnosis/delegate-registry) 5 | 6 | Install 7 | ------- 8 | ### Install requirements with yarn: 9 | 10 | ```bash 11 | yarn 12 | // Setup env 13 | cp .env.sample .env 14 | ``` 15 | 16 | ### Build contracts 17 | 18 | With docker: 19 | ```bash 20 | docker-compose up 21 | ``` 22 | 23 | Without docker: 24 | ```bash 25 | yarn compile 26 | ``` 27 | 28 | ### Run all tests (requires Node version >=7 for `async/await`): 29 | 30 | Running the tests with docker: 31 | 32 | ```bash 33 | docker build -t delegate-registry . 34 | docker run delegate-registry yarn test 35 | ``` 36 | 37 | If you want to run it without docker: 38 | 39 | ```bash 40 | yarn compile 41 | yarn test 42 | ``` 43 | 44 | In this case it is expected that the deployment check test fails. 45 | 46 | ### Deploy 47 | 48 | Docker is used to ensure that always the same bytecode is generated. 49 | 50 | Preparation: 51 | - Set `INFURA_TOKEN` in `.env` 52 | - Set `MNEMONIC` in `.env` 53 | 54 | Deploying with docker (should always result in the same registry address): 55 | 56 | ```bash 57 | ./deploy.sh 58 | ``` 59 | 60 | If you want to run it without docker (might result in different registry address): 61 | 62 | ```bash 63 | yarn compile 64 | yarn deploy 65 | ``` 66 | 67 | ### Verify contract 68 | 69 | Note: To completely replicate the bytecode that has been deployed it is required that the project path is always the same. For this use the provided Dockerfile and map the the build folder into your local build folder. For this a docker-compose file is provided which can be used with: 70 | ```bash 71 | docker-compose up 72 | ``` 73 | 74 | You can locally verify contract using the scripts `generate_meta.js` and `verify_deployment.js`. 75 | 76 | With `node scripts/generate_meta.js` a `meta` folder is created in the `build` folder that contains all files required to verify the source code on https://verification.komputing.org/ and https://etherscan.io/ 77 | 78 | For Etherscan only the `DelegateRegistryEtherscan.json` file is required. For sourcify the `DelegateRegistryMeta.json` and all the `.sol` files are required. 79 | 80 | Once the meta data has been generated you can verify that your local compiled code corresponds to the version deployed by Gnosis with `yarn do scripts/verify_deployment.js`. 81 | 82 | Documentation 83 | ------------- 84 | - [Coding guidelines](docs/guidelines.md) 85 | 86 | Audits/ Formal Verification 87 | --------- 88 | - TBD 89 | 90 | Security and Liability 91 | ---------------------- 92 | All contracts are WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 93 | 94 | License 95 | ------- 96 | All smart contracts are released under LGPL v.3. 97 | 98 | Contributors 99 | ------------ 100 | - Richard Meissner ([rmeissner](https://github.com/rmeissner)) 101 | - Auryn Macmillan ([auryn-macmillan](https://github.com/auryn-macmillan)) 102 | -------------------------------------------------------------------------------- /contracts/DelegateRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-only 2 | pragma solidity >=0.7.0 <0.8.0; 3 | 4 | contract DelegateRegistry { 5 | 6 | // The first key is the delegator and the second key a id. 7 | // The value is the address of the delegate 8 | mapping (address => mapping (bytes32 => address)) public delegation; 9 | 10 | // Using these events it is possible to process the events to build up reverse lookups. 11 | // The indeces allow it to be very partial about how to build this lookup (e.g. only for a specific delegate). 12 | event SetDelegate(address indexed delegator, bytes32 indexed id, address indexed delegate); 13 | event ClearDelegate(address indexed delegator, bytes32 indexed id, address indexed delegate); 14 | 15 | /// @dev Sets a delegate for the msg.sender and a specific id. 16 | /// The combination of msg.sender and the id can be seen as a unique key. 17 | /// @param id Id for which the delegate should be set 18 | /// @param delegate Address of the delegate 19 | function setDelegate(bytes32 id, address delegate) public { 20 | require (delegate != msg.sender, "Can't delegate to self"); 21 | require (delegate != address(0), "Can't delegate to 0x0"); 22 | address currentDelegate = delegation[msg.sender][id]; 23 | require (delegate != currentDelegate, "Already delegated to this address"); 24 | 25 | // Update delegation mapping 26 | delegation[msg.sender][id] = delegate; 27 | 28 | if (currentDelegate != address(0)) { 29 | emit ClearDelegate(msg.sender, id, currentDelegate); 30 | } 31 | 32 | emit SetDelegate(msg.sender, id, delegate); 33 | } 34 | 35 | /// @dev Clears a delegate for the msg.sender and a specific id. 36 | /// The combination of msg.sender and the id can be seen as a unique key. 37 | /// @param id Id for which the delegate should be set 38 | function clearDelegate(bytes32 id) public { 39 | address currentDelegate = delegation[msg.sender][id]; 40 | require (currentDelegate != address(0), "No delegate set"); 41 | 42 | // update delegation mapping 43 | delegation[msg.sender][id] = address(0); 44 | 45 | emit ClearDelegate(msg.sender, id, currentDelegate); 46 | } 47 | } -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cp .env .env.deploy 4 | echo $'\nNETWORK='$1 >> .env.deploy 5 | 6 | docker-compose -f docker-compose.yml -f docker-compose.deploy.yml --env-file .env.deploy up --build 7 | 8 | node scripts/clean_build.js 9 | 10 | rm .env.deploy 11 | -------------------------------------------------------------------------------- /docker-compose.deploy.yml: -------------------------------------------------------------------------------- 1 | version: "3.5" 2 | 3 | services: 4 | build: 5 | env_file: 6 | - .env.deploy 7 | command: "yarn deploy ${NETWORK}" -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.5" 2 | 3 | services: 4 | build: 5 | image: delegate-registry 6 | build: 7 | context: . 8 | dockerfile: ./Dockerfile 9 | env_file: 10 | - .env 11 | volumes: 12 | - ./build:/build:rw 13 | command: "yarn compile" -------------------------------------------------------------------------------- /docs/guidelines.md: -------------------------------------------------------------------------------- 1 | ## Coding Guidelines 2 | 3 | ### Declaration of variables 4 | New variables will use a hash based storage approach to avoid conflicts in the storage layout of the proxy contract when updating the master copy. 5 | 6 | For this a variable identifier should be definied (e.g. `fallback_manager.handler.address` for the handler addres in the fallback manager contract) and hash this identifier to generate the storage location from where the data should be loaded. 7 | 8 | The data can be stored to this location with 9 | 10 | ``` 11 | bytes32 slot = VARIABLE_SLOT; 12 | // solium-disable-next-line security/no-inline-assembly 13 | assembly { 14 | sstore(slot, value) 15 | } 16 | ``` 17 | 18 | and read with 19 | 20 | ``` 21 | bytes32 slot = VARIABLE_SLOT; 22 | // solium-disable-next-line security/no-inline-assembly 23 | assembly { 24 | value := sload(slot) 25 | } 26 | ``` 27 | 28 | Note: Make sure to use a unique identifier else unexpected behaviour will occur -------------------------------------------------------------------------------- /migrations/1_deploy_registry.js: -------------------------------------------------------------------------------- 1 | const { deployTruffleContract } = require('./utils/singleton_factory'); 2 | 3 | const DelegateRegistry = artifacts.require("./DelegateRegistry.sol"); 4 | 5 | module.exports = (d) => d.then(async () => { 6 | await deployTruffleContract(web3, DelegateRegistry); 7 | }); 8 | -------------------------------------------------------------------------------- /migrations/utils/address_utils.js: -------------------------------------------------------------------------------- 1 | const web3 = require('web3'); 2 | 3 | const buildCreate2Address = (deployer, salt, bytecode) => { 4 | return web3.utils.toChecksumAddress(`0x${web3.utils.soliditySha3( 5 | { t: 'bytes', v: '0xff' }, 6 | { t: 'address', v: deployer }, 7 | { t: 'bytes32', v: salt }, 8 | { t: 'bytes32', v: web3.utils.keccak256(bytecode) } 9 | ).slice(-40)}`); 10 | } 11 | 12 | Object.assign(exports, { 13 | buildCreate2Address, 14 | }) -------------------------------------------------------------------------------- /migrations/utils/promise_utils.js: -------------------------------------------------------------------------------- 1 | const toConfirmationPromise = promiEvent => new Promise((resolve, reject) => { 2 | promiEvent 3 | .on('confirmation', (_n, receipt) => resolve(receipt)) 4 | .on('error', reject); 5 | }); 6 | 7 | Object.assign(exports, { 8 | toConfirmationPromise, 9 | }) -------------------------------------------------------------------------------- /migrations/utils/singleton_factory.js: -------------------------------------------------------------------------------- 1 | const truffleContract = require("@truffle/contract") 2 | 3 | const { toConfirmationPromise } = require('./promise_utils'); 4 | const { buildCreate2Address } = require('./address_utils'); 5 | 6 | const SINGLETON_FACTORY = '0xce0042B868300000d44A59004Da54A005ffdcf9f' 7 | const SINGLETON_FACTORY_DEPLOYER = '0xBb6e024b9cFFACB947A71991E386681B1Cd1477D' 8 | const SINGLETON_FACTORY_CODE = '0xf9016c8085174876e8008303c4d88080b90154608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c634300060200331b83247000822470' 9 | const SINGLETON_FACTORY_ABI = [ 10 | { 11 | "constant": false, 12 | "inputs": [ 13 | { 14 | "internalType": "bytes", 15 | "name": "_initCode", 16 | "type": "bytes" 17 | }, 18 | { 19 | "internalType": "bytes32", 20 | "name": "_salt", 21 | "type": "bytes32" 22 | } 23 | ], 24 | "name": "deploy", 25 | "outputs": [ 26 | { 27 | "internalType": "address payable", 28 | "name": "createdContract", 29 | "type": "address" 30 | } 31 | ], 32 | "payable": false, 33 | "stateMutability": "nonpayable", 34 | "type": "function" 35 | } 36 | ] 37 | 38 | const requireFactoryDeployment = async (web3) => { 39 | return (await web3.eth.getCode(SINGLETON_FACTORY)) === '0x' 40 | } 41 | 42 | const deployFactory = async (web3) => { 43 | await toConfirmationPromise(web3.eth.sendSignedTransaction(SINGLETON_FACTORY_CODE)); 44 | } 45 | 46 | const ensureFactory = async (web3) => { 47 | const [deployer] = await web3.eth.getAccounts(); 48 | if (await requireFactoryDeployment(web3)) { 49 | // greetz @3esmit and @forshtat 50 | await toConfirmationPromise(web3.eth.sendTransaction({ 51 | from: deployer, 52 | to: SINGLETON_FACTORY_DEPLOYER, 53 | value: 1e18 54 | })); 55 | await deployFactory(web3); 56 | console.log(`Deployed EIP 2470 SingletonFactory at ${SINGLETON_FACTORY}`); 57 | } else { 58 | console.log(`EIP 2470 SingletonFactory already deployed at ${SINGLETON_FACTORY}`); 59 | } 60 | const factoryContract = truffleContract({ abi: SINGLETON_FACTORY_ABI }) 61 | factoryContract.setProvider(web3.currentProvider) 62 | const singletonFactory = await factoryContract.at(SINGLETON_FACTORY) 63 | return singletonFactory; 64 | } 65 | 66 | const deployContract = async (web3, bytecode, salt) => { 67 | const [deployer] = await web3.eth.getAccounts(); 68 | const contractAddress = buildCreate2Address(SINGLETON_FACTORY, salt, bytecode); 69 | const requireDeployment = (await web3.eth.getCode(contractAddress)) === '0x'; 70 | if (!requireDeployment) { 71 | return { txHash: null, newContract: false, contractAddress }; 72 | } 73 | const factory = await ensureFactory(web3); 74 | const { tx } = await factory.deploy(bytecode, salt, { from: deployer }); 75 | return { txHash: tx, newContract: true, contractAddress }; 76 | } 77 | 78 | const deployTruffleContract = async (web3, artifact, salt) => { 79 | const artifactName = artifact.contractName || "Artifact" 80 | const deploymentSalt = salt || '0x'; 81 | const { contractAddress, txHash, newContract } = await deployContract(web3, artifact.bytecode, deploymentSalt); 82 | if (newContract) { 83 | console.log(`Deployed ${artifactName} at ${contractAddress}`); 84 | 85 | artifact.address = contractAddress; 86 | artifact.transactionHash = txHash; 87 | } else { 88 | try { 89 | const addressOnArtifact = artifact.address; 90 | if (addressOnArtifact !== contractAddress) { 91 | console.warn(`Expected to find ${contractAddress 92 | } set as ${artifactName} address but instead found ${artifact.address 93 | } so the address is being updated, but the transaction hash should be manually corrected`); 94 | } else { 95 | console.log(`Found ${artifactName} at ${contractAddress}`); 96 | } 97 | } catch (e) { 98 | if (e.message.startsWith(`${artifactName} has no network configuration for its current network id`)) { 99 | console.warn(`Expected to find ${contractAddress 100 | } set as ${artifactName} address but instead couldn't find an address, so the address is being updated, but the transaction hash should be manually added`); 101 | } else { 102 | throw e; 103 | } 104 | } 105 | artifact.address = contractAddress; 106 | } 107 | } 108 | 109 | Object.assign(exports, { 110 | SINGLETON_FACTORY, 111 | SINGLETON_FACTORY_DEPLOYER, 112 | SINGLETON_FACTORY_CODE, 113 | requireFactoryDeployment, 114 | deployFactory, 115 | ensureFactory, 116 | deployContract, 117 | deployTruffleContract, 118 | }) -------------------------------------------------------------------------------- /networks.json: -------------------------------------------------------------------------------- 1 | { 2 | "DelegateRegistry": { 3 | "4": { 4 | "events": { 5 | "0x9c4f00c4291262731946e308dc2979a56bd22cce8f95906b975065e96cd5a064": { 6 | "anonymous": false, 7 | "inputs": [ 8 | { 9 | "indexed": true, 10 | "internalType": "address", 11 | "name": "delegator", 12 | "type": "address" 13 | }, 14 | { 15 | "indexed": true, 16 | "internalType": "bytes32", 17 | "name": "id", 18 | "type": "bytes32" 19 | }, 20 | { 21 | "indexed": true, 22 | "internalType": "address", 23 | "name": "delegate", 24 | "type": "address" 25 | } 26 | ], 27 | "name": "ClearDelegate", 28 | "type": "event" 29 | }, 30 | "0xa9a7fd460f56bddb880a465a9c3e9730389c70bc53108148f16d55a87a6c468e": { 31 | "anonymous": false, 32 | "inputs": [ 33 | { 34 | "indexed": true, 35 | "internalType": "address", 36 | "name": "delegator", 37 | "type": "address" 38 | }, 39 | { 40 | "indexed": true, 41 | "internalType": "bytes32", 42 | "name": "id", 43 | "type": "bytes32" 44 | }, 45 | { 46 | "indexed": true, 47 | "internalType": "address", 48 | "name": "delegate", 49 | "type": "address" 50 | } 51 | ], 52 | "name": "SetDelegate", 53 | "type": "event" 54 | } 55 | }, 56 | "links": {}, 57 | "address": "0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446", 58 | "transactionHash": "0x6987fb77279d3df3177c62e20520a8735a07a2342b5eb8ad0f978958d8656979" 59 | }, 60 | "42": { 61 | "events": { 62 | "0x9c4f00c4291262731946e308dc2979a56bd22cce8f95906b975065e96cd5a064": { 63 | "anonymous": false, 64 | "inputs": [ 65 | { 66 | "indexed": true, 67 | "internalType": "address", 68 | "name": "delegator", 69 | "type": "address" 70 | }, 71 | { 72 | "indexed": true, 73 | "internalType": "bytes32", 74 | "name": "id", 75 | "type": "bytes32" 76 | }, 77 | { 78 | "indexed": true, 79 | "internalType": "address", 80 | "name": "delegate", 81 | "type": "address" 82 | } 83 | ], 84 | "name": "ClearDelegate", 85 | "type": "event" 86 | }, 87 | "0xa9a7fd460f56bddb880a465a9c3e9730389c70bc53108148f16d55a87a6c468e": { 88 | "anonymous": false, 89 | "inputs": [ 90 | { 91 | "indexed": true, 92 | "internalType": "address", 93 | "name": "delegator", 94 | "type": "address" 95 | }, 96 | { 97 | "indexed": true, 98 | "internalType": "bytes32", 99 | "name": "id", 100 | "type": "bytes32" 101 | }, 102 | { 103 | "indexed": true, 104 | "internalType": "address", 105 | "name": "delegate", 106 | "type": "address" 107 | } 108 | ], 109 | "name": "SetDelegate", 110 | "type": "event" 111 | } 112 | }, 113 | "links": {}, 114 | "address": "0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446", 115 | "transactionHash": "0x983f6a0fab4cfdd3d6cadd0b865a0366b3069d5b5622d1b95c1e3e77f45046bb" 116 | } 117 | } 118 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "delegate-registry", 3 | "version": "1.0.0", 4 | "description": "Registry of delegates", 5 | "homepage": "https://github.com/gnosis/delegate-registry/", 6 | "license": "GPL-3.0", 7 | "files": [ 8 | "contracts", 9 | "test", 10 | "build", 11 | "networks.json" 12 | ], 13 | "ethereum": { 14 | "networks": [ 15 | 1, 16 | 4, 17 | 42, 18 | 5, 19 | 100, 20 | 246, 21 | 73799 22 | ], 23 | "contracts": [ 24 | "DelegateRegistry" 25 | ] 26 | }, 27 | "scripts": { 28 | "test": "run(){ run-with-testrpc -l 20000000 --noVMErrorsOnRPCResponse \"truffle test $@\"; }; run", 29 | "compile": "run(){ truffle compile $@; }; run", 30 | "coverage": "run(){ truffle run coverage $@; }; run", 31 | "deploy": "run(){ truffle deploy --network=$@; }; run", 32 | "do": "run(){ truffle exec --network=$@; }; run", 33 | "prepare": "yarn truffle compile && yarn tnt iN", 34 | "preversion": "node scripts/clean_build.js && yarn tnt cB" 35 | }, 36 | "repository": { 37 | "type": "git", 38 | "url": "git+https://github.com/gnosis/delegate-registry.git" 39 | }, 40 | "keywords": [ 41 | "Ethereum", 42 | "Wallet", 43 | "Safe" 44 | ], 45 | "author": "stefan@gnosis.pm", 46 | "bugs": { 47 | "url": "https://github.com/gnosis/delegate-registry/issues" 48 | }, 49 | "devDependencies": { 50 | "@digix/tempo": "^0.2.0", 51 | "@gnosis.pm/safe-contracts": "^1.2.0", 52 | "@gnosis.pm/truffle-nice-tools": "^1.3.0", 53 | "@truffle/contract": "^4.2.23", 54 | "@truffle/hdwallet-provider": "^1.0.0", 55 | "coveralls": "^3.1.0", 56 | "dotenv": "^8.0.0", 57 | "eth-lightwallet": "^4.0.0", 58 | "ethereumjs-abi": "^0.6.8", 59 | "ethereumjs-util": "^6.2.0", 60 | "ganache-cli": "6.3.0", 61 | "ipfs-http-client": "^44.2.0", 62 | "random-buffer": "*", 63 | "run-with-testrpc": "^0.3.0", 64 | "solidity-coverage": "^0.7.11", 65 | "truffle": "^5.1.42", 66 | "web3": "^1.2.6" 67 | }, 68 | "dependencies": { 69 | "openzeppelin-solidity": "^2.0.0", 70 | "shelljs": "^0.8.3", 71 | "solc": "0.7.2" 72 | }, 73 | "resolutions": { 74 | "bitcore-lib": "8.1.1", 75 | "run-with-testrpc/ganache-cli": "6.3.0" 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /scripts/clean_build.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | const fs = require('fs') 3 | const util = require('util') 4 | const path = require('path') 5 | 6 | const readFile = util.promisify(fs.readFile) 7 | const writeFile = util.promisify(fs.writeFile) 8 | 9 | const pkg = require(path.join("..", "package.json")) 10 | 11 | const contractDir = path.join("build", "contracts"); 12 | const networksFile = path.join("networks.json"); 13 | const supportedNetworks = pkg.ethereum.networks 14 | const supportedContracts = pkg.ethereum.contracts 15 | 16 | async function process() { 17 | const contractFiles = fs.readdirSync(contractDir); 18 | const extractedNetworks = JSON.parse(fs.readFileSync(networksFile)) 19 | for (let contract of contractFiles) { 20 | const contractFile = path.join(contractDir, contract) 21 | if (supportedContracts.indexOf(contract.slice(0, -5)) < 0) { 22 | console.log(`Delete ${contractFile}`) 23 | try { 24 | fs.unlinkSync(contractFile) 25 | } catch(e) { 26 | console.log(`Could not delete ${contractFile}`) 27 | } 28 | } else { 29 | const contractJson = JSON.parse(fs.readFileSync(contractFile)) 30 | const networks = contractJson.networks 31 | contractJson.networks = {} 32 | for (let network of supportedNetworks) { 33 | const networkData = networks[network] 34 | if (!networkData) continue 35 | contractJson.networks[network] = networkData 36 | if (!extractedNetworks[contractJson.contractName]) { 37 | extractedNetworks[contractJson.contractName] = {} 38 | } 39 | extractedNetworks[contractJson.contractName][network] = networkData 40 | } 41 | try { 42 | await writeFile(contractFile, JSON.stringify(contractJson, null, 2)) 43 | } catch(e) { 44 | console.log(`Could not write clean ${contractFile}`) 45 | } 46 | } 47 | } 48 | await writeFile(networksFile, JSON.stringify(extractedNetworks, null, 2)) 49 | } 50 | 51 | process() -------------------------------------------------------------------------------- /scripts/generate_meta.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | const IPFS = require('ipfs-http-client'); 3 | 4 | const fs = require('fs') 5 | const util = require('util') 6 | const path = require('path') 7 | 8 | const log = console.log 9 | 10 | const copyFile = util.promisify(fs.copyFile) 11 | const writeFile = util.promisify(fs.writeFile) 12 | 13 | const contractDir = path.join("build", "contracts") 14 | const metaDir = path.join("build", "meta") 15 | 16 | async function main() { 17 | const upload = process.argv.findIndex((value) => value === "--upload") >= 0 18 | const ipfs = IPFS({ 19 | host: 'ipfs.infura.io', 20 | port: '5001', 21 | protocol: 'https' 22 | }); 23 | const contractArtifact = require(path.join(process.cwd(), contractDir, "DelegateRegistry.json")); 24 | 25 | if (!fs.existsSync(metaDir)) { 26 | fs.mkdirSync(metaDir); 27 | } 28 | 29 | log("Generating metadata...") 30 | log("======================") 31 | 32 | log(); 33 | log(contractArtifact.contractName); 34 | log("-".repeat(contractArtifact.contractName.length)); 35 | 36 | const etherscanConfig = { 37 | language: "", 38 | sources: {}, 39 | settings: {}, 40 | evmVersion: "" 41 | } 42 | 43 | const meta = JSON.parse(contractArtifact.metadata) 44 | etherscanConfig.language = meta.language 45 | etherscanConfig.evmVersion = meta.evmVersion 46 | for (let source in meta.sources) { 47 | const pathParts = source.split("/") 48 | await copyFile(source, path.join(metaDir, pathParts[pathParts.length - 1])); 49 | const contractSource = fs.readFileSync(source) 50 | etherscanConfig.sources[source] = { content: contractSource.toString() } 51 | if (upload) { 52 | for await (const res of ipfs.add(contractSource)) { 53 | log(`metadata: ${res.path}`); 54 | } 55 | } 56 | } 57 | 58 | log('Write DelegateRegistryMeta.json'); 59 | const contractMetaFile = path.join(process.cwd(), metaDir, "DelegateRegistryMeta.json"); 60 | await writeFile(contractMetaFile, contractArtifact.metadata) 61 | 62 | log('Write DelegateRegistryEtherscan.json'); 63 | const contractEtherscanFile = path.join(process.cwd(), metaDir, "DelegateRegistryEtherscan.json"); 64 | await writeFile(contractEtherscanFile, JSON.stringify(etherscanConfig)) 65 | 66 | log(); 67 | log('Finished.'); 68 | log(); 69 | } 70 | 71 | main() 72 | .then(() => process.exit(0)) 73 | .catch(err => { 74 | console.log(err); 75 | process.exit(1) 76 | }) -------------------------------------------------------------------------------- /scripts/verify_deployment.js: -------------------------------------------------------------------------------- 1 | /* 2 | Set INFURA_TOKEN in .env 3 | Run with `yarn do rinkeby scripts/simulate_verify.js` 4 | */ 5 | 6 | const solc = require('solc') 7 | const path = require('path') 8 | const fs = require('fs') 9 | 10 | function reformatMetadata( 11 | metadata, 12 | sources 13 | ) { 14 | 15 | const input = {}; 16 | let fileName = ''; 17 | let contractName = ''; 18 | 19 | input.settings = metadata.settings; 20 | 21 | for (fileName in metadata.settings.compilationTarget) { 22 | contractName = metadata.settings.compilationTarget[fileName]; 23 | } 24 | 25 | delete input['settings']['compilationTarget'] 26 | 27 | if (contractName == '') { 28 | const err = new Error("Could not determine compilation target from metadata."); 29 | console.log({ loc: '[REFORMAT]', err: err }); 30 | throw err; 31 | } 32 | 33 | input['sources'] = {} 34 | for (const source in sources) { 35 | let content = sources[source].content 36 | if (!content) { 37 | content = fs.readFileSync(source).toString() 38 | } 39 | input.sources[source] = { content } 40 | } 41 | 42 | input.language = metadata.language 43 | input.settings.metadata = input.settings.metadata || {} 44 | input.settings.outputSelection = input.settings.outputSelection || {} 45 | input.settings.outputSelection[fileName] = input.settings.outputSelection[fileName] || {} 46 | 47 | input.settings.outputSelection[fileName][contractName] = [ 48 | 'evm.bytecode', 49 | 'evm.deployedBytecode', 50 | 'metadata' 51 | ]; 52 | 53 | return { 54 | input: input, 55 | fileName: fileName, 56 | contractName: contractName 57 | } 58 | } 59 | 60 | const metaDir = path.join("..", "build", "meta") 61 | 62 | process = async () => { 63 | const networkId = await web3.eth.net.getId() 64 | const network = require(path.join("..", "networks.json")); 65 | const meta = require(path.join(metaDir, "DelegateRegistryMeta.json")); 66 | const { 67 | input, 68 | fileName, 69 | contractName 70 | } = reformatMetadata(meta, meta.sources); 71 | const solcjs = await new Promise((resolve, reject) => { 72 | solc.loadRemoteVersion(`v${meta.compiler.version}`, (error, soljson) => { 73 | (error) ? reject(error) : resolve(soljson); 74 | }); 75 | }); 76 | const compiled = solcjs.compile(JSON.stringify(input)); 77 | const output = JSON.parse(compiled); 78 | const contract = output.contracts[fileName][contractName]; 79 | const onchainBytecode = await web3.eth.getCode(network["DelegateRegistry"][networkId]["address"]); 80 | const onchainBytecodeHash = web3.utils.sha3(onchainBytecode) 81 | const localBytecodeHash = web3.utils.sha3(`0x${contract.evm.deployedBytecode.object}`) 82 | console.log(`On-chain bytecode hash: ${onchainBytecodeHash}`) 83 | console.log(`Local bytecode hash: ${localBytecodeHash}`) 84 | const verifySuccess = onchainBytecodeHash === localBytecodeHash ? "was SUCCESSFUL" : "FAILED" 85 | console.log(`Verification ${verifySuccess}`) 86 | } 87 | 88 | module.exports = function (callback) { 89 | process() 90 | .then(() => { callback() }) 91 | .catch((err) => { callback(err) }) 92 | } -------------------------------------------------------------------------------- /test/check_deployment.js: -------------------------------------------------------------------------------- 1 | const DelegateRegistry = artifacts.require("./DelegateRegistry.sol") 2 | 3 | contract('DelegateRegistry - Check deployment', () => { 4 | // Note: Skip this test when running without docker, as resulting address will be different. 5 | it('check that the deployment generates the correct address [ @skip-on-coverage ]', async () => { 6 | const registry = await DelegateRegistry.deployed() 7 | // This should correspond to the address in the networks.json file 8 | assert.equal(await registry.address, "0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446") 9 | }) 10 | }) 11 | -------------------------------------------------------------------------------- /test/delegate_with_eoa.js: -------------------------------------------------------------------------------- 1 | const ethUtil = require('ethereumjs-util') 2 | const { checkTxEvent, formatAddress } = require('@gnosis.pm/safe-contracts/test/utils/general') 3 | const abi = require('ethereumjs-abi') 4 | 5 | const DelegateRegistry = artifacts.require("./DelegateRegistry.sol") 6 | 7 | contract('DelegateRegistry - With EOA', (accounts) => { 8 | 9 | const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" 10 | const TEST_DELEGATE_1 = "0x0000000000000000000000000000000000baDDAd" 11 | const TEST_DELEGATE_2 = "0x0000000000000000000000000000000000BADbed" 12 | const TEST_ID_1 = ethUtil.keccak("test_1_project") 13 | const TEST_ID_2 = ethUtil.keccak("test_2_project") 14 | 15 | let registry 16 | 17 | beforeEach(async () => { 18 | // Deploy Registry 19 | registry = await DelegateRegistry.new() 20 | }) 21 | 22 | it('set and clear delegate, same id', async () => { 23 | const setTx = await registry.setDelegate(TEST_ID_1, TEST_DELEGATE_1, { from: accounts[0] }) 24 | const setEvent = checkTxEvent(setTx, 'SetDelegate', registry.address, true, "Set Delegate") 25 | assert.equal(setEvent.args.delegator, formatAddress(accounts[0])) 26 | assert.equal(setEvent.args.id, "0x" + TEST_ID_1.toString("hex")) 27 | assert.equal(setEvent.args.delegate, TEST_DELEGATE_1) 28 | checkTxEvent(setTx, 'ClearDelegate', registry.address, false) 29 | 30 | assert.equal(await registry.delegation(accounts[0], TEST_ID_1), TEST_DELEGATE_1) 31 | 32 | // Reset delegate 33 | const clearTx = await registry.clearDelegate(TEST_ID_1, { from: accounts[0] }) 34 | const clearEvent = checkTxEvent(clearTx, 'ClearDelegate', registry.address, true, "Clear Delegate") 35 | assert.equal(clearEvent.args.delegator, formatAddress(accounts[0])) 36 | assert.equal(clearEvent.args.id, "0x" + TEST_ID_1.toString("hex")) 37 | assert.equal(clearEvent.args.delegate, TEST_DELEGATE_1) 38 | checkTxEvent(clearTx, 'SetDelegate', registry.address, false) 39 | 40 | assert.equal(await registry.delegation(accounts[0], TEST_ID_1), ZERO_ADDRESS) 41 | }) 42 | 43 | it('set and overwrite delegate, same id', async () => { 44 | const setTx = await registry.setDelegate(TEST_ID_1, TEST_DELEGATE_1, { from: accounts[0] }) 45 | const setEvent = checkTxEvent(setTx, 'SetDelegate', registry.address, true, "Set Delegate") 46 | assert.equal(setEvent.args.delegator, formatAddress(accounts[0])) 47 | assert.equal(setEvent.args.id, "0x" + TEST_ID_1.toString("hex")) 48 | assert.equal(setEvent.args.delegate, TEST_DELEGATE_1) 49 | checkTxEvent(setTx, 'ClearDelegate', registry.address, false) 50 | 51 | assert.equal(await registry.delegation(accounts[0], TEST_ID_1), TEST_DELEGATE_1) 52 | 53 | // Overwrite delegate 54 | const overwriteTx = await registry.setDelegate(TEST_ID_1, TEST_DELEGATE_2, { from: accounts[0] }) 55 | const overwriteEvent = checkTxEvent(overwriteTx, 'SetDelegate', registry.address, true, "Overwrite Delegate") 56 | assert.equal(overwriteEvent.args.delegator, formatAddress(accounts[0])) 57 | assert.equal(overwriteEvent.args.id, "0x" + TEST_ID_1.toString("hex")) 58 | assert.equal(overwriteEvent.args.delegate, TEST_DELEGATE_2) 59 | const clearEvent = checkTxEvent(overwriteTx, 'ClearDelegate', registry.address, true) 60 | assert.equal(clearEvent.args.delegator, formatAddress(accounts[0])) 61 | assert.equal(clearEvent.args.id, "0x" + TEST_ID_1.toString("hex")) 62 | assert.equal(clearEvent.args.delegate, TEST_DELEGATE_1) 63 | 64 | assert.equal(await registry.delegation(accounts[0], TEST_ID_1), TEST_DELEGATE_2) 65 | }) 66 | 67 | it('set and clear delegate, 0 id', async () => { 68 | const TEST_ID_0 = "0x0000000000000000000000000000000000000000000000000000000000000000" 69 | const setTx = await registry.setDelegate(TEST_ID_0, TEST_DELEGATE_1, { from: accounts[0] }) 70 | const setEvent = checkTxEvent(setTx, 'SetDelegate', registry.address, true, "Set Delegate") 71 | assert.equal(setEvent.args.delegator, formatAddress(accounts[0])) 72 | assert.equal(setEvent.args.id, TEST_ID_0) 73 | assert.equal(setEvent.args.delegate, TEST_DELEGATE_1) 74 | checkTxEvent(setTx, 'ClearDelegate', registry.address, false) 75 | 76 | assert.equal(await registry.delegation(accounts[0], TEST_ID_0), TEST_DELEGATE_1) 77 | 78 | // Reset delegate 79 | const clearTx = await registry.clearDelegate(TEST_ID_0, { from: accounts[0] }) 80 | const clearEvent = checkTxEvent(clearTx, 'ClearDelegate', registry.address, true, "Clear Delegate") 81 | assert.equal(clearEvent.args.delegator, formatAddress(accounts[0])) 82 | assert.equal(clearEvent.args.id, TEST_ID_0) 83 | assert.equal(clearEvent.args.delegate, TEST_DELEGATE_1) 84 | checkTxEvent(clearTx, 'SetDelegate', registry.address, false) 85 | 86 | assert.equal(await registry.delegation(accounts[0], TEST_ID_0), ZERO_ADDRESS) 87 | }) 88 | 89 | it('set and clear delegates, multiple ids', async () => { 90 | const setTx1 = await registry.setDelegate(TEST_ID_1, TEST_DELEGATE_1, { from: accounts[0] }) 91 | const setEvent1 = checkTxEvent(setTx1, 'SetDelegate', registry.address, true, "Set Delegate 1") 92 | assert.equal(setEvent1.args.delegator, formatAddress(accounts[0])) 93 | assert.equal(setEvent1.args.id, "0x" + TEST_ID_1.toString("hex")) 94 | assert.equal(setEvent1.args.delegate, TEST_DELEGATE_1) 95 | checkTxEvent(setTx1, 'ClearDelegate', registry.address, false) 96 | 97 | const setTx2 = await registry.setDelegate(TEST_ID_2, TEST_DELEGATE_2, { from: accounts[0] }) 98 | const setEvent2 = checkTxEvent(setTx2, 'SetDelegate', registry.address, true, "Set Delegate 2") 99 | assert.equal(setEvent2.args.delegator, formatAddress(accounts[0])) 100 | assert.equal(setEvent2.args.id, "0x" + TEST_ID_2.toString("hex")) 101 | assert.equal(setEvent2.args.delegate, TEST_DELEGATE_2) 102 | checkTxEvent(setTx2, 'ClearDelegate', registry.address, false) 103 | 104 | assert.equal(await registry.delegation(accounts[0], TEST_ID_1), TEST_DELEGATE_1) 105 | assert.equal(await registry.delegation(accounts[0], TEST_ID_2), TEST_DELEGATE_2) 106 | 107 | // Reset delegate for first id 108 | const clearTx1 = await registry.clearDelegate(TEST_ID_1, { from: accounts[0] }) 109 | const clearEvent1 = checkTxEvent(clearTx1, 'ClearDelegate', registry.address, true, "Clear Delegate 1") 110 | assert.equal(clearEvent1.args.delegator, formatAddress(accounts[0])) 111 | assert.equal(clearEvent1.args.id, "0x" + TEST_ID_1.toString("hex")) 112 | assert.equal(clearEvent1.args.delegate, TEST_DELEGATE_1) 113 | checkTxEvent(clearTx1, 'SetDelegate', registry.address, false) 114 | 115 | assert.equal(await registry.delegation(accounts[0], TEST_ID_1), ZERO_ADDRESS) 116 | assert.equal(await registry.delegation(accounts[0], TEST_ID_2), TEST_DELEGATE_2) 117 | 118 | // Reset delegate for second id 119 | const clearTx2 = await registry.clearDelegate(TEST_ID_2, { from: accounts[0] }) 120 | const clearEvent2 = checkTxEvent(clearTx2, 'ClearDelegate', registry.address, true, "Clear Delegate 2") 121 | assert.equal(clearEvent2.args.delegator, formatAddress(accounts[0])) 122 | assert.equal(clearEvent2.args.id, "0x" + TEST_ID_2.toString("hex")) 123 | assert.equal(clearEvent2.args.delegate, TEST_DELEGATE_2) 124 | checkTxEvent(clearTx2, 'SetDelegate', registry.address, false) 125 | 126 | assert.equal(await registry.delegation(accounts[0], TEST_ID_1), ZERO_ADDRESS) 127 | assert.equal(await registry.delegation(accounts[0], TEST_ID_2), ZERO_ADDRESS) 128 | }) 129 | }) 130 | -------------------------------------------------------------------------------- /test/delegate_with_safe.js: -------------------------------------------------------------------------------- 1 | const ethUtil = require('ethereumjs-util') 2 | const safeUtils = require('@gnosis.pm/safe-contracts/test/utils/general') 3 | const { checkTxEvent, formatAddress } = safeUtils 4 | 5 | const truffleContract = require("@truffle/contract") 6 | 7 | // Create GnosisSafe truffle contract 8 | const GnosisSafeBuildInfo = require("@gnosis.pm/safe-contracts/build/contracts/GnosisSafe.json") 9 | const GnosisSafe = truffleContract(GnosisSafeBuildInfo) 10 | GnosisSafe.setProvider(web3.currentProvider) 11 | 12 | // Create GnosisSafeProxy truffle contract 13 | const GnosisSafeProxyBuildInfo = require("@gnosis.pm/safe-contracts/build/contracts/GnosisSafeProxy.json") 14 | const GnosisSafeProxy = truffleContract(GnosisSafeProxyBuildInfo) 15 | GnosisSafeProxy.setProvider(web3.currentProvider) 16 | 17 | const DelegateRegistry = artifacts.require("./DelegateRegistry.sol") 18 | 19 | contract('DelegateRegistry - With Safe', (accounts) => { 20 | 21 | const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" 22 | const TEST_DELEGATE_1 = "0x0000000000000000000000000000000000baDDAd" 23 | const TEST_DELEGATE_2 = "0x0000000000000000000000000000000000BADbed" 24 | const TEST_ID_1 = ethUtil.keccak("test_1_project") 25 | const TEST_ID_2 = ethUtil.keccak("test_2_project") 26 | 27 | let lw 28 | let registry 29 | let gnosisSafe 30 | 31 | beforeEach(async () => { 32 | lw = await safeUtils.createLightwallet() 33 | 34 | // Deploy Registry 35 | registry = await DelegateRegistry.new() 36 | 37 | // Create a Safe 38 | const gnosisSafeMasterCopy = await GnosisSafe.new({ from: accounts[0] }) 39 | const proxy = await GnosisSafeProxy.new(gnosisSafeMasterCopy.address, { from: accounts[0] }) 40 | gnosisSafe = await GnosisSafe.at(proxy.address) 41 | 42 | await gnosisSafe.setup([lw.accounts[0], lw.accounts[1], accounts[1]], 2, ZERO_ADDRESS, "0x", ZERO_ADDRESS, ZERO_ADDRESS, 0, ZERO_ADDRESS, { from: accounts[0] }) 43 | }) 44 | 45 | let execTransaction = async function (to, data, message) { 46 | let nonce = await gnosisSafe.nonce() 47 | let transactionHash = await gnosisSafe.getTransactionHash(to, 0, data, 0, 0, 0, 0, ZERO_ADDRESS, ZERO_ADDRESS, nonce) 48 | let sigs = safeUtils.signTransaction(lw, [lw.accounts[0], lw.accounts[1]], transactionHash) 49 | let tx = await gnosisSafe.execTransaction(to, 0, data, 0, 0, 0, 0, ZERO_ADDRESS, ZERO_ADDRESS, sigs, { from: accounts[0] }) 50 | safeUtils.logGasUsage( 51 | 'execTransaction ' + message, 52 | tx 53 | ) 54 | return tx 55 | } 56 | 57 | it('set and clear delegate, same id', async () => { 58 | await execTransaction( 59 | registry.address, 60 | await registry.contract.methods.setDelegate(TEST_ID_1, TEST_DELEGATE_1).encodeABI(), 61 | "Set Delegate" 62 | ) 63 | 64 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_1), TEST_DELEGATE_1) 65 | 66 | // Reset delegate 67 | await execTransaction( 68 | registry.address, 69 | await registry.contract.methods.clearDelegate(TEST_ID_1).encodeABI(), 70 | "Set Delegate" 71 | ) 72 | 73 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_1), ZERO_ADDRESS) 74 | }) 75 | 76 | it('set and overwrite delegate, same id', async () => { 77 | await execTransaction( 78 | registry.address, 79 | await registry.contract.methods.setDelegate(TEST_ID_1, TEST_DELEGATE_1).encodeABI(), 80 | "Set Delegate" 81 | ) 82 | 83 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_1), TEST_DELEGATE_1) 84 | 85 | // Overwrite delegate 86 | await execTransaction( 87 | registry.address, 88 | await registry.contract.methods.setDelegate(TEST_ID_1, TEST_DELEGATE_2).encodeABI(), 89 | "Overwrite Delegate" 90 | ) 91 | 92 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_1), TEST_DELEGATE_2) 93 | }) 94 | 95 | it('set and clear delegate, 0 id', async () => { 96 | const TEST_ID_0 = "0x0000000000000000000000000000000000000000000000000000000000000000" 97 | await execTransaction( 98 | registry.address, 99 | await registry.contract.methods.setDelegate(TEST_ID_0, TEST_DELEGATE_1).encodeABI(), 100 | "Set Delegate" 101 | ) 102 | 103 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_0), TEST_DELEGATE_1) 104 | 105 | // Reset delegate 106 | await execTransaction( 107 | registry.address, 108 | await registry.contract.methods.clearDelegate(TEST_ID_0).encodeABI(), 109 | "Set Delegate" 110 | ) 111 | 112 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_0), ZERO_ADDRESS) 113 | }) 114 | 115 | it('set and clear delegates, multiple ids', async () => { 116 | await execTransaction( 117 | registry.address, 118 | await registry.contract.methods.setDelegate(TEST_ID_1, TEST_DELEGATE_1).encodeABI(), 119 | "Set Delegate" 120 | ) 121 | await execTransaction( 122 | registry.address, 123 | await registry.contract.methods.setDelegate(TEST_ID_2, TEST_DELEGATE_2).encodeABI(), 124 | "Set Delegate" 125 | ) 126 | 127 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_1), TEST_DELEGATE_1) 128 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_2), TEST_DELEGATE_2) 129 | 130 | // Reset delegate for first id 131 | // Reset delegate 132 | await execTransaction( 133 | registry.address, 134 | await registry.contract.methods.clearDelegate(TEST_ID_1).encodeABI(), 135 | "Clear Delegate" 136 | ) 137 | 138 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_1), ZERO_ADDRESS) 139 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_2), TEST_DELEGATE_2) 140 | 141 | // Reset delegate for second id 142 | // Reset delegate 143 | await execTransaction( 144 | registry.address, 145 | await registry.contract.methods.clearDelegate(TEST_ID_2).encodeABI(), 146 | "Clear Delegate" 147 | ) 148 | 149 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_1), ZERO_ADDRESS) 150 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_2), ZERO_ADDRESS) 151 | }) 152 | 153 | it('set delegates, eoa and Safe', async () => { 154 | await execTransaction( 155 | registry.address, 156 | await registry.contract.methods.setDelegate(TEST_ID_1, TEST_DELEGATE_1).encodeABI(), 157 | "Set Delegate" 158 | ) 159 | safeUtils.logGasUsage( 160 | 'Set Delegate with TEST_ID_1 and TEST_DELEGATE_2', 161 | await registry.setDelegate(TEST_ID_1, TEST_DELEGATE_2, { from: accounts[8] }) 162 | ) 163 | safeUtils.logGasUsage( 164 | 'Set Delegate with TEST_ID_2 and TEST_DELEGATE_2', 165 | await registry.setDelegate(TEST_ID_2, TEST_DELEGATE_2, { from: accounts[8] }) 166 | ) 167 | 168 | assert.equal(await registry.delegation(gnosisSafe.address, TEST_ID_1), TEST_DELEGATE_1) 169 | assert.equal(await registry.delegation(accounts[8], TEST_ID_1), TEST_DELEGATE_2) 170 | assert.equal(await registry.delegation(accounts[8], TEST_ID_2), TEST_DELEGATE_2) 171 | }) 172 | }) 173 | -------------------------------------------------------------------------------- /test/invalid_calls.js: -------------------------------------------------------------------------------- 1 | const { assertRejects } = require('./utils/assertions') 2 | 3 | const ethUtil = require('ethereumjs-util') 4 | const abi = require('ethereumjs-abi') 5 | 6 | const DelegateRegistry = artifacts.require("./DelegateRegistry.sol") 7 | 8 | contract('DelegateRegistry - Error Cases', (accounts) => { 9 | 10 | const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" 11 | const TEST_DELEGATE_1 = "0x0000000000000000000000000000000000baDDAd" 12 | const TEST_DELEGATE_2 = "0x0000000000000000000000000000000000BADbed" 13 | const TEST_ID_1 = ethUtil.keccak("test_1_project") 14 | const TEST_ID_2 = ethUtil.keccak("test_2_project") 15 | 16 | let registry 17 | 18 | beforeEach(async () => { 19 | // Deploy Registry 20 | registry = await DelegateRegistry.new() 21 | }) 22 | 23 | it('cannot set delegate to self', async () => { 24 | await assertRejects( 25 | registry.setDelegate(TEST_ID_1, accounts[0], { from: accounts[0]}), 26 | "Delegate should not be msg.sender" 27 | ) 28 | }) 29 | 30 | it('cannot set delegate to 0x0', async () => { 31 | await assertRejects( 32 | registry.setDelegate(TEST_ID_1, ZERO_ADDRESS, { from: accounts[0]}), 33 | "Delegate should not be 0x0" 34 | ) 35 | }) 36 | 37 | it('cannot set delegate to same twice', async () => { 38 | await registry.setDelegate(TEST_ID_1, TEST_DELEGATE_1, { from: accounts[0]}) 39 | await assertRejects( 40 | registry.setDelegate(TEST_ID_1, TEST_DELEGATE_1, { from: accounts[0]}), 41 | "Delegate should not be set again" 42 | ) 43 | }) 44 | 45 | it('cannot clear unset delegate', async () => { 46 | await assertRejects( 47 | registry.clearDelegate(TEST_ID_1, { from: accounts[0]}), 48 | "Delegate should be set" 49 | ) 50 | }) 51 | 52 | }) 53 | -------------------------------------------------------------------------------- /test/utils/assertions.js: -------------------------------------------------------------------------------- 1 | const assertRejects = async (q, msg) => { 2 | let res, catchFlag = false 3 | try { 4 | res = await q 5 | } catch(e) { 6 | catchFlag = true 7 | } finally { 8 | if(!catchFlag) 9 | assert.fail(res, null, msg) 10 | } 11 | return res 12 | } 13 | 14 | Object.assign(exports, { 15 | assertRejects 16 | }) 17 | -------------------------------------------------------------------------------- /truffle-config.js: -------------------------------------------------------------------------------- 1 | const HDWalletProvider = require('@truffle/hdwallet-provider') 2 | require('dotenv').config() 3 | const package = require('./package') 4 | const mnemonic = process.env.MNEMONIC 5 | const token = process.env.INFURA_TOKEN 6 | 7 | module.exports = { 8 | networks: { 9 | development: { 10 | host: "localhost", 11 | port: 8545, 12 | network_id: "*" // Match any network id 13 | }, 14 | rinkeby: { 15 | provider: () => { 16 | return new HDWalletProvider(mnemonic, 'https://rinkeby.infura.io/v3/' + token) 17 | }, 18 | network_id: '4', 19 | gasPrice: 25000000000, // 25 Gwei 20 | }, 21 | goerli: { 22 | provider: () => { 23 | return new HDWalletProvider(mnemonic, 'https://goerli.infura.io/v3/' + token) 24 | }, 25 | network_id: '5', 26 | gasPrice: 25000000000, // 25 Gwei 27 | }, 28 | kovan: { 29 | provider: () => { 30 | return new HDWalletProvider(mnemonic, 'https://kovan.infura.io/v3/' + token) 31 | }, 32 | network_id: '42', 33 | gasPrice: 25000000000, // 25 Gwei 34 | }, 35 | mainnet: { 36 | provider: () => { 37 | return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/v3/' + token) 38 | }, 39 | network_id: '1', 40 | gasPrice: 25000000000, // 25 Gwei 41 | }, 42 | xdai: { 43 | provider: () => { 44 | return new HDWalletProvider(mnemonic, 'https://dai.poa.network') 45 | }, 46 | network_id: '100', 47 | gasPrice: 1000000000, // 1 Gwei 48 | }, 49 | volta: { 50 | provider: () => { 51 | return new HDWalletProvider(mnemonic, 'https://volta-rpc.energyweb.org') 52 | }, 53 | network_id: '73799', 54 | gasPrice: 1 55 | }, 56 | ewc: { 57 | provider: () => { 58 | return new HDWalletProvider(mnemonic, 'https://rpc.energyweb.org') 59 | }, 60 | network_id: '246', 61 | gasPrice: 1 62 | } 63 | }, 64 | compilers: { 65 | solc: { 66 | version: package.dependencies.solc, 67 | settings: { 68 | optimizer: { 69 | enabled: false 70 | }, 71 | evmVersion: "petersburg" 72 | } 73 | } 74 | }, 75 | plugins: ["solidity-coverage"] 76 | }; 77 | --------------------------------------------------------------------------------