add version 2

pull/4/head
Tisamenus 1 year ago
parent 066f5e1dbf
commit f13858761c

@ -7,4 +7,3 @@ end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
ยฉ 2020 GitHub, Inc.

@ -0,0 +1,6 @@
etherscan_api_key=
goerli_rpc_key=
mainnet_rpc_key=
goerli_account_pk=
mainnet_account_pk=
use_latest_block=false

@ -5,7 +5,7 @@
"es6": true,
"mocha": true
},
"extends": "eslint:recommended",
"extends": ["eslint:recommended", "plugin:prettier/recommended", "prettier"],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
@ -21,6 +21,7 @@
"semi": ["error", "never"],
"object-curly-spacing": ["error", "always"],
"comma-dangle": ["error", "always-multiline"],
"require-await": "error"
"require-await": "error",
"prettier/prettier": ["error", { "printWidth": 110 }]
}
}

@ -9,74 +9,19 @@ on:
jobs:
build:
runs-on: ubuntu-latest
env:
etherscan_api_key: ${{ secrets.ETHERSCAN_API_KEY }}
goerli_rpc_key: ${{ secrets.GOERLI_RPC_KEY }}
mainnet_rpc_key: ${{ secrets.MAINNET_RPC_KEY }}
goerli_account_pk: ${{ secrets.GOERLI_ACCOUNT_PK }}
mainnet_account_pk: ${{ secrets.MAINNET_ACCOUNT_PK }}
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
node-version: 14
- run: yarn install
- run: yarn test
- run: yarn hardhat compile
- run: yarn lint
- name: Telegram Failure Notification
uses: appleboy/telegram-action@0.0.7
if: failure()
with:
message: โ— Build failed for [${{ github.repository }}](https://github.com/${{ github.repository }}/actions) because of ${{ github.actor }}
format: markdown
to: ${{ secrets.TELEGRAM_CHAT_ID }}
token: ${{ secrets.TELEGRAM_BOT_TOKEN }}
publish:
runs-on: ubuntu-latest
needs: build
if: startsWith(github.ref, 'refs/tags')
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install dependencies
run: yarn install
- name: NPM login
# NPM doesn't understand env vars and needs auth file lol
run: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Set vars
id: vars
run: |
echo "::set-output name=version::$(echo ${GITHUB_REF#refs/tags/v})"
echo "::set-output name=repo_name::$(echo ${GITHUB_REPOSITORY#*/})"
- name: Check package.json version vs tag
run: |
[ ${{ steps.vars.outputs.version }} = $(grep '"version":' package.json | grep -o "[0-9.]*") ] || (echo "Git tag doesn't match version in package.json" && false)
- name: Publish to npm
run: npm publish
- name: Create GitHub Release Draft
uses: actions/create-release@v1
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ steps.vars.outputs.version }}
draft: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Telegram Notification
uses: appleboy/telegram-action@0.0.7
with:
message: ๐Ÿš€ Published [${{ steps.vars.outputs.repo_name }}](https://github.com/${{ github.repository }}) version [${{ steps.vars.outputs.version }}](https://www.npmjs.com/package/${{ steps.vars.outputs.repo_name }}/v/${{ steps.vars.outputs.version }}) to npm
format: markdown
to: ${{ secrets.TELEGRAM_CHAT_ID }}
token: ${{ secrets.TELEGRAM_BOT_TOKEN }}
- name: Telegram Failure Notification
uses: appleboy/telegram-action@0.0.7
if: failure()
with:
message: โ— Failed to publish [${{ steps.vars.outputs.repo_name }}](https://github.com/${{ github.repository }}/actions) because of ${{ github.actor }}
format: markdown
to: ${{ secrets.TELEGRAM_CHAT_ID }}
token: ${{ secrets.TELEGRAM_BOT_TOKEN }}
- run: yarn hardhat test

101
.gitignore vendored

@ -1,99 +1,6 @@
node_modules
cache
artifacts
build
.vscode
/index.js
flats/*
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
ERC20Tornado_flat.sol
ETHTornado_flat.sol
dist
.env

@ -0,0 +1 @@
14

@ -1,3 +1,8 @@
.vscode
.idea
cache
artifacts
build
scripts
dist
README.md
contracts/v2-vault-and-gas/libraries/EtherSend.sol

@ -1,13 +1,14 @@
# Tornado.Cash Governance [![Build Status](https://github.com/tornadocash/tornado-governance/workflows/build/badge.svg)](https://github.com/tornadocash/tornado-governance/actions) [![npm](https://img.shields.io/npm/v/tornado-governance)](https://www.npmjs.com/package/tornado-governance)
# tornado-governance
Usage:
## Description
This repository holds all the tornado.cash governance upgrade and original governance contracts.
The highest governance version right now is version 2, which includes a gas and vault upgrade.
```
## Setup
```bash
git clone https://github.com/tornadocash/tornado-governance.git
yarn
cp .env.example .env
cp .env.example .env # you must enter your details into .env
yarn test
```
## How to upgrade implementation
1. Make sure once you deploy new Governance implementation, call `initialize` methods right after it.
```

@ -1,5 +0,0 @@
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "torn-token/contracts/mocks/TORNMock.sol";

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
@ -20,7 +22,7 @@ contract Configuration {
/// @notice If the outcome of a proposal changes during CLOSING_PERIOD, the vote will be extended by VOTE_EXTEND_TIME (no more than once)
uint256 public VOTE_EXTEND_TIME;
modifier onlySelf {
modifier onlySelf() {
require(msg.sender == address(this), "Governance: unauthorized");
_;
}
@ -29,7 +31,7 @@ contract Configuration {
EXECUTION_DELAY = 2 days;
EXECUTION_EXPIRATION = 3 days;
QUORUM_VOTES = 25000e18; // 0.25% of TORN
PROPOSAL_THRESHOLD = 1000e18; // 0.01% of TORN
PROPOSAL_THRESHOLD = 10000e18; // 0.1% of TORN
VOTING_DELAY = 75 seconds;
VOTING_PERIOD = 3 days;
CLOSING_PERIOD = 1 hours;

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
@ -13,7 +15,15 @@ import "./Configuration.sol";
contract Governance is Initializable, Configuration, Delegation, EnsResolve {
using SafeMath for uint256;
/// @notice Possible states that a proposal may be in
enum ProposalState { Pending, Active, Defeated, Timelocked, AwaitingExecution, Executed, Expired }
enum ProposalState {
Pending,
Active,
Defeated,
Timelocked,
AwaitingExecution,
Executed,
Expired
}
struct Proposal {
// Creator of the proposal
@ -79,8 +89,8 @@ contract Governance is Initializable, Configuration, Delegation, EnsResolve {
_initializeConfiguration();
}
function initialize(bytes32 _torn) public initializer {
torn = TORN(resolve(_torn));
function initialize(address _torn) public initializer {
torn = TORN(_torn);
// Create a dummy proposal so that indexes start from 1
proposals.push(
Proposal({
@ -172,7 +182,7 @@ contract Governance is Initializable, Configuration, Delegation, EnsResolve {
return proposalId;
}
function execute(uint256 proposalId) external virtual payable {
function execute(uint256 proposalId) external payable virtual {
require(state(proposalId) == ProposalState.AwaitingExecution, "Governance::execute: invalid proposal state");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
@ -274,7 +284,7 @@ contract Governance is Initializable, Configuration, Delegation, EnsResolve {
return proposals.length - 1;
}
function getBlockTimestamp() internal virtual view returns (uint256) {
function getBlockTimestamp() internal view virtual returns (uint256) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}

@ -1,4 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol";
@ -12,11 +13,7 @@ contract LoopbackProxy is TransparentUpgradeableProxy, EnsResolve {
/**
* @dev Initializes an upgradeable proxy backed by the implementation at `_logic`.
*/
constructor(bytes32 _logic, bytes memory _data)
public
payable
TransparentUpgradeableProxy(resolve(_logic), address(this), _data)
{}
constructor(address _logic, bytes memory _data) public payable TransparentUpgradeableProxy(_logic, address(this), _data) {}
/**
* @dev Override to allow admin (itself) access the fallback function.

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
@ -11,12 +13,16 @@ contract MockGovernance is Governance {
time = time_;
}
function getBlockTimestamp() internal override view returns (uint256) {
function getBlockTimestamp() internal view override returns (uint256) {
// solium-disable-next-line security/no-block-members
return time;
}
function resolve(bytes32 addr) public override view returns (address) {
function setTorn(address torna) external {
torn = TORN(torna);
}
function resolve(bytes32 addr) public view override returns (address) {
return address(uint160(uint256(addr) >> (12 * 8)));
}
}

@ -1,12 +1,14 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../LoopbackProxy.sol";
contract MockProxy is LoopbackProxy {
constructor(bytes32 _logic, bytes memory _data) public payable LoopbackProxy(_logic, _data) {}
constructor(address _logic, bytes memory _data) public payable LoopbackProxy(_logic, _data) {}
function resolve(bytes32 addr) public override view returns (address) {
function resolve(bytes32 addr) public view override returns (address) {
return address(uint160(uint256(addr) >> (12 * 8)));
}
}

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

@ -1,3 +1,5 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
@ -12,14 +14,20 @@ contract NewImplementation is MockGovernance {
uint256 public newVariable;
event Overriden(uint256 x);
function execute(uint256 proposalId) public override payable {
function execute(uint256 proposalId) public payable override {
newVariable = 999;
emit Overriden(proposalId);
}
}
contract ProposalUpgrade {
address public immutable newLogic;
constructor(address _newLogic) public {
newLogic = _newLogic;
}
function executeProposal() public {
IProxy(address(this)).upgradeTo(0xF7E3e47e06F1bDDecb1b2F3a7F60b6b25fd2e233);
IProxy(address(this)).upgradeTo(newLogic);
}
}

@ -0,0 +1,33 @@
// SPDX-License-Identifier: MIT
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "torn-token/contracts/mocks/TORNMock.sol";
struct Recipient2 {
address to;
uint256 amount;
}
contract TORNMock2 is TORNMock {
constructor(
address _governance,
uint256 _pausePeriod,
Recipient2[] memory vesting
) public TORNMock(solve(_governance), _pausePeriod, solve2(vesting)) {}
function solve(address x) private returns (bytes32) {
return bytes32(uint256(x) << 96);
}
function solve2(Recipient2[] memory vesting) private returns (Recipient[] memory) {
Recipient[] memory realVesting = new Recipient[](vesting.length);
for (uint256 i = 0; i < vesting.length; i++) {
realVesting[i].to = solve(vesting[i].to);
realVesting[i].amount = vesting[i].amount;
}
return realVesting;
}
}

@ -0,0 +1,39 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
interface IGovernanceMultisigAddress {
function returnMultisigAddress() external pure returns (address);
}
/**
* @notice Contract which hold governance information. Useful for avoiding code duplication.
* */
contract ImmutableGovernanceInformation {
address internal constant GovernanceAddress = 0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce;
address internal constant TornTokenAddress = 0x77777FeDdddFfC19Ff86DB637967013e6C6A116C;
modifier onlyGovernance() {
require(msg.sender == GovernanceAddress, "only governance");
_;
}
/**
* @dev this modifier calls the pure governance returnMultisigAddress() function,
* if governance version is not -> vault-and-gas upgrade <= version
* then this will not work!
*/
modifier onlyMultisig() {
require(msg.sender == IGovernanceMultisigAddress(GovernanceAddress).returnMultisigAddress(), "only multisig");
_;
}
/**
* @notice Function to return a payable version of the governance address.
* @return payable version of the address
* */
function returnPayableGovernance() internal pure returns (address payable) {
return payable(GovernanceAddress);
}
}

@ -0,0 +1,37 @@
# Tornado Governance Changes Documentation
`LotteryAndVaultProposal.sol`, if executed, modifies the tornado.cash governance contract in multiple ways.
This serves as documentation for all functions which are being added or modified and which have relevant functionality:
## Governance (Governance.sol)
The `Governance` contract available in the `tornado-governance` repository modifies the original Governance source code to enable overriding functions via inheritance. This has been submitted via PR.
This is a non issue, as logic and memory slots are left unaffected and properly referenced to. `tornado-governance` is being imported as a package.
## Governance Vault Upgrade (GovernanceVaultUpgrade.sol)
`GovernanceVaultUpgrade` is the first major upgrade to tornado governance. This upgrade introduces new logic which is used to communicate with `TornVault` from the governance contract. The motivation behind this upgrade:
- split DAO member locked TORN from vesting locked TORN.
- block Governance from being able to interact with user TORN.
To solve point 1 of the formerly stated problems, and to reduce the logic bloat of the lock and unlock functionalities, we have opted for calculating the amount of user TORN locked in the governance contract. The calculations and explanations may be found [here](https://github.com/h-ivor/tornado-lottery-period/blob/final_with_auction/scripts/balance_estimation.md).
### Additions and changes
| Function/variable signature | is addition or change? | describe significance |
| ---------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `_transferTokens(address,uint256)` | change | instead of transferring to the governance contract, funds are now transferred to the torn vault with a `transferFrom` call, this has an effect on both the `lock` and `lockWithApproval` function |
| `unlock(uint256)` | change | unlock now triggers `withdrawTorn(address,uint256)` within the vault which reverts on an unsuccessful transfer (safeTransfer) |
| `version` | addition | tells current version of governance contract |
| `address immutable userVault` | addition | address of the deployed vault |
### Tornado Vault (TornadoVault.sol)
The compliment to the above upgrade. Stores user TORN, does not keep records of it. Serves exclusively for deposits and withdrawals. Works in effect as personal store of TORN for a user with the balance being user for voting. Locking mechanisms are still in effect.
| Function/variable signature | describe significance |
| ------------------------------- | --------------------------------------------------- |
| `withdrawTorn(address,uint256)` | used for withdrawing TORN balance to users' account |

@ -0,0 +1,89 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { LoopbackProxy } from "tornado-governance/contracts/LoopbackProxy.sol";
import { TornadoVault } from "./vault/TornadoVault.sol";
import { TornadoAuctionHandler } from "./auction/TornadoAuctionHandler.sol";
import { GovernanceGasUpgrade } from "./gas/GovernanceGasUpgrade.sol";
import { IGovernanceVesting } from "./interfaces/IGovernanceVesting.sol";
import { ImmutableGovernanceInformation } from "./ImmutableGovernanceInformation.sol";
/**
* @notice This proposal should upgrade governance to the vault and gas version without breaking any logic.
* */
contract VaultAndGasProposal is ImmutableGovernanceInformation {
using SafeMath for uint256;
IGovernanceVesting public constant GovernanceVesting = IGovernanceVesting(0x179f48C78f57A3A78f0608cC9197B8972921d1D2);
address public immutable gasCompLogic;
/// @notice the new voting period we would like to include
uint256 public immutable votingPeriod;
event TornadoAuctionHandlerCreated(address indexed handler);
constructor(address _gasCompLogic, uint256 _votingPeriod) public {
gasCompLogic = _gasCompLogic;
votingPeriod = _votingPeriod;
}
/// @notice the entry point for the governance upgrade logic execution
/// @dev this function bundles all of the initialization logic for all of the contracts of the project
function executeProposal() external {
address vault = address(new TornadoVault());
LoopbackProxy(returnPayableGovernance()).upgradeTo(address(new GovernanceGasUpgrade(gasCompLogic, vault)));
GovernanceGasUpgrade newGovernance = GovernanceGasUpgrade(returnPayableGovernance());
IERC20 tornToken = IERC20(TornTokenAddress);
newGovernance.setVotingPeriod(votingPeriod);
/**
The below variable holds the total amount of TORN outflows from all of the proposal executions,
which will be used to calculate the proper amount of TORN for transfer to Governance.
For an explanation as to how this variable has been calculated with these fix values, please look at:
https://github.com/h-ivor/tornado-lottery-period/blob/production/scripts/balance_estimation.md
*/
uint256 totalOutflowsOfProposalExecutions = 120000000000000000000000 +
22916666666666666666666 +
54999999999999969408000 -
27e18;
require(
tornToken.transfer(
address(newGovernance.userVault()),
(tornToken.balanceOf(address(this))).sub(GovernanceVesting.released().sub(totalOutflowsOfProposalExecutions))
),
"TORN: transfer failed"
);
uint96 amountOfTornToAuctionOff = 100 ether;
uint96 minBuyAmount = 1.51 ether;
uint256 minBidInTorn = 0.01 ether;
uint256 fundingThreshold = 5 ether;
TornadoAuctionHandler auctionHandler = new TornadoAuctionHandler();
emit TornadoAuctionHandlerCreated(address(auctionHandler));
tornToken.transfer(address(auctionHandler), amountOfTornToAuctionOff);
/**
As with above, please see:
https://github.com/h-ivor/tornado-lottery-period/blob/production/contracts/auction/TornadoAuctionHandler.sol
*/
auctionHandler.initializeAuction(
block.timestamp + 5 days,
amountOfTornToAuctionOff,
minBuyAmount,
minBidInTorn,
fundingThreshold
);
}
}

@ -0,0 +1,59 @@
# Auctioning some Tornado for compensations ETH
To boost voting activity, one of our ideas is to compensate gas used for voting on proposals.
Both for the castVote and castDelegatedVote functionality.
To make this as smooth as possible, we will compensate users directly in **ETH** (non-wrapped) for voting.
The priority fee is not compensated for, as to make exploiting the compensations unnecessary and unprofitable.
In order to receive ETH, TORN will be auctioned off by the governance contract with the help of a auction helper
(see contracts/auction/TornadoAuctionHandler.sol).
This contract has two functionalities:
- Initiate an auction.
- Convert all WETH it holds into ETH and send to Governance (callable by anyone).
This way, Governance does not need to handle WETH swap logic (would require extra logic) and ETH will be directly sent to the governance contract.
The initializeAuction function takes a couple of parameters:
```
function initializeAuction(
uint256 _auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 _minBidPerOrder,
uint256 _minFundingThreshold
) external onlyGovernance {
```
- \_auctionEndDate -> the auction end date expressed in UNIX format.
- \_auctionedSellAmount -> the amount of TORN to be sold in the auction.
- \_minBuyAmount -> this variable helps to define the minimum price via the following formula: \_auctionedSellAmount/\_minBuyAmount, in other words the minimum amount of TORN per ETH.
- \_minBidPerOrder -> minimum buy amount per a single order (of tokens being auctioned), is also used to prevent users from buying too low amounts and hurting themselves.
- \_minFundingThreshold -> minimum amount of buy tokens (ETH) for the ENTIRE auction. If this is not reached, the auction reverts and all tokens are sent back to their original owners.
This function does not take all the parameters for initializing the auction, the entire function may be seen below, some were left out of convenience:
```
IEasyAuction(EasyAuctionAddress).initiateAuction(
IERC20(TornTokenAddress),
IERC20(WETHAddress),
0, // orderCancellationEndDate
_auctionEndDate,
_auctionedSellAmount,
_minBuyAmount,
_minBidPerOrder,
_minFundingThreshold,
true, // isAtomicClosureAllowed
address(0x0000000000000000000000000000000000000000), // access
new bytes(0) // access
);
```
- Addresses of the tokens being bought/sold (ETH/TORN).
- orderCancellationEndDate -> date until order can be cancelled. For us, this is 0, meaning orders can't be cancelled once set.
- isAtomicClosureAllowed -> when auction end date is reached, a participant may set a last order in exchange for closing the auction, meaning it incentivizes the user to end the auction (gas payments, time saving) by giving him a risk-free action at the end. For us, false, due to tests showing that dust collection might not work if this is used.
- Last two fields are for access management, we have no whitelist for the auction, thus redundant and set to 0 for us.

@ -0,0 +1,58 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IWETH } from "./interfaces/IWETH.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { EtherSend } from "../libraries/EtherSend.sol";
import { IEasyAuction } from "./interfaces/IEasyAuction.sol";
import { ImmutableGovernanceInformation } from "../ImmutableGovernanceInformation.sol";
/// @notice Handler which should help governance start an auction and transfer results of an auction to governance.
/// @dev The reasoning behind this contract is to not bloat governance with unnecessary logic.
contract TornadoAuctionHandler is ImmutableGovernanceInformation {
using EtherSend for address;
address public constant EasyAuctionAddress = 0x0b7fFc1f4AD541A4Ed16b40D8c37f0929158D101;
address public constant WETHAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @notice main auction initialization function, please see: https://github.com/h-ivor/tornado-lottery-period/blob/only-vault-and-gas/contracts/auction/Auction.md
/// @dev calls easy auction deployed on eth mainnet
function initializeAuction(
uint256 _auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 _minBidPerOrder,
uint256 _minFundingThreshold
) external onlyGovernance {
require(IERC20(TornTokenAddress).balanceOf(address(this)) >= _auctionedSellAmount, "torn balance not enough");
IERC20(TornTokenAddress).approve(EasyAuctionAddress, _auctionedSellAmount);
IEasyAuction(EasyAuctionAddress).initiateAuction(
IERC20(TornTokenAddress),
IERC20(WETHAddress),
0,
_auctionEndDate,
_auctionedSellAmount,
_minBuyAmount,
_minBidPerOrder,
_minFundingThreshold,
false,
address(0x0000000000000000000000000000000000000000),
new bytes(0)
);
}
/// @notice function to transfer all eth and TORN dust to governance
function convertAndTransferToGovernance() external {
IWETH(WETHAddress).withdraw(IWETH(WETHAddress).balanceOf(address(this)));
if (address(this).balance > 0) require(GovernanceAddress.sendEther(address(this).balance), "pay fail");
if (IERC20(TornTokenAddress).balanceOf(address(this)) > 0)
IERC20(TornTokenAddress).transfer(GovernanceAddress, IERC20(TornTokenAddress).balanceOf(address(this)));
}
/// @notice receive eth that should only allow mainnet WETH to send eth
receive() external payable {
require(msg.sender == WETHAddress, "only weth");
}
}

@ -0,0 +1,21 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IEasyAuction {
function initiateAuction(
IERC20 _auctioningToken,
IERC20 _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
bool isAtomicClosureAllowed,
address accessManagerContract,
bytes memory accessManagerContractData
) external returns (uint256);
}

@ -0,0 +1,7 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IPayableGovernance {
function receiveEther() external payable returns (bool);
}

@ -0,0 +1,23 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IWETH {
function balanceOf(address account) external view returns (uint256);
function deposit() external payable;
function withdraw(uint256 wad) external;
function totalSupply() external view returns (uint256);
function approve(address guy, uint256 wad) external returns (bool);
function transfer(address dst, uint256 wad) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 wad
) external returns (bool);
}

@ -0,0 +1,49 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import { EtherSend } from "../libraries/EtherSend.sol";
interface IPayableGovernance {
function receiveEther() external payable returns (bool);
}
/**
* @notice this contract should store ether for gas compensations and also retrieve the basefee
* */
contract GasCompensationVault {
using EtherSend for address;
address private constant GovernanceAddress = 0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce;
modifier onlyGovernance() {
require(msg.sender == GovernanceAddress, "only gov");
_;
}
/**
* @notice function to compensate gas by sending amount eth to a recipient
* @param recipient address to receive amount eth
* @param gasAmount the amount of gas to be compensated
* */
function compensateGas(address recipient, uint256 gasAmount) external onlyGovernance {
uint256 vaultBalance = address(this).balance;
uint256 toCompensate = gasAmount * block.basefee;
if (vaultBalance == 0) return;
payable(recipient).send((toCompensate > vaultBalance) ? vaultBalance : toCompensate);
}
/**
* @notice function to withdraw compensate eth back to governance
* @param amount the amount of eth to withdraw back to governance
* */
function withdrawToGovernance(uint256 amount) external onlyGovernance {
uint256 vaultBalance = address(this).balance;
require(GovernanceAddress.sendEther((amount > vaultBalance) ? vaultBalance : amount), "pay fail");
}
/**
* @notice receive ether function, does nothing but receive ether
* */
receive() external payable {}
}

@ -0,0 +1,58 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
interface IGasCompensationVault {
function compensateGas(address recipient, uint256 gasAmount) external;
function withdrawToGovernance(uint256 amount) external;
}
/**
* @notice This abstract contract is used to add gas compensation functionality to a contract.
* */
abstract contract GasCompensator {
using SafeMath for uint256;
/// @notice this vault is necessary for the gas compensation functionality to work
IGasCompensationVault public immutable gasCompensationVault;
constructor(address _gasCompensationVault) public {
gasCompensationVault = IGasCompensationVault(_gasCompensationVault);
}
/**
* @notice modifier which should compensate gas to account if eligible
* @dev Consider reentrancy, repeated calling of the function being compensated, eligibility.
* @param account address to be compensated
* @param eligible if the account is eligible for compensations or not
* @param extra extra amount in gas to be compensated, will be multiplied by basefee
* */
modifier gasCompensation(
address account,
bool eligible,
uint256 extra
) {
if (eligible) {
uint256 startGas = gasleft();
_;
uint256 gasToCompensate = startGas.sub(gasleft()).add(extra).add(10e3);
gasCompensationVault.compensateGas(account, gasToCompensate);
} else {
_;
}
}
/**
* @notice inheritable unimplemented function to withdraw ether from the vault
* */
function withdrawFromHelper(uint256 amount) external virtual;
/**
* @notice inheritable unimplemented function to deposit ether into the vault
* */
function setGasCompensations(uint256 _gasCompensationsLimit) external virtual;
}

@ -0,0 +1,155 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { GovernanceVaultUpgrade } from "../vault/GovernanceVaultUpgrade.sol";
import { GasCompensator } from "./GasCompensator.sol";
import { Math } from "@openzeppelin/contracts/math/Math.sol";
/**
* @notice This contract should upgrade governance to be able to compensate gas for certain actions.
* These actions are set to castVote, castDelegatedVote in this contract.
* */
contract GovernanceGasUpgrade is GovernanceVaultUpgrade, GasCompensator {
/**
* @notice constructor
* @param _gasCompLogic gas compensation vault address
* @param _userVault tornado vault address
* */
constructor(address _gasCompLogic, address _userVault)
public
GovernanceVaultUpgrade(_userVault)
GasCompensator(_gasCompLogic)
{}
/// @notice check that msg.sender is multisig
modifier onlyMultisig() {
require(msg.sender == returnMultisigAddress(), "only multisig");
_;
}
/**
* @notice receive ether function, does nothing but receive ether
* */
receive() external payable {}
/**
* @notice function to add a certain amount of ether for gas compensations
* @dev send ether is used in the logic as we don't expect multisig to make a reentrancy attack on governance
* @param gasCompensationsLimit the amount of gas to be compensated
* */
function setGasCompensations(uint256 gasCompensationsLimit) external virtual override onlyMultisig {
require(payable(address(gasCompensationVault)).send(Math.min(gasCompensationsLimit, address(this).balance)));
}
/**
* @notice function to withdraw funds from the gas compensator
* @dev send ether is used in the logic as we don't expect multisig to make a reentrancy attack on governance
* @param amount the amount of ether to withdraw
* */
function withdrawFromHelper(uint256 amount) external virtual override onlyMultisig {
gasCompensationVault.withdrawToGovernance(amount);
}
/**
* @notice function to cast callers votes on a proposal
* @dev IMPORTANT: This function uses the gasCompensation modifier.
* as such this function can trigger a payable fallback.
It is not possible to vote without revert more than once,
without hasAccountVoted being true, eliminating gas refunds in this case.
Gas compensation is also using the low level send(), forwarding 23000 gas
as to disallow further logic execution above that threshold.
* @param proposalId id of proposal account is voting on
* @param support true if yes false if no
* */
function castVote(uint256 proposalId, bool support)
external
virtual
override
gasCompensation(
msg.sender,
!hasAccountVoted(proposalId, msg.sender) && !checkIfQuorumReached(proposalId),
(msg.sender == tx.origin ? 21e3 : 0)
)
{
_castVote(msg.sender, proposalId, support);
}
/**
* @notice function to cast callers votes and votes delegated to the caller
* @param from array of addresses that should have delegated to voter
* @param proposalId id of proposal account is voting on
* @param support true if yes false if no
* */
function castDelegatedVote(
address[] memory from,
uint256 proposalId,
bool support
) external virtual override {
require(from.length > 0, "Can not be empty");
_castDelegatedVote(from, proposalId, support, !hasAccountVoted(proposalId, msg.sender) && !checkIfQuorumReached(proposalId));
}
/// @notice checker for success on deployment
/// @return returns precise version of governance
function version() external pure virtual override returns (string memory) {
return "2.lottery-and-gas-upgrade";
}
/**
* @notice function to check if quorum has been reached on a given proposal
* @param proposalId id of proposal
* @return true if quorum has been reached
* */
function checkIfQuorumReached(uint256 proposalId) public view returns (bool) {
return (proposals[proposalId].forVotes + proposals[proposalId].againstVotes >= QUORUM_VOTES);
}
/**
* @notice function to check if account has voted on a proposal
* @param proposalId id of proposal account should have voted on
* @param account address of the account
* @return true if acc has voted
* */
function hasAccountVoted(uint256 proposalId, address account) public view returns (bool) {
return proposals[proposalId].receipts[account].hasVoted;
}
/**
* @notice function to retrieve the multisig address
* @dev reasoning: if multisig changes we need governance to approve the next multisig address,
* so simply inherit in a governance upgrade from this function and set the new address
* @return the multisig address
* */
function returnMultisigAddress() public pure virtual returns (address) {
return 0xb04E030140b30C27bcdfaafFFA98C57d80eDa7B4;
}
/**
* @notice This should handle the logic of the external function
* @dev IMPORTANT: This function uses the gasCompensation modifier.
* as such this function can trigger a payable fallback.
* It is not possible to vote without revert more than once,
* without hasAccountVoted being true, eliminating gas refunds in this case.
* Gas compensation is also using the low level send(), forwarding 23000 gas
* as to disallow further logic execution above that threshold.
* @param from array of addresses that should have delegated to voter
* @param proposalId id of proposal account is voting on
* @param support true if yes false if no
* @param gasCompensated true if gas should be compensated (given all internal checks pass)
* */
function _castDelegatedVote(
address[] memory from,
uint256 proposalId,
bool support,
bool gasCompensated
) internal gasCompensation(msg.sender, gasCompensated, (msg.sender == tx.origin ? 21e3 : 0)) {
for (uint256 i = 0; i < from.length; i++) {
address delegator = from[i];
require(delegatedTo[delegator] == msg.sender || delegator == msg.sender, "Governance: not authorized");
require(!gasCompensated || !hasAccountVoted(proposalId, delegator), "Governance: voted already");
_castVote(delegator, proposalId, support);
}
}
}

@ -0,0 +1,8 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
interface IGovernanceVesting {
function released() external view returns (uint256);
}

@ -0,0 +1,8 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
interface ITornadoVault {
function withdrawTorn(address recipient, uint256 amount) external;
}

@ -0,0 +1,17 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12 || ^0.8.7;
/// @notice very short library which implements a method to transfer ether via <address>.call
library EtherSend {
/**
* @notice function to transfer ether via filling the value field of a call
* @dev DICLAIMER: you must handle the possibility of reentrancy when using this function!!!
* @param to address to be transferred to
* @param amount amount to be transferred
* @return success true if transfer successful
* */
function sendEther(address to, uint256 amount) internal returns (bool success) {
(success, ) = payable(to).call{ value: amount }("");
}
}

@ -0,0 +1,26 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract GasCompensationVault {
address private constant GovernanceAddress = 0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce;
modifier onlyGovernance() {
require(msg.sender == GovernanceAddress, "only gov");
_;
}
function compensateGas(address recipient, uint256 amount) external onlyGovernance {
if (address(this).balance == 0) return;
require(
(amount > address(this).balance) ? payable(recipient).send(address(this).balance) : payable(recipient).send(amount),
"compensation failed"
);
}
receive() external payable {}
function getBasefee() external view returns (uint256) {
return 5;
}
}

@ -0,0 +1,16 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "tornado-governance/contracts/Governance.sol";
contract MockProposal1 {
address public constant GovernanceAddress = 0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce;
function executeProposal() external {
Governance gov = Governance(GovernanceAddress);
gov.setVotingPeriod(27000);
require(gov.VOTING_PERIOD() == 27000, "Voting period change failed!");
}
}

@ -0,0 +1,16 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { IterableOrderedOrderSet } from "@gnosis.pm/ido-contracts/contracts/libraries/IterableOrderedOrderSet.sol";
contract OrderEncoderHelper {
function encodeOrder(
uint64 userId,
uint96 buyAmount,
uint96 sellAmount
) external pure returns (bytes32) {
return IterableOrderedOrderSet.encodeOrder(userId, buyAmount, sellAmount);
}
}

@ -0,0 +1,43 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { Governance } from "../../v1/Governance.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ITornadoVault } from "../interfaces/ITornadoVault.sol";
/// @title Version 2 Governance contract of the tornado.cash governance
contract GovernanceVaultUpgrade is Governance {
using SafeMath for uint256;
// vault which stores user TORN
ITornadoVault public immutable userVault;
// call Governance v1 constructor
constructor(address _userVault) public Governance() {
userVault = ITornadoVault(_userVault);
}
/// @notice Withdraws TORN from governance if conditions permit
/// @param amount the amount of TORN to withdraw
function unlock(uint256 amount) public virtual override {
require(getBlockTimestamp() > canWithdrawAfter[msg.sender], "Governance: tokens are locked");
lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount, "Governance: insufficient balance");
userVault.withdrawTorn(msg.sender, amount);
}
/// @notice checker for success on deployment
/// @return returns precise version of governance
function version() external pure virtual returns (string memory) {
return "2.vault-migration";
}
/// @notice transfers tokens from the contract to the vault, withdrawals are unlock()
/// @param owner account/contract which (this) spender will send to the user vault
/// @param amount amount which spender will send to the user vault
function _transferTokens(address owner, uint256 amount) internal virtual override {
require(torn.transferFrom(owner, address(userVault), amount), "TORN: transferFrom failed");
lockedBalance[owner] = lockedBalance[owner].add(amount);
}
}

