├── .eslintignore ├── .eslintrc.js ├── .github └── workflows │ ├── cla.yml │ └── test.yml ├── .gitignore ├── .prettierrc.json ├── README.md ├── lerna.json ├── package.json ├── packages ├── contract-proxy-kit │ ├── .env.example │ ├── LICENSE │ ├── README.md │ ├── assets │ │ └── CPKdiagram.png │ ├── contracts │ │ ├── CPKFactory.sol │ │ ├── Deps.sol │ │ └── Multistep.sol │ ├── migrations-ts │ │ └── 1-deploy-contracts.ts │ ├── mocha │ │ └── setup.ts │ ├── package.json │ ├── src │ │ ├── CPK.ts │ │ ├── abis │ │ │ ├── CpkFactoryAbi.json │ │ │ ├── MultiSendAbi.json │ │ │ ├── SafeAbiV1-1-1.json │ │ │ └── SafeAbiV1-2-0.json │ │ ├── config │ │ │ ├── networks.ts │ │ │ └── transactionManagers.ts │ │ ├── contractManager │ │ │ ├── ContractV111Utils.ts │ │ │ ├── ContractV120Utils.ts │ │ │ ├── ContractVersionUtils.ts │ │ │ └── index.ts │ │ ├── ethLibAdapters │ │ │ ├── EthLibAdapter.ts │ │ │ ├── EthersAdapter │ │ │ │ ├── EthersV4ContractAdapter.ts │ │ │ │ ├── EthersV5ContractAdapter.ts │ │ │ │ └── index.ts │ │ │ └── Web3Adapter │ │ │ │ ├── Web3ContractAdapter.ts │ │ │ │ └── index.ts │ │ ├── index.ts │ │ ├── safeAppsSdkConnector │ │ │ └── index.ts │ │ ├── transactionManagers │ │ │ ├── CpkTransactionManager │ │ │ │ └── index.ts │ │ │ ├── RocksideTxRelayManager │ │ │ │ └── index.ts │ │ │ ├── SafeTxRelayManager │ │ │ │ └── index.ts │ │ │ ├── TransactionManager.ts │ │ │ └── utils.ts │ │ └── utils │ │ │ ├── basicTypes.ts │ │ │ ├── checkConnectedToSafe.ts │ │ │ ├── constants.ts │ │ │ ├── hexData.ts │ │ │ ├── httpRequests.ts │ │ │ ├── networks.ts │ │ │ └── transactions.ts │ ├── test │ │ ├── .eslintrc.js │ │ ├── contract-proxy-kit.ts │ │ ├── ethers │ │ │ ├── shouldWorkWithEthers.ts │ │ │ ├── testEthersAdapter.ts │ │ │ └── utils.ts │ │ ├── transactions │ │ │ ├── testConnectedSafeTransactionsWithRelay.ts │ │ │ └── testSafeTransactions.ts │ │ ├── utils │ │ │ ├── contracts.ts │ │ │ ├── index.ts │ │ │ └── makeEmulatedSafeProvider.ts │ │ └── web3 │ │ │ ├── shouldWorkWithWeb3.ts │ │ │ ├── testWeb3Adapter.ts │ │ │ └── utils.ts │ ├── truffle-config.js │ ├── tsconfig.cjs.json │ ├── tsconfig.json │ └── tsconfig.migrate.json └── cpk-configuration-app │ ├── README.md │ ├── package.json │ ├── public │ ├── CORS │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt │ ├── src │ ├── assets │ │ └── images │ │ │ └── logo.svg │ ├── components │ │ ├── App │ │ │ └── index.tsx │ │ ├── ConnectButton │ │ │ └── index.tsx │ │ ├── CpkInfo │ │ │ └── index.tsx │ │ ├── SafeModules │ │ │ └── index.tsx │ │ └── Transactions │ │ │ └── index.tsx │ ├── index.tsx │ ├── react-app-env.d.ts │ ├── serviceWorker.js │ ├── setupTests.js │ ├── styles │ │ └── globalStyles.ts │ ├── types │ │ └── fonts.d.ts │ └── utils │ │ ├── balances.ts │ │ └── networks.ts │ └── tsconfig.json ├── tsconfig.base.json └── yarn.lock /.eslintignore: -------------------------------------------------------------------------------- 1 | !.eslintrc.js 2 | truffle-config.js 3 | lib/ 4 | **/*.d.ts 5 | migrations/*.js 6 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', // Specifies the ESLint parser 3 | extends: [ 4 | 'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin 5 | 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier 6 | 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. 7 | ], 8 | parserOptions: { 9 | ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features 10 | sourceType: 'module', // Allows for the use of imports 11 | }, 12 | } 13 | -------------------------------------------------------------------------------- /.github/workflows/cla.yml: -------------------------------------------------------------------------------- 1 | name: 'CLA Assistant' 2 | on: 3 | issue_comment: 4 | types: [created] 5 | pull_request_target: 6 | types: [opened, closed, synchronize] 7 | 8 | jobs: 9 | CLAssistant: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: 'CLA Assistant' 13 | if: (github.event.comment.body == 'recheckcla' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target' 14 | # Alpha Release 15 | uses: gnosis/github-action@master 16 | # GitHub token, automatically provided to the action 17 | # (No need to define this secret in the repo settings) 18 | env: 19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 20 | with: 21 | path-to-signatures: 'signatures/version1/cla.json' 22 | path-to-cla-document: 'https://gnosis-safe.io/cla/' 23 | branch: 'cla-signatures' 24 | allowlist: germartinez,mikheevm,rmeissner,Uxio0,dasanra,davidalbela,luarx,giacomolicari,lukasschor,tschubotz,gnosis-info,bot* 25 | empty-commit-flag: false 26 | blockchain-storage-flag: false 27 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: CPK Tests 2 | on: [push, pull_request] 3 | jobs: 4 | test: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout 8 | id: checkout 9 | uses: actions/checkout@v2 10 | 11 | - name: Install node 12 | id: install-node 13 | uses: actions/setup-node@v1 14 | with: 15 | node-version: 15.11.x 16 | 17 | - name: Start Safe Relay Service 18 | id: safe-relay-service 19 | run: | 20 | git clone https://github.com/gnosis/safe-relay-service.git 21 | cd safe-relay-service 22 | git checkout cpk-test 23 | sudo service postgresql stop 24 | docker-compose -f docker-compose.yml -f docker-compose.dev.yml build 25 | docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d 26 | 27 | - name: Install 28 | id: installation 29 | run: | 30 | yarn global add ganache-cli@6.12.2 31 | yarn 32 | 33 | - name: Run tests 34 | id: tests 35 | run: | 36 | ganache-cli -d --defaultBalanceEther 10000 -h 0.0.0.0 --noVMErrorsOnRPCResponse > /dev/null & 37 | sleep 10 38 | yarn cpk:test 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript 40 | typings/ 41 | lib 42 | **/types/truffle-contracts 43 | 44 | # Optional npm cache directory 45 | .npm 46 | 47 | # Optional eslint cache 48 | .eslintcache 49 | 50 | # Optional REPL history 51 | .node_repl_history 52 | 53 | # Output of 'npm pack' 54 | *.tgz 55 | 56 | # Yarn Integrity file 57 | .yarn-integrity 58 | 59 | # dotenv environment variables file 60 | .env 61 | 62 | # next.js build output 63 | .next 64 | 65 | # Truffle 66 | build/ 67 | 68 | # Typechain for migrations 69 | migrations/ 70 | 71 | # Documentation 72 | docs/ 73 | 74 | # VSCode 75 | .vscode 76 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "bracketSpacing": true, 3 | "arrowParens": "always", 4 | "printWidth": 100, 5 | "trailingComma": "none", 6 | "tabWidth": 2, 7 | "semi": false, 8 | "singleQuote": true 9 | } 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Contract Proxy Kit Monorepo 2 | 3 | [![Coverage Status](https://coveralls.io/repos/github/gnosis/contract-proxy-kit/badge.svg?branch=master)](https://coveralls.io/github/gnosis/contract-proxy-kit?branch=master) 4 | 5 | ## Packages 6 | 7 | | Package | Description | 8 | | ------- | ----------- | 9 | | [contract-proxy-kit](https://github.com/gnosis/contract-proxy-kit/tree/master/packages/contract-proxy-kit) [![npm version](https://badge.fury.io/js/contract-proxy-kit.svg)](https://badge.fury.io/js/contract-proxy-kit) | TypeScript SDK that enables batched transactions and contract account interactions using a unique deterministic Gnosis Safe. | 10 | | [cpk-configuration-app](https://github.com/gnosis/contract-proxy-kit/tree/master/packages/cpk-configuration-app) | Example Dapp that uses the CPK showing all its possible configurations and allowing to play around with it. | 11 | 12 | ## Setting up the development environment 13 | 14 | ### Installing dependencies 15 | 16 | ``` 17 | yarn global add lerna 18 | lerna bootstrap 19 | ``` 20 | 21 | ### Running commands 22 | 23 | Build the Contract Proxy Kit: 24 | ``` 25 | yarn cpk:build 26 | ``` 27 | 28 | Test the Contract Proxy Kit: 29 | ``` 30 | yarn cpk:test 31 | ``` 32 | 33 | Build the CPK Configuration App 34 | ``` 35 | yarn app:build 36 | ``` 37 | 38 | Run the CPK Configuration App 39 | ``` 40 | yarn app:start 41 | ``` 42 | 43 | ## Useful links 44 | 45 | - [API Documentation](https://cpk-docs.surge.sh/) 46 | - [CPK Configuration App demo](https://cpk-app.surge.sh) 47 | - [Video introduction to Building with Safe Apps SDK & Contract Proxy Kit](https://www.youtube.com/watch?v=YGw8WfBw5OI) 48 | 49 | You can find more resources on the Contract Proxy Kit in the [Gnosis Safe Developer Portal](https://docs.gnosis.io/safe/docs/sdks_safe_apps/). 50 | -------------------------------------------------------------------------------- /lerna.json: -------------------------------------------------------------------------------- 1 | { 2 | "packages": ["packages/*"], 3 | "npmClient": "yarn", 4 | "version": "independent", 5 | "useWorkspaces": true 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "contract-proxy-kit-monorepo", 3 | "private": true, 4 | "workspaces": { 5 | "packages": [ 6 | "packages/*" 7 | ] 8 | }, 9 | "scripts": { 10 | "cpk:build": "lerna run build --scope contract-proxy-kit --stream", 11 | "cpk:test": "FORCE_COLOR=1 lerna run test --scope contract-proxy-kit --stream", 12 | "cpk:publish-docs": "lerna run publish-docs --scope contract-proxy-kit --stream", 13 | "app:build": "lerna run build --scope cpk-configuration-app --stream", 14 | "app:start": "lerna run start --scope cpk-configuration-app --stream", 15 | "app:deploy": "lerna run deploy --scope cpk-configuration-app --stream" 16 | }, 17 | "devDependencies": { 18 | "@gnosis.pm/conditional-tokens-contracts": "^0.5.4", 19 | "@gnosis.pm/safe-contracts": "1.2.0", 20 | "@testing-library/jest-dom": "^5.14.1", 21 | "@testing-library/react": "^11.2.5", 22 | "@testing-library/user-event": "^12.7.0", 23 | "@truffle/hdwallet-provider": "^1.4.1", 24 | "@typechain/truffle-v5": "^4.0.1", 25 | "@types/chai": "^4.2.21", 26 | "@types/chai-as-promised": "^7.1.4", 27 | "@types/mocha": "^8.2.3", 28 | "@types/node-fetch": "^2.5.11", 29 | "@types/react": "^17.0.14", 30 | "@types/react-dom": "^17.0.9", 31 | "@types/styled-components": "^5.1.11", 32 | "@typescript-eslint/eslint-plugin": "^4.28.3", 33 | "@typescript-eslint/parser": "^4.28.3", 34 | "chai": "^4.3.4", 35 | "chai-as-promised": "^7.1.1", 36 | "coveralls": "^3.1.1", 37 | "dotenv": "^8.2.0", 38 | "eslint": "^7.31.0", 39 | "eslint-config-prettier": "^7.2.0", 40 | "eslint-plugin-prettier": "^3.4.0", 41 | "ethers-4": "npm:ethers@^4.0.45", 42 | "ethers-5": "npm:ethers@^5.4.1", 43 | "ganache-cli": "^6.12.2", 44 | "geth-dev-assistant": "^0.1.8", 45 | "jsdom": "^16.6.0", 46 | "jsdom-global": "^3.0.2", 47 | "lerna": "^3.22.1", 48 | "nyc": "^15.1.0", 49 | "prettier": "^2.3.2", 50 | "prettier-eslint-cli": "^5.0.1", 51 | "run-with-testrpc": "^0.3.1", 52 | "should": "^13.2.3", 53 | "truffle": "^5.4.1", 54 | "truffle-typings": "^1.0.8", 55 | "ts-node": "^10.1.0", 56 | "typechain": "^4.0.1", 57 | "typedoc": "^0.21.4", 58 | "typescript": "^4.3.5", 59 | "wait-port": "^0.2.9", 60 | "web3-1-4": "npm:web3@^1.4.0", 61 | "web3-2-alpha": "npm:web3@^2.0.0-alpha.1" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/.env.example: -------------------------------------------------------------------------------- 1 | SEED= 2 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/assets/CPKdiagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5afe/contract-proxy-kit/cfc799fba5f4c3d0f1d90d32a5ff1ea70b4e0bbe/packages/contract-proxy-kit/assets/CPKdiagram.png -------------------------------------------------------------------------------- /packages/contract-proxy-kit/contracts/CPKFactory.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0 <0.7.0; 2 | 3 | import { Enum } from "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; 4 | import { GnosisSafeProxy } from "@gnosis.pm/safe-contracts/contracts/proxies/GnosisSafeProxy.sol"; 5 | import { GnosisSafe } from "@gnosis.pm/safe-contracts/contracts/GnosisSafe.sol"; 6 | 7 | contract CPKFactory { 8 | event ProxyCreation(GnosisSafeProxy proxy); 9 | 10 | function proxyCreationCode() external pure returns (bytes memory) { 11 | return type(GnosisSafeProxy).creationCode; 12 | } 13 | 14 | function createProxyAndExecTransaction( 15 | address masterCopy, 16 | uint256 saltNonce, 17 | address fallbackHandler, 18 | address to, 19 | uint256 value, 20 | bytes calldata data, 21 | Enum.Operation operation 22 | ) 23 | external 24 | returns (bool execTransactionSuccess) 25 | { 26 | GnosisSafe proxy; 27 | bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, abi.encode(masterCopy)); 28 | bytes32 salt = keccak256(abi.encode(msg.sender, saltNonce)); 29 | // solium-disable-next-line security/no-inline-assembly 30 | assembly { 31 | proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt) 32 | } 33 | require(address(proxy) != address(0), "create2 call failed"); 34 | 35 | { 36 | address[] memory tmp = new address[](1); 37 | tmp[0] = address(this); 38 | proxy.setup(tmp, 1, address(0), "", fallbackHandler, address(0), 0, address(0)); 39 | } 40 | 41 | execTransactionSuccess = proxy.execTransaction(to, value, data, operation, 0, 0, 0, address(0), address(0), 42 | abi.encodePacked(uint(address(this)), uint(0), uint8(1))); 43 | 44 | proxy.execTransaction( 45 | address(proxy), 0, 46 | abi.encodeWithSignature("swapOwner(address,address,address)", address(1), address(this), msg.sender), 47 | Enum.Operation.Call, 48 | 0, 0, 0, address(0), address(0), 49 | abi.encodePacked(uint(address(this)), uint(0), uint8(1)) 50 | ); 51 | 52 | emit ProxyCreation(GnosisSafeProxy(address(proxy))); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/contracts/Deps.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0 <0.7.0; 2 | 3 | import { GnosisSafeProxyFactory } from "@gnosis.pm/safe-contracts/contracts/proxies/GnosisSafeProxyFactory.sol"; 4 | import { MultiSend } from "@gnosis.pm/safe-contracts/contracts/libraries/MultiSend.sol"; 5 | import { GnosisSafe } from "@gnosis.pm/safe-contracts/contracts/GnosisSafe.sol"; 6 | import { DefaultCallbackHandler } from "@gnosis.pm/safe-contracts/contracts/handler/DefaultCallbackHandler.sol"; 7 | import { DailyLimitModule } from "@gnosis.pm/safe-contracts/contracts/modules/DailyLimitModule.sol"; 8 | import { ConditionalTokens } from "@gnosis.pm/conditional-tokens-contracts/contracts/ConditionalTokens.sol"; 9 | import { ERC20Mintable } from "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol"; 10 | 11 | contract GnosisSafe2 is GnosisSafe {} 12 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/contracts/Multistep.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0 <0.7.0; 2 | 3 | import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; 4 | 5 | contract Multistep { 6 | event ExpensiveHashMade(bytes32 h); 7 | 8 | mapping(address => uint) public lastStepFinished; 9 | 10 | function makeExpensiveHash(uint v) internal { 11 | bytes32 h = bytes32(v); 12 | for (uint i = 0; i < 64; i++) { 13 | h = keccak256(abi.encode(v)); 14 | } 15 | emit ExpensiveHashMade(h); 16 | } 17 | 18 | function doStep(uint step) external { 19 | require(lastStepFinished[msg.sender] + 1 == step, "must do the next step"); 20 | lastStepFinished[msg.sender]++; 21 | makeExpensiveHash(step); 22 | } 23 | 24 | function doDeepStep(uint finalStep, uint numSteps, address sender) external { 25 | if (numSteps == 0) { 26 | require(lastStepFinished[sender] == finalStep, "must end on the right step"); 27 | } else { 28 | lastStepFinished[sender]++; 29 | makeExpensiveHash(lastStepFinished[sender]); 30 | this.doDeepStep(finalStep, numSteps - 1, sender); 31 | } 32 | } 33 | 34 | function doEtherStep(uint step) external payable { 35 | require(lastStepFinished[msg.sender] + 1 == step, "must do the next ether step"); 36 | require(msg.value >= step * 1 ether, "must provide right amount of ether"); 37 | lastStepFinished[msg.sender]++; 38 | msg.sender.transfer(msg.value - step * 1 ether); 39 | makeExpensiveHash(step); 40 | } 41 | 42 | function doERC20Step(uint step, IERC20 token) external payable { 43 | require(lastStepFinished[msg.sender] + 1 == step, "must do the next ERC20 step"); 44 | lastStepFinished[msg.sender]++; 45 | require(token.transferFrom(msg.sender, address(this), step * 1 ether), "could not transfer right amount of ERC20"); 46 | makeExpensiveHash(step); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/migrations-ts/1-deploy-contracts.ts: -------------------------------------------------------------------------------- 1 | module.exports = function (deployer: Truffle.Deployer, network: string) { 2 | const deploy = (name: any): Truffle.Deployer => deployer.deploy(artifacts.require(name)) 3 | 4 | deploy('CPKFactory') 5 | 6 | if (network === 'test' || network === 'local') { 7 | ;[ 8 | 'GnosisSafe', 9 | 'GnosisSafe2', 10 | 'GnosisSafeProxyFactory', 11 | 'MultiSend', 12 | 'DefaultCallbackHandler', 13 | 'Multistep', 14 | 'DailyLimitModule', 15 | 'ERC20Mintable', 16 | 'ConditionalTokens' 17 | ].forEach(deploy) 18 | } 19 | } as Truffle.Migration 20 | 21 | export { } 22 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/mocha/setup.ts: -------------------------------------------------------------------------------- 1 | import crypto from 'crypto' 2 | 3 | function getRandomValues(buf: Uint8Array) { 4 | if (!(buf instanceof Uint8Array)) { 5 | throw new TypeError('expected Uint8Array') 6 | } 7 | if (buf.length > 65536) { 8 | const e = new Error() 9 | e.message = 10 | "Failed to execute 'getRandomValues' on 'Crypto': The " + 11 | "ArrayBufferView's byte length (" + 12 | buf.length + 13 | ') exceeds the ' + 14 | 'number of bytes of entropy available via this API (65536).' 15 | e.name = 'QuotaExceededError' 16 | throw e 17 | } 18 | const bytes = crypto.randomBytes(buf.length) 19 | buf.set(bytes) 20 | 21 | return buf 22 | } 23 | 24 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 25 | // @ts-ignore 26 | window.crypto = { getRandomValues } 27 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "contract-proxy-kit", 3 | "version": "3.0.0", 4 | "description": "Enable batched transactions and contract account interactions using a unique deterministic Gnosis Safe.", 5 | "main": "lib/cjs/index.js", 6 | "module": "lib/esm/index.js", 7 | "scripts": { 8 | "generate-types": "typechain --target=truffle-v5 './build/contracts/*.json'", 9 | "migrate": "tsc -p ./tsconfig.migrate.json --outDir ./migrations && truffle migrate --network local", 10 | "test-ts": "TS_NODE_PROJECT='./tsconfig.cjs.json' nyc mocha -t 20000 -r ts-node/register -r jsdom-global/register --file ./mocha/setup.ts ./test/contract-proxy-kit.ts --exit", 11 | "test": "yarn generate-types && yarn migrate && yarn test-ts", 12 | "test-rpc": "run-with-testrpc --noVMErrorsOnRPCResponse 'yarn test'", 13 | "coverage": "nyc report --reporter=text-lcov | coveralls", 14 | "format": "prettier-eslint --write $PWD/'src/**/*.{js,ts,json}' $PWD/'test/**/*.{js,ts,json}'", 15 | "build": "tsc && tsc -p tsconfig.cjs.json && yarn typedoc src/index.ts", 16 | "publish-docs": "yarn build && surge --project=docs --domain=https://cpk-docs.surge.sh" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "git+https://github.com/gnosis/contract-proxy-kit.git" 21 | }, 22 | "keywords": [ 23 | "gnosis", 24 | "safe", 25 | "proxy", 26 | "cpk", 27 | "sdk", 28 | "ethereum", 29 | "smart", 30 | "contract", 31 | "batch", 32 | "transaction", 33 | "wallet" 34 | ], 35 | "author": "Gnosis (https://gnosis.io)", 36 | "license": "GPL-3.0", 37 | "bugs": { 38 | "url": "https://github.com/gnosis/contract-proxy-kit/issues" 39 | }, 40 | "files": [ 41 | "contracts", 42 | "lib", 43 | "src" 44 | ], 45 | "homepage": "https://github.com/gnosis/contract-proxy-kit#readme", 46 | "dependencies": { 47 | "@gnosis.pm/safe-apps-sdk": "^1.1.0", 48 | "@truffle/contract": "^4.3.25", 49 | "@types/uuid": "^8.3.1", 50 | "bignumber.js": "^9.0.1", 51 | "ethereumjs-util": "^7.1.0", 52 | "ethers": "4.0.45", 53 | "node-fetch": "^2.6.1", 54 | "uuid": "^8.3.2" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/abis/CpkFactoryAbi.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "constant": true, 4 | "inputs": [], 5 | "name": "proxyCreationCode", 6 | "outputs": [ 7 | { 8 | "internalType": "bytes", 9 | "name": "", 10 | "type": "bytes" 11 | } 12 | ], 13 | "payable": false, 14 | "stateMutability": "pure", 15 | "type": "function" 16 | }, 17 | { 18 | "constant": false, 19 | "inputs": [ 20 | { 21 | "internalType": "address", 22 | "name": "masterCopy", 23 | "type": "address" 24 | }, 25 | { 26 | "internalType": "uint256", 27 | "name": "saltNonce", 28 | "type": "uint256" 29 | }, 30 | { 31 | "internalType": "address", 32 | "name": "fallbackHandler", 33 | "type": "address" 34 | }, 35 | { 36 | "internalType": "address", 37 | "name": "to", 38 | "type": "address" 39 | }, 40 | { 41 | "internalType": "uint256", 42 | "name": "value", 43 | "type": "uint256" 44 | }, 45 | { 46 | "internalType": "bytes", 47 | "name": "data", 48 | "type": "bytes" 49 | }, 50 | { 51 | "internalType": "enum Enum.Operation", 52 | "name": "operation", 53 | "type": "uint8" 54 | } 55 | ], 56 | "name": "createProxyAndExecTransaction", 57 | "outputs": [ 58 | { 59 | "internalType": "bool", 60 | "name": "execTransactionSuccess", 61 | "type": "bool" 62 | } 63 | ], 64 | "payable": false, 65 | "stateMutability": "nonpayable", 66 | "type": "function" 67 | } 68 | ] 69 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/abis/MultiSendAbi.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "constant": false, 4 | "inputs": [ 5 | { 6 | "internalType": "bytes", 7 | "name": "transactions", 8 | "type": "bytes" 9 | } 10 | ], 11 | "name": "multiSend", 12 | "outputs": [], 13 | "payable": false, 14 | "stateMutability": "nonpayable", 15 | "type": "function" 16 | } 17 | ] 18 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/abis/SafeAbiV1-1-1.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "constant": true, 4 | "inputs": [], 5 | "name": "nonce", 6 | "outputs": [ 7 | { 8 | "internalType": "uint256", 9 | "name": "", 10 | "type": "uint256" 11 | } 12 | ], 13 | "payable": false, 14 | "stateMutability": "view", 15 | "type": "function" 16 | }, 17 | { 18 | "constant": true, 19 | "inputs": [], 20 | "name": "VERSION", 21 | "outputs": [ 22 | { 23 | "internalType": "string", 24 | "name": "", 25 | "type": "string" 26 | } 27 | ], 28 | "payable": false, 29 | "stateMutability": "view", 30 | "type": "function" 31 | }, 32 | { 33 | "constant": false, 34 | "inputs": [ 35 | { 36 | "name": "_owners", 37 | "type": "address[]" 38 | }, 39 | { 40 | "name": "_threshold", 41 | "type": "uint256" 42 | }, 43 | { 44 | "name": "to", 45 | "type": "address" 46 | }, 47 | { 48 | "name": "data", 49 | "type": "bytes" 50 | }, 51 | { 52 | "name": "fallbackHandler", 53 | "type": "address" 54 | }, 55 | { 56 | "name": "paymentToken", 57 | "type": "address" 58 | }, 59 | { 60 | "name": "payment", 61 | "type": "uint256" 62 | }, 63 | { 64 | "name": "paymentReceiver", 65 | "type": "address" 66 | } 67 | ], 68 | "name": "setup", 69 | "outputs": [], 70 | "payable": false, 71 | "stateMutability": "nonpayable", 72 | "type": "function" 73 | }, 74 | { 75 | "constant": false, 76 | "inputs": [ 77 | { 78 | "name": "to", 79 | "type": "address" 80 | }, 81 | { 82 | "name": "value", 83 | "type": "uint256" 84 | }, 85 | { 86 | "name": "data", 87 | "type": "bytes" 88 | }, 89 | { 90 | "name": "operation", 91 | "type": "uint8" 92 | }, 93 | { 94 | "name": "safeTxGas", 95 | "type": "uint256" 96 | }, 97 | { 98 | "name": "baseGas", 99 | "type": "uint256" 100 | }, 101 | { 102 | "name": "gasPrice", 103 | "type": "uint256" 104 | }, 105 | { 106 | "name": "gasToken", 107 | "type": "address" 108 | }, 109 | { 110 | "name": "refundReceiver", 111 | "type": "address" 112 | }, 113 | { 114 | "name": "signatures", 115 | "type": "bytes" 116 | } 117 | ], 118 | "name": "execTransaction", 119 | "outputs": [ 120 | { 121 | "name": "success", 122 | "type": "bool" 123 | } 124 | ], 125 | "payable": false, 126 | "stateMutability": "nonpayable", 127 | "type": "function" 128 | }, 129 | { 130 | "constant": false, 131 | "inputs": [ 132 | { 133 | "name": "prevOwner", 134 | "type": "address" 135 | }, 136 | { 137 | "name": "oldOwner", 138 | "type": "address" 139 | }, 140 | { 141 | "name": "newOwner", 142 | "type": "address" 143 | } 144 | ], 145 | "name": "swapOwner", 146 | "outputs": [], 147 | "payable": false, 148 | "stateMutability": "nonpayable", 149 | "type": "function" 150 | }, 151 | { 152 | "constant": false, 153 | "inputs": [ 154 | { 155 | "name": "to", 156 | "type": "address" 157 | }, 158 | { 159 | "name": "value", 160 | "type": "uint256" 161 | }, 162 | { 163 | "name": "data", 164 | "type": "bytes" 165 | }, 166 | { 167 | "name": "operation", 168 | "type": "uint8" 169 | } 170 | ], 171 | "name": "requiredTxGas", 172 | "outputs": [ 173 | { 174 | "name": "", 175 | "type": "uint256" 176 | } 177 | ], 178 | "payable": false, 179 | "stateMutability": "nonpayable", 180 | "type": "function" 181 | }, 182 | { 183 | "constant": true, 184 | "inputs": [ 185 | { 186 | "internalType": "address", 187 | "name": "to", 188 | "type": "address" 189 | }, 190 | { 191 | "internalType": "uint256", 192 | "name": "value", 193 | "type": "uint256" 194 | }, 195 | { 196 | "internalType": "bytes", 197 | "name": "data", 198 | "type": "bytes" 199 | }, 200 | { 201 | "internalType": "enum Enum.Operation", 202 | "name": "operation", 203 | "type": "uint8" 204 | }, 205 | { 206 | "internalType": "uint256", 207 | "name": "safeTxGas", 208 | "type": "uint256" 209 | }, 210 | { 211 | "internalType": "uint256", 212 | "name": "baseGas", 213 | "type": "uint256" 214 | }, 215 | { 216 | "internalType": "uint256", 217 | "name": "gasPrice", 218 | "type": "uint256" 219 | }, 220 | { 221 | "internalType": "address", 222 | "name": "gasToken", 223 | "type": "address" 224 | }, 225 | { 226 | "internalType": "address", 227 | "name": "refundReceiver", 228 | "type": "address" 229 | }, 230 | { 231 | "internalType": "uint256", 232 | "name": "_nonce", 233 | "type": "uint256" 234 | } 235 | ], 236 | "name": "getTransactionHash", 237 | "outputs": [ 238 | { 239 | "internalType": "bytes32", 240 | "name": "", 241 | "type": "bytes32" 242 | } 243 | ], 244 | "payable": false, 245 | "stateMutability": "view", 246 | "type": "function" 247 | }, 248 | { 249 | "constant": true, 250 | "inputs": [], 251 | "name": "getModules", 252 | "outputs": [ 253 | { 254 | "internalType": "address[]", 255 | "name": "", 256 | "type": "address[]" 257 | } 258 | ], 259 | "payable": false, 260 | "stateMutability": "view", 261 | "type": "function" 262 | }, 263 | { 264 | "constant": false, 265 | "inputs": [ 266 | { 267 | "internalType": "contract Module", 268 | "name": "module", 269 | "type": "address" 270 | } 271 | ], 272 | "name": "enableModule", 273 | "outputs": [], 274 | "payable": false, 275 | "stateMutability": "nonpayable", 276 | "type": "function" 277 | }, 278 | { 279 | "constant": false, 280 | "inputs": [ 281 | { 282 | "internalType": "contract Module", 283 | "name": "prevModule", 284 | "type": "address" 285 | }, 286 | { 287 | "internalType": "contract Module", 288 | "name": "module", 289 | "type": "address" 290 | } 291 | ], 292 | "name": "disableModule", 293 | "outputs": [], 294 | "payable": false, 295 | "stateMutability": "nonpayable", 296 | "type": "function" 297 | } 298 | ] 299 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/abis/SafeAbiV1-2-0.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "constant": true, 4 | "inputs": [], 5 | "name": "nonce", 6 | "outputs": [ 7 | { 8 | "internalType": "uint256", 9 | "name": "", 10 | "type": "uint256" 11 | } 12 | ], 13 | "payable": false, 14 | "stateMutability": "view", 15 | "type": "function" 16 | }, 17 | { 18 | "constant": true, 19 | "inputs": [], 20 | "name": "VERSION", 21 | "outputs": [ 22 | { 23 | "internalType": "string", 24 | "name": "", 25 | "type": "string" 26 | } 27 | ], 28 | "payable": false, 29 | "stateMutability": "view", 30 | "type": "function" 31 | }, 32 | { 33 | "constant": false, 34 | "inputs": [ 35 | { 36 | "name": "_owners", 37 | "type": "address[]" 38 | }, 39 | { 40 | "name": "_threshold", 41 | "type": "uint256" 42 | }, 43 | { 44 | "name": "to", 45 | "type": "address" 46 | }, 47 | { 48 | "name": "data", 49 | "type": "bytes" 50 | }, 51 | { 52 | "name": "fallbackHandler", 53 | "type": "address" 54 | }, 55 | { 56 | "name": "paymentToken", 57 | "type": "address" 58 | }, 59 | { 60 | "name": "payment", 61 | "type": "uint256" 62 | }, 63 | { 64 | "name": "paymentReceiver", 65 | "type": "address" 66 | } 67 | ], 68 | "name": "setup", 69 | "outputs": [], 70 | "payable": false, 71 | "stateMutability": "nonpayable", 72 | "type": "function" 73 | }, 74 | { 75 | "constant": false, 76 | "inputs": [ 77 | { 78 | "name": "to", 79 | "type": "address" 80 | }, 81 | { 82 | "name": "value", 83 | "type": "uint256" 84 | }, 85 | { 86 | "name": "data", 87 | "type": "bytes" 88 | }, 89 | { 90 | "name": "operation", 91 | "type": "uint8" 92 | }, 93 | { 94 | "name": "safeTxGas", 95 | "type": "uint256" 96 | }, 97 | { 98 | "name": "baseGas", 99 | "type": "uint256" 100 | }, 101 | { 102 | "name": "gasPrice", 103 | "type": "uint256" 104 | }, 105 | { 106 | "name": "gasToken", 107 | "type": "address" 108 | }, 109 | { 110 | "name": "refundReceiver", 111 | "type": "address" 112 | }, 113 | { 114 | "name": "signatures", 115 | "type": "bytes" 116 | } 117 | ], 118 | "name": "execTransaction", 119 | "outputs": [ 120 | { 121 | "name": "success", 122 | "type": "bool" 123 | } 124 | ], 125 | "payable": false, 126 | "stateMutability": "nonpayable", 127 | "type": "function" 128 | }, 129 | { 130 | "constant": false, 131 | "inputs": [ 132 | { 133 | "name": "prevOwner", 134 | "type": "address" 135 | }, 136 | { 137 | "name": "oldOwner", 138 | "type": "address" 139 | }, 140 | { 141 | "name": "newOwner", 142 | "type": "address" 143 | } 144 | ], 145 | "name": "swapOwner", 146 | "outputs": [], 147 | "payable": false, 148 | "stateMutability": "nonpayable", 149 | "type": "function" 150 | }, 151 | { 152 | "constant": false, 153 | "inputs": [ 154 | { 155 | "name": "to", 156 | "type": "address" 157 | }, 158 | { 159 | "name": "value", 160 | "type": "uint256" 161 | }, 162 | { 163 | "name": "data", 164 | "type": "bytes" 165 | }, 166 | { 167 | "name": "operation", 168 | "type": "uint8" 169 | } 170 | ], 171 | "name": "requiredTxGas", 172 | "outputs": [ 173 | { 174 | "name": "", 175 | "type": "uint256" 176 | } 177 | ], 178 | "payable": false, 179 | "stateMutability": "nonpayable", 180 | "type": "function" 181 | }, 182 | { 183 | "constant": true, 184 | "inputs": [ 185 | { 186 | "internalType": "address", 187 | "name": "to", 188 | "type": "address" 189 | }, 190 | { 191 | "internalType": "uint256", 192 | "name": "value", 193 | "type": "uint256" 194 | }, 195 | { 196 | "internalType": "bytes", 197 | "name": "data", 198 | "type": "bytes" 199 | }, 200 | { 201 | "internalType": "enum Enum.Operation", 202 | "name": "operation", 203 | "type": "uint8" 204 | }, 205 | { 206 | "internalType": "uint256", 207 | "name": "safeTxGas", 208 | "type": "uint256" 209 | }, 210 | { 211 | "internalType": "uint256", 212 | "name": "baseGas", 213 | "type": "uint256" 214 | }, 215 | { 216 | "internalType": "uint256", 217 | "name": "gasPrice", 218 | "type": "uint256" 219 | }, 220 | { 221 | "internalType": "address", 222 | "name": "gasToken", 223 | "type": "address" 224 | }, 225 | { 226 | "internalType": "address", 227 | "name": "refundReceiver", 228 | "type": "address" 229 | }, 230 | { 231 | "internalType": "uint256", 232 | "name": "_nonce", 233 | "type": "uint256" 234 | } 235 | ], 236 | "name": "getTransactionHash", 237 | "outputs": [ 238 | { 239 | "internalType": "bytes32", 240 | "name": "", 241 | "type": "bytes32" 242 | } 243 | ], 244 | "payable": false, 245 | "stateMutability": "view", 246 | "type": "function" 247 | }, 248 | { 249 | "constant": true, 250 | "inputs": [], 251 | "name": "getModules", 252 | "outputs": [ 253 | { 254 | "internalType": "address[]", 255 | "name": "", 256 | "type": "address[]" 257 | } 258 | ], 259 | "payable": false, 260 | "stateMutability": "view", 261 | "type": "function" 262 | }, 263 | { 264 | "constant": false, 265 | "inputs": [ 266 | { 267 | "internalType": "contract Module", 268 | "name": "module", 269 | "type": "address" 270 | } 271 | ], 272 | "name": "enableModule", 273 | "outputs": [], 274 | "payable": false, 275 | "stateMutability": "nonpayable", 276 | "type": "function" 277 | }, 278 | { 279 | "constant": false, 280 | "inputs": [ 281 | { 282 | "internalType": "contract Module", 283 | "name": "prevModule", 284 | "type": "address" 285 | }, 286 | { 287 | "internalType": "contract Module", 288 | "name": "module", 289 | "type": "address" 290 | } 291 | ], 292 | "name": "disableModule", 293 | "outputs": [], 294 | "payable": false, 295 | "stateMutability": "nonpayable", 296 | "type": "function" 297 | }, 298 | { 299 | "constant": true, 300 | "inputs": [ 301 | { 302 | "internalType": "contract Module", 303 | "name": "module", 304 | "type": "address" 305 | } 306 | ], 307 | "name": "isModuleEnabled", 308 | "outputs": [ 309 | { 310 | "internalType": "bool", 311 | "name": "", 312 | "type": "bool" 313 | } 314 | ], 315 | "payable": false, 316 | "stateMutability": "view", 317 | "type": "function" 318 | } 319 | ] 320 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/config/networks.ts: -------------------------------------------------------------------------------- 1 | import { Address } from '../utils/basicTypes' 2 | 3 | interface MasterCopyAddressVersion { 4 | version: string 5 | address: Address 6 | } 7 | 8 | export interface NetworkConfigEntry { 9 | masterCopyAddress?: Address 10 | masterCopyAddressVersions?: Array 11 | proxyFactoryAddress: Address 12 | multiSendAddress: Address 13 | fallbackHandlerAddress: Address 14 | } 15 | 16 | export interface NetworksConfig { 17 | [id: string]: NetworkConfigEntry 18 | } 19 | 20 | export interface NormalizedNetworkConfigEntry { 21 | masterCopyAddressVersions: MasterCopyAddressVersion[] 22 | proxyFactoryAddress: Address 23 | multiSendAddress: Address 24 | fallbackHandlerAddress: Address 25 | } 26 | 27 | export interface NormalizedNetworksConfig { 28 | [id: string]: NormalizedNetworkConfigEntry 29 | } 30 | 31 | // First element belongs to latest release. Do not alter this order. New releases go first. 32 | const masterCopyAddressVersions: MasterCopyAddressVersion[] = [ 33 | { 34 | version: '1.2.0', 35 | address: '0x6851D6fDFAfD08c0295C392436245E5bc78B0185' 36 | }, 37 | { 38 | version: '1.1.1', 39 | address: '0x34CfAC646f301356fAa8B21e94227e3583Fe3F5F' 40 | } 41 | ] 42 | 43 | export const defaultNetworks: NormalizedNetworksConfig = { 44 | // mainnet 45 | 1: { 46 | masterCopyAddressVersions, 47 | proxyFactoryAddress: '0x0fB4340432e56c014fa96286de17222822a9281b', 48 | multiSendAddress: '0x8D29bE29923b68abfDD21e541b9374737B49cdAD', 49 | fallbackHandlerAddress: '0xd5D82B6aDDc9027B22dCA772Aa68D5d74cdBdF44' 50 | }, 51 | // rinkeby 52 | 4: { 53 | masterCopyAddressVersions, 54 | proxyFactoryAddress: '0x336c19296d3989e9e0c2561ef21c964068657c38', 55 | multiSendAddress: '0x8D29bE29923b68abfDD21e541b9374737B49cdAD', 56 | fallbackHandlerAddress: '0xd5D82B6aDDc9027B22dCA772Aa68D5d74cdBdF44' 57 | }, 58 | // goerli 59 | 5: { 60 | masterCopyAddressVersions, 61 | proxyFactoryAddress: '0xfC7577774887aAE7bAcdf0Fc8ce041DA0b3200f7', 62 | multiSendAddress: '0x8D29bE29923b68abfDD21e541b9374737B49cdAD', 63 | fallbackHandlerAddress: '0xd5D82B6aDDc9027B22dCA772Aa68D5d74cdBdF44' 64 | }, 65 | // kovan 66 | 42: { 67 | masterCopyAddressVersions, 68 | proxyFactoryAddress: '0xfC7577774887aAE7bAcdf0Fc8ce041DA0b3200f7', 69 | multiSendAddress: '0x8D29bE29923b68abfDD21e541b9374737B49cdAD', 70 | fallbackHandlerAddress: '0xd5D82B6aDDc9027B22dCA772Aa68D5d74cdBdF44' 71 | }, 72 | // xdai 73 | 100: { 74 | masterCopyAddressVersions, 75 | proxyFactoryAddress: '0xfC7577774887aAE7bAcdf0Fc8ce041DA0b3200f7', 76 | multiSendAddress: '0x8D29bE29923b68abfDD21e541b9374737B49cdAD', 77 | fallbackHandlerAddress: '0xd5D82B6aDDc9027B22dCA772Aa68D5d74cdBdF44' 78 | } 79 | } 80 | 81 | export function normalizeNetworksConfig( 82 | defaultNetworks: NormalizedNetworksConfig, 83 | networks?: NetworksConfig 84 | ): NormalizedNetworksConfig { 85 | if (!networks) { 86 | return defaultNetworks 87 | } 88 | const normalizedNetworks: NormalizedNetworksConfig = {} 89 | for (const networkId of Object.keys(networks)) { 90 | const currentNetwork = networks[networkId] 91 | let mcVersions: MasterCopyAddressVersion[] = [] 92 | if (currentNetwork.masterCopyAddress) { 93 | mcVersions = [ 94 | { 95 | version: masterCopyAddressVersions[0].version, 96 | address: currentNetwork.masterCopyAddress 97 | } 98 | ] 99 | } else if (currentNetwork.masterCopyAddressVersions) { 100 | mcVersions = currentNetwork.masterCopyAddressVersions 101 | } 102 | if (mcVersions.length === 0) { 103 | throw new Error( 104 | 'Properties "masterCopyAddress" or "masterCopyAddressVersions" are missing in CPK network configuration' 105 | ) 106 | } 107 | normalizedNetworks[networkId] = { 108 | masterCopyAddressVersions: mcVersions, 109 | proxyFactoryAddress: currentNetwork.proxyFactoryAddress, 110 | multiSendAddress: currentNetwork.multiSendAddress, 111 | fallbackHandlerAddress: currentNetwork.fallbackHandlerAddress 112 | } 113 | } 114 | return { 115 | ...defaultNetworks, 116 | ...normalizedNetworks 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/config/transactionManagers.ts: -------------------------------------------------------------------------------- 1 | export const safeTxRelayUrl = 'https://safe-relay.gnosis.io/' 2 | export const rocksideTxRelayUrl = 'https://api.rockside.io' 3 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/contractManager/ContractV111Utils.ts: -------------------------------------------------------------------------------- 1 | import { Address } from '../utils/basicTypes' 2 | import ContractVersionUtils from './ContractVersionUtils' 3 | 4 | class ContractV111Utils extends ContractVersionUtils { 5 | async isModuleEnabled(moduleAddress: Address): Promise { 6 | const modules = await super.contract.call('getModules', []) 7 | const selectedModules = modules.filter( 8 | (module: Address) => module.toLowerCase() === moduleAddress.toLowerCase() 9 | ) 10 | return selectedModules.length > 0 11 | } 12 | } 13 | 14 | export default ContractV111Utils 15 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/contractManager/ContractV120Utils.ts: -------------------------------------------------------------------------------- 1 | import { Address } from '../utils/basicTypes' 2 | import ContractVersionUtils from './ContractVersionUtils' 3 | 4 | class ContractV120Utils extends ContractVersionUtils { 5 | async isModuleEnabled(moduleAddress: Address): Promise { 6 | return this.contract.call('isModuleEnabled', [moduleAddress]) 7 | } 8 | } 9 | 10 | export default ContractV120Utils 11 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/contractManager/ContractVersionUtils.ts: -------------------------------------------------------------------------------- 1 | import { Contract } from '../ethLibAdapters/EthLibAdapter' 2 | import { Address } from '../utils/basicTypes' 3 | import { sentinelModules } from '../utils/constants' 4 | 5 | abstract class ContractVersionUtils { 6 | contract: Contract 7 | 8 | constructor(contract: Contract) { 9 | this.contract = contract 10 | } 11 | 12 | async getContractVersion(): Promise { 13 | return this.contract.call('VERSION', []) 14 | } 15 | 16 | async getModules(): Promise { 17 | return this.contract.call('getModules', []) 18 | } 19 | 20 | abstract isModuleEnabled(moduleAddress: Address): Promise 21 | 22 | async encodeEnableModule(moduleAddress: Address): Promise { 23 | return this.contract.encode('enableModule', [moduleAddress]) 24 | } 25 | 26 | async encodeDisableModule(moduleAddress: Address): Promise { 27 | const modules = await this.contract.call('getModules', []) 28 | const index = modules.findIndex( 29 | (module: Address) => module.toLowerCase() === moduleAddress.toLowerCase() 30 | ) 31 | const prevModuleAddress = index === 0 ? sentinelModules : modules[index - 1] 32 | return this.contract.encode('disableModule', [prevModuleAddress, moduleAddress]) 33 | } 34 | } 35 | 36 | export default ContractVersionUtils 37 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/contractManager/index.ts: -------------------------------------------------------------------------------- 1 | import cpkFactoryAbi from '../abis/CpkFactoryAbi.json' 2 | import multiSendAbi from '../abis/MultiSendAbi.json' 3 | import safeAbiV111 from '../abis/SafeAbiV1-1-1.json' 4 | import safeAbiV120 from '../abis/SafeAbiV1-2-0.json' 5 | import { NormalizedNetworkConfigEntry } from '../config/networks' 6 | import EthLibAdapter, { Contract } from '../ethLibAdapters/EthLibAdapter' 7 | import { Address } from '../utils/basicTypes' 8 | import ContractV111Utils from './ContractV111Utils' 9 | import ContractV120Utils from './ContractV120Utils' 10 | import ContractVersionUtils from './ContractVersionUtils' 11 | 12 | export interface ContractManagerProps { 13 | ethLibAdapter: EthLibAdapter 14 | network: NormalizedNetworkConfigEntry 15 | ownerAccount: Address | undefined 16 | saltNonce: string 17 | isSafeApp: boolean 18 | isConnectedToSafe: boolean 19 | } 20 | 21 | class ContractManager { 22 | #versionUtils?: ContractVersionUtils 23 | #contract?: Contract 24 | #proxyFactory: Contract 25 | #masterCopyAddress: Address 26 | #multiSend: Contract 27 | #fallbackHandlerAddress: Address 28 | 29 | static async create(opts: ContractManagerProps): Promise { 30 | const contractManager = new ContractManager(opts.ethLibAdapter, opts.network) 31 | await contractManager.init(opts) 32 | return contractManager 33 | } 34 | 35 | constructor(ethLibAdapter: EthLibAdapter, network: NormalizedNetworkConfigEntry) { 36 | this.#masterCopyAddress = network.masterCopyAddressVersions[0].address 37 | this.#fallbackHandlerAddress = network.fallbackHandlerAddress 38 | this.#multiSend = ethLibAdapter.getContract(multiSendAbi, network.multiSendAddress) 39 | this.#proxyFactory = ethLibAdapter.getContract(cpkFactoryAbi, network.proxyFactoryAddress) 40 | } 41 | 42 | async init(opts: ContractManagerProps): Promise { 43 | await this.calculateVersionUtils(opts) 44 | } 45 | 46 | private async calculateVersionUtils(opts: ContractManagerProps) { 47 | const { ethLibAdapter, ownerAccount, saltNonce, network, isSafeApp, isConnectedToSafe } = opts 48 | let proxyAddress 49 | let properVersion 50 | 51 | if (isSafeApp || isConnectedToSafe) { 52 | const temporaryContract = ethLibAdapter.getContract(safeAbiV111, ownerAccount) 53 | properVersion = await temporaryContract.call('VERSION', []) 54 | proxyAddress = ownerAccount 55 | } else { 56 | const salt = ethLibAdapter.keccak256( 57 | ethLibAdapter.abiEncode(['address', 'uint256'], [ownerAccount, saltNonce]) 58 | ) 59 | 60 | for (const masterCopyVersion of network.masterCopyAddressVersions) { 61 | proxyAddress = await this.calculateProxyAddress( 62 | masterCopyVersion.address, 63 | salt, 64 | ethLibAdapter 65 | ) 66 | 67 | const codeAtAddress = await ethLibAdapter.getCode(proxyAddress) 68 | const isDeployed = codeAtAddress !== '0x' 69 | if (isDeployed) { 70 | const temporaryContract = ethLibAdapter.getContract(safeAbiV111, proxyAddress) 71 | properVersion = await temporaryContract.call('VERSION', []) 72 | break 73 | } 74 | } 75 | 76 | if (!properVersion) { 77 | // Last version released 78 | properVersion = network.masterCopyAddressVersions[0].version 79 | proxyAddress = await this.calculateProxyAddress( 80 | network.masterCopyAddressVersions[0].address, 81 | salt, 82 | ethLibAdapter 83 | ) 84 | } 85 | } 86 | 87 | switch (properVersion) { 88 | case '1.2.0': 89 | this.#contract = ethLibAdapter.getContract(safeAbiV120, proxyAddress) 90 | this.#versionUtils = new ContractV120Utils(this.#contract) 91 | break 92 | case '1.1.1': 93 | this.#contract = ethLibAdapter.getContract(safeAbiV111, proxyAddress) 94 | this.#versionUtils = new ContractV111Utils(this.#contract) 95 | break 96 | default: 97 | throw new Error('CPK Proxy version is not valid') 98 | } 99 | } 100 | 101 | private async calculateProxyAddress( 102 | masterCopyAddress: Address, 103 | salt: string, 104 | ethLibAdapter: EthLibAdapter 105 | ): Promise
{ 106 | const initCode = ethLibAdapter.abiEncodePacked( 107 | { type: 'bytes', value: await this.#proxyFactory.call('proxyCreationCode', []) }, 108 | { 109 | type: 'bytes', 110 | value: ethLibAdapter.abiEncode(['address'], [masterCopyAddress]) 111 | } 112 | ) 113 | const proxyAddress = ethLibAdapter.calcCreate2Address( 114 | this.#proxyFactory.address, 115 | salt, 116 | initCode 117 | ) 118 | return proxyAddress 119 | } 120 | 121 | get versionUtils(): ContractVersionUtils | undefined { 122 | return this.#versionUtils 123 | } 124 | 125 | /** 126 | * Returns the instance of the Safe contract in use. 127 | * 128 | * @returns The instance of the Safe contract in use 129 | */ 130 | get contract(): Contract | undefined { 131 | return this.#contract 132 | } 133 | 134 | /** 135 | * Returns the instance of the Proxy Factory contract in use. 136 | * 137 | * @returns The instance of the Proxy Factory contract in use 138 | */ 139 | get proxyFactory(): Contract { 140 | return this.#proxyFactory 141 | } 142 | 143 | /** 144 | * Returns the Master Copy contract address in use. 145 | * 146 | * @returns The Master Copy contract address in use 147 | */ 148 | get masterCopyAddress(): Address { 149 | return this.#masterCopyAddress 150 | } 151 | 152 | /** 153 | * Returns the instance of the MultiSend contract in use. 154 | * 155 | * @returns The instance of the MultiSend contract in use 156 | */ 157 | get multiSend(): Contract { 158 | return this.#multiSend 159 | } 160 | 161 | /** 162 | * Returns the FallbackHandler contract address in use. 163 | * 164 | * @returns The FallbackHandler contract address in use 165 | */ 166 | get fallbackHandlerAddress(): Address { 167 | return this.#fallbackHandlerAddress 168 | } 169 | } 170 | 171 | export default ContractManager 172 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/ethLibAdapters/EthLibAdapter.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js' 2 | import { Abi, Address } from '../utils/basicTypes' 3 | import { joinHexData } from '../utils/hexData' 4 | import { 5 | CallOptions, 6 | EthCallTx, 7 | EthSendTx, 8 | SendOptions, 9 | TransactionResult 10 | } from '../utils/transactions' 11 | 12 | export interface Contract { 13 | address: Address 14 | call(methodName: string, params: any[], options?: CallOptions): Promise 15 | send(methodName: string, params: any[], options?: SendOptions): Promise 16 | estimateGas(methodName: string, params: any[], options?: CallOptions): Promise 17 | encode(methodName: string, params: any[]): string 18 | } 19 | 20 | abstract class EthLibAdapter { 21 | /** 22 | * Returns the keccak256 hash of the data. 23 | * 24 | * @param data - Desired data 25 | * @returns The keccak256 of the data 26 | */ 27 | abstract keccak256(data: string): string 28 | 29 | /** 30 | * Encodes a function parameters based on its JSON interface object. 31 | * 32 | * @param types - An array with the types or a JSON interface of a function 33 | * @param values - The parameters to encode 34 | * @returns The ABI encoded parameters 35 | */ 36 | abstract abiEncode(types: string[], values: any[]): string 37 | 38 | /** 39 | * Decodes ABI encoded parameters to is JavaScript types. 40 | * 41 | * @param types - An array with the types or a JSON interface outputs array 42 | * @param data - The ABI byte code to decode 43 | * @returns The ABI encoded parameters 44 | */ 45 | abstract abiDecode(types: string[], data: string): any[] 46 | 47 | /** 48 | * Deterministically returns the address where a contract will be deployed. 49 | * 50 | * @param deployer - Account that deploys the contract 51 | * @param salt - Salt 52 | * @param initCode - Code to be deployed 53 | * @returns The address where the contract will be deployed 54 | */ 55 | abstract calcCreate2Address(deployer: Address, salt: string, initCode: string): string 56 | 57 | /** 58 | * Returns the current provider 59 | * 60 | * @returns The current provider 61 | */ 62 | abstract getProvider(): any 63 | 64 | /** 65 | * Sends a network request via JSON-RPC. 66 | * 67 | * @param method - JSON-RPC method 68 | * @param params - Params 69 | * @returns The request response 70 | */ 71 | abstract providerSend(method: string, params: any[]): Promise 72 | 73 | /** 74 | * Signs data using a specific account. 75 | * 76 | * @param message - Data to sign 77 | * @param ownerAccount - Address to sign the data with 78 | * @returns The signature 79 | */ 80 | abstract signMessage(message: string, ownerAccount: Address): Promise 81 | 82 | /** 83 | * Returns the current network ID. 84 | * 85 | * @returns The network ID 86 | */ 87 | abstract getNetworkId(): Promise 88 | 89 | /** 90 | * Returns the default account used as the default "from" property. 91 | * 92 | * @returns The default account address 93 | */ 94 | abstract getAccount(): Promise
95 | 96 | /** 97 | * Returns the balance of an address. 98 | * 99 | * @param address - The desired address 100 | * @returns The balance of the address 101 | */ 102 | abstract getBalance(address: Address): Promise 103 | 104 | /** 105 | * Returns the code at a specific address. 106 | * 107 | * @param address - The desired address 108 | * @returns The code of the contract 109 | */ 110 | abstract getCode(address: Address): Promise 111 | 112 | /** 113 | * Returns a block matching the block number or block hash. 114 | * 115 | * @param blockHashOrBlockNumber - The block number or block hash 116 | * @returns The block object 117 | */ 118 | abstract getBlock(blockHashOrBlockNumber: string | number): Promise<{ [property: string]: any }> 119 | 120 | /** 121 | * Returns an instance of a contract. 122 | * 123 | * @param abi - ABI of the desired contract 124 | * @param address - Contract address 125 | * @returns The contract instance 126 | */ 127 | abstract getContract(abi: Abi, address?: Address): Contract 128 | 129 | /** 130 | * Returns the revert reason when a call fails. 131 | * 132 | * @param tx - Transaction to execute 133 | * @param block - Block number 134 | * @returns The revert data when the call fails 135 | */ 136 | abstract getCallRevertData(tx: EthCallTx, block: string | number): Promise 137 | 138 | /** 139 | * Sends a transaction to the network. 140 | * 141 | * @param tx - Transaction to send 142 | * @returns The transaction response 143 | */ 144 | abstract ethSendTransaction(tx: EthSendTx): Promise 145 | 146 | /** 147 | * Formats transaction result depending on the current provider. 148 | * 149 | * @param txHash - Transaction hash 150 | * @param tx - Transaction response 151 | * @returns The formatted transaction response 152 | */ 153 | abstract toSafeRelayTxResult(txHash: string, tx: Record): Promise 154 | 155 | abstract toRocksideRelayTxResult(tx: Record): Promise 156 | 157 | abiEncodePacked(...params: { type: string; value: any }[]): string { 158 | return joinHexData( 159 | params.map(({ type, value }) => { 160 | const encoded = this.abiEncode([type], [value]) 161 | 162 | if (type === 'bytes' || type === 'string') { 163 | const bytesLength = parseInt(encoded.slice(66, 130), 16) 164 | return encoded.slice(130, 130 + 2 * bytesLength) 165 | } 166 | 167 | let typeMatch = type.match(/^(?:u?int\d*|bytes\d+|address)\[\]$/) 168 | if (typeMatch) { 169 | return encoded.slice(130) 170 | } 171 | 172 | if (type.startsWith('bytes')) { 173 | const bytesLength = parseInt(type.slice(5)) 174 | return encoded.slice(2, 2 + 2 * bytesLength) 175 | } 176 | 177 | typeMatch = type.match(/^u?int(\d*)$/) 178 | if (typeMatch) { 179 | if (typeMatch[1] !== '') { 180 | const bytesLength = parseInt(typeMatch[1]) / 8 181 | return encoded.slice(-2 * bytesLength) 182 | } 183 | return encoded.slice(-64) 184 | } 185 | 186 | if (type === 'address') { 187 | return encoded.slice(-40) 188 | } 189 | 190 | throw new Error(`unsupported type ${type}`) 191 | }) 192 | ) 193 | } 194 | 195 | decodeError(revertData: string): string { 196 | if (!revertData.startsWith('0x08c379a0')) throw new Error('Unrecognized error format') 197 | 198 | return this.abiDecode(['string'], `0x${revertData.slice(10)}`)[0] 199 | } 200 | } 201 | 202 | export default EthLibAdapter 203 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/ethLibAdapters/EthersAdapter/EthersV4ContractAdapter.ts: -------------------------------------------------------------------------------- 1 | import { Address } from '../../utils/basicTypes' 2 | import { 3 | CallOptions, 4 | EthersTransactionResult, 5 | normalizeGasLimit, 6 | SendOptions 7 | } from '../../utils/transactions' 8 | import { Contract } from '../EthLibAdapter' 9 | import EthersAdapter from './' 10 | 11 | class EthersV4ContractAdapter implements Contract { 12 | constructor(public contract: any, public ethersAdapter: EthersAdapter) {} 13 | 14 | get address(): Address { 15 | return this.contract.address 16 | } 17 | 18 | async call(methodName: string, params: any[], options?: CallOptions): Promise { 19 | const data = this.encode(methodName, params) 20 | const resHex = await this.ethersAdapter.ethCall( 21 | { 22 | ...options, 23 | to: this.address, 24 | data 25 | }, 26 | 'latest' 27 | ) 28 | const rets = this.contract.interface.functions[methodName].decode(resHex) 29 | 30 | if (rets.length === 1) { 31 | return rets[0] 32 | } 33 | 34 | return rets 35 | } 36 | 37 | async send( 38 | methodName: string, 39 | params: any[], 40 | options?: SendOptions 41 | ): Promise { 42 | let transactionResponse 43 | if (options) { 44 | const { from, gas, ...sendOptions } = normalizeGasLimit(options) 45 | await this.ethersAdapter.checkFromAddress(from) 46 | transactionResponse = await this.contract.functions[methodName](...params, { 47 | gasLimit: gas, 48 | ...sendOptions 49 | }) 50 | } else { 51 | transactionResponse = await this.contract.functions[methodName](...params) 52 | } 53 | return { transactionResponse, hash: transactionResponse.hash } 54 | } 55 | 56 | async estimateGas(methodName: string, params: any[], options?: CallOptions): Promise { 57 | if (!options) { 58 | return (await this.contract.estimate[methodName](...params)).toNumber() 59 | } else { 60 | const { gas, ...callOptions } = normalizeGasLimit(options) 61 | return ( 62 | await this.contract.estimate[methodName](...params, { gasLimit: gas, ...callOptions }) 63 | ).toNumber() 64 | } 65 | } 66 | 67 | encode(methodName: string, params: any[]): string { 68 | return this.contract.interface.functions[methodName].encode(params) 69 | } 70 | } 71 | 72 | export default EthersV4ContractAdapter 73 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/ethLibAdapters/EthersAdapter/EthersV5ContractAdapter.ts: -------------------------------------------------------------------------------- 1 | import { Address } from '../../utils/basicTypes' 2 | import { 3 | CallOptions, 4 | EthersTransactionResult, 5 | normalizeGasLimit, 6 | SendOptions 7 | } from '../../utils/transactions' 8 | import { Contract } from '../EthLibAdapter' 9 | import EthersAdapter from './' 10 | 11 | class EthersV5ContractAdapter implements Contract { 12 | constructor(public contract: any, public ethersAdapter: EthersAdapter) {} 13 | 14 | get address(): Address { 15 | return this.contract.address 16 | } 17 | 18 | async call(methodName: string, params: any[], options?: CallOptions): Promise { 19 | const data = this.encode(methodName, params) 20 | const resHex = await this.ethersAdapter.ethCall( 21 | { 22 | ...options, 23 | to: this.address, 24 | data 25 | }, 26 | 'latest' 27 | ) 28 | const rets = this.contract.interface.decodeFunctionResult(methodName, resHex) 29 | 30 | if (rets.length === 1) { 31 | return rets[0] 32 | } 33 | 34 | return rets 35 | } 36 | 37 | async send( 38 | methodName: string, 39 | params: any[], 40 | options?: SendOptions 41 | ): Promise { 42 | let transactionResponse 43 | if (options) { 44 | const { from, gas, ...sendOptions } = normalizeGasLimit(options) 45 | await this.ethersAdapter.checkFromAddress(from) 46 | transactionResponse = await this.contract.functions[methodName](...params, { 47 | gasLimit: gas, 48 | ...sendOptions 49 | }) 50 | } else { 51 | transactionResponse = await this.contract.functions[methodName](...params) 52 | } 53 | return { transactionResponse, hash: transactionResponse.hash } 54 | } 55 | 56 | async estimateGas(methodName: string, params: any[], options?: CallOptions): Promise { 57 | if (!options) { 58 | return (await this.contract.estimateGas[methodName](...params)).toNumber() 59 | } else { 60 | const { gas, ...callOptions } = normalizeGasLimit(options) 61 | return ( 62 | await this.contract.estimateGas[methodName](...params, { gasLimit: gas, ...callOptions }) 63 | ).toNumber() 64 | } 65 | } 66 | 67 | encode(methodName: string, params: any[]): string { 68 | return this.contract.interface.encodeFunctionData(methodName, params) 69 | } 70 | } 71 | 72 | export default EthersV5ContractAdapter 73 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/ethLibAdapters/EthersAdapter/index.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js' 2 | import { Abi, Address } from '../../utils/basicTypes' 3 | import { zeroAddress } from '../../utils/constants' 4 | import { 5 | EthCallTx, 6 | EthersTransactionResult, 7 | EthSendTx, 8 | formatCallTx, 9 | normalizeGasLimit 10 | } from '../../utils/transactions' 11 | import EthLibAdapter, { Contract } from '../EthLibAdapter' 12 | import EthersV4ContractAdapter from './EthersV4ContractAdapter' 13 | import EthersV5ContractAdapter from './EthersV5ContractAdapter' 14 | 15 | export interface EthersAdapterConfig { 16 | ethers: any 17 | signer: any 18 | } 19 | 20 | class EthersAdapter extends EthLibAdapter { 21 | ethers: any 22 | signer: any 23 | 24 | /** 25 | * Creates an instance of EthersAdapter 26 | * 27 | * @param options - EthersAdapter configuration 28 | * @returns The EthersAdapter instance 29 | */ 30 | constructor({ ethers, signer }: EthersAdapterConfig) { 31 | super() 32 | 33 | if (!ethers) { 34 | throw new Error('ethers property missing from options') 35 | } 36 | if (!signer) { 37 | throw new Error('signer property missing from options') 38 | } 39 | this.ethers = ethers 40 | this.signer = signer 41 | } 42 | 43 | /** 44 | * Returns the current provider 45 | * 46 | * @returns The current provider 47 | */ 48 | getProvider(): any { 49 | // eslint-disable-next-line no-underscore-dangle 50 | return this.signer.provider.provider || this.signer.provider._web3Provider 51 | } 52 | 53 | /** 54 | * Sends a network request via JSON-RPC. 55 | * 56 | * @param method - JSON-RPC method 57 | * @param params - Params 58 | * @returns The request response 59 | */ 60 | providerSend(method: string, params: any[]): Promise { 61 | return this.signer.provider.send(method, params) 62 | } 63 | 64 | /** 65 | * Signs data using a specific account. 66 | * 67 | * @param message - Data to sign 68 | * @param ownerAccount - Address to sign the data with 69 | * @returns The signature 70 | */ 71 | signMessage(message: string): Promise { 72 | const messageArray = this.ethers.utils.arrayify(message) 73 | return this.signer.signMessage(messageArray) 74 | } 75 | 76 | /** 77 | * Returns the current network ID. 78 | * 79 | * @returns The network ID 80 | */ 81 | async getNetworkId(): Promise { 82 | return (await this.signer.provider.getNetwork()).chainId 83 | } 84 | 85 | /** 86 | * Returns the default account used as the default "from" property. 87 | * 88 | * @returns The default account address 89 | */ 90 | async getAccount(): Promise
{ 91 | return this.signer.getAddress() 92 | } 93 | 94 | /** 95 | * Returns the balance of an address. 96 | * 97 | * @param address - The desired address 98 | * @returns The balance of the address 99 | */ 100 | async getBalance(address: Address): Promise { 101 | const balance = await this.signer.provider.getBalance(address) 102 | return new BigNumber(balance.toString()) 103 | } 104 | 105 | /** 106 | * Returns the keccak256 hash of the data. 107 | * 108 | * @param data - Desired data 109 | * @returns The keccak256 of the data 110 | */ 111 | keccak256(data: string): string { 112 | return this.ethers.utils.keccak256(data) 113 | } 114 | 115 | /** 116 | * Encodes a function parameters based on its JSON interface object. 117 | * 118 | * @param types - An array with the types or a JSON interface of a function 119 | * @param values - The parameters to encode 120 | * @returns The ABI encoded parameters 121 | */ 122 | abiEncode(types: string[], values: any[]): string { 123 | return this.ethers.utils.defaultAbiCoder.encode(types, values) 124 | } 125 | 126 | /** 127 | * Decodes ABI encoded parameters to is JavaScript types. 128 | * 129 | * @param types - An array with the types or a JSON interface outputs array 130 | * @param data - The ABI byte code to decode 131 | * @returns The ABI encoded parameters 132 | */ 133 | abiDecode(types: string[], data: string): any[] { 134 | return this.ethers.utils.defaultAbiCoder.decode(types, data) 135 | } 136 | 137 | /** 138 | * Returns an instance of a contract. 139 | * 140 | * @param abi - ABI of the desired contract 141 | * @param address - Contract address 142 | * @returns The contract instance 143 | */ 144 | getContract(abi: Abi, address?: Address): Contract { 145 | const contract = new this.ethers.Contract(address || zeroAddress, abi, this.signer) 146 | const ethersVersion = this.ethers.version 147 | 148 | // TO-DO: Use semver comparison 149 | if (ethersVersion.split('.')[0] === '4') { 150 | return new EthersV4ContractAdapter(contract, this) 151 | } 152 | if (ethersVersion.split('.')[0] === 'ethers/5') { 153 | return new EthersV5ContractAdapter(contract, this) 154 | } 155 | throw new Error(`ethers version ${ethersVersion} not supported`) 156 | } 157 | 158 | /** 159 | * Deterministically returns the address where a contract will be deployed. 160 | * 161 | * @param deployer - Account that deploys the contract 162 | * @param salt - Salt 163 | * @param initCode - Code to be deployed 164 | * @returns The address where the contract will be deployed 165 | */ 166 | calcCreate2Address(deployer: Address, salt: string, initCode: string): string { 167 | return this.ethers.utils.getAddress( 168 | this.ethers.utils 169 | .solidityKeccak256( 170 | ['bytes', 'address', 'bytes32', 'bytes32'], 171 | ['0xff', deployer, salt, this.keccak256(initCode)] 172 | ) 173 | .slice(-40) 174 | ) 175 | } 176 | 177 | /** 178 | * Returns the code at a specific address. 179 | * 180 | * @param address - The desired address 181 | * @returns The code of the contract 182 | */ 183 | getCode(address: Address): Promise { 184 | return this.signer.provider.getCode(address) 185 | } 186 | 187 | /** 188 | * Returns a block matching the block number or block hash. 189 | * 190 | * @param blockHashOrBlockNumber - The block number or block hash 191 | * @returns The block object 192 | */ 193 | getBlock(blockHashOrBlockNumber: string | number): Promise<{ [property: string]: any }> { 194 | return this.signer.provider.getBlock(blockHashOrBlockNumber) 195 | } 196 | 197 | /** 198 | * Returns the revert reason when a call fails. 199 | * 200 | * @param tx - Transaction to execute 201 | * @param block - Block number 202 | * @returns The revert data when the call fails 203 | */ 204 | async getCallRevertData(tx: EthCallTx, block: string | number): Promise { 205 | try { 206 | // Handle old Geth/Ganache --noVMErrorsOnRPCResponse revert data 207 | return await this.ethCall(tx, block) 208 | } catch (e) { 209 | if (typeof e.data === 'string') { 210 | if (e.data.startsWith('Reverted 0x')) 211 | // handle OpenEthereum revert data format 212 | return e.data.slice(9) 213 | 214 | if (e.data.startsWith('0x')) 215 | // handle new Geth format 216 | return e.data 217 | } 218 | 219 | // handle Ganache revert data format 220 | const txHash = Object.getOwnPropertyNames(e.data).filter((k) => k.startsWith('0x'))[0] 221 | return e.data[txHash].return 222 | } 223 | } 224 | 225 | ethCall(tx: EthCallTx, block: number | string): Promise { 226 | // This is to workaround https://github.com/ethers-io/ethers.js/issues/819 227 | return this.providerSend('eth_call', [formatCallTx(tx), block]) 228 | } 229 | 230 | async checkFromAddress(from: Address): Promise { 231 | const { getAddress } = this.ethers.utils 232 | const expectedFrom = await this.getAccount() 233 | if (getAddress(from) !== expectedFrom) { 234 | throw new Error(`want from ${expectedFrom} but got from ${from}`) 235 | } 236 | } 237 | 238 | /** 239 | * Sends a transaction to the network. 240 | * 241 | * @param tx - Transaction to send 242 | * @returns The transaction response 243 | */ 244 | async ethSendTransaction(tx: EthSendTx): Promise { 245 | const { from, gas, ...sendTx } = normalizeGasLimit(tx) 246 | await this.checkFromAddress(from) 247 | const transactionResponse = await this.signer.sendTransaction({ gasLimit: gas, ...sendTx }) 248 | return { transactionResponse, hash: transactionResponse.hash } 249 | } 250 | 251 | /** 252 | * Formats transaction result depending on the current provider. 253 | * 254 | * @param txHash - Transaction hash 255 | * @param tx - Transaction response 256 | * @returns The formatted transaction response 257 | */ 258 | toSafeRelayTxResult(txHash: string, tx: Record): Promise { 259 | tx['hash'] = tx['txHash'] 260 | delete tx['txHash'] 261 | return new Promise((resolve, reject) => 262 | resolve({ 263 | transactionResponse: new Promise((resolve, reject) => resolve(tx)), 264 | hash: txHash 265 | }) 266 | ) 267 | } 268 | 269 | toRocksideRelayTxResult(tx: Record): Promise { 270 | tx['hash'] = tx['transaction_hash'] 271 | delete tx['transaction_hash'] 272 | return new Promise((resolve, reject) => 273 | resolve({ 274 | transactionResponse: new Promise((resolve, reject) => resolve(tx)), 275 | hash: tx['hash'] 276 | }) 277 | ) 278 | } 279 | } 280 | 281 | export default EthersAdapter 282 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/ethLibAdapters/Web3Adapter/Web3ContractAdapter.ts: -------------------------------------------------------------------------------- 1 | import { Address } from '../../utils/basicTypes' 2 | import { 3 | CallOptions, 4 | normalizeGasLimit, 5 | SendOptions, 6 | Web3TransactionResult 7 | } from '../../utils/transactions' 8 | import { Contract } from '../EthLibAdapter' 9 | import { toTxResult } from './' 10 | 11 | class Web3ContractAdapter implements Contract { 12 | constructor(public contract: any) {} 13 | 14 | get address(): Address { 15 | return this.contract.options.address 16 | } 17 | 18 | call(methodName: string, params: any[], options?: CallOptions): Promise { 19 | return this.contract.methods[methodName](...params).call(options && normalizeGasLimit(options)) 20 | } 21 | 22 | send(methodName: string, params: any[], options?: SendOptions): Promise { 23 | const promiEvent = this.contract.methods[methodName](...params).send( 24 | options && normalizeGasLimit(options) 25 | ) 26 | return toTxResult(promiEvent, options) 27 | } 28 | 29 | async estimateGas(methodName: string, params: any[], options?: CallOptions): Promise { 30 | return Number( 31 | await this.contract.methods[methodName](...params).estimateGas( 32 | options && normalizeGasLimit(options) 33 | ) 34 | ) 35 | } 36 | 37 | encode(methodName: string, params: any[]): string { 38 | return this.contract.methods[methodName](...params).encodeABI() 39 | } 40 | } 41 | 42 | export default Web3ContractAdapter 43 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/ethLibAdapters/Web3Adapter/index.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js' 2 | import { Abi, Address } from '../../utils/basicTypes' 3 | import { 4 | EthCallTx, 5 | EthSendTx, 6 | formatCallTx, 7 | normalizeGasLimit, 8 | SendOptions, 9 | Web3TransactionResult 10 | } from '../../utils/transactions' 11 | import EthLibAdapter, { Contract } from '../EthLibAdapter' 12 | import Web3ContractAdapter from './Web3ContractAdapter' 13 | 14 | export function toTxResult( 15 | promiEvent: any, 16 | sendOptions?: SendOptions 17 | ): Promise { 18 | return new Promise((resolve, reject) => 19 | promiEvent 20 | .once('transactionHash', (hash: string) => resolve({ sendOptions, promiEvent, hash })) 21 | .catch(reject) 22 | ) 23 | } 24 | 25 | export interface Web3AdapterConfig { 26 | web3: any 27 | } 28 | 29 | class Web3Adapter extends EthLibAdapter { 30 | web3: any 31 | 32 | /** 33 | * Creates an instance of Web3Adapter 34 | * 35 | * @param options - Web3Adapter configuration 36 | * @returns The Web3Adapter instance 37 | */ 38 | constructor({ web3 }: Web3AdapterConfig) { 39 | super() 40 | 41 | if (!web3) { 42 | throw new Error('web3 property missing from options') 43 | } 44 | this.web3 = web3 45 | } 46 | 47 | /** 48 | * Returns the current provider 49 | * 50 | * @returns The current provider 51 | */ 52 | getProvider(): any { 53 | return this.web3.currentProvider 54 | } 55 | 56 | /** 57 | * Sends a network request via JSON-RPC. 58 | * 59 | * @param method - JSON-RPC method 60 | * @param params - Params 61 | * @returns The request response 62 | */ 63 | providerSend(method: string, params: any[]): Promise { 64 | // TO-DO: Use semver comparison 65 | return this.web3.version.split('.')[0] > 1 66 | ? this.web3.currentProvider.send(method, params) 67 | : new Promise((resolve, reject) => 68 | this.web3.currentProvider.send( 69 | { 70 | jsonrpc: '2.0', 71 | id: new Date().getTime(), 72 | method, 73 | params 74 | }, 75 | (err: any, result: any) => { 76 | if (err) return reject(err) 77 | if (result.error) return reject(result.error) 78 | return resolve(result.result) 79 | } 80 | ) 81 | ) 82 | } 83 | 84 | /** 85 | * Signs data using a specific account. 86 | * 87 | * @param message - Data to sign 88 | * @param ownerAccount - Address to sign the data with 89 | * @returns The signature 90 | */ 91 | signMessage(message: string, ownerAccount: Address): Promise { 92 | return this.web3.eth.sign(message, ownerAccount) 93 | } 94 | 95 | /** 96 | * Returns the current network ID. 97 | * 98 | * @returns The network ID 99 | */ 100 | async getNetworkId(): Promise { 101 | return this.web3.eth.net.getId() 102 | } 103 | 104 | /** 105 | * Returns the default account used as the default "from" property. 106 | * 107 | * @returns The default account address 108 | */ 109 | async getAccount(): Promise
{ 110 | return this.web3.eth.defaultAccount || (await this.web3.eth.getAccounts())[0] 111 | } 112 | 113 | /** 114 | * Returns the balance of an address. 115 | * 116 | * @param address - The desired address 117 | * @returns The balance of the address 118 | */ 119 | async getBalance(address: Address): Promise { 120 | const balance = await this.web3.eth.getBalance(address) 121 | return new BigNumber(balance.toString()) 122 | } 123 | 124 | /** 125 | * Returns the keccak256 hash of the data. 126 | * 127 | * @param data - Desired data 128 | * @returns The keccak256 of the data 129 | */ 130 | keccak256(data: string): string { 131 | return this.web3.utils.keccak256(data) 132 | } 133 | 134 | /** 135 | * Encodes a function parameters based on its JSON interface object. 136 | * 137 | * @param types - An array with the types or a JSON interface of a function 138 | * @param values - The parameters to encode 139 | * @returns The ABI encoded parameters 140 | */ 141 | abiEncode(types: string[], values: any[]): string { 142 | return this.web3.eth.abi.encodeParameters(types, values) 143 | } 144 | 145 | /** 146 | * Decodes ABI encoded parameters to is JavaScript types. 147 | * 148 | * @param types - An array with the types or a JSON interface outputs array 149 | * @param data - The ABI byte code to decode 150 | * @returns The ABI encoded parameters 151 | */ 152 | abiDecode(types: string[], data: string): any[] { 153 | return this.web3.eth.abi.decodeParameters(types, data) 154 | } 155 | 156 | /** 157 | * Deterministically returns the address where a contract will be deployed. 158 | * 159 | * @param deployer - Account that deploys the contract 160 | * @param salt - Salt 161 | * @param initCode - Code to be deployed 162 | * @returns The address where the contract will be deployed 163 | */ 164 | calcCreate2Address(deployer: Address, salt: string, initCode: string): string { 165 | return this.web3.utils.toChecksumAddress( 166 | this.web3.utils 167 | .soliditySha3( 168 | '0xff', 169 | { t: 'address', v: deployer }, 170 | { t: 'bytes32', v: salt }, 171 | this.keccak256(initCode) 172 | ) 173 | .slice(-40) 174 | ) 175 | } 176 | 177 | /** 178 | * Returns the code at a specific address. 179 | * 180 | * @param address - The desired address 181 | * @returns The code of the contract 182 | */ 183 | getCode(address: Address): Promise { 184 | return this.web3.eth.getCode(address) 185 | } 186 | 187 | /** 188 | * Returns a block matching the block number or block hash. 189 | * 190 | * @param blockHashOrBlockNumber - The block number or block hash 191 | * @returns The block object 192 | */ 193 | getBlock(blockHashOrBlockNumber: string | number): Promise<{ [property: string]: any }> { 194 | return this.web3.eth.getBlock(blockHashOrBlockNumber) 195 | } 196 | 197 | /** 198 | * Returns an instance of a contract. 199 | * 200 | * @param abi - ABI of the desired contract 201 | * @param address - Contract address 202 | * @returns The contract instance 203 | */ 204 | getContract(abi: Abi, address: Address): Contract { 205 | const contract = new this.web3.eth.Contract(abi, address) 206 | return new Web3ContractAdapter(contract) 207 | } 208 | 209 | /** 210 | * Returns the revert reason when a call fails. 211 | * 212 | * @param tx - Transaction to execute 213 | * @param block - Block number 214 | * @returns The revert data when the call fails 215 | */ 216 | async getCallRevertData(tx: EthCallTx, block: string | number): Promise { 217 | try { 218 | // this block handles old Geth/Ganache --noVMErrorsOnRPCResponse 219 | // use a low level eth_call instead of web3.eth.call so 220 | // full error data from eth node is available if provider is Web3 1.x 221 | return await this.providerSend('eth_call', [formatCallTx(tx), block]) 222 | } catch (e) { 223 | let errData = e.data 224 | if (!errData && e.message.startsWith('Node error: ')) { 225 | // parse out error data from eth node if provider is Web3 2.x 226 | errData = JSON.parse(e.message.slice(12)).data 227 | } 228 | 229 | if (typeof errData === 'string') { 230 | if (errData.startsWith('Reverted 0x')) 231 | // handle OpenEthereum revert data format 232 | return errData.slice(9) 233 | 234 | if (errData.startsWith('0x')) 235 | // handle new Geth format 236 | return errData 237 | } 238 | 239 | // handle Ganache revert data format 240 | const txHash = Object.getOwnPropertyNames(errData).filter((k) => k.startsWith('0x'))[0] 241 | return errData[txHash].return 242 | } 243 | } 244 | 245 | /** 246 | * Sends a transaction to the network. 247 | * 248 | * @param tx - Transaction to send 249 | * @returns The transaction response 250 | */ 251 | ethSendTransaction(tx: EthSendTx): Promise { 252 | return toTxResult(this.web3.eth.sendTransaction(normalizeGasLimit(tx)), tx) 253 | } 254 | 255 | /** 256 | * Formats transaction result depending on the current provider. 257 | * 258 | * @param txHash - Transaction hash 259 | * @param tx - Transaction response 260 | * @returns The formatted transaction response 261 | */ 262 | toSafeRelayTxResult(txHash: string, tx: Record): Promise { 263 | tx['transactionHash'] = tx['txHash'] 264 | delete tx['txHash'] 265 | return new Promise((resolve, reject) => 266 | resolve({ 267 | promiEvent: new Promise((resolve, reject) => resolve(tx)), 268 | hash: txHash 269 | }) 270 | ) 271 | } 272 | 273 | toRocksideRelayTxResult(tx: Record): Promise { 274 | tx['transactionHash'] = tx['transaction_hash'] 275 | delete tx['transaction_hash'] 276 | return new Promise((resolve, reject) => 277 | resolve({ 278 | promiEvent: new Promise((resolve, reject) => resolve(tx)), 279 | hash: tx['transactionHash'] 280 | }) 281 | ) 282 | } 283 | } 284 | 285 | export default Web3Adapter 286 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/index.ts: -------------------------------------------------------------------------------- 1 | import { TxServiceModel } from '@gnosis.pm/safe-apps-sdk' 2 | import { defaultNetworks, NetworksConfig } from './config/networks' 3 | import CPK, { CPKConfig } from './CPK' 4 | import EthersAdapter, { EthersAdapterConfig } from './ethLibAdapters/EthersAdapter' 5 | import EthLibAdapter from './ethLibAdapters/EthLibAdapter' 6 | import Web3Adapter, { Web3AdapterConfig } from './ethLibAdapters/Web3Adapter' 7 | import CpkTransactionManager from './transactionManagers/CpkTransactionManager' 8 | import RocksideTxRelayManager, { RocksideSpeed } from './transactionManagers/RocksideTxRelayManager' 9 | import SafeTxRelayManager from './transactionManagers/SafeTxRelayManager' 10 | import TransactionManager, { 11 | TransactionManagerConfig, 12 | TransactionManagerNames 13 | } from './transactionManagers/TransactionManager' 14 | import { ExecOptions, OperationType, Transaction, TransactionResult } from './utils/transactions' 15 | 16 | export default CPK 17 | 18 | export { 19 | EthLibAdapter, 20 | EthersAdapter, 21 | Web3Adapter, 22 | // TransactionManagers 23 | CpkTransactionManager, 24 | SafeTxRelayManager, 25 | RocksideTxRelayManager, 26 | RocksideSpeed, 27 | TransactionManagerNames, 28 | // Transactions 29 | OperationType, 30 | // Configuration 31 | defaultNetworks 32 | } 33 | export type { 34 | // CPK 35 | CPKConfig, 36 | // EthLibAdapters 37 | EthersAdapterConfig, 38 | Web3AdapterConfig, 39 | // TransactionManagers 40 | TransactionManager, 41 | TransactionManagerConfig, 42 | // Transactions 43 | Transaction, 44 | ExecOptions, 45 | TransactionResult, 46 | TxServiceModel, 47 | // Configuration 48 | NetworksConfig 49 | } 50 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/safeAppsSdkConnector/index.ts: -------------------------------------------------------------------------------- 1 | import SafeAppsSDK, { SafeInfo, TxServiceModel } from '@gnosis.pm/safe-apps-sdk' 2 | import { Address } from '../utils/basicTypes' 3 | import { SimpleTransactionResult, StandardTransaction } from '../utils/transactions' 4 | 5 | interface SafeTransactionParams { 6 | safeTxGas?: number 7 | } 8 | 9 | class SafeAppsSdkConnector { 10 | #appsSdk: SafeAppsSDK 11 | #safeAddress?: Address 12 | #isSafeApp = false 13 | 14 | constructor() { 15 | this.#appsSdk = new SafeAppsSDK() 16 | this.#appsSdk.getSafeInfo().then((appInfo: SafeInfo) => { 17 | this.#isSafeApp = !!appInfo.safeAddress 18 | this.#safeAddress = appInfo.safeAddress 19 | }) 20 | } 21 | 22 | /** 23 | * Checks if the CPK is running as a Safe App or as a standalone app. 24 | * 25 | * @returns TRUE if the CPK is running as a Safe App 26 | */ 27 | get isSafeApp(): boolean { 28 | return this.#isSafeApp 29 | } 30 | 31 | /** 32 | * Returns the Safe address connected to the CPK if the CPK is running as a Safe App. 33 | * 34 | * @returns The Safe address 35 | */ 36 | get safeAddress(): Address | undefined { 37 | return this.#safeAddress 38 | } 39 | 40 | /** 41 | * Returns an instance of the Safe Apps SDK used by the CPK. 42 | * 43 | * @returns The Safe Apps SDK instance 44 | */ 45 | get appsSdk() { 46 | return this.#appsSdk 47 | } 48 | 49 | /** 50 | * Returns the information of the connected Safe App. 51 | * 52 | * @returns The information of the connected Safe App 53 | */ 54 | getSafeInfo(): Promise { 55 | return this.#appsSdk.getSafeInfo() 56 | } 57 | 58 | /** 59 | * Returns the transaction response for the given Safe transaction hash. 60 | * 61 | * @param safeTxHash - The desired Safe transaction hash 62 | * @returns The transaction response for the Safe transaction hash 63 | */ 64 | getBySafeTxHash(safeTxHash: string): Promise { 65 | return this.#appsSdk.txs.getBySafeTxHash(safeTxHash) 66 | } 67 | 68 | sendTransactions( 69 | transactions: StandardTransaction[], 70 | params: SafeTransactionParams 71 | ): Promise { 72 | return this.#appsSdk.txs.send({ txs: transactions, params }) 73 | } 74 | } 75 | 76 | export default SafeAppsSdkConnector 77 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/transactionManagers/CpkTransactionManager/index.ts: -------------------------------------------------------------------------------- 1 | import EthLibAdapter, { Contract } from '../../ethLibAdapters/EthLibAdapter' 2 | import { Address, NumberLike } from '../../utils/basicTypes' 3 | import { zeroAddress } from '../../utils/constants' 4 | import { 5 | NormalizeGas, 6 | OperationType, 7 | SendOptions, 8 | SimpleTransactionResult, 9 | StandardTransaction, 10 | TransactionError, 11 | TransactionResult 12 | } from '../../utils/transactions' 13 | import TransactionManager, { 14 | ExecTransactionProps, 15 | TransactionManagerConfig, 16 | TransactionManagerNames 17 | } from '../TransactionManager' 18 | 19 | interface ContractTxObj { 20 | contract: Contract 21 | methodName: string 22 | params: any[] 23 | } 24 | 25 | class CpkTransactionManager implements TransactionManager { 26 | /** 27 | * Returns the configuration of the CpkTransactionManager. 28 | * 29 | * @returns The name of the TransactionManager in use and the URL of the service 30 | */ 31 | get config(): TransactionManagerConfig { 32 | return { 33 | name: TransactionManagerNames.CpkTxManager, 34 | url: undefined 35 | } 36 | } 37 | 38 | /** 39 | * Executes a list of transactions. 40 | * 41 | * @param options 42 | * @returns The transaction response 43 | */ 44 | async execTransactions({ 45 | ownerAccount, 46 | safeExecTxParams, 47 | transactions, 48 | ethLibAdapter, 49 | contractManager, 50 | saltNonce, 51 | isDeployed, 52 | isConnectedToSafe, 53 | sendOptions 54 | }: ExecTransactionProps): Promise { 55 | const { 56 | contract: safeContract, 57 | proxyFactory, 58 | masterCopyAddress, 59 | fallbackHandlerAddress 60 | } = contractManager 61 | if (!safeContract) { 62 | throw new Error('CPK Proxy contract uninitialized') 63 | } 64 | 65 | if (isConnectedToSafe) { 66 | return this.execTxsWhileConnectedToSafe(ethLibAdapter, transactions, sendOptions) 67 | } 68 | 69 | // (r, s, v) where v is 1 means this signature is approved by the address encoded in value r 70 | // "Hashes are automatically approved by the sender of the message" 71 | const autoApprovedSignature = ethLibAdapter.abiEncodePacked( 72 | { type: 'uint256', value: ownerAccount }, // r 73 | { type: 'uint256', value: 0 }, // s 74 | { type: 'uint8', value: 1 } // v 75 | ) 76 | 77 | const txObj: ContractTxObj = isDeployed 78 | ? this.getSafeProxyTxObj(safeContract, safeExecTxParams, autoApprovedSignature) 79 | : this.getCPKFactoryTxObj( 80 | masterCopyAddress, 81 | fallbackHandlerAddress, 82 | safeExecTxParams, 83 | saltNonce, 84 | proxyFactory 85 | ) 86 | 87 | const { success, gasLimit } = await this.findGasLimit(ethLibAdapter, txObj, sendOptions) 88 | sendOptions.gas = gasLimit 89 | const isSingleTx = transactions.length === 1 90 | 91 | if (!success) { 92 | throw await this.makeTransactionError( 93 | ethLibAdapter, 94 | safeExecTxParams, 95 | safeContract.address, 96 | gasLimit, 97 | isDeployed, 98 | isSingleTx 99 | ) 100 | } 101 | 102 | const { contract, methodName, params } = txObj 103 | 104 | return contract.send(methodName, params, sendOptions) 105 | } 106 | 107 | private async execTxsWhileConnectedToSafe( 108 | ethLibAdapter: EthLibAdapter, 109 | transactions: StandardTransaction[], 110 | sendOptions: SendOptions 111 | ): Promise { 112 | if (transactions.some(({ operation }) => operation === OperationType.DelegateCall)) { 113 | throw new Error('DelegateCall unsupported by Gnosis Safe') 114 | } 115 | 116 | if (transactions.length === 1) { 117 | const { to, value, data } = transactions[0] 118 | return ethLibAdapter.ethSendTransaction({ 119 | to, 120 | value, 121 | data, 122 | ...sendOptions 123 | }) 124 | } 125 | 126 | return { 127 | hash: await ethLibAdapter.providerSend( 128 | 'gs_multi_send', 129 | transactions.map(({ to, value, data }) => ({ to, value, data })) 130 | ) 131 | } 132 | } 133 | 134 | private getSafeProxyTxObj( 135 | safeContract: Contract, 136 | { to, value, data, operation }: StandardTransaction, 137 | safeAutoApprovedSignature: string 138 | ): ContractTxObj { 139 | return { 140 | contract: safeContract, 141 | methodName: 'execTransaction', 142 | params: [ 143 | to, 144 | value, 145 | data, 146 | operation, 147 | 0, 148 | 0, 149 | 0, 150 | zeroAddress, 151 | zeroAddress, 152 | safeAutoApprovedSignature 153 | ] 154 | } 155 | } 156 | 157 | private getCPKFactoryTxObj( 158 | masterCopyAddress: Address, 159 | fallbackHandlerAddress: Address, 160 | { to, value, data, operation }: StandardTransaction, 161 | saltNonce: string, 162 | proxyFactory: Contract 163 | ): ContractTxObj { 164 | return { 165 | contract: proxyFactory, 166 | methodName: 'createProxyAndExecTransaction', 167 | params: [masterCopyAddress, saltNonce, fallbackHandlerAddress, to, value, data, operation] 168 | } 169 | } 170 | 171 | private async findGasLimit( 172 | ethLibAdapter: EthLibAdapter, 173 | { contract, methodName, params }: ContractTxObj, 174 | sendOptions: NormalizeGas 175 | ): Promise<{ success: boolean; gasLimit: number }> { 176 | async function checkOptions(options: NormalizeGas): Promise { 177 | try { 178 | return await contract.call(methodName, params, options) 179 | } catch (e) { 180 | return false 181 | } 182 | } 183 | 184 | const toNumber = (num: NumberLike): number => Number(num.toString()) 185 | if (!sendOptions.gas) { 186 | const blockGasLimit = toNumber((await ethLibAdapter.getBlock('latest')).gasLimit) 187 | 188 | const gasEstimateOptions = { ...sendOptions, gas: blockGasLimit } 189 | if (!(await checkOptions(gasEstimateOptions))) { 190 | return { success: false, gasLimit: blockGasLimit } 191 | } 192 | 193 | const gasSearchError = 10000 194 | let gasLow = await contract.estimateGas(methodName, params, sendOptions) 195 | let gasHigh = blockGasLimit 196 | 197 | gasEstimateOptions.gas = gasLow 198 | 199 | if (!(await checkOptions(gasEstimateOptions))) { 200 | while (gasLow + gasSearchError <= gasHigh) { 201 | const testGasLimit = Math.floor((gasLow + gasHigh) * 0.5) 202 | gasEstimateOptions.gas = testGasLimit 203 | 204 | if (await checkOptions(gasEstimateOptions)) { 205 | // values > gasHigh will work 206 | gasHigh = testGasLimit - 1 207 | } else { 208 | // values <= gasLow will fail 209 | gasLow = testGasLimit + 1 210 | } 211 | } 212 | } else { 213 | gasHigh = gasLow - 1 214 | } 215 | // the final target gas value is > gasHigh 216 | 217 | const gasLimit = Math.min(Math.ceil((gasHigh + 1) * 1.02), blockGasLimit) 218 | 219 | return { success: true, gasLimit } 220 | } 221 | 222 | return { 223 | success: await checkOptions(sendOptions), 224 | gasLimit: toNumber(sendOptions.gas) 225 | } 226 | } 227 | 228 | private async makeTransactionError( 229 | ethLibAdapter: EthLibAdapter, 230 | { to, value, data, operation }: StandardTransaction, 231 | safeAddress: Address, 232 | gasLimit: number, 233 | isDeployed: boolean, 234 | isSingleTx: boolean 235 | ): Promise { 236 | let errorMessage = `${isDeployed ? '' : 'proxy creation and '}${ 237 | isSingleTx ? 'transaction' : 'batch transaction' 238 | } execution expected to fail` 239 | 240 | let revertData, revertMessage 241 | if (isSingleTx && operation === OperationType.Call) { 242 | try { 243 | revertData = await ethLibAdapter.getCallRevertData( 244 | { 245 | from: safeAddress, 246 | to, 247 | value, 248 | data, 249 | gasLimit 250 | }, 251 | 'latest' 252 | ) 253 | revertMessage = ethLibAdapter.decodeError(revertData) 254 | errorMessage = `${errorMessage}: ${revertMessage}` 255 | } catch (e) { 256 | // empty 257 | } 258 | } 259 | return new TransactionError(errorMessage, revertData, revertMessage) 260 | } 261 | } 262 | 263 | export default CpkTransactionManager 264 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/transactionManagers/RocksideTxRelayManager/index.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js' 2 | import { rocksideTxRelayUrl } from '../../config/transactionManagers' 3 | import EthLibAdapter from '../../ethLibAdapters/EthLibAdapter' 4 | import { Address } from '../../utils/basicTypes' 5 | import { zeroAddress } from '../../utils/constants' 6 | import { HttpMethod, sendRequest } from '../../utils/httpRequests' 7 | import { TransactionResult } from '../../utils/transactions' 8 | import TransactionManager, { 9 | ExecTransactionProps, 10 | TransactionManagerConfig, 11 | TransactionManagerNames 12 | } from '../TransactionManager' 13 | import { getTransactionHashSignature } from '../utils' 14 | 15 | export enum RocksideSpeed { 16 | Fast = 'fast', 17 | Fastest = 'fastest', 18 | Safelow = 'safelow', 19 | Standard = 'standard' 20 | } 21 | 22 | interface RocksideRelayTxManagerConfig { 23 | speed: RocksideSpeed 24 | } 25 | 26 | interface TxRelayParamsResult { 27 | gas_price: string 28 | relayer: Address 29 | } 30 | 31 | class RocksideRelayTransactionManager implements TransactionManager { 32 | #speed: string 33 | 34 | constructor({ speed }: RocksideRelayTxManagerConfig) { 35 | this.#speed = speed 36 | } 37 | 38 | get config(): TransactionManagerConfig { 39 | return { 40 | name: TransactionManagerNames.RocksideTxRelayManager, 41 | speed: this.#speed 42 | } 43 | } 44 | 45 | async execTransactions({ 46 | ownerAccount, 47 | safeExecTxParams, 48 | contractManager, 49 | ethLibAdapter 50 | }: ExecTransactionProps): Promise { 51 | const { contract } = contractManager 52 | if (!contract) { 53 | throw new Error('CPK Proxy contract uninitialized') 54 | } 55 | 56 | let network 57 | const networkId = await ethLibAdapter.getNetworkId() 58 | switch (networkId) { 59 | case 1: 60 | network = 'mainnet' 61 | break 62 | case 3: 63 | network = 'ropsten' 64 | break 65 | default: 66 | throw new Error('Network not supported when using Rockside transaction relay') 67 | } 68 | 69 | const nonce = await contract.call('nonce', []) 70 | 71 | const txRelayParams = await this.getTxRelayParams(contract.address, network) 72 | 73 | const safeTransaction = { 74 | to: safeExecTxParams.to, 75 | value: safeExecTxParams.value, 76 | data: safeExecTxParams.data, 77 | operation: safeExecTxParams.operation, 78 | safeTxGas: 0, 79 | baseGas: 0, 80 | gasPrice: Number(txRelayParams.gas_price), 81 | gasToken: zeroAddress, 82 | refundReceiver: txRelayParams.relayer, 83 | nonce 84 | } 85 | 86 | const transactionHash = await contract.call('getTransactionHash', [ 87 | safeTransaction.to, 88 | new BigNumber(safeExecTxParams.value).toString(10), 89 | safeTransaction.data, 90 | safeTransaction.operation, 91 | safeTransaction.safeTxGas, 92 | safeTransaction.baseGas, 93 | safeTransaction.gasPrice, 94 | safeTransaction.gasToken, 95 | safeTransaction.refundReceiver, 96 | safeTransaction.nonce 97 | ]) 98 | 99 | const signatures = await getTransactionHashSignature( 100 | ethLibAdapter, 101 | ownerAccount, 102 | transactionHash 103 | ) 104 | 105 | const data = contract.encode('execTransaction', [ 106 | safeTransaction.to, 107 | new BigNumber(safeExecTxParams.value).toString(10), 108 | safeTransaction.data, 109 | safeTransaction.operation, 110 | safeTransaction.safeTxGas, 111 | safeTransaction.baseGas, 112 | safeTransaction.gasPrice, 113 | safeTransaction.gasToken, 114 | safeTransaction.refundReceiver, 115 | signatures 116 | ]) 117 | 118 | const trackingId = await this.sendTxToRelay(contract.address, data, network) 119 | return this.followTransaction(network, trackingId, ethLibAdapter) 120 | } 121 | 122 | private async getTxRelayParams( 123 | safeAccount: string, 124 | network: string 125 | ): Promise { 126 | const jsonResponse = await sendRequest({ 127 | url: `${rocksideTxRelayUrl}/ethereum/${network}/relay/${safeAccount}/params`, 128 | method: HttpMethod.GET, 129 | expectedHttpCodeResponse: 200 130 | }) 131 | 132 | return jsonResponse.speeds[this.#speed] 133 | } 134 | 135 | private async sendTxToRelay( 136 | safeAccount: Address, 137 | data: string, 138 | network: string 139 | ): Promise { 140 | const jsonResponse = await sendRequest({ 141 | url: `${rocksideTxRelayUrl}/ethereum/${network}/relay/${safeAccount}`, 142 | method: HttpMethod.POST, 143 | body: JSON.stringify({ data, speed: this.#speed }), 144 | expectedHttpCodeResponse: 200 145 | }) 146 | 147 | return jsonResponse.tracking_id 148 | } 149 | 150 | private async followTransaction( 151 | network: string, 152 | trackingId: string, 153 | ethLibAdapter: EthLibAdapter 154 | ): Promise { 155 | const jsonResponse = await sendRequest({ 156 | url: `${rocksideTxRelayUrl}/ethereum/${network}/transactions/${trackingId}`, 157 | method: HttpMethod.GET, 158 | expectedHttpCodeResponse: 200 159 | }) 160 | 161 | return ethLibAdapter.toRocksideRelayTxResult(jsonResponse) 162 | } 163 | } 164 | 165 | export default RocksideRelayTransactionManager 166 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/transactionManagers/SafeTxRelayManager/index.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js' 2 | import EthLibAdapter from '../../ethLibAdapters/EthLibAdapter' 3 | import { Address } from '../../utils/basicTypes' 4 | import { zeroAddress } from '../../utils/constants' 5 | import { HttpMethod, sendRequest } from '../../utils/httpRequests' 6 | import { OperationType, TransactionResult } from '../../utils/transactions' 7 | import TransactionManager, { 8 | ExecTransactionProps, 9 | TransactionManagerConfig, 10 | TransactionManagerNames 11 | } from '../TransactionManager' 12 | 13 | BigNumber.set({ EXPONENTIAL_AT: [-7, 255] }) 14 | 15 | interface SafeRelayTransactionManagerConfig { 16 | url: string 17 | } 18 | 19 | interface TransactionEstimationsProps { 20 | safe: Address 21 | to: Address 22 | value: string 23 | data: string 24 | operation: OperationType 25 | gasToken?: Address 26 | } 27 | 28 | interface RelayEstimation { 29 | safeTxGas: number 30 | baseGas: number 31 | dataGas: number 32 | operationalGas: number 33 | gasPrice: number 34 | lastUsedNonce: number 35 | gasToken: Address 36 | } 37 | 38 | interface TransactionToRelayProps { 39 | url: string 40 | tx: any 41 | safe: Address 42 | signatures: any 43 | ethLibAdapter: EthLibAdapter 44 | } 45 | 46 | class SafeRelayTransactionManager implements TransactionManager { 47 | url: string 48 | 49 | /** 50 | * Initializes an instance of the Safe Relay Transaction Manager. 51 | * 52 | * @param options - The URL pointing to the Safe Transaction Service 53 | * @returns The SafeRelayTransactionManager instance 54 | */ 55 | constructor(options: SafeRelayTransactionManagerConfig) { 56 | const { url } = options 57 | if (!url) { 58 | throw new Error('url property missing from options') 59 | } 60 | this.url = url 61 | } 62 | 63 | /** 64 | * Returns the configuration of the Safe Relay Transaction Manager. 65 | * 66 | * @returns The name of the TransactionManager in use and the URL of the service 67 | */ 68 | get config(): TransactionManagerConfig { 69 | return { 70 | name: TransactionManagerNames.SafeTxRelayManager, 71 | url: this.url 72 | } 73 | } 74 | 75 | /** 76 | * Executes a list of transactions via the Safe Transaction Relay. 77 | * 78 | * @param options 79 | * @returns The transaction response 80 | */ 81 | async execTransactions({ 82 | ownerAccount, 83 | safeExecTxParams, 84 | contractManager, 85 | ethLibAdapter, 86 | isConnectedToSafe 87 | }: ExecTransactionProps): Promise { 88 | const { contract } = contractManager 89 | if (!contract) { 90 | throw new Error('CPK Proxy contract uninitialized') 91 | } 92 | 93 | if (isConnectedToSafe) { 94 | throw new Error( 95 | 'The use of the relay service is not supported when the CPK is connected to a Gnosis Safe' 96 | ) 97 | } 98 | 99 | const relayEstimations = await this.getTransactionEstimations({ 100 | safe: contract.address, 101 | to: safeExecTxParams.to, 102 | value: new BigNumber(safeExecTxParams.value).toString(10), 103 | data: safeExecTxParams.data, 104 | operation: safeExecTxParams.operation 105 | }) 106 | 107 | // TO-DO: dataGas will be obsolete. Check again when this endpoint is updated to v2 108 | const tx = { 109 | to: safeExecTxParams.to, 110 | value: new BigNumber(safeExecTxParams.value).toString(10), 111 | data: safeExecTxParams.data, 112 | operation: safeExecTxParams.operation, 113 | safeTxGas: relayEstimations.safeTxGas, 114 | dataGas: relayEstimations.baseGas, 115 | gasPrice: relayEstimations.gasPrice, 116 | gasToken: relayEstimations.gasToken, 117 | refundReceiver: zeroAddress, 118 | nonce: relayEstimations.lastUsedNonce + 1 119 | } 120 | 121 | const txHash = await contract.call('getTransactionHash', [ 122 | tx.to, 123 | tx.value, 124 | tx.data, 125 | tx.operation, 126 | tx.safeTxGas, 127 | tx.dataGas, 128 | tx.gasPrice, 129 | tx.gasToken, 130 | tx.refundReceiver, 131 | tx.nonce 132 | ]) 133 | 134 | const rsvSignature = await this.signTransactionHash(ethLibAdapter, ownerAccount, txHash) 135 | 136 | return this.sendTransactionToRelay({ 137 | url: this.url, 138 | safe: contract.address, 139 | tx, 140 | signatures: [rsvSignature], 141 | ethLibAdapter 142 | }) 143 | } 144 | 145 | private async getTransactionEstimations({ 146 | safe, 147 | to, 148 | value, 149 | data, 150 | operation, 151 | gasToken 152 | }: TransactionEstimationsProps): Promise { 153 | const body: { [key: string]: any } = { 154 | safe, 155 | to, 156 | value, 157 | data, 158 | operation 159 | } 160 | if (gasToken) { 161 | body.gasToken = gasToken 162 | } 163 | 164 | const jsonResponse = await sendRequest({ 165 | url: `${this.url}/api/v1/safes/${safe}/transactions/estimate/`, 166 | method: HttpMethod.POST, 167 | body: JSON.stringify(body), 168 | expectedHttpCodeResponse: 200 169 | }) 170 | 171 | return jsonResponse 172 | } 173 | 174 | private async sendTransactionToRelay({ 175 | tx, 176 | safe, 177 | signatures, 178 | ethLibAdapter 179 | }: TransactionToRelayProps): Promise { 180 | const jsonResponse = await sendRequest({ 181 | url: `${this.url}/api/v1/safes/${safe}/transactions/`, 182 | method: HttpMethod.POST, 183 | body: JSON.stringify({ safe, ...tx, signatures }), 184 | expectedHttpCodeResponse: 201 185 | }) 186 | 187 | return ethLibAdapter.toSafeRelayTxResult(jsonResponse.txHash, jsonResponse.ethereumTx) 188 | } 189 | 190 | private async signTransactionHash( 191 | ethLibAdapter: EthLibAdapter, 192 | ownerAccount: Address, 193 | txHash: string 194 | ) { 195 | let sig = await ethLibAdapter.signMessage(txHash, ownerAccount) 196 | let sigV = parseInt(sig.slice(-2), 16) 197 | 198 | switch (sigV) { 199 | case 0: 200 | case 1: 201 | sigV += 31 202 | break 203 | case 27: 204 | case 28: 205 | sigV += 4 206 | break 207 | default: 208 | throw new Error('Invalid signature') 209 | } 210 | 211 | sig = sig.slice(0, -2) + sigV.toString(16) 212 | 213 | return { 214 | r: new BigNumber('0x' + sig.slice(2, 66)).toString(10), 215 | s: new BigNumber('0x' + sig.slice(66, 130)).toString(10), 216 | v: new BigNumber('0x' + sig.slice(130, 132)).toString(10) 217 | } 218 | } 219 | } 220 | 221 | export default SafeRelayTransactionManager 222 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/transactionManagers/TransactionManager.ts: -------------------------------------------------------------------------------- 1 | import ContractManager from '../contractManager' 2 | import EthLibAdapter, { Contract } from '../ethLibAdapters/EthLibAdapter' 3 | import { Address } from '../utils/basicTypes' 4 | import { StandardTransaction, TransactionResult, SendOptions } from '../utils/transactions' 5 | 6 | export enum TransactionManagerNames { 7 | CpkTxManager = 'CpkTransactionManager', 8 | SafeTxRelayManager = 'SafeTransactionRelayManager', 9 | RocksideTxRelayManager = 'RocksideTransactionRelayManager' 10 | } 11 | 12 | export interface TransactionManagerConfig { 13 | name: string 14 | url?: string 15 | speed?: string 16 | } 17 | 18 | export interface CPKContracts { 19 | safeContract: Contract 20 | proxyFactory: Contract 21 | masterCopyAddress: Address 22 | fallbackHandlerAddress: Address 23 | } 24 | 25 | export interface ExecTransactionProps { 26 | ownerAccount: Address 27 | safeExecTxParams: StandardTransaction 28 | transactions: StandardTransaction[] 29 | contractManager: ContractManager 30 | ethLibAdapter: EthLibAdapter 31 | saltNonce: string 32 | isDeployed: boolean 33 | isConnectedToSafe: boolean 34 | sendOptions: SendOptions 35 | } 36 | 37 | interface TransactionManager { 38 | config: TransactionManagerConfig 39 | 40 | /** 41 | * Executes a list of transactions. 42 | * 43 | * @param options 44 | * @returns The transaction response 45 | */ 46 | execTransactions(options: ExecTransactionProps): Promise 47 | } 48 | 49 | export default TransactionManager 50 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/transactionManagers/utils.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js' 2 | import { bufferToHex, ecrecover, pubToAddress } from 'ethereumjs-util' 3 | import EthLibAdapter from '../ethLibAdapters/EthLibAdapter' 4 | import { Address } from '../utils/basicTypes' 5 | import { OperationType } from '../utils/transactions' 6 | 7 | export interface SafeTransaction { 8 | to: Address 9 | value: number 10 | data: string 11 | operation: OperationType 12 | safeTxGas: number 13 | dataGas: number 14 | gasPrice: number 15 | gasToken: Address 16 | refundReceiver: Address 17 | nonce: number 18 | } 19 | 20 | export const getTransactionHashSignature = async ( 21 | ethLibAdapter: EthLibAdapter, 22 | ownerAccount: Address, 23 | txHash: string 24 | ) => { 25 | let signature = await ethLibAdapter.signMessage(txHash, ownerAccount) 26 | const hasPrefix = isTxHashSignedWithPrefix(txHash, signature, ownerAccount) 27 | 28 | let signatureV = parseInt(signature.slice(-2), 16) 29 | switch (signatureV) { 30 | case 0: 31 | case 1: 32 | signatureV += 31 33 | break 34 | case 27: 35 | case 28: 36 | if (hasPrefix) { 37 | signatureV += 4 38 | } 39 | break 40 | default: 41 | throw new Error('Invalid signature') 42 | } 43 | 44 | signature = signature.slice(0, -2) + signatureV.toString(16) 45 | return signature 46 | } 47 | 48 | export const getTransactionHashSignatureRSV = async ( 49 | ethLibAdapter: EthLibAdapter, 50 | ownerAccount: Address, 51 | txHash: string 52 | ) => { 53 | const signature = await getTransactionHashSignature(ethLibAdapter, ownerAccount, txHash) 54 | 55 | return { 56 | r: new BigNumber('0x' + signature.slice(2, 66)).toString(10), 57 | s: new BigNumber('0x' + signature.slice(66, 130)).toString(10), 58 | v: new BigNumber('0x' + signature.slice(130, 132)).toString(10) 59 | } 60 | } 61 | 62 | const isTxHashSignedWithPrefix = ( 63 | txHash: string, 64 | signature: string, 65 | ownerAccount: string 66 | ): boolean => { 67 | let hasPrefix 68 | try { 69 | const rsvSig = { 70 | r: Buffer.from(signature.slice(2, 66), 'hex'), 71 | s: Buffer.from(signature.slice(66, 130), 'hex'), 72 | v: parseInt(signature.slice(130, 132), 16) 73 | } 74 | const recoveredData = ecrecover( 75 | Buffer.from(txHash.slice(2), 'hex'), 76 | rsvSig.v, 77 | rsvSig.r, 78 | rsvSig.s 79 | ) 80 | const recoveredAccount = bufferToHex(pubToAddress(recoveredData)) 81 | hasPrefix = recoveredAccount.toLowerCase() !== ownerAccount.toLowerCase() 82 | } catch (e) { 83 | hasPrefix = true 84 | } 85 | return hasPrefix 86 | } 87 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/utils/basicTypes.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js' 2 | 3 | type Json = string | number | boolean | null | JsonObject | Json[] 4 | 5 | type JsonObject = { [property: string]: Json } 6 | 7 | export type Address = string 8 | 9 | export type Abi = JsonObject[] 10 | 11 | export type NumberLike = number | string | bigint | BigNumber 12 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/utils/checkConnectedToSafe.ts: -------------------------------------------------------------------------------- 1 | export async function checkConnectedToSafe(provider: any): Promise { 2 | if (provider == null) return false 3 | 4 | const wc = 5 | (await provider.getWalletConnector?.()) || 6 | (await provider.connection?.getWalletConnector?.()) || 7 | provider.wc || 8 | provider.connection?.wc 9 | 10 | const peerName = wc?.peerMeta?.name 11 | 12 | if (peerName === 'Safe Multisig WalletConnect' || peerName?.startsWith?.('Gnosis Safe')) { 13 | return true 14 | } 15 | 16 | if (provider._providers) { 17 | return (await Promise.all(provider._providers.map(checkConnectedToSafe))).includes(true) 18 | } 19 | 20 | return false 21 | } 22 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/utils/constants.ts: -------------------------------------------------------------------------------- 1 | import { OperationType } from './transactions' 2 | 3 | export const zeroAddress = `0x${'0'.repeat(40)}` 4 | 5 | export const sentinelModules = '0x0000000000000000000000000000000000000001' 6 | 7 | export const defaultTxOperation = OperationType.Call 8 | export const defaultTxValue = '0x0' 9 | export const defaultTxData = '0x' 10 | 11 | // keccak256(toUtf8Bytes('Contract Proxy Kit')) 12 | export const predeterminedSaltNonce = 13 | '0xcfe33a586323e7325be6aa6ecd8b4600d232a9037e83c8ece69413b777dabe65' 14 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/utils/hexData.ts: -------------------------------------------------------------------------------- 1 | import { NumberLike } from './basicTypes' 2 | 3 | export function joinHexData(hexData: string[]): string { 4 | return `0x${hexData 5 | .map((hex) => { 6 | const stripped = hex.replace(/^0x/, '') 7 | return stripped.length % 2 === 0 ? stripped : '0' + stripped 8 | }) 9 | .join('')}` 10 | } 11 | 12 | export function getHexDataLength(hexData: string): number { 13 | return Math.ceil((hexData.startsWith('0x') ? hexData.length - 2 : hexData.length) / 2) 14 | } 15 | 16 | export function toHex(v: NumberLike): string { 17 | return `0x${Number(v.toString()).toString(16)}` 18 | } 19 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/utils/httpRequests.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch' 2 | 3 | export enum HttpMethod { 4 | GET = 'GET', 5 | POST = 'POST' 6 | } 7 | 8 | interface HttpRequest { 9 | url: string 10 | method: HttpMethod 11 | body?: string 12 | expectedHttpCodeResponse: number 13 | } 14 | 15 | export const sendRequest = async ({ url, method, body, expectedHttpCodeResponse }: HttpRequest) => { 16 | const headers = { 17 | Accept: 'application/json', 18 | 'Content-Type': 'application/json' 19 | } 20 | 21 | const response = await fetch(url, { method, headers, body }) 22 | 23 | const jsonResponse = await response.json() 24 | 25 | if (response.status !== expectedHttpCodeResponse) { 26 | throw new Error(jsonResponse.exception) 27 | } 28 | return jsonResponse 29 | } 30 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/utils/networks.ts: -------------------------------------------------------------------------------- 1 | export enum NetworkNames { 2 | MAINNET = 'MAINNET', 3 | MORDEN = 'MORDEN', 4 | ROPSTEN = 'ROPSTEN', 5 | RINKEBY = 'RINKEBY', 6 | GOERLI = 'GOERLI', 7 | KOVAN = 'KOVAN', 8 | XDAI = 'XDAI', 9 | ENERGY_WEB_CHAIN = 'ENERGY_WEB_CHAIN', 10 | VOLTA = 'VOLTA' 11 | } 12 | 13 | type Networks = { 14 | [key in NetworkNames]: number 15 | } 16 | 17 | export const getNetworkIdFromName = (networkName?: string): number | undefined => { 18 | if (!networkName) return 19 | const networks: Networks = { 20 | MAINNET: 1, 21 | MORDEN: 2, 22 | ROPSTEN: 3, 23 | RINKEBY: 4, 24 | GOERLI: 5, 25 | KOVAN: 42, 26 | XDAI: 100, 27 | ENERGY_WEB_CHAIN: 246, 28 | VOLTA: 73799 29 | } 30 | return networks[networkName.toUpperCase() as NetworkNames] 31 | } 32 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/src/utils/transactions.ts: -------------------------------------------------------------------------------- 1 | import { Address, NumberLike } from './basicTypes' 2 | import { defaultTxData, defaultTxOperation, defaultTxValue } from './constants' 3 | import { toHex } from './hexData' 4 | 5 | export enum OperationType { 6 | Call, // 0 7 | DelegateCall // 1 8 | } 9 | 10 | interface GasLimitOptions { 11 | gas?: NumberLike 12 | gasLimit?: NumberLike 13 | safeTxGas?: number 14 | } 15 | 16 | interface BaseTxOptions extends GasLimitOptions { 17 | gasPrice?: NumberLike 18 | } 19 | 20 | export interface ExecOptions extends BaseTxOptions { 21 | nonce?: NumberLike 22 | } 23 | 24 | export interface CallOptions extends BaseTxOptions { 25 | from?: Address 26 | } 27 | 28 | export interface SendOptions extends ExecOptions { 29 | from: Address 30 | } 31 | 32 | export interface EthTx { 33 | to: string 34 | value?: NumberLike 35 | data?: string 36 | } 37 | 38 | export interface EthCallTx extends EthTx, CallOptions {} 39 | 40 | export interface EthSendTx extends EthTx, SendOptions {} 41 | 42 | export interface Transaction extends EthTx { 43 | operation?: OperationType 44 | } 45 | 46 | export interface SimpleTransactionResult { 47 | hash?: string 48 | safeTxHash?: string 49 | } 50 | 51 | export interface Web3TransactionResult extends SimpleTransactionResult { 52 | sendOptions?: SendOptions 53 | promiEvent: Promise 54 | } 55 | 56 | export interface EthersTransactionResult extends SimpleTransactionResult { 57 | transactionResponse: Record 58 | } 59 | 60 | export interface TransactionResult extends SimpleTransactionResult { 61 | sendOptions?: SendOptions 62 | promiEvent?: any 63 | transactionResponse?: Record 64 | } 65 | 66 | export class TransactionError extends Error { 67 | revertData?: string 68 | revertMessage?: string 69 | 70 | constructor(message: string, revertData?: string, revertMessage?: string) { 71 | super(message) 72 | this.revertData = revertData 73 | this.revertMessage = revertMessage 74 | } 75 | } 76 | 77 | export interface StandardTransaction { 78 | operation: OperationType 79 | to: Address 80 | value: string 81 | data: string 82 | } 83 | 84 | export function standardizeTransaction(tx: Transaction): StandardTransaction { 85 | return { 86 | operation: tx.operation ? tx.operation : defaultTxOperation, 87 | to: tx.to, 88 | value: tx.value ? tx.value.toString() : defaultTxValue.toString(), 89 | data: tx.data ? tx.data : defaultTxData 90 | } 91 | } 92 | 93 | export type NormalizeGas = Pick> 94 | 95 | export function normalizeGasLimit(options: T): NormalizeGas { 96 | const { gas, gasLimit, ...rest } = options 97 | if (gas != null && gasLimit != null) { 98 | throw new Error(`specified both gas and gasLimit on options: ${options}`) 99 | } 100 | return { 101 | ...rest, 102 | gas: gas || gasLimit 103 | } as NormalizeGas 104 | } 105 | 106 | export interface RpcCallTx { 107 | from?: Address 108 | to: Address 109 | gas?: string 110 | gasPrice?: string 111 | value?: string 112 | data?: string 113 | } 114 | 115 | export function formatCallTx(tx: EthCallTx): RpcCallTx { 116 | const { from, to, value, data, gas } = normalizeGasLimit(tx) 117 | 118 | return { 119 | from, 120 | to, 121 | value: !value ? undefined : toHex(value), 122 | data, 123 | gas: !gas ? undefined : toHex(gas) 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | mocha: true, 4 | }, 5 | globals: { 6 | artifacts: 'readonly', 7 | contract: 'readonly', 8 | web3: 'readonly', 9 | should: 'readonly', 10 | }, 11 | }; 12 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/contract-proxy-kit.ts: -------------------------------------------------------------------------------- 1 | import { SafeInfo } from '@gnosis.pm/safe-apps-sdk' 2 | import chai from 'chai' 3 | import chaiAsPromised from 'chai-as-promised' 4 | import { ethers as ethersMaj4 } from 'ethers-4' 5 | import { ethers as ethersMaj5 } from 'ethers-5' 6 | import should from 'should' 7 | import Web3Maj1Min3 from 'web3-1-4' 8 | import Web3Maj2Alpha from 'web3-2-alpha' 9 | import CPK, { SafeTxRelayManager, Web3Adapter } from '../src' 10 | import { Address } from '../src/utils/basicTypes' 11 | import { zeroAddress } from '../src/utils/constants' 12 | import { testCpkWithEthers } from './ethers/shouldWorkWithEthers' 13 | import { testEthersAdapter } from './ethers/testEthersAdapter' 14 | import { 15 | getContractInstances, 16 | getContracts, 17 | initializeContracts, 18 | TestContractInstances 19 | } from './utils/contracts' 20 | import makeEmulatedSafeProvider from './utils/makeEmulatedSafeProvider' 21 | import { testCpkWithWeb3 } from './web3/shouldWorkWithWeb3' 22 | import { testWeb3Adapter } from './web3/testWeb3Adapter' 23 | chai.use(chaiAsPromised) 24 | 25 | const web3Versions = [Web3Maj1Min3, Web3Maj2Alpha] 26 | const ethersVersions = [ethersMaj4, ethersMaj5] 27 | 28 | describe('Contract Proxy Kit', () => { 29 | let web3: any 30 | const defaultAccountBox: Address[] = [] 31 | const safeOwnerBox: Address[] = [] 32 | let contracts: TestContractInstances 33 | const gnosisSafeProviderBox: any[] = [] 34 | 35 | before('initialize user accounts', async () => { 36 | web3 = new Web3Maj1Min3('http://localhost:8545') 37 | const accounts = await web3.eth.getAccounts() 38 | 39 | // First account is used as the Safe relayer account 40 | defaultAccountBox[0] = accounts[2] 41 | safeOwnerBox[0] = accounts[3] 42 | }) 43 | 44 | before('initialize contracts', async () => { 45 | await initializeContracts(safeOwnerBox[0]) 46 | contracts = getContractInstances() 47 | }) 48 | 49 | before('emulate Gnosis Safe WalletConnect provider', async () => { 50 | const { gnosisSafe, defaultCallbackHandler, gnosisSafeProxyFactory, multiSend } = contracts 51 | const safeSetupData = gnosisSafe.contract.methods 52 | .setup( 53 | [safeOwnerBox[0]], 54 | 1, 55 | zeroAddress, 56 | '0x', 57 | defaultCallbackHandler.address, 58 | zeroAddress, 59 | 0, 60 | zeroAddress 61 | ) 62 | .encodeABI() 63 | const { logs } = await gnosisSafeProxyFactory.createProxy(gnosisSafe.address, safeSetupData, { 64 | from: safeOwnerBox[0] 65 | }) 66 | const proxyCreationEvents = logs.find(({ event }: { event: any }) => event === 'ProxyCreation') 67 | const safeAddress: Address = proxyCreationEvents && proxyCreationEvents.args.proxy 68 | const safeSignature = `0x000000000000000000000000${safeOwnerBox[0] 69 | .replace(/^0x/, '') 70 | .toLowerCase()}000000000000000000000000000000000000000000000000000000000000000001` 71 | const safe = await getContracts().GnosisSafe.at(safeAddress) 72 | const emulatedSafeProvider = makeEmulatedSafeProvider({ 73 | web3, 74 | safe, 75 | safeAddress, 76 | safeOwnerBox, 77 | safeMasterCopy: gnosisSafe, 78 | multiSend, 79 | safeSignature 80 | }) 81 | gnosisSafeProviderBox[0] = emulatedSafeProvider 82 | }) 83 | 84 | it('should exist', () => { 85 | should.exist(CPK) 86 | }) 87 | 88 | it('should produce uninitialized CPK instances when running standalone and options are missing', async () => { 89 | const cpk = await CPK.create(undefined as any) 90 | should.exist(cpk) 91 | should.not.exist(cpk.ethLibAdapter) 92 | should.not.exist(cpk.contractManager?.contract) 93 | should.not.exist(cpk.contractManager?.multiSend) 94 | should.not.exist(cpk.contractManager?.proxyFactory) 95 | should.not.exist(cpk.contractManager?.masterCopyAddress) 96 | should.not.exist(cpk.contractManager?.fallbackHandlerAddress) 97 | cpk.safeAppsSdkConnector?.isSafeApp.should.equal(false) 98 | }) 99 | 100 | it.skip('should produce CPK instances when running as a Safe App and options are missing', async () => { 101 | // Test fails because the window.postMessage is not received in the safe-apps-sdk 102 | const cpk = await CPK.create(undefined as any) 103 | 104 | const message: SafeInfo = { 105 | safeAddress: '0x0000000000000000000000000000000000000001', 106 | network: 'RINKEBY' 107 | } 108 | window.postMessage({ messageId: 'ON_SAFE_INFO', message }, '*') 109 | 110 | should.exist(cpk) 111 | should.exist(cpk.ethLibAdapter) 112 | should.exist(cpk.address) 113 | cpk.address?.should.equal(message.safeAddress) 114 | should.not.exist(cpk.contractManager?.contract) 115 | should.not.exist(cpk.contractManager?.multiSend) 116 | should.not.exist(cpk.contractManager?.proxyFactory) 117 | should.not.exist(cpk.contractManager?.masterCopyAddress) 118 | should.not.exist(cpk.contractManager?.fallbackHandlerAddress) 119 | cpk.safeAppsSdkConnector?.isSafeApp.should.equal(true) 120 | }) 121 | 122 | it.skip('should produce CPK instances when running as a Safe App', async () => { 123 | // Test fails because the window.postMessage is not received in the safe-apps-sdk 124 | const cpk = await CPK.create({ 125 | ethLibAdapter: new Web3Adapter({ web3 }), 126 | ownerAccount: '0x0000000000000000000000000000000000000002' 127 | }) 128 | 129 | const message: SafeInfo = { 130 | safeAddress: '0x0000000000000000000000000000000000000001', 131 | network: 'RINKEBY' 132 | } 133 | window.postMessage({ messageId: 'ON_SAFE_INFO', message }, '*') 134 | 135 | should.exist(cpk) 136 | should.exist(cpk.ethLibAdapter) 137 | should.exist(cpk.address) 138 | cpk.address?.should.equal(message.safeAddress) 139 | should.not.exist(cpk.contractManager?.contract) 140 | should.not.exist(cpk.contractManager?.multiSend) 141 | should.not.exist(cpk.contractManager?.proxyFactory) 142 | should.not.exist(cpk.contractManager?.masterCopyAddress) 143 | should.not.exist(cpk.contractManager?.fallbackHandlerAddress) 144 | should.exist(cpk.safeAppsSdkConnector) 145 | cpk.safeAppsSdkConnector?.isSafeApp.should.equal(true) 146 | }) 147 | 148 | it('should not produce CPK instances when ethLibAdapter not provided', async () => { 149 | await CPK.create({} as any).should.be.rejectedWith( 150 | 'ethLibAdapter property missing from options' 151 | ) 152 | }) 153 | 154 | it('should not produce SafeTxRelayManager instances when url not provided', async () => { 155 | ;(() => new SafeTxRelayManager({} as any)).should.throw('url property missing from options') 156 | }) 157 | 158 | describe('EthLibAdapters', () => { 159 | web3Versions.forEach((Web3) => testWeb3Adapter({ Web3, defaultAccountBox, safeOwnerBox })) 160 | ethersVersions.forEach((ethers) => 161 | testEthersAdapter({ ethers, defaultAccountBox, safeOwnerBox }) 162 | ) 163 | }) 164 | 165 | describe('CPK with Transaction Manager', () => { 166 | web3Versions.forEach((Web3) => { 167 | testCpkWithWeb3({ 168 | Web3, 169 | defaultAccountBox, 170 | safeOwnerBox, 171 | gnosisSafeProviderBox 172 | }) 173 | }) 174 | ethersVersions.forEach((ethers) => { 175 | testCpkWithEthers({ 176 | ethers, 177 | defaultAccountBox, 178 | safeOwnerBox, 179 | gnosisSafeProviderBox 180 | }) 181 | }) 182 | }) 183 | /* 184 | describe('CPK with Safe Relay Transaction Manager', () => { 185 | const transactionManager = new SafeTxRelayManager({ url: 'http://localhost:8000' }) 186 | web3Versions.forEach((Web3) => { 187 | testCpkWithWeb3({ 188 | Web3, 189 | defaultAccountBox, 190 | safeOwnerBox, 191 | gnosisSafeProviderBox, 192 | transactionManager 193 | }) 194 | }) 195 | ethersVersions.forEach((ethers) => { 196 | testCpkWithEthers({ 197 | ethers, 198 | defaultAccountBox, 199 | safeOwnerBox, 200 | gnosisSafeProviderBox, 201 | transactionManager 202 | }) 203 | }) 204 | }) 205 | */ 206 | }) 207 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/ethers/shouldWorkWithEthers.ts: -------------------------------------------------------------------------------- 1 | import should from 'should' 2 | import Web3Maj1Min3 from 'web3-1-4' 3 | import CPK, { EthersAdapter, NetworksConfig, Transaction, TransactionManager } from '../../src' 4 | import { Address } from '../../src/utils/basicTypes' 5 | import { testConnectedSafeTransactionsWithRelay } from '../transactions/testConnectedSafeTransactionsWithRelay' 6 | import { testSafeTransactions } from '../transactions/testSafeTransactions' 7 | import { AccountType, toTxHashPromise } from '../utils' 8 | import { getContractInstances, TestContractInstances } from '../utils/contracts' 9 | import { ethersTestHelpers } from './utils' 10 | 11 | interface testCpkWithEthersProps { 12 | ethers: any 13 | defaultAccountBox: Address[] 14 | safeOwnerBox: Address[] 15 | gnosisSafeProviderBox: any 16 | transactionManager?: TransactionManager 17 | } 18 | 19 | export function testCpkWithEthers({ 20 | ethers, 21 | defaultAccountBox, 22 | safeOwnerBox, 23 | gnosisSafeProviderBox, 24 | transactionManager 25 | }: testCpkWithEthersProps): void { 26 | describe(`with ethers version ${ethers.version}`, () => { 27 | let contracts: TestContractInstances 28 | const web3 = new Web3Maj1Min3('http://localhost:8545') 29 | const isCpkTransactionManager = 30 | !transactionManager || transactionManager.config.name === 'CpkTransactionManager' 31 | 32 | const signer = ethers.Wallet.createRandom().connect( 33 | new ethers.providers.Web3Provider(web3.currentProvider) 34 | ) 35 | 36 | before('setup contracts', async () => { 37 | contracts = getContractInstances() 38 | }) 39 | 40 | it('should not produce CPK instances when ethers not connected to a recognized network', async () => { 41 | const ethLibAdapter = new EthersAdapter({ ethers, signer }) 42 | await CPK.create({ ethLibAdapter }).should.be.rejectedWith(/Unrecognized network ID \d+/) 43 | }) 44 | 45 | describe('with valid networks configuration', () => { 46 | let networks: NetworksConfig 47 | 48 | before('obtain addresses from artifacts', async () => { 49 | const { gnosisSafe, gnosisSafe2, cpkFactory, multiSend, defaultCallbackHandler } = contracts 50 | 51 | networks = { 52 | [(await signer.provider.getNetwork()).chainId]: { 53 | masterCopyAddressVersions: [ 54 | { 55 | address: gnosisSafe.address, 56 | version: '1.2.0' 57 | }, 58 | { 59 | address: gnosisSafe2.address, 60 | version: '1.1.1' 61 | } 62 | ], 63 | proxyFactoryAddress: cpkFactory.address, 64 | multiSendAddress: multiSend.address, 65 | fallbackHandlerAddress: defaultCallbackHandler.address 66 | } 67 | } 68 | }) 69 | 70 | it('can produce instances', async () => { 71 | const ethLibAdapter = new EthersAdapter({ ethers, signer }) 72 | should.exist(ethLibAdapter) 73 | should.exist(await CPK.create({ ethLibAdapter, networks })) 74 | should.exist(await CPK.create({ ethLibAdapter, transactionManager, networks })) 75 | }) 76 | 77 | it('should instantiate SafeAppsSdkConnector when isSafeApp is not set', async () => { 78 | const ethLibAdapter = new EthersAdapter({ ethers, signer }) 79 | const cpk = await CPK.create({ ethLibAdapter, networks }) 80 | should.exist(cpk.safeAppsSdkConnector) 81 | }) 82 | 83 | it('should not instantiate SafeAppsSdkConnector when isSafeApp configuration param is set to false', async () => { 84 | const ethLibAdapter = new EthersAdapter({ ethers, signer }) 85 | const cpk = await CPK.create({ ethLibAdapter, networks, isSafeApp: false }) 86 | should.not.exist(cpk.safeAppsSdkConnector) 87 | }) 88 | 89 | it('can encode multiSend call data', async () => { 90 | const { multiStep } = contracts 91 | const transactions: Transaction[] = [ 92 | { 93 | to: multiStep.address, 94 | data: multiStep.contract.methods.doStep(1).encodeABI() 95 | }, 96 | { 97 | to: multiStep.address, 98 | data: multiStep.contract.methods.doStep(2).encodeABI() 99 | } 100 | ] 101 | 102 | const ethLibAdapter = new EthersAdapter({ ethers, signer }) 103 | const uninitializedCPK = new CPK({ ethLibAdapter }) 104 | const dataHash = uninitializedCPK.encodeMultiSendCallData(transactions) 105 | 106 | const multiStepAddress = multiStep.address.slice(2).toLowerCase() 107 | dataHash.should.be.equal( 108 | `0x8d80ff0a000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000f200${multiStepAddress}00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024c01cf093000000000000000000000000000000000000000000000000000000000000000100${multiStepAddress}00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024c01cf09300000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000` 109 | ) 110 | }) 111 | 112 | describe('with warm instance', () => { 113 | let cpk: CPK 114 | 115 | before('fund owner/signer', async () => { 116 | await toTxHashPromise( 117 | web3.eth.sendTransaction({ 118 | from: defaultAccountBox[0], 119 | to: signer.address, 120 | value: `${3e18}`, 121 | gas: '0x5b8d80' 122 | }) 123 | ) 124 | }) 125 | 126 | before('create instance', async () => { 127 | const ethLibAdapter = new EthersAdapter({ ethers, signer }) 128 | 129 | cpk = await CPK.create({ 130 | ethLibAdapter, 131 | transactionManager, 132 | networks 133 | }) 134 | 135 | await toTxHashPromise( 136 | web3.eth.sendTransaction({ 137 | from: defaultAccountBox[0], 138 | to: cpk.address, 139 | value: `${5e18}` 140 | }) 141 | ) 142 | }) 143 | 144 | before('warm instance', async () => { 145 | const idPrecompile = `0x${'0'.repeat(39)}4` 146 | await cpk.execTransactions([ 147 | { 148 | to: idPrecompile 149 | } 150 | ]) 151 | }) 152 | 153 | testSafeTransactions({ 154 | web3, 155 | ...ethersTestHelpers(ethers, signer, [signer]), 156 | async getCPK() { 157 | return cpk 158 | }, 159 | defaultAccount: defaultAccountBox, 160 | isCpkTransactionManager, 161 | accountType: AccountType.Warm 162 | }) 163 | }) 164 | 165 | describe('with fresh accounts', () => { 166 | const freshSignerBox: any[] = [] 167 | testSafeTransactions({ 168 | web3, 169 | ...ethersTestHelpers(ethers, signer, freshSignerBox), 170 | async getCPK() { 171 | freshSignerBox[0] = ethers.Wallet.createRandom().connect( 172 | new ethers.providers.Web3Provider(web3.currentProvider) 173 | ) 174 | 175 | await toTxHashPromise( 176 | web3.eth.sendTransaction({ 177 | from: defaultAccountBox[0], 178 | to: freshSignerBox[0].address, 179 | value: `${3e18}`, 180 | gas: '0x5b8d80' 181 | }) 182 | ) 183 | 184 | const ethLibAdapter = new EthersAdapter({ ethers, signer: freshSignerBox[0] }) 185 | const cpk = await CPK.create({ ethLibAdapter, transactionManager, networks }) 186 | 187 | await toTxHashPromise( 188 | web3.eth.sendTransaction({ 189 | from: defaultAccountBox[0], 190 | to: cpk.address, 191 | value: `${5e18}` 192 | }) 193 | ) 194 | 195 | return cpk 196 | }, 197 | defaultAccount: defaultAccountBox, 198 | isCpkTransactionManager, 199 | accountType: AccountType.Fresh 200 | }) 201 | }) 202 | 203 | describe('with mock connected to a Gnosis Safe provider', () => { 204 | const safeSignerBox: any[] = [] 205 | 206 | before('create Web3 instance', async () => { 207 | const provider = new ethers.providers.Web3Provider(gnosisSafeProviderBox[0]) 208 | safeSignerBox[0] = provider.getSigner() 209 | }) 210 | 211 | let cpk: CPK 212 | 213 | before('create instance', async () => { 214 | const ethLibAdapter = new EthersAdapter({ ethers, signer: safeSignerBox[0] }) 215 | cpk = await CPK.create({ ethLibAdapter, transactionManager, networks }) 216 | 217 | await toTxHashPromise( 218 | web3.eth.sendTransaction({ 219 | from: defaultAccountBox[0], 220 | to: cpk.address, 221 | value: `${5e18}` 222 | }) 223 | ) 224 | }) 225 | 226 | if (!isCpkTransactionManager) { 227 | testConnectedSafeTransactionsWithRelay({ 228 | web3, 229 | ...ethersTestHelpers(ethers, signer, safeSignerBox), 230 | async getCPK() { 231 | return cpk 232 | }, 233 | ownerIsRecognizedContract: true, 234 | executor: safeOwnerBox, 235 | defaultAccount: defaultAccountBox, 236 | isCpkTransactionManager, 237 | accountType: AccountType.Connected 238 | }) 239 | return 240 | } 241 | 242 | testSafeTransactions({ 243 | web3, 244 | ...ethersTestHelpers(ethers, signer, safeSignerBox), 245 | async getCPK() { 246 | return cpk 247 | }, 248 | ownerIsRecognizedContract: true, 249 | executor: safeOwnerBox, 250 | defaultAccount: defaultAccountBox, 251 | isCpkTransactionManager, 252 | accountType: AccountType.Connected 253 | }) 254 | }) 255 | }) 256 | }) 257 | } 258 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/ethers/testEthersAdapter.ts: -------------------------------------------------------------------------------- 1 | import Web3Maj1Min3 from 'web3-1-4' 2 | import { EthersAdapter } from '../../src' 3 | import { Address } from '../../src/utils/basicTypes' 4 | import { toTxHashPromise } from '../utils' 5 | 6 | interface TestEthersAdapterProps { 7 | ethers: any 8 | defaultAccountBox: Address[] 9 | safeOwnerBox: Address[] 10 | } 11 | 12 | export function testEthersAdapter({ 13 | ethers, 14 | defaultAccountBox, 15 | safeOwnerBox 16 | }: TestEthersAdapterProps): void { 17 | describe(`with ethers version ${ethers.version}`, () => { 18 | const web3 = new Web3Maj1Min3('http://localhost:8545') 19 | const signer = ethers.Wallet.createRandom().connect( 20 | new ethers.providers.Web3Provider(web3.currentProvider) 21 | ) 22 | const ethersAdapter = new EthersAdapter({ ethers, signer }) 23 | 24 | it('should not produce ethLibAdapter instances when ethers not provided', async () => { 25 | ;((): EthersAdapter => new EthersAdapter({ signer } as any)).should.throw( 26 | 'ethers property missing from options' 27 | ) 28 | }) 29 | 30 | it('should not produce ethLibAdapter instances when signer not provided', async () => { 31 | ;((): EthersAdapter => new EthersAdapter({ ethers } as any)).should.throw( 32 | 'signer property missing from options' 33 | ) 34 | }) 35 | 36 | it('should return the ETH balance of an account', async () => { 37 | const address = safeOwnerBox[0] 38 | const initialEthBalance = await ethersAdapter.getBalance(address) 39 | const value = `${1e18}` 40 | await toTxHashPromise( 41 | web3.eth.sendTransaction({ 42 | from: defaultAccountBox[0], 43 | to: address, 44 | value, 45 | gas: '0x5b8d80' 46 | }) 47 | ) 48 | const finalEthBalance = await ethersAdapter.getBalance(address) 49 | finalEthBalance.toString().should.equal(initialEthBalance.plus(value).toString()) 50 | }) 51 | }) 52 | } 53 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/ethers/utils.ts: -------------------------------------------------------------------------------- 1 | import should from 'should' 2 | import { TransactionResult } from '../../src' 3 | import { Address } from '../../src/utils/basicTypes' 4 | import { AccountType } from '../utils' 5 | 6 | export const ethersTestHelpers = (ethers: any, signer: any, signerBox: any[]): any => ({ 7 | checkAddressChecksum: (address?: Address): boolean => { 8 | if (!address) { 9 | return false 10 | } 11 | return ethers.utils.getAddress(address) === address 12 | }, 13 | sendTransaction: async ({ 14 | from, 15 | gas, 16 | ...txObj 17 | }: { 18 | from: Address 19 | gas: number 20 | }): Promise => { 21 | const signer = signerBox[0] 22 | const expectedFrom = await signer.getAddress() 23 | if (from && from.toLowerCase() !== expectedFrom.toLowerCase()) { 24 | throw new Error(`from ${from} doesn't match signer ${expectedFrom}`) 25 | } 26 | 27 | if (signer.constructor.name === 'JsonRpcSigner') { 28 | // mock Gnosis Safe provider 29 | return (await signer.sendTransaction({ gasLimit: gas, ...txObj })).hash 30 | } 31 | 32 | // See: https://github.com/ethers-io/ethers.js/issues/299 33 | const nonce: number = await signer.provider.getTransactionCount(await signer.getAddress()) 34 | 35 | let signedTx: string 36 | // TO-DO: Use semver comparison 37 | if (ethers.version.split('.')[0] === '4') { 38 | signedTx = await signer.sign({ nonce, gasLimit: gas, ...txObj }) 39 | } else if (ethers.version.split('.')[0] === 'ethers/5') { 40 | signedTx = await signer.signTransaction({ nonce, gasLimit: gas, ...txObj }) 41 | } else throw new Error(`ethers version ${ethers.version} not supported`) 42 | 43 | return (await signer.provider.sendTransaction(signedTx)).hash 44 | }, 45 | randomHexWord: (): string => ethers.utils.hexlify(ethers.utils.randomBytes(32)), 46 | fromWei: (amount: number): number => Number(ethers.utils.formatUnits(amount.toString(), 'ether')), 47 | getTransactionCount: (address: Address): Promise => 48 | signer.provider.getTransactionCount(address), 49 | getBalance: (address: Address): Promise => signer.provider.getBalance(address), 50 | testedTxObjProps: 'the TransactionResponse and the hash', 51 | checkTxObj: (txsSize: number, accountType: AccountType, txResult: TransactionResult): void => { 52 | const safeConnected = accountType === AccountType.Connected 53 | should.exist(txResult.hash) 54 | if (!safeConnected || (safeConnected && txsSize === 1)) { 55 | should.exist(txResult.transactionResponse) 56 | } 57 | }, 58 | waitTxReceipt: (txResult: TransactionResult): any => 59 | signer.provider.waitForTransaction(txResult.hash), 60 | waitSafeTxReceipt: async (txResult: TransactionResult): Promise => { 61 | if (!txResult.transactionResponse) return 62 | const receipt = await txResult.transactionResponse 63 | if (!receipt) return 64 | txResult.hash?.should.equal(receipt.hash) 65 | return receipt 66 | } 67 | }) 68 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/transactions/testConnectedSafeTransactionsWithRelay.ts: -------------------------------------------------------------------------------- 1 | import should from 'should' 2 | import CPK, { TransactionResult } from '../../src' 3 | import { Address } from '../../src/utils/basicTypes' 4 | import { getContracts } from '../utils/contracts' 5 | 6 | interface TestConnectedSafeTransactionsWithRelayProps { 7 | web3: any 8 | getCPK: () => CPK 9 | checkAddressChecksum: (address?: Address) => any 10 | sendTransaction: (txObj: any) => any 11 | randomHexWord: () => string 12 | fromWei: (amount: number) => number 13 | testedTxObjProps: string 14 | waitTxReceipt: (txResult: TransactionResult) => Promise 15 | ownerIsRecognizedContract?: boolean 16 | } 17 | 18 | export function testConnectedSafeTransactionsWithRelay({ 19 | web3, 20 | getCPK, 21 | checkAddressChecksum, 22 | sendTransaction, 23 | randomHexWord, 24 | fromWei, 25 | testedTxObjProps, 26 | waitTxReceipt, 27 | ownerIsRecognizedContract 28 | }: TestConnectedSafeTransactionsWithRelayProps): void { 29 | it('can get checksummed address of instance', async () => { 30 | const cpk = await getCPK() 31 | should.exist(cpk.address) 32 | checkAddressChecksum(cpk.address).should.be.true() 33 | }) 34 | 35 | if (ownerIsRecognizedContract) { 36 | it("has same owner as instance's address", async () => { 37 | const cpk = await getCPK() 38 | const proxyOwner = await cpk.getOwnerAccount() 39 | should.exist(proxyOwner) 40 | proxyOwner?.should.be.equal(cpk.address) 41 | }) 42 | } 43 | 44 | describe('with mock contracts', () => { 45 | let cpk: CPK 46 | let proxyOwner: Address 47 | let conditionalTokens: any 48 | let multiStep: any 49 | let erc20: any 50 | 51 | beforeEach(async () => { 52 | cpk = await getCPK() 53 | const pOwner = await cpk.getOwnerAccount() 54 | if (!pOwner) throw new Error('proxyOwner is undefined') 55 | proxyOwner = pOwner 56 | }) 57 | 58 | before('deploy conditional tokens', async () => { 59 | conditionalTokens = await getContracts().ConditionalTokens.new() 60 | }) 61 | 62 | beforeEach(async () => { 63 | multiStep = await getContracts().MultiStep.new() 64 | erc20 = await getContracts().ERC20Mintable.new() 65 | await erc20.mint(proxyOwner, `${1e20}`) 66 | }) 67 | 68 | beforeEach(async () => { 69 | const hash = await sendTransaction({ 70 | from: proxyOwner, 71 | to: erc20.address, 72 | value: 0, 73 | gas: '0x5b8d80', 74 | data: erc20.contract.methods.approve(cpk.address, `${1e20}`).encodeABI() 75 | }) 76 | await waitTxReceipt({ hash }) 77 | }) 78 | 79 | it("can't execute a single transaction", async () => { 80 | ;(await multiStep.lastStepFinished(cpk.address)).toNumber().should.equal(0) 81 | 82 | await cpk 83 | .execTransactions([ 84 | { 85 | to: multiStep.address, 86 | data: multiStep.contract.methods.doStep(1).encodeABI() 87 | } 88 | ]) 89 | .should.be.rejectedWith( 90 | /The use of the relay service is not supported when the CPK is connected to a Gnosis Safe/ 91 | ) 92 | ;(await multiStep.lastStepFinished(cpk.address)).toNumber().should.equal(0) 93 | }) 94 | 95 | it("can't execute deep transactions", async () => { 96 | ;(await multiStep.lastStepFinished(cpk.address)).toNumber().should.equal(0) 97 | const numSteps = 10 98 | 99 | await cpk 100 | .execTransactions([ 101 | { 102 | to: multiStep.address, 103 | data: multiStep.contract.methods.doDeepStep(numSteps, numSteps, cpk.address).encodeABI() 104 | } 105 | ]) 106 | .should.be.rejectedWith( 107 | /The use of the relay service is not supported when the CPK is connected to a Gnosis Safe/ 108 | ) 109 | ;(await multiStep.lastStepFinished(cpk.address)).toNumber().should.equal(0) 110 | }) 111 | 112 | it("can't batch transactions together", async () => { 113 | ;(await multiStep.lastStepFinished(cpk.address)).toNumber().should.equal(0) 114 | 115 | await cpk 116 | .execTransactions([ 117 | { 118 | to: multiStep.address, 119 | data: multiStep.contract.methods.doStep(1).encodeABI() 120 | }, 121 | { 122 | to: multiStep.address, 123 | data: multiStep.contract.methods.doStep(2).encodeABI() 124 | } 125 | ]) 126 | .should.be.rejectedWith( 127 | /The use of the relay service is not supported when the CPK is connected to a Gnosis Safe/ 128 | ) 129 | ;(await multiStep.lastStepFinished(cpk.address)).toNumber().should.equal(0) 130 | }) 131 | 132 | it("can't batch ERC20 transactions", async () => { 133 | ;(await multiStep.lastStepFinished(cpk.address)).toNumber().should.equal(0) 134 | 135 | await cpk 136 | .execTransactions([ 137 | { 138 | to: erc20.address, 139 | data: erc20.contract.methods 140 | .transferFrom(proxyOwner, cpk.address, `${3e18}`) 141 | .encodeABI() 142 | }, 143 | { 144 | to: erc20.address, 145 | data: erc20.contract.methods.approve(multiStep.address, `${3e18}`).encodeABI() 146 | }, 147 | { 148 | to: multiStep.address, 149 | data: multiStep.contract.methods.doStep(1).encodeABI() 150 | }, 151 | { 152 | to: multiStep.address, 153 | data: multiStep.contract.methods.doERC20Step(2, erc20.address).encodeABI() 154 | } 155 | ]) 156 | .should.be.rejectedWith( 157 | /The use of the relay service is not supported when the CPK is connected to a Gnosis Safe/ 158 | ) 159 | ;(await multiStep.lastStepFinished(cpk.address)).toNumber().should.equal(0) 160 | 161 | fromWei(await erc20.balanceOf(cpk.address)).should.equal(100) 162 | fromWei(await erc20.balanceOf(multiStep.address)).should.equal(0) 163 | }) 164 | 165 | it("can't batch ERC-1155 token interactions", async () => { 166 | const questionId = randomHexWord() 167 | const conditionId: string = web3.utils.soliditySha3( 168 | { t: 'address', v: cpk.address }, 169 | { t: 'bytes32', v: questionId }, 170 | { t: 'uint', v: 2 } 171 | ) 172 | 173 | await cpk 174 | .execTransactions([ 175 | { 176 | to: erc20.address, 177 | data: erc20.contract.methods 178 | .transferFrom(proxyOwner, cpk.address, `${3e18}`) 179 | .encodeABI() 180 | }, 181 | { 182 | to: erc20.address, 183 | data: erc20.contract.methods.approve(conditionalTokens.address, `${1e18}`).encodeABI() 184 | }, 185 | { 186 | to: conditionalTokens.address, 187 | data: conditionalTokens.contract.methods 188 | .prepareCondition(cpk.address, questionId, 2) 189 | .encodeABI() 190 | }, 191 | { 192 | to: conditionalTokens.address, 193 | data: conditionalTokens.contract.methods 194 | .splitPosition(erc20.address, `0x${'0'.repeat(64)}`, conditionId, [1, 2], `${1e18}`) 195 | .encodeABI() 196 | } 197 | ]) 198 | .should.be.rejectedWith( 199 | /The use of the relay service is not supported when the CPK is connected to a Gnosis Safe/ 200 | ) 201 | 202 | fromWei(await erc20.balanceOf(cpk.address)).should.equal(100) 203 | fromWei(await erc20.balanceOf(conditionalTokens.address)).should.equal(0) 204 | }) 205 | 206 | it(`does not return an object with ${testedTxObjProps} when doing a transaction`, async () => { 207 | await cpk 208 | .execTransactions([ 209 | { 210 | to: multiStep.address, 211 | data: multiStep.contract.methods.doStep(1).encodeABI() 212 | } 213 | ]) 214 | .should.be.rejectedWith( 215 | /The use of the relay service is not supported when the CPK is connected to a Gnosis Safe/ 216 | ) 217 | }) 218 | }) 219 | } 220 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/utils/contracts.ts: -------------------------------------------------------------------------------- 1 | const TruffleContract = require('@truffle/contract') 2 | import Web3Maj1Min3 from 'web3-1-4' 3 | import ConditionalTokensJson from '../../build/contracts/ConditionalTokens.json' 4 | import CPKFactoryJson from '../../build/contracts/CPKFactory.json' 5 | import DailyLimitModuleJson from '../../build/contracts/DailyLimitModule.json' 6 | import DefaultCallbackHandlerJson from '../../build/contracts/DefaultCallbackHandler.json' 7 | import ERC20MintableJson from '../../build/contracts/ERC20Mintable.json' 8 | import GnosisSafeJson from '../../build/contracts/GnosisSafe.json' 9 | import GnosisSafe2Json from '../../build/contracts/GnosisSafe2.json' 10 | import GnosisSafeProxyFactoryJson from '../../build/contracts/GnosisSafeProxyFactory.json' 11 | import MultiSendJson from '../../build/contracts/MultiSend.json' 12 | import MultistepJson from '../../build/contracts/Multistep.json' 13 | import { Address } from '../../src/utils/basicTypes' 14 | 15 | let CPKFactory: any 16 | let GnosisSafe: any 17 | let GnosisSafe2: any 18 | let GnosisSafeProxyFactory: any 19 | let MultiSend: any 20 | let DefaultCallbackHandler: any 21 | let MultiStep: any 22 | let ERC20Mintable: any 23 | let ConditionalTokens: any 24 | let DailyLimitModule: any 25 | 26 | let cpkFactory: any 27 | let gnosisSafe: any 28 | let gnosisSafe2: any 29 | let gnosisSafeProxyFactory: any 30 | let multiSend: any 31 | let defaultCallbackHandler: any 32 | let multiStep: any 33 | let erc20: any 34 | let conditionalTokens: any 35 | let dailyLimitModule: any 36 | 37 | export interface TestContractInstances { 38 | cpkFactory: any 39 | gnosisSafe: any 40 | gnosisSafe2: any 41 | gnosisSafeProxyFactory: any 42 | multiSend: any 43 | defaultCallbackHandler: any 44 | multiStep: any 45 | erc20: any 46 | conditionalTokens: any 47 | dailyLimitModule: any 48 | } 49 | 50 | export interface TestContracts { 51 | CPKFactory: any 52 | GnosisSafe: any 53 | GnosisSafe2: any 54 | GnosisSafeProxyFactory: any 55 | MultiSend: any 56 | DefaultCallbackHandler: any 57 | MultiStep: any 58 | ERC20Mintable: any 59 | ConditionalTokens: any 60 | DailyLimitModule: any 61 | } 62 | 63 | export const initializeContracts = async (safeOwner: Address): Promise => { 64 | const provider = new Web3Maj1Min3.providers.HttpProvider('http://localhost:8545') 65 | 66 | CPKFactory = TruffleContract(CPKFactoryJson) 67 | CPKFactory.setProvider(provider) 68 | CPKFactory.defaults({ from: safeOwner }) 69 | cpkFactory = await CPKFactory.deployed() 70 | 71 | GnosisSafe = TruffleContract(GnosisSafeJson) 72 | GnosisSafe.setProvider(provider) 73 | GnosisSafe.defaults({ from: safeOwner }) 74 | gnosisSafe = await GnosisSafe.deployed() 75 | 76 | GnosisSafe2 = TruffleContract(GnosisSafe2Json) 77 | GnosisSafe2.setProvider(provider) 78 | GnosisSafe2.defaults({ from: safeOwner }) 79 | gnosisSafe2 = await GnosisSafe2.deployed() 80 | 81 | GnosisSafeProxyFactory = TruffleContract(GnosisSafeProxyFactoryJson) 82 | GnosisSafeProxyFactory.setProvider(provider) 83 | GnosisSafeProxyFactory.defaults({ from: safeOwner }) 84 | gnosisSafeProxyFactory = await GnosisSafeProxyFactory.deployed() 85 | 86 | MultiSend = TruffleContract(MultiSendJson) 87 | MultiSend.setProvider(provider) 88 | MultiSend.defaults({ from: safeOwner }) 89 | multiSend = await MultiSend.deployed() 90 | 91 | DefaultCallbackHandler = TruffleContract(DefaultCallbackHandlerJson) 92 | DefaultCallbackHandler.setProvider(provider) 93 | DefaultCallbackHandler.defaults({ from: safeOwner }) 94 | defaultCallbackHandler = await DefaultCallbackHandler.deployed() 95 | 96 | MultiStep = TruffleContract(MultistepJson) 97 | MultiStep.setProvider(provider) 98 | MultiStep.defaults({ from: safeOwner }) 99 | multiStep = await MultiStep.deployed() 100 | 101 | ERC20Mintable = TruffleContract(ERC20MintableJson) 102 | ERC20Mintable.setProvider(provider) 103 | ERC20Mintable.defaults({ from: safeOwner }) 104 | erc20 = await ERC20Mintable.deployed() 105 | 106 | ConditionalTokens = TruffleContract(ConditionalTokensJson) 107 | ConditionalTokens.setProvider(provider) 108 | ConditionalTokens.defaults({ from: safeOwner }) 109 | conditionalTokens = await ConditionalTokens.deployed() 110 | 111 | DailyLimitModule = TruffleContract(DailyLimitModuleJson) 112 | DailyLimitModule.setProvider(provider) 113 | DailyLimitModule.defaults({ from: safeOwner }) 114 | dailyLimitModule = await DailyLimitModule.deployed() 115 | } 116 | 117 | export const getContracts = (): TestContracts => ({ 118 | CPKFactory, 119 | GnosisSafe, 120 | GnosisSafe2, 121 | GnosisSafeProxyFactory, 122 | MultiSend, 123 | DefaultCallbackHandler, 124 | MultiStep, 125 | ERC20Mintable, 126 | ConditionalTokens, 127 | DailyLimitModule 128 | }) 129 | 130 | export const getContractInstances = (): TestContractInstances => ({ 131 | cpkFactory, 132 | gnosisSafe, 133 | gnosisSafe2, 134 | gnosisSafeProxyFactory, 135 | multiSend, 136 | defaultCallbackHandler, 137 | multiStep, 138 | erc20, 139 | conditionalTokens, 140 | dailyLimitModule 141 | }) 142 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/utils/index.ts: -------------------------------------------------------------------------------- 1 | export const toTxHashPromise = (promiEvent: any): Promise => { 2 | return new Promise((resolve, reject) => promiEvent.once('transactionHash', resolve).catch(reject)) 3 | } 4 | 5 | export enum AccountType { 6 | Warm, 7 | Fresh, 8 | Connected 9 | } 10 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/utils/makeEmulatedSafeProvider.ts: -------------------------------------------------------------------------------- 1 | import { OperationType, Transaction } from '../../src' 2 | import { Address } from '../../src/utils/basicTypes' 3 | import { zeroAddress } from '../../src/utils/constants' 4 | 5 | interface EmulatedSafeProviderProps { 6 | web3: any 7 | safe: any 8 | safeAddress: Address 9 | safeOwnerBox: Address[] 10 | safeMasterCopy: any 11 | multiSend: any 12 | safeSignature: string 13 | } 14 | 15 | const makeEmulatedSafeProvider: any = ({ 16 | web3, 17 | safe, 18 | safeAddress, 19 | safeOwnerBox, 20 | safeMasterCopy, 21 | multiSend, 22 | safeSignature 23 | }: EmulatedSafeProviderProps) => { 24 | return { 25 | ...web3.currentProvider, 26 | wc: { 27 | peerMeta: { 28 | name: 'Gnosis Safe - Mock' 29 | } 30 | }, 31 | send(rpcData: any, callback: any) { 32 | const { id, jsonrpc, method, params } = rpcData 33 | 34 | if (method === 'eth_accounts') { 35 | return callback(null, { 36 | id, 37 | jsonrpc, 38 | result: [safeAddress] 39 | }) 40 | } 41 | 42 | if (method === 'eth_sendTransaction') { 43 | const [{ from, to, gasPrice, value, data, nonce }] = params 44 | 45 | if (from.toLowerCase() !== safeAddress.toLowerCase()) { 46 | return callback( 47 | new Error(`expected to be from safe address ${safeAddress} but got ${from}`) 48 | ) 49 | } 50 | 51 | return web3.currentProvider.send( 52 | { 53 | id, 54 | jsonrpc, 55 | method, 56 | params: [ 57 | { 58 | from: safeOwnerBox[0], 59 | to: safeAddress, 60 | // Override with 3M as gas limit in this mock provider 61 | // as Safe app/gas relayer ultimately has control over 62 | // this parameter, so we just set it to some value that 63 | // should allow all txs in this test suite to work. 64 | gas: web3.utils.toHex(3e6), 65 | gasPrice, 66 | value, 67 | nonce, 68 | data: safeMasterCopy.contract.methods 69 | .execTransaction( 70 | to, 71 | value || 0, 72 | data, 73 | OperationType.Call, 74 | 0, 75 | 0, 76 | 0, 77 | zeroAddress, 78 | zeroAddress, 79 | safeSignature 80 | ) 81 | .encodeABI() 82 | } 83 | ] 84 | }, 85 | callback 86 | ) 87 | } 88 | 89 | if (method === 'eth_getTransactionCount') { 90 | const [account, block] = params 91 | if (account === safeAddress) { 92 | return web3.currentProvider.send( 93 | { 94 | id, 95 | jsonrpc, 96 | method, 97 | params: [safeOwnerBox[0], block] 98 | }, 99 | callback 100 | ) 101 | } 102 | } 103 | 104 | if (method === 'eth_estimateGas') { 105 | const [{ from, to, gas, gasPrice, value, data, nonce }] = params 106 | 107 | if (from.toLowerCase() === safeAddress.toLowerCase()) { 108 | return web3.currentProvider.send( 109 | { 110 | id, 111 | jsonrpc, 112 | method, 113 | params: [ 114 | { 115 | from: safeOwnerBox[0], 116 | to: safeAddress, 117 | gas, 118 | gasPrice, 119 | value, 120 | nonce, 121 | data: safeMasterCopy.contract.methods 122 | .execTransaction( 123 | to, 124 | value || 0, 125 | data, 126 | OperationType.Call, 127 | 0, 128 | 0, 129 | 0, 130 | zeroAddress, 131 | zeroAddress, 132 | safeSignature 133 | ) 134 | .encodeABI() 135 | } 136 | ] 137 | }, 138 | callback 139 | ) 140 | } 141 | } 142 | 143 | if (method === 'gs_multi_send') { 144 | params.forEach((tx: Transaction) => { 145 | if (typeof tx.operation !== 'undefined') { 146 | throw new Error('expected operation property to be unset') 147 | } 148 | }) 149 | 150 | const callData = multiSend.contract.methods 151 | .multiSend( 152 | `0x${params 153 | .map((tx: Transaction) => 154 | [ 155 | web3.eth.abi.encodeParameter('uint8', OperationType.Call).slice(-2), 156 | web3.eth.abi.encodeParameter('address', tx.to).slice(-40), 157 | web3.eth.abi.encodeParameter('uint256', tx.value || 0).slice(-64), 158 | web3.eth.abi 159 | .encodeParameter('uint256', web3.utils.hexToBytes(tx.data).length) 160 | .slice(-64), 161 | tx.data && tx.data.replace(/^0x/, '') 162 | ].join('') 163 | ) 164 | .join('')}` 165 | ) 166 | .encodeABI() 167 | 168 | return safe 169 | .execTransaction( 170 | multiSend.address, 171 | 0, 172 | callData, 173 | OperationType.DelegateCall, 174 | 0, 175 | 0, 176 | 0, 177 | zeroAddress, 178 | zeroAddress, 179 | safeSignature, 180 | { from: safeOwnerBox[0], gas: web3.utils.toHex(3e6) } 181 | ) 182 | .then(({ tx }: { tx: any }) => callback(null, { id, jsonrpc, result: tx }), callback) 183 | } 184 | 185 | return web3.currentProvider.send(rpcData, callback) 186 | } 187 | } 188 | } 189 | 190 | export default makeEmulatedSafeProvider 191 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/web3/shouldWorkWithWeb3.ts: -------------------------------------------------------------------------------- 1 | import should from 'should' 2 | import Web3Maj1Min3 from 'web3-1-4' 3 | import Web3Maj2Alpha from 'web3-2-alpha' 4 | import CPK, { NetworksConfig, Transaction, TransactionManager, Web3Adapter } from '../../src' 5 | import { Address } from '../../src/utils/basicTypes' 6 | import { testConnectedSafeTransactionsWithRelay } from '../transactions/testConnectedSafeTransactionsWithRelay' 7 | import { testSafeTransactions } from '../transactions/testSafeTransactions' 8 | import { AccountType } from '../utils' 9 | import { getContractInstances, TestContractInstances } from '../utils/contracts' 10 | import { testHelperMaker } from './utils' 11 | 12 | interface TestCpkWithWeb3Props { 13 | Web3: typeof Web3Maj1Min3 | typeof Web3Maj2Alpha 14 | defaultAccountBox: Address[] 15 | safeOwnerBox: Address[] 16 | gnosisSafeProviderBox: any 17 | transactionManager?: TransactionManager 18 | } 19 | 20 | export function testCpkWithWeb3({ 21 | Web3, 22 | defaultAccountBox, 23 | safeOwnerBox, 24 | gnosisSafeProviderBox, 25 | transactionManager 26 | }: TestCpkWithWeb3Props): void { 27 | describe(`with Web3 version ${new Web3(Web3.givenProvider).version}`, () => { 28 | let contracts: TestContractInstances 29 | const ueb3 = new Web3('http://localhost:8545') 30 | const isCpkTransactionManager = 31 | !transactionManager || transactionManager.config.name === 'CpkTransactionManager' 32 | 33 | const ueb3TestHelpers = testHelperMaker(isCpkTransactionManager, [ueb3]) 34 | 35 | before('setup contracts', async () => { 36 | contracts = getContractInstances() 37 | }) 38 | 39 | it('should not produce CPK instances when web3 not connected to a recognized network', async () => { 40 | const ethLibAdapter = new Web3Adapter({ web3: ueb3 }) 41 | await CPK.create({ ethLibAdapter }).should.be.rejectedWith(/Unrecognized network ID \d+/) 42 | }) 43 | 44 | describe('with valid networks configuration', () => { 45 | let networks: NetworksConfig 46 | 47 | before('obtain addresses from artifacts', async () => { 48 | const { gnosisSafe, gnosisSafe2, cpkFactory, multiSend, defaultCallbackHandler } = contracts 49 | 50 | networks = { 51 | [await ueb3.eth.net.getId()]: { 52 | masterCopyAddressVersions: [ 53 | { 54 | address: gnosisSafe.address, 55 | version: '1.2.0' 56 | }, 57 | { 58 | address: gnosisSafe2.address, 59 | version: '1.1.1' 60 | } 61 | ], 62 | proxyFactoryAddress: cpkFactory.address, 63 | multiSendAddress: multiSend.address, 64 | fallbackHandlerAddress: defaultCallbackHandler.address 65 | } 66 | } 67 | }) 68 | 69 | it('can produce instances', async () => { 70 | const ethLibAdapter = new Web3Adapter({ web3: ueb3 }) 71 | should.exist(ethLibAdapter) 72 | should.exist(await CPK.create({ ethLibAdapter, networks })) 73 | should.exist( 74 | await CPK.create({ 75 | ethLibAdapter, 76 | networks, 77 | ownerAccount: defaultAccountBox[0] 78 | }) 79 | ) 80 | should.exist(await CPK.create({ ethLibAdapter, transactionManager, networks })) 81 | should.exist( 82 | await CPK.create({ 83 | ethLibAdapter, 84 | transactionManager, 85 | networks, 86 | ownerAccount: defaultAccountBox[0] 87 | }) 88 | ) 89 | }) 90 | 91 | it('should instantiate SafeAppsSdkConnector when isSafeApp is not set', async () => { 92 | const ethLibAdapter = new Web3Adapter({ web3: ueb3 }) 93 | const cpk = await CPK.create({ ethLibAdapter, networks }) 94 | should.exist(cpk.safeAppsSdkConnector) 95 | }) 96 | 97 | it('should not instantiate SafeAppsSdkConnector when isSafeApp configuration param is set to false', async () => { 98 | const ethLibAdapter = new Web3Adapter({ web3: ueb3 }) 99 | const cpk = await CPK.create({ ethLibAdapter, networks, isSafeApp: false }) 100 | should.not.exist(cpk.safeAppsSdkConnector) 101 | }) 102 | 103 | it('can encode multiSend call data', async () => { 104 | const { multiStep } = contracts 105 | const transactions: Transaction[] = [ 106 | { 107 | to: multiStep.address, 108 | data: multiStep.contract.methods.doStep(1).encodeABI() 109 | }, 110 | { 111 | to: multiStep.address, 112 | data: multiStep.contract.methods.doStep(2).encodeABI() 113 | } 114 | ] 115 | 116 | const ethLibAdapter = new Web3Adapter({ web3: ueb3 }) 117 | const uninitializedCPK = new CPK({ ethLibAdapter }) 118 | const dataHash = uninitializedCPK.encodeMultiSendCallData(transactions) 119 | 120 | const multiStepAddress = multiStep.address.slice(2).toLowerCase() 121 | dataHash.should.be.equal( 122 | `0x8d80ff0a000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000f200${multiStepAddress}00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024c01cf093000000000000000000000000000000000000000000000000000000000000000100${multiStepAddress}00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024c01cf09300000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000` 123 | ) 124 | }) 125 | 126 | describe('with warm instance', () => { 127 | let cpk: CPK 128 | 129 | before('create instance', async () => { 130 | const ethLibAdapter = new Web3Adapter({ web3: ueb3 }) 131 | 132 | cpk = await CPK.create({ 133 | ethLibAdapter, 134 | transactionManager, 135 | networks, 136 | ownerAccount: defaultAccountBox[0] 137 | }) 138 | 139 | await ueb3TestHelpers.sendTransaction({ 140 | from: defaultAccountBox[0], 141 | to: cpk.address, 142 | value: `${5e18}` 143 | }) 144 | }) 145 | 146 | before('warm instance', async () => { 147 | const idPrecompile = `0x${'0'.repeat(39)}4` 148 | await cpk.execTransactions([ 149 | { 150 | to: idPrecompile 151 | } 152 | ]) 153 | }) 154 | 155 | testSafeTransactions({ 156 | web3: ueb3, 157 | ...ueb3TestHelpers, 158 | async getCPK() { 159 | return cpk 160 | }, 161 | defaultAccount: defaultAccountBox, 162 | isCpkTransactionManager, 163 | accountType: AccountType.Warm 164 | }) 165 | }) 166 | 167 | describe('with fresh accounts', () => { 168 | testSafeTransactions({ 169 | web3: ueb3, 170 | ...ueb3TestHelpers, 171 | async getCPK() { 172 | const newAccount = ueb3.eth.accounts.create() 173 | ueb3.eth.accounts.wallet.add(newAccount) 174 | await ueb3TestHelpers.sendTransaction({ 175 | from: defaultAccountBox[0], 176 | to: newAccount.address, 177 | value: `${3e18}`, 178 | gas: '0x5b8d80' 179 | }) 180 | 181 | const ethLibAdapter = new Web3Adapter({ web3: ueb3 }) 182 | const cpk = await CPK.create({ 183 | ethLibAdapter, 184 | transactionManager, 185 | networks, 186 | ownerAccount: newAccount.address 187 | }) 188 | 189 | await ueb3TestHelpers.sendTransaction({ 190 | from: defaultAccountBox[0], 191 | to: cpk.address, 192 | value: `${5e18}` 193 | }) 194 | 195 | return cpk 196 | }, 197 | defaultAccount: defaultAccountBox, 198 | isCpkTransactionManager, 199 | accountType: AccountType.Fresh 200 | }) 201 | }) 202 | 203 | describe('with mock connected to a Gnosis Safe provider', () => { 204 | const safeWeb3Box: any[] = [] 205 | 206 | before('create Web3 instance', async () => { 207 | safeWeb3Box[0] = new Web3(gnosisSafeProviderBox[0]) 208 | }) 209 | 210 | let cpk: CPK 211 | 212 | before('create instance', async () => { 213 | const ethLibAdapter = new Web3Adapter({ web3: safeWeb3Box[0] }) 214 | 215 | cpk = await CPK.create({ ethLibAdapter, transactionManager, networks }) 216 | 217 | await ueb3TestHelpers.sendTransaction({ 218 | from: defaultAccountBox[0], 219 | to: cpk.address, 220 | value: `${5e18}` 221 | }) 222 | }) 223 | 224 | if (!isCpkTransactionManager) { 225 | testConnectedSafeTransactionsWithRelay({ 226 | web3: ueb3, 227 | ...testHelperMaker(isCpkTransactionManager, safeWeb3Box), 228 | async getCPK() { 229 | return cpk 230 | }, 231 | ownerIsRecognizedContract: true, 232 | executor: safeOwnerBox, 233 | defaultAccount: defaultAccountBox 234 | }) 235 | return 236 | } 237 | 238 | testSafeTransactions({ 239 | web3: ueb3, 240 | ...testHelperMaker(isCpkTransactionManager, safeWeb3Box), 241 | async getCPK() { 242 | return cpk 243 | }, 244 | ownerIsRecognizedContract: true, 245 | executor: safeOwnerBox, 246 | defaultAccount: defaultAccountBox, 247 | isCpkTransactionManager, 248 | accountType: AccountType.Connected 249 | }) 250 | }) 251 | }) 252 | }) 253 | } 254 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/web3/testWeb3Adapter.ts: -------------------------------------------------------------------------------- 1 | import Web3Maj1Min3 from 'web3-1-4' 2 | import Web3Maj2Alpha from 'web3-2-alpha' 3 | import { Web3Adapter } from '../../src' 4 | import { Address } from '../../src/utils/basicTypes' 5 | import { testHelperMaker } from './utils' 6 | 7 | interface TestWeb3AdapterProps { 8 | Web3: typeof Web3Maj1Min3 | typeof Web3Maj2Alpha 9 | defaultAccountBox: Address[] 10 | safeOwnerBox: Address[] 11 | } 12 | 13 | export function testWeb3Adapter({ 14 | Web3, 15 | defaultAccountBox, 16 | safeOwnerBox 17 | }: TestWeb3AdapterProps): void { 18 | describe(`with Web3 version ${new Web3(Web3.givenProvider).version}`, () => { 19 | const web3 = new Web3('http://localhost:8545') 20 | const web3Adapter = new Web3Adapter({ web3 }) 21 | const ueb3TestHelpers = testHelperMaker(true, [web3]) 22 | 23 | it('should not produce ethLibAdapter instances when web3 not provided', async () => { 24 | ;((): Web3Adapter => new Web3Adapter({} as any)).should.throw( 25 | 'web3 property missing from options' 26 | ) 27 | }) 28 | 29 | it('should return the ETH balance of an account', async () => { 30 | const address = safeOwnerBox[0] 31 | const initialEthBalance = await web3Adapter.getBalance(address) 32 | const value = `${1e18}` 33 | await ueb3TestHelpers.sendTransaction({ 34 | from: defaultAccountBox[0], 35 | to: address, 36 | value 37 | }) 38 | const finalEthBalance = await web3Adapter.getBalance(address) 39 | finalEthBalance.toString().should.equal(initialEthBalance.plus(value).toString()) 40 | }) 41 | }) 42 | } 43 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/test/web3/utils.ts: -------------------------------------------------------------------------------- 1 | import should from 'should' 2 | import { TransactionResult } from '../../src' 3 | import { Address } from '../../src/utils/basicTypes' 4 | import { AccountType, toTxHashPromise } from '../utils' 5 | 6 | export const testHelperMaker = (isCpkTransactionManager: boolean, web3Box: any): any => ({ 7 | checkAddressChecksum: (address?: Address): boolean => { 8 | if (!address) { 9 | return false 10 | } 11 | return web3Box[0].utils.checkAddressChecksum(address) 12 | }, 13 | sendTransaction: (txObj: any): any => toTxHashPromise(web3Box[0].eth.sendTransaction(txObj)), 14 | randomHexWord: (): string => web3Box[0].utils.randomHex(32), 15 | fromWei: (amount: number): number => Number(web3Box[0].utils.fromWei(amount)), 16 | getTransactionCount: (account: Address): number => web3Box[0].eth.getTransactionCount(account), 17 | testedTxObjProps: 'the PromiEvent for the transaction and the hash', 18 | getBalance: (address: Address): number => 19 | web3Box[0].eth.getBalance(address).then((balance: number) => web3Box[0].utils.toBN(balance)), 20 | checkTxObj: ( 21 | txsSize: number, 22 | accountType: AccountType, 23 | txResult: TransactionResult, 24 | isCpkTransactionManager: boolean 25 | ): void => { 26 | const safeConnected = accountType === AccountType.Connected 27 | should.exist(txResult.hash) 28 | if (!safeConnected || (safeConnected && txsSize === 1)) { 29 | should.exist(txResult.promiEvent) 30 | if (isCpkTransactionManager) { 31 | should.exist(txResult.sendOptions) 32 | } 33 | } 34 | }, 35 | waitTxReceipt: async (txResult: TransactionResult): Promise => { 36 | let receipt = await web3Box[0].eth.getTransactionReceipt(txResult.hash) 37 | while (!receipt) { 38 | await new Promise((resolve) => setTimeout(resolve, 50)) 39 | receipt = await web3Box[0].eth.getTransactionReceipt(txResult.hash) 40 | } 41 | return receipt 42 | }, 43 | waitSafeTxReceipt: async (txResult: TransactionResult): Promise => { 44 | let receipt: any 45 | if (!txResult.promiEvent) return 46 | if (isCpkTransactionManager) { 47 | receipt = await new Promise((resolve, reject) => 48 | txResult.promiEvent 49 | .on('confirmation', (confirmationNumber: any, receipt: any) => resolve(receipt)) 50 | .catch(reject) 51 | ) 52 | } else { 53 | receipt = txResult.promiEvent.transactionHash 54 | } 55 | if (!receipt) return 56 | txResult.hash?.should.equal(receipt.transactionHash) 57 | return receipt 58 | } 59 | }) 60 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/truffle-config.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | require('ts-node/register'); 3 | 4 | const seed = process.env.SEED || 'myth like bonus scare over problem client lizard pioneer submit female collect'; 5 | const HDWalletProvider = require('@truffle/hdwallet-provider'); 6 | 7 | const networks = Object.assign(...[ 8 | [1, 'mainnet', `${1e9}`], 9 | [3, 'ropsten'], 10 | [4, 'rinkeby'], 11 | [5, 'goerli', `${2e9}`], 12 | [42, 'kovan'], 13 | [100, 'dai',, true], 14 | ].map(([networkId, network, gasPrice, isPoa]) => ({ 15 | [network]: { 16 | network_id: networkId, 17 | gasPrice, 18 | provider: () => new HDWalletProvider( 19 | seed, 20 | isPoa ? `https://${network}.poa.network` : `https://${network}.infura.io/v3/17d5bb5953564f589d48d535f573e486`, 21 | ), 22 | }, 23 | })), { 24 | local: { 25 | host: 'localhost', 26 | port: 8545, 27 | network_id: '*', 28 | }, 29 | }); 30 | 31 | module.exports = { 32 | networks, 33 | mocha: { 34 | bail: true, 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/tsconfig.cjs.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "module": "CommonJS", 5 | "outDir": "lib/cjs" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.base.json", 3 | "compilerOptions": { 4 | "declaration": true, 5 | "sourceMap": true, 6 | "target": "ES6", 7 | "module": "ES2020", 8 | "outDir": "./lib/esm" 9 | }, 10 | "include": [ 11 | "./src/**/*.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /packages/contract-proxy-kit/tsconfig.migrate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.cjs.json", 3 | "compilerOptions": { 4 | "outDir": "migrations", 5 | "skipLibCheck": true, 6 | }, 7 | "include": [ 8 | "./migrations-ts", 9 | "./types" 10 | ] 11 | } -------------------------------------------------------------------------------- /packages/cpk-configuration-app/README.md: -------------------------------------------------------------------------------- 1 | ## CPK Configuration App 2 | 3 | An example Dapp using the Gnosis Safe [Contract Proxy Kit](https://github.com/gnosis/contract-proxy-kit) which works as a Safe App or a standalone app. This Dapp serves as an example to show the different states and functionality of the *CPK*. 4 | 5 | Only available for Rinkeby network at this moment. 6 | 7 | App can be found live here: https://cpk-app.surge.sh. 8 | 9 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 10 | 11 | ## Useful links 12 | 13 | - [Video introduction to Building with Safe Apps SDK & Contract Proxy Kit](https://www.youtube.com/watch?v=YGw8WfBw5OI) 14 | - [Contract Proxy Kit documentation](https://github.com/gnosis/contract-proxy-kit/tree/master/packages/contract-proxy-kit) 15 | 16 | ## Available Scripts 17 | 18 | In the project directory, you can run: 19 | 20 | ### `yarn start` 21 | 22 | Runs the app in the development mode.
23 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 24 | 25 | The page will reload if you make edits.
26 | You will also see any lint errors in the console. 27 | 28 | ### `yarn build` 29 | 30 | Builds the app for production to the `build` folder.
31 | It correctly bundles React in production mode and optimizes the build for the best performance. 32 | 33 | The build is minified and the filenames include the hashes.
34 | Your app is ready to be deployed! 35 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cpk-configuration-app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@gnosis.pm/safe-react-components": "^0.3.0", 7 | "@material-ui/core": "^4.11.3", 8 | "@walletconnect/web3-provider": "^1.3.6", 9 | "bignumber.js": "^9.0.1", 10 | "contract-proxy-kit": "file:../contract-proxy-kit", 11 | "keccak256": "^1.0.2", 12 | "prettier": "^2.2.1", 13 | "react": "^17.0.1", 14 | "react-dom": "^17.0.1", 15 | "react-scripts": "4.0.2", 16 | "styled-components": "^5.2.1", 17 | "typescript": "^4.1.5", 18 | "web3": "1.3.4", 19 | "web3connect": "^1.0.0-beta.33", 20 | "web3modal": "^1.9.3" 21 | }, 22 | "scripts": { 23 | "start": "react-scripts start", 24 | "build": "react-scripts build", 25 | "test": "react-scripts test", 26 | "format": "prettier --write src/**/*.{js,jsx,ts,tsx,json}", 27 | "deploy": "react-scripts build && surge --project=build --domain=https://cpk-app.surge.sh" 28 | }, 29 | "author": "Gnosis (https://gnosis.io)", 30 | "license": "MIT", 31 | "bugs": { 32 | "url": "https://github.com/gnosis/contract-proxy-kit/issues" 33 | }, 34 | "eslintConfig": { 35 | "extends": "react-app" 36 | }, 37 | "browserslist": { 38 | "production": [ 39 | ">0.2%", 40 | "not dead", 41 | "not op_mini all" 42 | ], 43 | "development": [ 44 | "last 1 chrome version", 45 | "last 1 firefox version", 46 | "last 1 safari version" 47 | ] 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/public/CORS: -------------------------------------------------------------------------------- 1 | * 2 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5afe/contract-proxy-kit/cfc799fba5f4c3d0f1d90d32a5ff1ea70b4e0bbe/packages/cpk-configuration-app/public/favicon.ico -------------------------------------------------------------------------------- /packages/cpk-configuration-app/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | CPK Manager 15 | 16 | 17 | 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5afe/contract-proxy-kit/cfc799fba5f4c3d0f1d90d32a5ff1ea70b4e0bbe/packages/cpk-configuration-app/public/logo192.png -------------------------------------------------------------------------------- /packages/cpk-configuration-app/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5afe/contract-proxy-kit/cfc799fba5f4c3d0f1d90d32a5ff1ea70b4e0bbe/packages/cpk-configuration-app/public/logo512.png -------------------------------------------------------------------------------- /packages/cpk-configuration-app/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "CPK Manager", 3 | "name": "CPK Manager", 4 | "description": "Web app to configure and try the CPK", 5 | "iconPath": "logo512.png", 6 | "icons": [ 7 | { 8 | "src": "favicon.ico", 9 | "sizes": "64x64 32x32 24x24 16x16", 10 | "type": "image/x-icon" 11 | }, 12 | { 13 | "src": "logo192.png", 14 | "type": "image/png", 15 | "sizes": "192x192" 16 | }, 17 | { 18 | "src": "logo512.png", 19 | "type": "image/png", 20 | "sizes": "512x512" 21 | } 22 | ], 23 | "start_url": ".", 24 | "display": "standalone", 25 | "theme_color": "#000000", 26 | "background_color": "#ffffff" 27 | } 28 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/assets/images/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/components/App/index.tsx: -------------------------------------------------------------------------------- 1 | import { Tab, TabItem, Title } from '@gnosis.pm/safe-react-components' 2 | import BigNumber from 'bignumber.js' 3 | import CpkInfo from 'components/CpkInfo' 4 | import SafeModules from 'components/SafeModules' 5 | import Transactions from 'components/Transactions' 6 | import CPK, { 7 | RocksideSpeed, 8 | RocksideTxRelayManager, 9 | TransactionManagerConfig, 10 | Web3Adapter 11 | } from 'contract-proxy-kit' 12 | import keccak256 from 'keccak256' 13 | import React, { useEffect, useState } from 'react' 14 | import styled from 'styled-components' 15 | import Web3 from 'web3' 16 | import ConnectButton from '../ConnectButton' 17 | 18 | const Container = styled.div` 19 | width: 550px; 20 | padding: 20px; 21 | margin: 0 auto; 22 | border: 1px solid #ccc; 23 | border-radius: 5px; 24 | ` 25 | 26 | const TitleLine = styled.div` 27 | display: flex; 28 | justify-content: space-between; 29 | align-items: center; 30 | h4 { 31 | margin: 0 !important; 32 | } 33 | ` 34 | 35 | const Content = styled.div` 36 | margin-top: 30px; 37 | ` 38 | 39 | export interface WalletState { 40 | isSafeApp?: boolean 41 | isConnectedToSafe?: boolean 42 | isProxyDeployed?: boolean 43 | saltNonce?: string 44 | contractVersion?: string 45 | cpkAddress?: string 46 | cpkBalance?: BigNumber 47 | networkId?: number 48 | ownerAddress?: string 49 | txManager?: TransactionManagerConfig 50 | } 51 | 52 | const initialWalletState: WalletState = { 53 | isSafeApp: undefined, 54 | isConnectedToSafe: undefined, 55 | isProxyDeployed: undefined, 56 | saltNonce: undefined, 57 | contractVersion: undefined, 58 | cpkAddress: undefined, 59 | cpkBalance: undefined, 60 | networkId: undefined, 61 | ownerAddress: undefined, 62 | txManager: undefined 63 | } 64 | 65 | const tabs: TabItem[] = [ 66 | { 67 | id: '1', 68 | label: 'CPK Info', 69 | icon: 'info' 70 | }, 71 | { 72 | id: '2', 73 | label: 'CPK Transactions', 74 | icon: 'transactionsInactive' 75 | }, 76 | { 77 | id: '3', 78 | label: 'CPK Modules', 79 | icon: 'apps' 80 | } 81 | ] 82 | 83 | const App = () => { 84 | const [selectedTab, setSelectedTab] = useState('1') 85 | const [enabledRocksideTxRelay, setEnabledRocksideTxRelay] = useState(false) 86 | const [web3, setWeb3] = React.useState(undefined) 87 | const [saltNonce, setSaltNonce] = React.useState('Contract Proxy Kit') 88 | const [cpk, setCpk] = useState(undefined) 89 | const [walletState, updateWalletState] = useState( 90 | initialWalletState 91 | ) 92 | 93 | const onWeb3Connect = (provider: any) => { 94 | if (provider) { 95 | setWeb3(new Web3(provider)) 96 | } 97 | } 98 | 99 | useEffect(() => { 100 | const initializeCpk = async () => { 101 | if (!web3) return 102 | let formatedSaltNonce = saltNonce 103 | if (saltNonce) { 104 | formatedSaltNonce = '0x' + keccak256(saltNonce).toString('hex') 105 | } 106 | const ethLibAdapter = new Web3Adapter({ web3 }) 107 | 108 | /* 109 | Safe contracts are not officially deployed on Ropsten. This means that in 110 | order to test Rockside's transaction relay (only available on Mainnet and 111 | Ropsten networks) we have to pass the contract addresses as a parameter 112 | when using the CPK. 113 | These are an exmaple of the Safe contracts deployed on Ropsten and there is 114 | no need to provide the contract addresses for Mainnet. 115 | */ 116 | const networks = { 117 | 3: { 118 | masterCopyAddress: '0x798960252148C0215F593c14b7c5B07183826212', 119 | proxyFactoryAddress: '0x8240eE136011392736920419cB7CB8bBadAc27E4', 120 | multiSendAddress: '0xe637DE43c1702fd59A2E7ab8F4224C7CBb0e9D3D', 121 | fallbackHandlerAddress: '0x83B1CB4017acf298b9Ff47FC4e380282738406B2' 122 | } 123 | } 124 | let transactionManager: RocksideTxRelayManager | undefined 125 | if (enabledRocksideTxRelay) { 126 | transactionManager = new RocksideTxRelayManager({ 127 | speed: RocksideSpeed.Fastest 128 | }) 129 | } 130 | 131 | let newCpk 132 | try { 133 | newCpk = await CPK.create({ 134 | ethLibAdapter, 135 | networks, 136 | saltNonce: formatedSaltNonce, 137 | transactionManager 138 | }) 139 | } catch (error: any) { 140 | alert('Try with a different network') 141 | console.error(error) 142 | return 143 | } 144 | setCpk(newCpk) 145 | } 146 | initializeCpk() 147 | }, [web3, saltNonce, enabledRocksideTxRelay]) 148 | 149 | useEffect(() => { 150 | const updateCpk = async () => { 151 | if (!cpk) return 152 | const isProxyDeployed = await cpk.isProxyDeployed() 153 | const contractVersion = isProxyDeployed 154 | ? await cpk.getContractVersion() 155 | : undefined 156 | 157 | updateWalletState({ 158 | isSafeApp: cpk.safeAppsSdkConnector?.isSafeApp, 159 | isConnectedToSafe: cpk.isConnectedToSafe, 160 | isProxyDeployed, 161 | saltNonce: await cpk.saltNonce, 162 | contractVersion, 163 | cpkAddress: await cpk.address, 164 | cpkBalance: await cpk.getBalance(), 165 | networkId: await cpk.getNetworkId(), 166 | ownerAddress: await cpk.getOwnerAccount() 167 | }) 168 | } 169 | updateCpk() 170 | }, [cpk]) 171 | 172 | return ( 173 | 174 | 175 | CPK Configuration App 176 | 177 | 178 | {cpk && ( 179 | 180 | 186 | {selectedTab === '1' && ( 187 | 192 | )} 193 | {selectedTab === '2' && ( 194 | 200 | )} 201 | {selectedTab === '3' && ( 202 | 203 | )} 204 | 205 | )} 206 | 207 | ) 208 | } 209 | 210 | export default App 211 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/components/ConnectButton/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import styled from 'styled-components' 3 | import Web3Connect from 'web3connect' 4 | 5 | const Web3ConnectButton = styled.div` 6 | display: flex; 7 | justify-content: center; 8 | width: 180px; 9 | & > div { 10 | padding: 0; 11 | } 12 | .web3connect-connect-button { 13 | outline: none; 14 | background: #008c73; 15 | border-radius: 4px; 16 | color: #fff; 17 | cursor: pointer; 18 | transform: none; 19 | font-weight: normal; 20 | font-size: 14px; 21 | box-shadow: none; 22 | } 23 | .web3connect-connect-button:hover { 24 | background: #005546; 25 | box-shadow: none; 26 | transform: none; 27 | } 28 | ` 29 | 30 | const { 31 | default: WalletConnectProvider 32 | } = require('@walletconnect/web3-provider') 33 | 34 | type ConnectButtonProps = { 35 | onConnect: Function 36 | } 37 | 38 | const ConnectButton = ({ onConnect }: ConnectButtonProps) => ( 39 | 40 | {}} 51 | /> 52 | 53 | ) 54 | 55 | export default ConnectButton 56 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/components/CpkInfo/index.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | EthHashInfo, 3 | Text, 4 | TextField, 5 | Title 6 | } from '@gnosis.pm/safe-react-components' 7 | import { WalletState } from 'components/App' 8 | import React from 'react' 9 | import styled from 'styled-components' 10 | import { formatBalance } from 'utils/balances' 11 | import { getNetworkNameFromId } from 'utils/networks' 12 | 13 | const Line = styled.div` 14 | display: flex; 15 | align-items: center; 16 | min-height: 45px; 17 | ` 18 | 19 | const TitleLine = styled.div` 20 | margin-right: 10px; 21 | ` 22 | 23 | const STextField = styled(TextField)` 24 | width: 600px !important; 25 | ` 26 | 27 | interface CpkInfoProps { 28 | walletState: WalletState 29 | saltNonce: string 30 | setSaltNonce: Function 31 | } 32 | 33 | const CpkInfo = ({ walletState, saltNonce, setSaltNonce }: CpkInfoProps) => { 34 | return ( 35 | <> 36 | Information 37 | 38 | 39 | 40 | Network: 41 | 42 | 43 | 44 | {walletState?.networkId && 45 | getNetworkNameFromId(walletState?.networkId)} 46 | 47 | 48 | 49 | 50 | 51 | Running as a: 52 | 53 | 54 | 55 | {walletState?.isSafeApp ? 'Safe App' : 'Standalone App'} 56 | 57 | 58 | 59 | 60 | 61 | Connected to: 62 | 63 | 64 | 65 | {walletState?.isConnectedToSafe ? 'Safe account' : 'EOA'} 66 | 67 | 68 | 69 | 70 | 71 | State of the Proxy: 72 | 73 | 74 | 75 | {walletState?.isProxyDeployed 76 | ? `Deployed ${ 77 | walletState?.contractVersion && 78 | `(v${walletState?.contractVersion})` 79 | }` 80 | : 'Not deployed'} 81 | 82 | 83 | 84 | 85 | 86 | Owner address: 87 | 88 | 89 | {walletState?.ownerAddress && ( 90 | 98 | )} 99 | 100 | 101 | 102 | 103 | CPK address: 104 | 105 | 106 | {walletState?.cpkAddress && ( 107 | 115 | )} 116 | 117 | 118 | 119 | 120 | CPK Balance: 121 | 122 | 123 | {formatBalance(walletState?.cpkBalance)} 124 | 125 | 126 | 127 | 128 | CPK salt nonce: 129 | 130 | 131 | {walletState?.saltNonce && ( 132 | 138 | )} 139 | 140 | Configuration 141 | 142 | setSaltNonce(e.target.value)} 147 | /> 148 | 149 | 150 | ) 151 | } 152 | 153 | export default CpkInfo 154 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/components/SafeModules/index.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | Button, 3 | Card, 4 | EthHashInfo, 5 | Loader, 6 | Table, 7 | TableHeader, 8 | TableRow, 9 | Text, 10 | TextField, 11 | Title 12 | } from '@gnosis.pm/safe-react-components' 13 | import { WalletState } from 'components/App' 14 | import CPK, { TransactionResult } from 'contract-proxy-kit' 15 | import React, { useCallback, useEffect, useState } from 'react' 16 | import styled from 'styled-components' 17 | import { getNetworkNameFromId } from 'utils/networks' 18 | 19 | const Line = styled.div` 20 | display: flex; 21 | align-items: center; 22 | height: 40px; 23 | ` 24 | 25 | const TitleLine = styled.div` 26 | margin-right: 10px; 27 | ` 28 | 29 | const BigLine = styled.div` 30 | display: flex; 31 | align-items: center; 32 | justify-content: space-between; 33 | margin-top: 20px; 34 | ` 35 | 36 | const SButton = styled(Button)` 37 | width: 242px; 38 | ` 39 | 40 | const STextField = styled(TextField)` 41 | width: 600px !important; 42 | ` 43 | 44 | const SCard = styled(Card)` 45 | width: 100%; 46 | display: flex; 47 | justify-content: center; 48 | ` 49 | 50 | interface SafeModulesProps { 51 | cpk: CPK 52 | walletState: WalletState 53 | } 54 | 55 | const headers: TableHeader[] = [ 56 | { 57 | id: '1', 58 | label: 'Enabled modules' 59 | } 60 | ] 61 | 62 | const SafeModules = ({ cpk, walletState }: SafeModulesProps) => { 63 | const [module, setModule] = useState('') 64 | const [txHash, setTxHash] = useState() 65 | const [safeTxHash, setSafeTxHash] = useState() 66 | const [showTxError, setShowTxError] = useState(false) 67 | const [isLoading, setIsLoading] = useState(false) 68 | const [rows, setRows] = useState([]) 69 | 70 | const getModules = useCallback(async () => { 71 | try { 72 | const modules = await cpk.getModules() 73 | const newRows: TableRow[] = modules.map((module, index) => ({ 74 | id: index.toString(), 75 | cells: [{ content: module }] 76 | })) 77 | setRows(newRows) 78 | } catch (error) { 79 | console.error(error) 80 | } 81 | }, [cpk]) 82 | 83 | useEffect(() => { 84 | getModules() 85 | }, [getModules]) 86 | 87 | const enableModule = async (): Promise => { 88 | if (!module) return 89 | let txResult 90 | setShowTxError(false) 91 | setTxHash('') 92 | 93 | try { 94 | txResult = await cpk.enableModule(module) 95 | } catch (e) { 96 | console.error(e) 97 | setShowTxError(true) 98 | return 99 | } 100 | 101 | await handleTxResult(txResult) 102 | } 103 | 104 | const disableModule = async (): Promise => { 105 | if (!module) return 106 | let txResult 107 | 108 | setShowTxError(false) 109 | setTxHash('') 110 | 111 | try { 112 | txResult = await cpk.disableModule(module) 113 | } catch (e) { 114 | console.error(e) 115 | setShowTxError(true) 116 | return 117 | } 118 | 119 | await handleTxResult(txResult) 120 | } 121 | 122 | const handleTxResult = async (txResult: TransactionResult) => { 123 | let txServiceModel 124 | 125 | if (txResult?.safeTxHash) { 126 | setSafeTxHash(txResult.safeTxHash) 127 | txServiceModel = await cpk.safeAppsSdkConnector?.getBySafeTxHash( 128 | txResult.safeTxHash 129 | ) 130 | } 131 | if (txResult?.hash || txServiceModel) { 132 | setTxHash(txResult.hash || txServiceModel?.transactionHash) 133 | } 134 | 135 | setIsLoading(true) 136 | await new Promise((resolve, reject) => 137 | txResult?.promiEvent 138 | ?.then((receipt: any) => resolve(receipt)) 139 | .catch(reject) 140 | ) 141 | await getModules() 142 | setIsLoading(false) 143 | } 144 | 145 | return ( 146 | <> 147 | Safe modules 148 | 149 | 150 | Test module available on Rinkeby: 151 | 152 | 160 | 161 | 162 | setModule(e.target.value)} 167 | /> 168 | 169 | 170 | 176 | Enable module 177 | 178 | 184 | Disable module 185 | 186 | 187 | {showTxError && ( 188 | 189 | 190 | Transaction rejected 191 | 192 | 193 | )} 194 | {txHash && ( 195 | 196 | 197 | 198 | Transaction hash: 199 | 200 | 201 | 209 | 210 | )} 211 | {safeTxHash && ( 212 | 213 | 214 | 215 | Safe transaction hash: 216 | 217 | 218 | 225 | 226 | )} 227 | {isLoading ? ( 228 | 229 | 230 | 231 | 232 | 233 | ) : ( 234 | 235 | {rows.length > 0 ? ( 236 | 237 | ) : ( 238 | 239 | No modules enabled 240 | 241 | )} 242 | 243 | )} 244 | 245 | ) 246 | } 247 | 248 | export default SafeModules 249 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/components/Transactions/index.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | Button, 3 | Checkbox, 4 | EthHashInfo, 5 | Text, 6 | Title 7 | } from '@gnosis.pm/safe-react-components' 8 | import { WalletState } from 'components/App' 9 | import CPK from 'contract-proxy-kit' 10 | import React, { useState } from 'react' 11 | import styled from 'styled-components' 12 | import { formatBalance } from 'utils/balances' 13 | import { getNetworkNameFromId } from 'utils/networks' 14 | 15 | const Line = styled.div` 16 | display: flex; 17 | align-items: center; 18 | padding: 10px 0; 19 | ` 20 | 21 | const SLine = styled(Line)` 22 | padding: 0; 23 | ` 24 | 25 | const SButton = styled(Button)` 26 | width: 100%; 27 | ` 28 | 29 | const TitleLine = styled.div` 30 | margin-right: 10px; 31 | ` 32 | 33 | interface TransactionsProps { 34 | cpk: CPK 35 | walletState: WalletState 36 | enabledRocksideTxRelay: boolean 37 | setEnabledRocksideTxRelay: Function 38 | } 39 | 40 | const Transactions = ({ 41 | cpk, 42 | walletState, 43 | enabledRocksideTxRelay, 44 | setEnabledRocksideTxRelay 45 | }: TransactionsProps) => { 46 | const [txHash, setTxHash] = useState() 47 | const [safeTxHash, setSafeTxHash] = useState() 48 | const [showTxError, setShowTxError] = useState(false) 49 | 50 | const makeTransaction = async (): Promise => { 51 | if (!walletState.ownerAddress) return 52 | let txResult 53 | setShowTxError(false) 54 | setTxHash('') 55 | 56 | const txs = [ 57 | { 58 | to: walletState.ownerAddress, 59 | value: `${11e17}` 60 | } 61 | ] 62 | try { 63 | txResult = await cpk.execTransactions(txs) 64 | } catch (e) { 65 | console.error(e) 66 | setShowTxError(true) 67 | } 68 | 69 | if (txResult?.safeTxHash) { 70 | setSafeTxHash(txResult.safeTxHash) 71 | } 72 | if (txResult?.hash) { 73 | setTxHash(txResult.hash) 74 | } 75 | } 76 | 77 | const getTransactionHashIfSafeApp = async () => { 78 | if (!safeTxHash) return 79 | const safeTransaction = await cpk.safeAppsSdkConnector?.getBySafeTxHash( 80 | safeTxHash 81 | ) 82 | setTxHash(safeTransaction?.transactionHash) 83 | } 84 | 85 | return ( 86 | <> 87 | Information 88 | 89 | 90 | 91 | CPK Balance: 92 | 93 | 94 | {formatBalance(walletState?.cpkBalance)} 95 | 96 | Configuration 97 | 98 | setEnabledRocksideTxRelay(checked)} 102 | label="Use Rockside transaction relay" 103 | /> 104 | 105 | Transactions 106 | 107 | 113 | Send 1.1 ETH to the CPK owner 114 | 115 | 116 | {showTxError && ( 117 | 118 | 119 | Transaction rejected 120 | 121 | 122 | )} 123 | {safeTxHash && ( 124 | 125 | 126 | 127 | Safe transaction hash: 128 | 129 | 130 | 137 | 138 | )} 139 | {walletState.isSafeApp && safeTxHash && ( 140 | 141 | 147 | Get transaction hash 148 | 149 | 150 | )} 151 | {txHash && ( 152 | 153 | 154 | 155 | Transaction hash: 156 | 157 | 158 | 166 | 167 | )} 168 | 169 | ) 170 | } 171 | 172 | export default Transactions 173 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/index.tsx: -------------------------------------------------------------------------------- 1 | import { theme } from '@gnosis.pm/safe-react-components' 2 | import React from 'react' 3 | import ReactDOM from 'react-dom' 4 | import { ThemeProvider } from 'styled-components' 5 | import GlobalStyle from 'styles/globalStyles' 6 | import App from './components/App' 7 | import * as serviceWorker from './serviceWorker' 8 | 9 | ReactDOM.render( 10 | 11 | 12 | 13 | 14 | 15 | , 16 | document.getElementById('root') 17 | ) 18 | 19 | // If you want your app to work offline and load faster, you can change 20 | // unregister() to register() below. Note this comes with some pitfalls. 21 | // Learn more about service workers: https://bit.ly/CRA-PWA 22 | serviceWorker.unregister() 23 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ) 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href) 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js` 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config) 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ) 48 | }) 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config) 52 | } 53 | }) 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then((registration) => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing 63 | if (installingWorker == null) { 64 | return 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ) 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration) 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.') 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration) 90 | } 91 | } 92 | } 93 | } 94 | } 95 | }) 96 | .catch((error) => { 97 | console.error('Error during service worker registration:', error) 98 | }) 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' } 105 | }) 106 | .then((response) => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type') 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then((registration) => { 115 | registration.unregister().then(() => { 116 | window.location.reload() 117 | }) 118 | }) 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config) 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ) 128 | }) 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready 134 | .then((registration) => { 135 | registration.unregister() 136 | }) 137 | .catch((error) => { 138 | console.error(error.message) 139 | }) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect' 6 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/styles/globalStyles.ts: -------------------------------------------------------------------------------- 1 | import avertaBoldFont from '@gnosis.pm/safe-react-components/dist/fonts/averta-bold.woff2' 2 | import avertaFont from '@gnosis.pm/safe-react-components/dist/fonts/averta-normal.woff2' 3 | import { createGlobalStyle } from 'styled-components' 4 | 5 | const GlobalStyle = createGlobalStyle` 6 | * { 7 | margin: 0; 8 | padding: 0; 9 | box-sizing: border-box; 10 | } 11 | 12 | html, body { 13 | margin: 0; 14 | padding: 0; 15 | } 16 | 17 | body { 18 | padding: 10px; 19 | } 20 | 21 | @font-face { 22 | font-family: 'Averta'; 23 | font-display: swap; 24 | src: local('Averta'), local('Averta Bold'), 25 | url(${avertaFont}) format('woff2'), 26 | url(${avertaBoldFont}) format('woff'); 27 | } 28 | 29 | h4 { 30 | color: #008c73; 31 | margin: 20px 0 10px 0 !important; 32 | } 33 | ` 34 | 35 | export default GlobalStyle 36 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/types/fonts.d.ts: -------------------------------------------------------------------------------- 1 | declare module '*.woff' 2 | declare module '*.woff2' 3 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/utils/balances.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js' 2 | 3 | export const formatBalance = (balance: BigNumber | undefined): string => { 4 | if (!balance) { 5 | return '0 ETH' 6 | } 7 | const ethDecimals = new BigNumber(10).pow(18) 8 | return balance.div(ethDecimals).decimalPlaces(7).toString() + ' ETH' 9 | } 10 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/src/utils/networks.ts: -------------------------------------------------------------------------------- 1 | type Networks = { 2 | [key: number]: string 3 | } 4 | 5 | export const getNetworkNameFromId = ( 6 | networkId?: number 7 | ): string | undefined => { 8 | if (!networkId) return 9 | const networks: Networks = { 10 | 1: 'Mainnet', 11 | 2: 'Morden', 12 | 3: 'Ropsten', 13 | 4: 'Rinkeby', 14 | 5: 'Goerli', 15 | 42: 'Kovan', 16 | 100: 'xDai', 17 | 246: 'Energy Web Chain', 18 | 73799: 'Volta (Energy Web Chain)' 19 | } 20 | return networks[networkId] 21 | } 22 | -------------------------------------------------------------------------------- /packages/cpk-configuration-app/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.base.json", 3 | "compilerOptions": { 4 | "baseUrl": "src", 5 | "jsx": "react-jsx", 6 | "lib": [ 7 | "es6", 8 | "dom" 9 | ], 10 | "module": "ESNext", 11 | "noEmit": true, 12 | "target": "ESNext", 13 | "allowJs": true 14 | }, 15 | "include": [ 16 | "src" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": true, 4 | "esModuleInterop": true, 5 | "forceConsistentCasingInFileNames": true, 6 | "isolatedModules": true, 7 | "moduleResolution": "node", 8 | "noFallthroughCasesInSwitch": true, 9 | "noImplicitThis": true, 10 | "resolveJsonModule": true, 11 | "skipLibCheck": true, 12 | "strict": true, 13 | "strictBindCallApply": true, 14 | "strictFunctionTypes": true, 15 | "strictNullChecks": true, 16 | }, 17 | "include": [ 18 | "packages/*/src" 19 | ] 20 | } 21 | --------------------------------------------------------------------------------