@ -0,0 +1,21 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title Vault which holds user funds
contract TornadoVault {
using SafeERC20 for IERC20;
address internal constant TornTokenAddress = 0x77777FeDdddFfC19Ff86DB637967013e6C6A116C;
address internal constant GovernanceAddress = 0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce;
/// @notice withdraws TORN from the contract
/// @param amount amount to withdraw
function withdrawTorn(address recipient, uint256 amount) external {
require(msg.sender == GovernanceAddress, "only gov");
IERC20(TornTokenAddress).safeTransfer(recipient, amount);
}
}

@ -1,3 +0,0 @@
#!/bin/bash
npx truffle-flattener contracts/Governance.sol > flats/Governance_flat.sol
npx truffle-flattener contracts/LoopbackProxy.sol > flats/MyProxy_flat.sol

@ -0,0 +1,77 @@
require('dotenv').config()
require('@nomiclabs/hardhat-ethers')
require('@nomiclabs/hardhat-etherscan')
require('@nomiclabs/hardhat-waffle')
require('hardhat-spdx-license-identifier')
require('hardhat-storage-layout')
require('hardhat-log-remover')
require('hardhat-contract-sizer')
require('./tasks/deploy_proposal.js')
/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: {
compilers: [
{
version: '0.6.12',
settings: {
optimizer: {
enabled: true,
runs: 1000,
},
},
},
{
version: '0.8.7',
settings: {
optimizer: {
enabled: true,
runs: 1000,
},
},
},
{
version: '0.7.6',
settings: {
optimizer: {
enabled: true,
runs: 1000,
},
},
},
],
},
networks: {
hardhat: {
forking: {
url: `https://mainnet.infura.io/v3/${process.env.mainnet_rpc_key}`,
blockNumber: 13042331,
},
initialBaseFeePerGas: 5,
},
localhost: {
url: 'http://localhost:8545',
timeout: 120000,
},
mainnet: {
url: `https://mainnet.infura.io/v3/${process.env.mainnet_rpc_key}`,
accounts: [`${process.env.mainnet_account_pk}`],
timeout: 2147483647,
},
goerli: {
url: `https://goerli.infura.io/v3/${process.env.goerli_rpc_key}`,
accounts: [`${process.env.goerli_account_pk}`],
timeout: 2147483647,
},
},
mocha: { timeout: 9999999999 },
spdxLicenseIdentifier: {
overwrite: true,
runOnCompile: true,
},
etherscan: {
apiKey: `${process.env.etherscan_api_key}`,
},
}

@ -1,43 +1,54 @@
{
"name": "tornado-governance",
"version": "1.0.3",
"version": "2.0.0",
"description": "",
"main": "index.js",
"files": [
"contracts/*"
],
"scripts": {
"compile": "truffle compile",
"test": "truffle test",
"test:stacktrace": "yarn test --stacktrace",
"eslint": "eslint --ext .js --ignore-path .gitignore .",
"prettier:check": "prettier --check . --config .prettierrc",
"prettier:fix": "prettier --write . --config .prettierrc",
"lint": "yarn eslint && yarn prettier:check"
"lint": "yarn eslint && yarn prettier:check",
"test:all": "yarn hardhat test",
"test": "yarn test:all",
"test:all:f": "yarn prettier:fix && yarn test && yarn lint",
"test:f": "yarn prettier:fix && yarn test",
"clean": "yarn prettier:fix && yarn lint",
"compile": "yarn prettier:fix && yarn hardhat compile"
},
"author": "Tornado.cash team <hello@tornado.cash>",
"license": "MIT",
"dependencies": {
"@openzeppelin/contracts": "^3.2.0-rc.0",
"@ethersproject/bignumber": "^5.5.0",