diff --git a/.gitignore b/.gitignore index 65433fac..3b1c9659 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ **/package-lock.json **/.idea/ **/cache/ +**/emv-* + diff --git a/CVLByExample/Curve/README.md b/CVLByExample/Curve/README.md new file mode 100644 index 00000000..67e3b93e --- /dev/null +++ b/CVLByExample/Curve/README.md @@ -0,0 +1,77 @@ + +#Curve + +This directory contains a simplified contract that is based on the past +`read-only reentrancy` vulnerability of one of the `Curve` pools described [here](https://chainsecurity.com/curve-lp-oracle-manipulation-post-mortem/) + +##Contracts +The original simplified contract is `SimplifiedCurve` whose weakness is found by the builtin rule `viewReentrancy`. +Another +contract is `ManualInstrumentationCurve` that allows finding the weakness also with a regular rule. This is used to +demonstrate what the builtin rule actually does. + +##Specs +`certora/specs` contains two spec files for exposing this weakness. + +1. `BuiltinViewReentrancy.spec` uses the builtin rule `viewReentrancy` that checks that for every solidity function and every + view function the read-only reentrancy weakness is not present. This spec is used for finding the weakness in SimplifiedCurve. +2. `ViewReentrancy.spec` uses regular rules for checking that for every solidity function + the read only reentrancy weakness is not present for the view function `getVirtualPrice()` only. + It is not checked for all view functions. + This is done by using ghosts for tracking: + 1. The value of `getVirtualPrice()` at the current state. + 2. The value of `getVirtualPrice()` before the unresolved call that is in the checked solidity function. + 3. The value of `getVirtualPrice()` after the unresolved call that is in the checked solidity function. + 4. The existence of a read-only weakness with respect to `getVirtualPrice()`. + Two hooks are defined. One for updating (1) and one for updating (4). + Additional instrumentation is required in order to catch the bug. This spec works on the contract + `ManualInstrumentationSimplifiedCurve`. + +Both rules check the existence of the weakness by checking +that the result of a view function after an +unresolved call is equal either to the result of this view function at the beginning or at the end of the +calling solidity function. + +Both specs find that the weakness exists in the the above contracts. + +## Failing Code: + +The rule `no_read_only_reentrancy` fails for function `remove_liquidity`. In `remove_liquidity` the unresolved call is performed in an unstable +state, after the call to `CurveToken(lp_token).burnFrom` and before the call to `ERC20(coins_1).transfer`. + +For running the builtin rule run +```certoraRun certora/conf/broken/runViewReentrancyBuiltinRule.conf``` + +For running the regular rule run + +```certoraRun certora/conf/broken/runViewReentrancyRegularRule.conf``` + +The report of this run can be found in + +[Report of failure with regular rule](https://prover.certora.com/output/1902/fac7a9437752438d85472b0446247aff?anonymousKey=a1fb2c1b2e88bd10a64601831ce2cd8912d2de53) + +## Correct Code + +The read-only reentrancy weakness was fixed by adding at the top of each view function a requiremt +that prevents running the view function in case of an inconsistent state. + +The resulting code without instrumentation is `SimplifiedCurveFixed.sol`. The command to check the builtin rule +on this contract is + +```certoraRun certora/conf/correct/runViewReentrancyFixedBuiltinRule.conf``` + +The report of this run can be found in + +[Report of correctness with builtin rule](https://prover.certora.com/output/1902/a2845c679b6a4028af918b842916ad8c?anonymousKey=fe54be4932f20347abe18ac7f7afeb9665d2a8f8) + + +The resulting code with instrumentation is `ManualInstrumentationSimplifiedCurveFixed`. The command to check the regular rule +on this contract is + +```certoraRun certora/conf/correct/runViewReentrancyFixedRegularRule.conf``` + +The report of this run can be found in + +[Report of correctness with regular rule](https://prover.certora.com/output/1902/a411fe10787b4a778f0b63848da18d78?anonymousKey=5c2538f9a28f026d9e471c76651212bb610bf488) + + diff --git a/CVLByExample/Curve/certora/conf/broken/runViewReentrancyBuiltinRule.conf b/CVLByExample/Curve/certora/conf/broken/runViewReentrancyBuiltinRule.conf new file mode 100644 index 00000000..db8309a7 --- /dev/null +++ b/CVLByExample/Curve/certora/conf/broken/runViewReentrancyBuiltinRule.conf @@ -0,0 +1,20 @@ +{ + "files": [ + "contracts/broken/SimplifiedCurve.sol", + "contracts/CurveTokenExample.sol", + "contracts/ERC20.sol" + ], + "verify": "SimplifiedCurve:certora/specs/BuiltinViewReentrancy.spec", + "link": [ + "SimplifiedCurve:lp_token=CurveTokenExample", + "SimplifiedCurve:coins_1=ERC20" + ], + "msg": "Simplified Curve with view reentrancy guard", + "send_only": true, + "optimistic_loop": true, + "loop_iter": "3", + "prover_args": [ + "-optimisticFallback true" + ], + "server": "production" +} diff --git a/CVLByExample/Curve/certora/conf/broken/runViewReentrancyRegularRule.conf b/CVLByExample/Curve/certora/conf/broken/runViewReentrancyRegularRule.conf new file mode 100644 index 00000000..1bb0249b --- /dev/null +++ b/CVLByExample/Curve/certora/conf/broken/runViewReentrancyRegularRule.conf @@ -0,0 +1,20 @@ +{ + "files": [ + "contracts/broken/ManualInstrumentationSimplifiedCurve.sol", + "contracts/CurveTokenExample.sol", + "contracts/ERC20.sol" + ], + "verify": "ManualInstrumentationSimplifiedCurve:certora/specs/ViewReentrancy.spec", + "link": [ + "ManualInstrumentationSimplifiedCurve:lp_token=CurveTokenExample", + "ManualInstrumentationSimplifiedCurve:coins_1=ERC20" + ], + "msg": "Simplified Curve with view reentrancy guard", + "send_only": true, + "optimistic_loop": true, + "loop_iter": "3", + "prover_args": [ + "-optimisticFallback true" + ], + "server": "production" +} diff --git a/CVLByExample/Curve/certora/conf/correct/runViewReentrancyFixedBuiltinRule.conf b/CVLByExample/Curve/certora/conf/correct/runViewReentrancyFixedBuiltinRule.conf new file mode 100644 index 00000000..d441359a --- /dev/null +++ b/CVLByExample/Curve/certora/conf/correct/runViewReentrancyFixedBuiltinRule.conf @@ -0,0 +1,20 @@ +{ + "files": [ + "contracts/correct/SimplifiedCurveFixed.sol", + "contracts/CurveTokenExample.sol", + "contracts/ERC20.sol" + ], + "verify": "SimplifiedCurveFixed:certora/specs/BuiltinViewReentrancy.spec", + "link": [ + "SimplifiedCurveFixed:lp_token=CurveTokenExample", + "SimplifiedCurveFixed:coins_1=ERC20" + ], + "msg": "Simplified Curve with view reentrancy guard", + "send_only": true, + "optimistic_loop": true, + "loop_iter": "3", + "prover_args": [ + "-optimisticFallback true" + ], + "server": "production" +} diff --git a/CVLByExample/Curve/certora/conf/correct/runViewReentrancyFixedRegularRule.conf b/CVLByExample/Curve/certora/conf/correct/runViewReentrancyFixedRegularRule.conf new file mode 100644 index 00000000..a4b7bb5f --- /dev/null +++ b/CVLByExample/Curve/certora/conf/correct/runViewReentrancyFixedRegularRule.conf @@ -0,0 +1,20 @@ +{ + "files": [ + "contracts/correct/ManualInstrumentationSimplifiedCurveFixed.sol", + "contracts/CurveTokenExample.sol", + "contracts/ERC20.sol" + ], + "verify": "ManualInstrumentationSimplifiedCurveFixed:certora/specs/ViewReentrancy.spec", + "link": [ + "ManualInstrumentationSimplifiedCurveFixed:lp_token=CurveTokenExample", + "ManualInstrumentationSimplifiedCurveFixed:coins_1=ERC20" + ], + "msg": "Simplified Curve with view reentrancy guard", + "send_only": true, + "optimistic_loop": true, + "loop_iter": "3", + "prover_args": [ + "-optimisticFallback true" + ], + "server": "production" +} diff --git a/CVLByExample/Curve/certora/specs/BuiltinViewReentrancy.spec b/CVLByExample/Curve/certora/specs/BuiltinViewReentrancy.spec new file mode 100644 index 00000000..d3b2b13d --- /dev/null +++ b/CVLByExample/Curve/certora/specs/BuiltinViewReentrancy.spec @@ -0,0 +1 @@ +use builtin rule viewReentrancy; diff --git a/CVLByExample/Curve/certora/specs/ViewReentrancy.spec b/CVLByExample/Curve/certora/specs/ViewReentrancy.spec new file mode 100644 index 00000000..13c13670 --- /dev/null +++ b/CVLByExample/Curve/certora/specs/ViewReentrancy.spec @@ -0,0 +1,35 @@ + +using ERC20 as Token; +using CurveTokenExample as LPToken; + + +ghost uint256 before_func1; +ghost uint256 after_func1; +ghost uint256 current_func1; +ghost bool cond; + +// hook on the return value of the view function +hook Sstore solghost_return_func1 uint256 newValue (uint256 oldValue) STORAGE { + current_func1 = newValue; +} + +// hook on the read only reentrancy condition. +// true is the current result of the view function is equal to the result before the unresolved or +// to the result after the unresolved. +hook Sstore solghost_trigger_check bool newValue (bool oldValue) STORAGE { + cond = cond && ((current_func1 == before_func1) || (current_func1 == after_func1)); +} + +// Using require for setting before_func1 to the value of getVirtualPrice before the unresolved call and +// setting after_func1 to the value of getVirtualPrice after the unresolved call. +rule no_read_only_reentrancy(method f) +{ + env e; + env e_external; + calldataarg data; + require cond; + require before_func1 == getVirtualPrice(e_external); + f(e, data); + require after_func1 == getVirtualPrice(e_external); + assert cond; +} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Context.sol b/CVLByExample/Curve/contracts/Context.sol similarity index 96% rename from CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Context.sol rename to CVLByExample/Curve/contracts/Context.sol index f304065b..69e78f22 100644 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Context.sol +++ b/CVLByExample/Curve/contracts/Context.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) -pragma solidity ^0.8.0; +pragma solidity ^0.8.13; /** * @dev Provides information about the current execution context, including the @@ -21,4 +21,4 @@ abstract contract Context { function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } -} +} \ No newline at end of file diff --git a/CVLByExample/Curve/contracts/Curve.sol b/CVLByExample/Curve/contracts/Curve.sol new file mode 100644 index 00000000..c53a382c --- /dev/null +++ b/CVLByExample/Curve/contracts/Curve.sol @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.13; +import "./ERC20.sol"; +import "./ReentrancyGuard.sol"; +import "./CurveToken.sol"; +import "./CurveTokenExample.sol"; + +contract MintableToken is ERC20 { + + constructor (string memory name, string memory sym) ERC20(name, sym) { + + } + + function mint(address _user, uint _amount) public { + _mint(_user, _amount); + } +} + +contract Curve is ReentrancyGuard{ + //uint128 public constant 2 = 2; + uint256 constant A_PRECISION =100; + uint256 constant PRECISION = 10e18; + uint256 future_A_time; + uint256 future_A; + uint256 initial_A_time; + uint256 initial_A; + uint256[2] admin_balances; + // storage var "address[2] coins" was seperated to be able to link + address public coins_0; + address public coins_1; + address public lp_token; + address owner; + // address public underlying_token; // would be linked to ERC20 and equal to coins[1], but can't do directly due to CVL limitations + uint256 kill_deadline; + uint256 fee; + uint256 admin_fee; + uint256 future_fee; + uint256 future_owner; + uint256 future_admin_fee; + uint256 _DEMO_D; + + mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) _DEMO_D_MAPPING; + + constructor(address _lp_token, address _token_addr) payable { + lp_token = _lp_token; + coins_1 = _token_addr; + } + + // The symplification returns the sum of the first two entries of xp. + function get_D(uint256[2] memory xp,uint256 amp) public view returns(uint256) { + uint256 S = 0; + uint256 Dprev = 0; + // Demo simplificaiton - in order to reduce the running time of the example. + // get_D currently crashes the prover's pre-SMT analysis or something + // uint256 x; + // return _DEMO_D; + // return _DEMO_D_MAPPING[xp[0]][xp[1]][amp]; + return xp[0] + xp[1]; + // Simplification end + + // Commenting out unreachable code of the simplification. + // The symplification does not affect the view reentrancy weakness + // because the fields that are changed + // before/ after the unresolved call are still read by the calling view function. + + // for (uint256 _x=0;_x Dprev){ + // if (D - Dprev <= 1){ + // return D; + // } + // } + // else{ + // if (Dprev - D <= 1){ + // return D; + // } + // } + // } + // revert(); + } + + function _A() view internal returns(uint256) { + + // Demo simplificaiton - return unconstrained CONST + return future_A; + // Simplification end + + // uint256 t1 = future_A_time; + // uint256 A1 = future_A; + // if (block.timestamp < t1){ + // uint256 A0 = initial_A; + // uint256 t0 = initial_A_time; + // if (A1 > A0){ + // return A0 + (A1 - A0) * (block.timestamp - t0) / (t1 - t0); + // } + // else{ + // return A0 - (A0 - A1) * (block.timestamp - t0) / (t1 - t0); + // } + // } + // else{ + // return A1; + // } + } + + function _balances(uint256 _value) internal view returns(uint256[2] memory) { + return [ + address(this).balance - admin_balances[0] - _value, + ERC20(coins_1).balanceOf(address(this)) - admin_balances[1]]; + } + + // function _balances_guarded(uint256 _value) public view returns(uint256[2] memory) { + // require(!_reentrancyGuardEntered(), "reading during reentrancy not allowed!"); + // return _balances(_value); + // } + + // function getVirtualPrice_guarded() public view returns(uint256) { + // require(!_reentrancyGuardEntered(), "reading during reentrancy not allowed!"); + // return getVirtualPrice(); + // } + + function getVirtualPrice() public view returns(uint256){ + uint256 D = this.get_D(_balances(0),_A()); + uint256 totalShares = ERC20(lp_token).totalSupply(); + return D * PRECISION / totalShares; + } + + function remove_liquidity( + uint256 _amount, + uint256[2] memory _min_amounts + ) + nonReentrant + public + returns(uint256[2] memory) + { + uint256[2] memory amounts = _balances(0); + uint256 total_supply = ERC20(lp_token).totalSupply(); + CurveToken(lp_token).burnFrom(msg.sender, _amount); + for (uint256 i;i<2;i++){ + uint256 value = amounts[i] * _amount / total_supply; + assert (value >= _min_amounts[i]); + amounts[i] = value; + if (i == 0){ + msg.sender.call{value:value}(""); + } + else{ + assert (ERC20(coins_1).transfer(msg.sender, value)); + } + } + return amounts; + } + + function addScenarioEther() public payable { + + } + +} + + +contract scenario { + + uint constant other_user_lp = 40e18; + uint constant underlying_asset_before = 80e18; + uint constant deposited_ether_before = 4e18; + uint constant attacker_lp = 40e18; + uint constant attacker_underlying = 80e18; + uint constant attacker_deposit_eth = 4e18; + address constant other_user = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2; + + function init_scenario(/*address other_user*/) payable public returns(address) { + CurveTokenExample lp_token = new CurveTokenExample(); + MintableToken token = new MintableToken("example", "ex"); + + // setup Curve contract and its ETH and shares BEFORE the attacker + require(msg.value >= deposited_ether_before + attacker_deposit_eth, "Not enough funds sent to init the scenario"); + Curve _curve = new Curve{value: deposited_ether_before}(address(lp_token), address(token)); + lp_token.mint(other_user, other_user_lp); + token.mint(address(_curve), underlying_asset_before); + + // Log the price before the attacker + // console.log("before the attacker got in the price is %s", _curve.getVirtualPrice()); + + // attakcer contract + attacker _attContract = new attacker(address(_curve)); + + // setup state (mints) + _curve.addScenarioEther{value: attacker_deposit_eth}(); + lp_token.mint(address(_attContract), attacker_lp); + token.mint(address(_curve), attacker_underlying); + + + // Run the exploit + _attContract.exec(); + + return address(_attContract); + } +} + +contract attacker{ + Curve public attacked; + ERC20 token; + CurveTokenExample lp_token; + + constructor(address attackedAddr){ + attacked = Curve(attackedAddr); + token = ERC20(attacked.coins_1()); + lp_token = CurveTokenExample(attacked.lp_token()); + } + function exec() public { + // prepare token + // console.log("After Attacker deposit price is %s",attacked.getVirtualPrice()); + uint256 my_lp_balance = lp_token.balanceOf(address(this)); + uint[2] memory zeros = [uint(0), 0]; + // console.log("trying to remove liq...."); + attacked.remove_liquidity(my_lp_balance, zeros); // virtual price dropped + // console.log("after the attack price is %s",attacked.getVirtualPrice()); + } + fallback() external payable { + // console.log("during the attack price is %s",attacked.getVirtualPrice()); + } +} \ No newline at end of file diff --git a/CVLByExample/Curve/contracts/CurveToken.sol b/CVLByExample/Curve/contracts/CurveToken.sol new file mode 100644 index 00000000..de689e38 --- /dev/null +++ b/CVLByExample/Curve/contracts/CurveToken.sol @@ -0,0 +1,6 @@ +pragma solidity ^0.8.13; + +interface CurveToken{ + function mint(address to, uint256 value) external returns(bool); + function burnFrom(address to, uint256 value) external returns(bool); +} diff --git a/CVLByExample/Curve/contracts/CurveTokenExample.sol b/CVLByExample/Curve/contracts/CurveTokenExample.sol new file mode 100644 index 00000000..84eaae02 --- /dev/null +++ b/CVLByExample/Curve/contracts/CurveTokenExample.sol @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.13; +import "./ERC20.sol"; +import "./CurveToken.sol"; + +contract CurveTokenExample is CurveToken, ERC20{ + + constructor() ERC20("ExampleLPToken", "ExCrvLP") {} + + function mint(address to, uint256 value) external returns(bool){ + _mint(to, value); + return true; + } + function burnFrom(address to, uint256 value) external returns(bool){ + _burn(to, value); + return true; + } +} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol b/CVLByExample/Curve/contracts/ERC20.sol similarity index 65% rename from CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol rename to CVLByExample/Curve/contracts/ERC20.sol index 3949e08e..040b11dd 100644 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol +++ b/CVLByExample/Curve/contracts/ERC20.sol @@ -1,23 +1,25 @@ // SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) +// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) -pragma solidity ^0.8.0; +pragma solidity ^0.8.13; -import "./IERC20.sol"; -import "./extensions/IERC20Metadata.sol"; -import "../../utils/Context.sol"; +// import "./IERC20.sol"; +import "./IERC20Metadata.sol"; +import "./Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide - * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How + * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * + * The default value of {decimals} is 18. To change this, you should override + * this function so it returns a different value. + * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 @@ -45,9 +47,6 @@ contract ERC20 is Context, IERC20, IERC20Metadata { /** * @dev Sets the values for {name} and {symbol}. * - * The default value of {decimals} is 18. To select a different value for - * {decimals} you should overload it. - * * All two of these values are immutable: they can only be set once during * construction. */ @@ -77,8 +76,8 @@ contract ERC20 is Context, IERC20, IERC20Metadata { * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the value {ERC20} uses, unless this function is - * overridden; + * Ether and Wei. This is the default value returned by this function, unless + * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including @@ -155,11 +154,7 @@ contract ERC20 is Context, IERC20, IERC20Metadata { * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ - function transferFrom( - address from, - address to, - uint256 amount - ) public virtual override returns (bool) { + function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); @@ -180,7 +175,7 @@ contract ERC20 is Context, IERC20, IERC20Metadata { */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); - _approve(owner, spender, _allowances[owner][spender] + addedValue); + _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } @@ -200,7 +195,7 @@ contract ERC20 is Context, IERC20, IERC20Metadata { */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); - uint256 currentAllowance = _allowances[owner][spender]; + uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); @@ -210,88 +205,78 @@ contract ERC20 is Context, IERC20, IERC20Metadata { } /** - * @dev Moves `amount` of tokens from `sender` to `recipient`. + * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `from` must have a balance of at least `amount`. + * NOTE: This function is not virtual, {_update} should be overridden instead. */ - function _transfer( - address from, - address to, - uint256 amount - ) internal virtual { + function _transfer(address from, address to, uint256 amount) internal { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); + _update(from, to, amount); + } - _beforeTokenTransfer(from, to, amount); + /** + * @dev Transfers `amount` of tokens from `from` to `to`, or alternatively mints (or burns) if `from` (or `to`) is + * the zero address. All customizations to transfers, mints, and burns should be done by overriding this function. + * + * Emits a {Transfer} event. + */ + function _update(address from, address to, uint256 amount) internal virtual { + if (from == address(0)) { + _totalSupply += amount; + } else { + uint256 fromBalance = _balances[from]; + require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); + unchecked { + // Overflow not possible: amount <= fromBalance <= totalSupply. + _balances[from] = fromBalance - amount; + } + } - uint256 fromBalance = _balances[from]; - require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); - unchecked { - _balances[from] = fromBalance - amount; + if (to == address(0)) { + unchecked { + // Overflow not possible: amount <= totalSupply or amount <= fromBalance <= totalSupply. + _totalSupply -= amount; + } + } else { + unchecked { + // Overflow not possible: balance + amount is at most totalSupply, which we know fits into a uint256. + _balances[to] += amount; + } } - _balances[to] += amount; emit Transfer(from, to, amount); - - _afterTokenTransfer(from, to, amount); } - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. + /** + * @dev Creates `amount` tokens and assigns them to `account`, by transferring it from address(0). + * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * - * Requirements: - * - * - `account` cannot be the zero address. + * NOTE: This function is not virtual, {_update} should be overridden instead. */ - function _mint(address account, uint256 amount) internal virtual { + function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); - - _beforeTokenTransfer(address(0), account, amount); - - _totalSupply += amount; - _balances[account] += amount; - emit Transfer(address(0), account, amount); - - _afterTokenTransfer(address(0), account, amount); + _update(address(0), account, amount); } /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. + * @dev Destroys `amount` tokens from `account`, by transferring it to address(0). + * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * - * Requirements: - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. + * NOTE: This function is not virtual, {_update} should be overridden instead */ - function _burn(address account, uint256 amount) internal virtual { + function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); - - _beforeTokenTransfer(account, address(0), amount); - - uint256 accountBalance = _balances[account]; - require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); - unchecked { - _balances[account] = accountBalance - amount; - } - _totalSupply -= amount; - - emit Transfer(account, address(0), amount); - - _afterTokenTransfer(account, address(0), amount); + _update(account, address(0), amount); } /** @@ -307,11 +292,7 @@ contract ERC20 is Context, IERC20, IERC20Metadata { * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ - function _approve( - address owner, - address spender, - uint256 amount - ) internal virtual { + function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); @@ -320,18 +301,14 @@ contract ERC20 is Context, IERC20, IERC20Metadata { } /** - * @dev Spend `amount` form the allowance of `owner` toward `spender`. + * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ - function _spendAllowance( - address owner, - address spender, - uint256 amount - ) internal virtual { + function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); @@ -340,44 +317,4 @@ contract ERC20 is Context, IERC20, IERC20Metadata { } } } - - /** - * @dev Hook that is called before any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} - - /** - * @dev Hook that is called after any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * has been transferred to `to`. - * - when `from` is zero, `amount` tokens have been minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens have been burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} -} +} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol b/CVLByExample/Curve/contracts/IERC20.sol similarity index 92% rename from CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol rename to CVLByExample/Curve/contracts/IERC20.sol index 810ff275..9dd764e7 100644 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol +++ b/CVLByExample/Curve/contracts/IERC20.sol @@ -1,12 +1,26 @@ // SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) +// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) -pragma solidity ^0.8.0; +pragma solidity ^0.8.13; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { + /** + * @dev Emitted when `value` tokens are moved from one account (`from`) to + * another (`to`). + * + * Note that `value` may be zero. + */ + event Transfer(address indexed from, address indexed to, uint256 value); + + /** + * @dev Emitted when the allowance of a `spender` for an `owner` is set by + * a call to {approve}. `value` is the new allowance. + */ + event Approval(address indexed owner, address indexed spender, uint256 value); + /** * @dev Returns the amount of tokens in existence. */ @@ -60,23 +74,5 @@ interface IERC20 { * * Emits a {Transfer} event. */ - function transferFrom( - address from, - address to, - uint256 amount - ) external returns (bool); - - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); -} + function transferFrom(address from, address to, uint256 amount) external returns (bool); +} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol b/CVLByExample/Curve/contracts/IERC20Metadata.sol similarity index 92% rename from CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol rename to CVLByExample/Curve/contracts/IERC20Metadata.sol index 83ba6ac5..979fd905 100644 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol +++ b/CVLByExample/Curve/contracts/IERC20Metadata.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) -pragma solidity ^0.8.0; +pragma solidity ^0.8.13; -import "../IERC20.sol"; +import "./IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. @@ -25,4 +25,4 @@ interface IERC20Metadata is IERC20 { * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); -} +} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol b/CVLByExample/Curve/contracts/ReentrancyGuard.sol similarity index 64% rename from CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol rename to CVLByExample/Curve/contracts/ReentrancyGuard.sol index ec8ccc7c..61705570 100644 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol +++ b/CVLByExample/Curve/contracts/ReentrancyGuard.sol @@ -1,24 +1,6 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Contract module that helps prevent reentrant calls to a function. - * - * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier - * available, which can be applied to functions to make sure there are no nested - * (reentrant) calls to them. - * - * Note that because there is a single `nonReentrant` guard, functions marked as - * `nonReentrant` may not call one another. This can be worked around by making - * those functions `private`, and then adding `external` `nonReentrant` entry - * points to them. - * - * TIP: If you would like to learn more about reentrancy and alternative ways - * to protect against it, check out our blog post - * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. - */ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.13; + abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the @@ -48,16 +30,30 @@ abstract contract ReentrancyGuard { * `private` function that does the actual work. */ modifier nonReentrant() { - // On the first call to nonReentrant, _notEntered will be true + _nonReentrantBefore(); + _; + _nonReentrantAfter(); + } + + function _nonReentrantBefore() private { + // On the first call to nonReentrant, _status will be _NOT_ENTERED require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; + } - _; - + function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } -} + + /** + * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a + * `nonReentrant` function in the call stack. + */ + function _reentrancyGuardEntered() internal view returns (bool) { + return _status == _ENTERED; + } +} \ No newline at end of file diff --git a/CVLByExample/Curve/contracts/broken/ManualInstrumentationSimplifiedCurve.sol b/CVLByExample/Curve/contracts/broken/ManualInstrumentationSimplifiedCurve.sol new file mode 100644 index 00000000..36534fef --- /dev/null +++ b/CVLByExample/Curve/contracts/broken/ManualInstrumentationSimplifiedCurve.sol @@ -0,0 +1,241 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.13; +import "../ERC20.sol"; +import "../ReentrancyGuard.sol"; +import "../CurveToken.sol"; +import "../CurveTokenExample.sol"; + +contract MintableToken is ERC20 { + + constructor (string memory name, string memory sym) ERC20(name, sym) { + + } + + function mint(address _user, uint _amount) public { + _mint(_user, _amount); + } +} + + +contract ManualInstrumentationSimplifiedCurve is ReentrancyGuard{ + // Manual instrumentation + uint256 public solghost_return_func1; + bool solghost_trigger_check; + // SOLIDITY GHOST Functions + function func1_caller() public returns(uint256) + { + return getVirtualPrice(); + } + + function sample_view_functions() internal{ + // Sample the values + solghost_return_func1 = getVirtualPrice(); + // Trigger the check in CVL + solghost_trigger_check = true; + } + + //uint128 public constant 2 = 2; + uint256 constant A_PRECISION =100; + uint256 constant PRECISION = 10e18; + uint256 future_A_time; + uint256 future_A; + uint256 initial_A_time; + uint256 initial_A; + uint256[2] admin_balances; + // storage var "address[2] coins" was seperated to be able to link + address public coins_0; + address public coins_1; + address public lp_token; + address owner; + // address public underlying_token; // would be linked to ERC20 and equal to coins[1], but can't do directly due to CVL limitations + uint256 kill_deadline; + uint256 fee; + uint256 admin_fee; + uint256 future_fee; + uint256 future_owner; + uint256 future_admin_fee; + uint256 _DEMO_D; + + mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) _DEMO_D_MAPPING; + + + + + // constructor(uint256 _future_A_time, uint256 _future_A, uint256 _initial_A_time, uint256 _initial_A, address owner ) { + + constructor(address _lp_token, address _token_addr) payable { + lp_token = _lp_token; + coins_1 = _token_addr; + } + + + // function get_D(uint xp_0, uint xp_1) + // Compute parameter D of Curve's price function. + function get_D(uint256[2] memory xp,uint256 amp) public view returns(uint256) { + uint256 S = 0; + uint256 Dprev = 0; + // Demo simplificaiton - unconstrained CONST + // get_D currently crashes the prover's pre-SMT analysis or something + // uint256 x; + // return _DEMO_D; + // return _DEMO_D_MAPPING[xp[0]][xp[1]][amp]; + return xp[0] + xp[1]; + // Simplification end + + for (uint256 _x=0;_x Dprev){ + if (D - Dprev <= 1){ + return D; + } + } + else{ + if (Dprev - D <= 1){ + return D; + } + } + } + revert(); + } + + function _A() view internal returns(uint256) { + + // Demo simplificaiton - return unconstrained CONST + return future_A; + // Simplification end + + uint256 t1 = future_A_time; + uint256 A1 = future_A; + if (block.timestamp < t1){ + uint256 A0 = initial_A; + uint256 t0 = initial_A_time; + if (A1 > A0){ + return A0 + (A1 - A0) * (block.timestamp - t0) / (t1 - t0); + } + else{ + return A0 - (A0 - A1) * (block.timestamp - t0) / (t1 - t0); + } + } + else{ + return A1; + } + } + + function _balances(uint256 _value) public view returns(uint256[2] memory) { + return [ + address(this).balance - admin_balances[0] - _value, + ERC20(coins_1).balanceOf(address(this)) - admin_balances[1]]; + } + + function getVirtualPrice() public view returns(uint256){ + uint256 D = this.get_D(_balances(0),_A()); + uint256 totalShares = ERC20(lp_token).totalSupply(); + return D * PRECISION / totalShares; + } + + function remove_liquidity( + uint256 _amount, + uint256[2] memory _min_amounts + ) + nonReentrant + public + returns(uint256[2] memory) + { + uint256[2] memory amounts = _balances(0); + uint256 total_supply = ERC20(lp_token).totalSupply(); + CurveToken(lp_token).burnFrom(msg.sender, _amount); + for (uint256 i;i<2;i++){ + uint256 value = amounts[i] * _amount / total_supply; + assert (value >= _min_amounts[i]); + amounts[i] = value; + if (i == 0){ + msg.sender.call{value:value}(""); + sample_view_functions(); + + } + else{ + assert (ERC20(coins_1).transfer(msg.sender, value)); + } + } + return amounts; + } + +} + + +contract scenario { + + uint constant other_user_lp = 40e18; + uint constant underlying_asset_before = 80e18; + uint constant deposited_ether_before = 4e18; + uint constant attacker_lp = 40e18; + uint constant attacker_underlying = 80e18; + uint constant attacker_deposit_eth = 4e18; + address constant other_user = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2; + + function init_scenario(/*address other_user*/) payable public returns(address) { + CurveTokenExample lp_token = new CurveTokenExample(); + MintableToken token = new MintableToken("example", "ex"); + + // setup ManualInstrumentationSimplifiedCurve contract and its ETH and shares BEFORE the attacker + require(msg.value >= deposited_ether_before + attacker_deposit_eth, "Not enough funds sent to init the scenario"); + ManualInstrumentationSimplifiedCurve _curve = new ManualInstrumentationSimplifiedCurve{value: deposited_ether_before}(address(lp_token), address(token)); + lp_token.mint(other_user, other_user_lp); + token.mint(address(_curve), underlying_asset_before); + + // Log the price before the attacker + // console.log("before the attacker got in the price is %s", _curve.getVirtualPrice()); + + // attacker contract + attacker _attContract = new attacker(address(_curve)); + + // setup state (mints) + // _curve.addScenarioEther{value: attacker_deposit_eth}(); + lp_token.mint(address(_attContract), attacker_lp); + token.mint(address(_curve), attacker_underlying); + + + // Run the exploit + _attContract.exec(); + + return address(_attContract); + } +} + +contract attacker{ + ManualInstrumentationSimplifiedCurve public attacked; + ERC20 token; + CurveTokenExample lp_token; + + constructor(address attackedAddr){ + attacked = ManualInstrumentationSimplifiedCurve(attackedAddr); + token = ERC20(attacked.coins_1()); + lp_token = CurveTokenExample(attacked.lp_token()); + } + function exec() public { + // prepare token + // console.log("After Attacker deposit price is %s",attacked.getVirtualPrice()); + uint256 my_lp_balance = lp_token.balanceOf(address(this)); + uint[2] memory zeros = [uint(0), 0]; + // console.log("trying to remove liq...."); + attacked.remove_liquidity(my_lp_balance, zeros); // virtual price dropped + // console.log("after the attack price is %s",attacked.getVirtualPrice()); + } + fallback() external payable { + // console.log("during the attack price is %s",attacked.getVirtualPrice()); + } +} \ No newline at end of file diff --git a/CVLByExample/Curve/contracts/broken/SimplifiedCurve.sol b/CVLByExample/Curve/contracts/broken/SimplifiedCurve.sol new file mode 100644 index 00000000..0b70680f --- /dev/null +++ b/CVLByExample/Curve/contracts/broken/SimplifiedCurve.sol @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.13; +import "../ERC20.sol"; +import "../ReentrancyGuard.sol"; +import "../CurveToken.sol"; +import "../CurveTokenExample.sol"; + +contract MintableToken is ERC20 { + + constructor (string memory name, string memory sym) ERC20(name, sym) { + + } + + function mint(address _user, uint _amount) public { + _mint(_user, _amount); + } +} + +contract SimplifiedCurve is ReentrancyGuard{ + //uint128 public constant 2 = 2; + uint256 constant A_PRECISION =100; + uint256 constant PRECISION = 10e18; + uint256 future_A_time; + uint256 future_A; + uint256 initial_A_time; + uint256 initial_A; + uint256[2] admin_balances; + // storage var "address[2] coins" was seperated to be able to link + address public coins_0; + address public coins_1; + address public lp_token; + address owner; + // address public underlying_token; // would be linked to ERC20 and equal to coins[1], but can't do directly due to CVL limitations + uint256 kill_deadline; + uint256 fee; + uint256 admin_fee; + uint256 future_fee; + uint256 future_owner; + uint256 future_admin_fee; + uint256 _DEMO_D; + + mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) _DEMO_D_MAPPING; + + constructor(address _lp_token, address _token_addr) payable { + lp_token = _lp_token; + coins_1 = _token_addr; + } + + // Compute parameter D of Curve's price function. + // The symplification returns the sum of the first two entries of xp. + function get_D(uint256[2] memory xp,uint256 amp) public view returns(uint256) { + uint256 S = 0; + uint256 Dprev = 0; + // Demo simplificaiton - in order to reduce the running time of the example. + // get_D currently crashes the prover's pre-SMT analysis or something + // uint256 x; + // return _DEMO_D; + // return _DEMO_D_MAPPING[xp[0]][xp[1]][amp]; + return xp[0] + xp[1]; + // Simplification end + + // Commenting out unreachable code of the simplification. + // The symplification does not affect the view reentrancy weakness + // because the fields that are changed + // before/ after the unresolved call are still read by the calling view function. + + // for (uint256 _x=0;_x Dprev){ + // if (D - Dprev <= 1){ + // return D; + // } + // } + // else{ + // if (Dprev - D <= 1){ + // return D; + // } + // } + // } + // revert(); + } + + function _A() view internal returns(uint256) { + + // Demo simplificaiton - return unconstrained CONST + return future_A; + // Simplification end + + // uint256 t1 = future_A_time; + // uint256 A1 = future_A; + // if (block.timestamp < t1){ + // uint256 A0 = initial_A; + // uint256 t0 = initial_A_time; + // if (A1 > A0){ + // return A0 + (A1 - A0) * (block.timestamp - t0) / (t1 - t0); + // } + // else{ + // return A0 - (A0 - A1) * (block.timestamp - t0) / (t1 - t0); + // } + // } + // else{ + // return A1; + // } + } + + function _balances(uint256 _value) internal view returns(uint256[2] memory) { + return [ + address(this).balance - admin_balances[0] - _value, + ERC20(coins_1).balanceOf(address(this)) - admin_balances[1]]; + } + + // function _balances_guarded(uint256 _value) public view returns(uint256[2] memory) { + // require(!_reentrancyGuardEntered(), "reading during reentrancy not allowed!"); + // return _balances(_value); + // } + + // function getVirtualPrice_guarded() public view returns(uint256) { + // require(!_reentrancyGuardEntered(), "reading during reentrancy not allowed!"); + // return getVirtualPrice(); + // } + + function getVirtualPrice() public view returns(uint256){ + uint256 D = this.get_D(_balances(0),_A()); + uint256 totalShares = ERC20(lp_token).totalSupply(); + return D * PRECISION / totalShares; + } + + function remove_liquidity( + uint256 _amount, + uint256[2] memory _min_amounts + ) + nonReentrant + public + returns(uint256[2] memory) + { + uint256[2] memory amounts = _balances(0); + uint256 total_supply = ERC20(lp_token).totalSupply(); + CurveToken(lp_token).burnFrom(msg.sender, _amount); + for (uint256 i;i<2;i++){ + uint256 value = amounts[i] * _amount / total_supply; + assert (value >= _min_amounts[i]); + amounts[i] = value; + if (i == 0){ + msg.sender.call{value:value}(""); + } + else{ + assert (ERC20(coins_1).transfer(msg.sender, value)); + } + } + return amounts; + } + + function addScenarioEther() public payable { + + } + +} + + +contract scenario { + + uint constant other_user_lp = 40e18; + uint constant underlying_asset_before = 80e18; + uint constant deposited_ether_before = 4e18; + uint constant attacker_lp = 40e18; + uint constant attacker_underlying = 80e18; + uint constant attacker_deposit_eth = 4e18; + address constant other_user = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2; + + function init_scenario(/*address other_user*/) payable public returns(address) { + CurveTokenExample lp_token = new CurveTokenExample(); + MintableToken token = new MintableToken("example", "ex"); + + // setup Curve contract and its ETH and shares BEFORE the attacker + require(msg.value >= deposited_ether_before + attacker_deposit_eth, "Not enough funds sent to init the scenario"); + SimplifiedCurve _curve = new SimplifiedCurve{value: deposited_ether_before}(address(lp_token), address(token)); + lp_token.mint(other_user, other_user_lp); + token.mint(address(_curve), underlying_asset_before); + + // Log the price before the attacker + // console.log("before the attacker got in the price is %s", _curve.getVirtualPrice()); + + // attakcer contract + attacker _attContract = new attacker(address(_curve)); + + // setup state (mints) + _curve.addScenarioEther{value: attacker_deposit_eth}(); + lp_token.mint(address(_attContract), attacker_lp); + token.mint(address(_curve), attacker_underlying); + + + // Run the exploit + _attContract.exec(); + + return address(_attContract); + } +} + +contract attacker{ + SimplifiedCurve public attacked; + ERC20 token; + CurveTokenExample lp_token; + + constructor(address attackedAddr){ + attacked = SimplifiedCurve(attackedAddr); + token = ERC20(attacked.coins_1()); + lp_token = CurveTokenExample(attacked.lp_token()); + } + function exec() public { + // prepare token + // console.log("After Attacker deposit price is %s",attacked.getVirtualPrice()); + uint256 my_lp_balance = lp_token.balanceOf(address(this)); + uint[2] memory zeros = [uint(0), 0]; + // console.log("trying to remove liq...."); + attacked.remove_liquidity(my_lp_balance, zeros); // virtual price dropped + // console.log("after the attack price is %s",attacked.getVirtualPrice()); + } + fallback() external payable { + // console.log("during the attack price is %s",attacked.getVirtualPrice()); + } +} \ No newline at end of file diff --git a/CVLByExample/Curve/contracts/correct/ManualInstrumentationSimplifiedCurveFixed.sol b/CVLByExample/Curve/contracts/correct/ManualInstrumentationSimplifiedCurveFixed.sol new file mode 100644 index 00000000..37eeb8de --- /dev/null +++ b/CVLByExample/Curve/contracts/correct/ManualInstrumentationSimplifiedCurveFixed.sol @@ -0,0 +1,247 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.13; +import "../ERC20.sol"; +import "../ReentrancyGuard.sol"; +import "../CurveToken.sol"; +import "../CurveTokenExample.sol"; + +contract MintableToken is ERC20 { + + constructor (string memory name, string memory sym) ERC20(name, sym) { + + } + + function mint(address _user, uint _amount) public { + _mint(_user, _amount); + } +} + + +contract ManualInstrumentationSimplifiedCurveFixed is ReentrancyGuard{ + // Manual instrumentation + uint256 public solghost_return_func1; + bool solghost_trigger_check; + // SOLIDITY GHOST Functions + function func1_caller() public returns(uint256) + { + return getVirtualPrice(); + } + + function sample_view_functions() internal{ + // Sample the values + solghost_return_func1 = getVirtualPrice(); + // Trigger the check in CVL + solghost_trigger_check = true; + } + + //uint128 public constant 2 = 2; + uint256 constant A_PRECISION =100; + uint256 constant PRECISION = 10e18; + uint256 future_A_time; + uint256 future_A; + uint256 initial_A_time; + uint256 initial_A; + uint256[2] admin_balances; + // storage var "address[2] coins" was seperated to be able to link + address public coins_0; + address public coins_1; + address public lp_token; + address owner; + // address public underlying_token; // would be linked to ERC20 and equal to coins[1], but can't do directly due to CVL limitations + uint256 kill_deadline; + uint256 fee; + uint256 admin_fee; + uint256 future_fee; + uint256 future_owner; + uint256 future_admin_fee; + uint256 _DEMO_D; + + mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) _DEMO_D_MAPPING; + + + + + // constructor(uint256 _future_A_time, uint256 _future_A, uint256 _initial_A_time, uint256 _initial_A, address owner ) { + + constructor(address _lp_token, address _token_addr) payable { + lp_token = _lp_token; + coins_1 = _token_addr; + } + + + // function get_D(uint xp_0, uint xp_1) + // Compute parameter D of Curve's price function. + function get_D(uint256[2] memory xp,uint256 amp) public view returns(uint256) { + require (!_reentrancyGuardEntered()); + uint256 S = 0; + uint256 Dprev = 0; + // Demo simplificaiton - unconstrained CONST + // get_D currently crashes the prover's pre-SMT analysis or something + // uint256 x; + // return _DEMO_D; + // return _DEMO_D_MAPPING[xp[0]][xp[1]][amp]; + return xp[0] + xp[1]; + // Simplification end + + for (uint256 _x=0;_x Dprev){ + if (D - Dprev <= 1){ + return D; + } + } + else{ + if (Dprev - D <= 1){ + return D; + } + } + } + revert(); + } + + function _A() view internal returns(uint256) { + + require (!_reentrancyGuardEntered()); + // Demo simplificaiton - return unconstrained CONST + return future_A; + // Simplification end + + uint256 t1 = future_A_time; + uint256 A1 = future_A; + if (block.timestamp < t1){ + uint256 A0 = initial_A; + uint256 t0 = initial_A_time; + if (A1 > A0){ + return A0 + (A1 - A0) * (block.timestamp - t0) / (t1 - t0); + } + else{ + return A0 - (A0 - A1) * (block.timestamp - t0) / (t1 - t0); + } + } + else{ + return A1; + } + } + + function _balances(uint256 _value) public view returns(uint256[2] memory) { + + require (!_reentrancyGuardEntered()); + return [ + address(this).balance - admin_balances[0] - _value, + ERC20(coins_1).balanceOf(address(this)) - admin_balances[1]]; + } + + function getVirtualPrice() public view returns(uint256){ + + require (!_reentrancyGuardEntered()); + uint256 D = this.get_D(_balances(0),_A()); + uint256 totalShares = ERC20(lp_token).totalSupply(); + return D * PRECISION / totalShares; + } + + function remove_liquidity( + uint256 _amount, + uint256[2] memory _min_amounts + ) + nonReentrant + public + returns(uint256[2] memory) + { + uint256[2] memory amounts = _balances(0); + uint256 total_supply = ERC20(lp_token).totalSupply(); + CurveToken(lp_token).burnFrom(msg.sender, _amount); + for (uint256 i;i<2;i++){ + uint256 value = amounts[i] * _amount / total_supply; + assert (value >= _min_amounts[i]); + amounts[i] = value; + if (i == 0){ + msg.sender.call{value:value}(""); + sample_view_functions(); + + } + else{ + assert (ERC20(coins_1).transfer(msg.sender, value)); + } + } + return amounts; + } + +} + + +contract scenario { + + uint constant other_user_lp = 40e18; + uint constant underlying_asset_before = 80e18; + uint constant deposited_ether_before = 4e18; + uint constant attacker_lp = 40e18; + uint constant attacker_underlying = 80e18; + uint constant attacker_deposit_eth = 4e18; + address constant other_user = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2; + + function init_scenario(/*address other_user*/) payable public returns(address) { + CurveTokenExample lp_token = new CurveTokenExample(); + MintableToken token = new MintableToken("example", "ex"); + + // setup ManualInstrumentationSimplifiedCurve contract and its ETH and shares BEFORE the attacker + require(msg.value >= deposited_ether_before + attacker_deposit_eth, "Not enough funds sent to init the scenario"); + ManualInstrumentationSimplifiedCurveFixed _curve = new ManualInstrumentationSimplifiedCurveFixed{value: deposited_ether_before}(address(lp_token), address(token)); + lp_token.mint(other_user, other_user_lp); + token.mint(address(_curve), underlying_asset_before); + + // Log the price before the attacker + // console.log("before the attacker got in the price is %s", _curve.getVirtualPrice()); + + // attacker contract + attacker _attContract = new attacker(address(_curve)); + + // setup state (mints) + // _curve.addScenarioEther{value: attacker_deposit_eth}(); + lp_token.mint(address(_attContract), attacker_lp); + token.mint(address(_curve), attacker_underlying); + + + // Run the exploit + _attContract.exec(); + + return address(_attContract); + } +} + +contract attacker{ + ManualInstrumentationSimplifiedCurveFixed public attacked; + ERC20 token; + CurveTokenExample lp_token; + + constructor(address attackedAddr){ + attacked = ManualInstrumentationSimplifiedCurveFixed(attackedAddr); + token = ERC20(attacked.coins_1()); + lp_token = CurveTokenExample(attacked.lp_token()); + } + function exec() public { + // prepare token + // console.log("After Attacker deposit price is %s",attacked.getVirtualPrice()); + uint256 my_lp_balance = lp_token.balanceOf(address(this)); + uint[2] memory zeros = [uint(0), 0]; + // console.log("trying to remove liq...."); + attacked.remove_liquidity(my_lp_balance, zeros); // virtual price dropped + // console.log("after the attack price is %s",attacked.getVirtualPrice()); + } + fallback() external payable { + // console.log("during the attack price is %s",attacked.getVirtualPrice()); + } +} \ No newline at end of file diff --git a/CVLByExample/Curve/contracts/correct/SimplifiedCurveFixed.sol b/CVLByExample/Curve/contracts/correct/SimplifiedCurveFixed.sol new file mode 100644 index 00000000..892f809f --- /dev/null +++ b/CVLByExample/Curve/contracts/correct/SimplifiedCurveFixed.sol @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.13; +import "../ERC20.sol"; +import "../ReentrancyGuard.sol"; +import "../CurveToken.sol"; +import "../CurveTokenExample.sol"; + +contract MintableToken is ERC20 { + + constructor (string memory name, string memory sym) ERC20(name, sym) { + + } + + function mint(address _user, uint _amount) public { + _mint(_user, _amount); + } +} + +contract SimplifiedCurveFixed is ReentrancyGuard{ + //uint128 public constant 2 = 2; + uint256 constant A_PRECISION =100; + uint256 constant PRECISION = 10e18; + uint256 future_A_time; + uint256 future_A; + uint256 initial_A_time; + uint256 initial_A; + uint256[2] admin_balances; + // storage var "address[2] coins" was seperated to be able to link + address public coins_0; + address public coins_1; + address public lp_token; + address owner; + // address public underlying_token; // would be linked to ERC20 and equal to coins[1], but can't do directly due to CVL limitations + uint256 kill_deadline; + uint256 fee; + uint256 admin_fee; + uint256 future_fee; + uint256 future_owner; + uint256 future_admin_fee; + uint256 _DEMO_D; + + mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) _DEMO_D_MAPPING; + + constructor(address _lp_token, address _token_addr) payable { + lp_token = _lp_token; + coins_1 = _token_addr; + } + + // The symplification returns the sum of the first two entries of xp. + // Compute parameter D of Curve's price function. + function get_D(uint256[2] memory xp,uint256 amp) public view returns(uint256) { + require (!_reentrancyGuardEntered()); + uint256 S = 0; + uint256 Dprev = 0; + // Demo simplificaiton - in order to reduce the running time of the example. + // get_D currently crashes the prover's pre-SMT analysis or something + // uint256 x; + // return _DEMO_D; + // return _DEMO_D_MAPPING[xp[0]][xp[1]][amp]; + return xp[0] + xp[1]; + // Simplification end + + // Commenting out unreachable code of the simplification. + // The symplification does not affect the view reentrancy weakness + // because the fields that are changed + // before/ after the unresolved call are still read by the calling view function. + + // for (uint256 _x=0;_x Dprev){ + // if (D - Dprev <= 1){ + // return D; + // } + // } + // else{ + // if (Dprev - D <= 1){ + // return D; + // } + // } + // } + // revert(); + } + + function _A() view internal returns(uint256) { + + // Demo simplificaiton - return unconstrained CONST + require (!_reentrancyGuardEntered()); + return future_A; + // Simplification end + + // uint256 t1 = future_A_time; + // uint256 A1 = future_A; + // if (block.timestamp < t1){ + // uint256 A0 = initial_A; + // uint256 t0 = initial_A_time; + // if (A1 > A0){ + // return A0 + (A1 - A0) * (block.timestamp - t0) / (t1 - t0); + // } + // else{ + // return A0 - (A0 - A1) * (block.timestamp - t0) / (t1 - t0); + // } + // } + // else{ + // return A1; + // } + } + + function _balances(uint256 _value) internal view returns(uint256[2] memory) { + require (!_reentrancyGuardEntered()); + return [ + address(this).balance - admin_balances[0] - _value, + ERC20(coins_1).balanceOf(address(this)) - admin_balances[1]]; + } + + // function _balances_guarded(uint256 _value) public view returns(uint256[2] memory) { + // require(!_reentrancyGuardEntered(), "reading during reentrancy not allowed!"); + // return _balances(_value); + // } + + // function getVirtualPrice_guarded() public view returns(uint256) { + // require(!_reentrancyGuardEntered(), "reading during reentrancy not allowed!"); + // return getVirtualPrice(); + // } + + function getVirtualPrice() public view returns(uint256){ + require (!_reentrancyGuardEntered()); + uint256 D = this.get_D(_balances(0),_A()); + uint256 totalShares = ERC20(lp_token).totalSupply(); + return D * PRECISION / totalShares; + } + + function remove_liquidity( + uint256 _amount, + uint256[2] memory _min_amounts + ) + nonReentrant + public + returns(uint256[2] memory) + { + uint256[2] memory amounts = _balances(0); + uint256 total_supply = ERC20(lp_token).totalSupply(); + CurveToken(lp_token).burnFrom(msg.sender, _amount); + for (uint256 i;i<2;i++){ + uint256 value = amounts[i] * _amount / total_supply; + assert (value >= _min_amounts[i]); + amounts[i] = value; + if (i == 0){ + msg.sender.call{value:value}(""); + } + else{ + assert (ERC20(coins_1).transfer(msg.sender, value)); + } + } + return amounts; + } + + function addScenarioEther() public payable { + + } + +} + + +contract scenario { + + uint constant other_user_lp = 40e18; + uint constant underlying_asset_before = 80e18; + uint constant deposited_ether_before = 4e18; + uint constant attacker_lp = 40e18; + uint constant attacker_underlying = 80e18; + uint constant attacker_deposit_eth = 4e18; + address constant other_user = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2; + + function init_scenario(/*address other_user*/) payable public returns(address) { + CurveTokenExample lp_token = new CurveTokenExample(); + MintableToken token = new MintableToken("example", "ex"); + + // setup Curve contract and its ETH and shares BEFORE the attacker + require(msg.value >= deposited_ether_before + attacker_deposit_eth, "Not enough funds sent to init the scenario"); + SimplifiedCurveFixed _curve = new SimplifiedCurveFixed{value: deposited_ether_before}(address(lp_token), address(token)); + lp_token.mint(other_user, other_user_lp); + token.mint(address(_curve), underlying_asset_before); + + // Log the price before the attacker + // console.log("before the attacker got in the price is %s", _curve.getVirtualPrice()); + + // attakcer contract + attacker _attContract = new attacker(address(_curve)); + + // setup state (mints) + _curve.addScenarioEther{value: attacker_deposit_eth}(); + lp_token.mint(address(_attContract), attacker_lp); + token.mint(address(_curve), attacker_underlying); + + + // Run the exploit + _attContract.exec(); + + return address(_attContract); + } +} + +contract attacker{ + SimplifiedCurveFixed public attacked; + ERC20 token; + CurveTokenExample lp_token; + + constructor(address attackedAddr){ + attacked = SimplifiedCurveFixed(attackedAddr); + token = ERC20(attacked.coins_1()); + lp_token = CurveTokenExample(attacked.lp_token()); + } + function exec() public { + // prepare token + // console.log("After Attacker deposit price is %s",attacked.getVirtualPrice()); + uint256 my_lp_balance = lp_token.balanceOf(address(this)); + uint[2] memory zeros = [uint(0), 0]; + // console.log("trying to remove liq...."); + attacked.remove_liquidity(my_lp_balance, zeros); // virtual price dropped + // console.log("after the attack price is %s",attacked.getVirtualPrice()); + } + fallback() external payable { + // console.log("during the attack price is %s",attacked.getVirtualPrice()); + } +} \ No newline at end of file diff --git a/CVLByExample/QuantifierExamples/README.md b/CVLByExample/QuantifierExamples/README.md index d1e4852e..b16afa1d 100644 --- a/CVLByExample/QuantifierExamples/README.md +++ b/CVLByExample/QuantifierExamples/README.md @@ -1,4 +1,4 @@ -# QuantifierExamples +# Quantifier Examples This repository contains examples of Certora specs using quantifiers and quantified invariants. These examples were presented in the advanced webinar on quantifiers: diff --git a/CVLByExample/aave-token-v3/.editorconfig b/CVLByExample/aave-token-v3/.editorconfig deleted file mode 100644 index 3ee22e5d..00000000 --- a/CVLByExample/aave-token-v3/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -# EditorConfig helps developers define and maintain consistent -# coding styles between different editors and IDEs -# http://editorconfig.org - -root = true - -[*] -indent_style = space -indent_size = 2 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true diff --git a/CVLByExample/aave-token-v3/.env.example b/CVLByExample/aave-token-v3/.env.example deleted file mode 100644 index de3ecbfa..00000000 --- a/CVLByExample/aave-token-v3/.env.example +++ /dev/null @@ -1,2 +0,0 @@ -ETH_RPC_URL=https://eth-mainnet.alchemyapi.io/v2/ALCHEMY_API_KEY -FORK_BLOCK=someBlockNumber diff --git a/CVLByExample/aave-token-v3/.gitmodules b/CVLByExample/aave-token-v3/.gitmodules deleted file mode 100644 index b0079ce3..00000000 --- a/CVLByExample/aave-token-v3/.gitmodules +++ /dev/null @@ -1,9 +0,0 @@ -[submodule "lib/openzeppelin-contracts"] - path = lib/openzeppelin-contracts - url = https://github.com/OpenZeppelin/openzeppelin-contracts -[submodule "lib/aave-token-v2"] - path = lib/aave-token-v2 - url = https://github.com/aave/aave-token-v2 -[submodule "lib/forge-std"] - path = lib/forge-std - url = https://github.com/foundry-rs/forge-std diff --git a/CVLByExample/aave-token-v3/.prettierrc b/CVLByExample/aave-token-v3/.prettierrc deleted file mode 100644 index 2caa9822..00000000 --- a/CVLByExample/aave-token-v3/.prettierrc +++ /dev/null @@ -1,16 +0,0 @@ -{ - "printWidth": 100, - "trailingComma": "es5", - "semi": true, - "singleQuote": true, - "tabWidth": 2, - "overrides": [ - { - "files": "*.sol", - "options": { - "semi": true, - "printWidth": 100 - } - } - ] -} diff --git a/CVLByExample/aave-token-v3/LICENSE b/CVLByExample/aave-token-v3/LICENSE deleted file mode 100644 index 07f396a0..00000000 --- a/CVLByExample/aave-token-v3/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2022 BGD Labs - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/CVLByExample/aave-token-v3/Makefile b/CVLByExample/aave-token-v3/Makefile deleted file mode 100644 index dfe4fd7a..00000000 --- a/CVLByExample/aave-token-v3/Makefile +++ /dev/null @@ -1,17 +0,0 @@ -# include .env file and export its env vars -# (-include to ignore error if it does not exist) --include .env - -# deps -update:; forge update - -# Build & test -build :; forge build --sizes - -.PHONY : test - -# IMPORTANT It is highly probable that will be necessary to modify the --fork-block-number, depending on the test -test :; forge test -vvv --rpc-url=${ETH_RPC_URL} --fork-block-number ${FORK_BLOCK} -trace :; forge test -vvvv --rpc-url=${ETH_RPC_URL} -clean :; forge clean -snapshot :; forge snapshot \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/README.md b/CVLByExample/aave-token-v3/README.md deleted file mode 100644 index e4cbd300..00000000 --- a/CVLByExample/aave-token-v3/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# $AAVE V3 - -Next iteration of the AAVE token, optimized for its usage on the upcoming new iteration of the Aave Governance. - -More detailed description and specification [HERE](./properties.md) - -## Setup - -This repository requires having Foundry installed in the running machine. Instructions on how to do it [HERE](https://github.com/foundry-rs/foundry#installation). - -After having installed Foundry: -1. Add a `.env` file with properly configured `ETH_RPC_URL` and `FORK_BLOCK`, following the example on `.env.example` -2. `make test` to run the simulation tests. - -## Copyright -2022 BGD Labs \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/certora/Makefile b/CVLByExample/aave-token-v3/certora/Makefile deleted file mode 100644 index 5e6e1bce..00000000 --- a/CVLByExample/aave-token-v3/certora/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -default: help - -PATCH = applyHarness.patch -CONTRACTS_DIR = ../src -LIB_DIR = ../lib -MUNGED_DIR = munged - -help: - @echo "usage:" - @echo " make clean: remove all generated files (those ignored by git)" - @echo " make $(MUNGED_DIR): create $(MUNGED_DIR) directory by applying the patch file to $(CONTRACTS_DIR)" - @echo " make record: record a new patch file capturing the differences between $(CONTRACTS_DIR) and $(MUNGED_DIR)" - -munged: $(wildcard $(CONTRACTS_DIR)/*.sol) $(PATCH) - rm -rf $@ - cp -r $(CONTRACTS_DIR) $@ - cp -r $(LIB_DIR) $@ - patch -p0 -d $@ < $(PATCH) - -record: - diff -uN $(CONTRACTS_DIR) $(MUNGED_DIR) | sed 's+$(CONTRACTS_DIR)/++g' | sed 's+$(MUNGED_DIR)++g' > $(PATCH) - -clean: - git clean -fdX - touch $(PATCH) - diff --git a/CVLByExample/aave-token-v3/certora/README.md b/CVLByExample/aave-token-v3/certora/README.md deleted file mode 100644 index 58912555..00000000 --- a/CVLByExample/aave-token-v3/certora/README.md +++ /dev/null @@ -1,42 +0,0 @@ -## Verification Overview -The current directory contains Certora's formal verification of AAVE's V3 token. -In this directory you will find three subdirectories: - -1. specs - Contains all the specification files that were written by Certora for the token code. We have created two spec files, `base.spec`, `delegate.spec`, `erc20.spec` and `general.spec`. -- `base.spec` contains method declarations, CVL functions and definitions used by the main specification files -- `delegate.spec` contains rules that prove various delegation properties -- `erc20.spec` contains rules that prove ERC20 general rules, e.g. correctness of transfer and others -- `general.spec` contains general delegation invariants, e.g. sum of delegated and undelegated balances equals to -total supply - -2. scripts - Contains all the necessary run scripts to execute the spec files on the Certora Prover. These scripts composed of a run command of Certora Prover, contracts to take into account in the verification context, declaration of the compiler and a set of additional settings. -- `verifyDelegate.sh` is a script for running `delegate.spec` -- `verifyGeneral.sh` is a script for running `general.spec` -- `erc20.sh` is a script for running `erc20.spec` - -3. harness - Contains all the inheriting contracts that add/simplify functionalities to the original contract. -We use two harnesses: -- `AaveTokenV3Harness.sol` used by `erc20.sh` and `delegate.sh`. It inherits from the original AaveV3Token -contract and adds a few getter functions. - -- `AaveTokenV3HarnessStorage.sol` used by `general.sh`. It uses a modified a version of AaveV3Token contract -where the `delegationState` field of the `_balances` struct is refactored to be of type uint8 instead of -`DelegationState` enum. This is done in order to bypass a current limitation of the tool and write a hook -on the `delegationState` field (hooks don't support enum fields at the moment) - - -
- ---- - -## Running Instructions -To run a verification job: - -1. Open terminal and `cd` your way to the main aave-token-v3 directory - -2. Run the script you'd like to get results for: - ``` - sh certora/scripts/verifyDelegate.sh - sh certora/scripts/verifyGeneral.sh - sh certora/scripts/erc20.sh - ``` diff --git a/CVLByExample/aave-token-v3/certora/applyHarness.patch b/CVLByExample/aave-token-v3/certora/applyHarness.patch deleted file mode 100644 index e69de29b..00000000 diff --git a/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3Harness.sol b/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3Harness.sol deleted file mode 100644 index 6a8a0998..00000000 --- a/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3Harness.sol +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: MIT - -/** - - This is an extension of the AaveTokenV3 with added getters on the _balances fields - - */ - -pragma solidity ^0.8.0; - -import {AaveTokenV3} from '../../src/AaveTokenV3.sol'; - -contract AaveTokenV3Harness is AaveTokenV3 { - // returns user's token balance, used in some community rules - function getBalance(address user) public view returns (uint104) { - return _balances[user].balance; - } - - // returns user's delegated proposition balance - function getDelegatedPropositionBalance(address user) public view returns (uint72) { - return _balances[user].delegatedPropositionBalance; - } - - // returns user's delegated voting balance - function getDelegatedVotingBalance(address user) public view returns (uint72) { - return _balances[user].delegatedVotingBalance; - } - - //returns user's delegating proposition status - function getDelegatingProposition(address user) public view returns (bool) { - return - _balances[user].delegationState == DelegationState.PROPOSITION_DELEGATED || - _balances[user].delegationState == DelegationState.FULL_POWER_DELEGATED; - } - - // returns user's delegating voting status - function getDelegatingVoting(address user) public view returns (bool) { - return - _balances[user].delegationState == DelegationState.VOTING_DELEGATED || - _balances[user].delegationState == DelegationState.FULL_POWER_DELEGATED; - } - - // returns user's voting delegate - function getVotingDelegate(address user) public view returns (address) { - return _votingDelegateeV2[user]; - } - - // returns user's proposition delegate - function getPropositionDelegate(address user) public view returns (address) { - return _propositionDelegateeV2[user]; - } - - // returns user's delegation state - function getDelegationState(address user) public view returns (DelegationState) { - return _balances[user].delegationState; - } -} diff --git a/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3HarnessCommunity.sol b/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3HarnessCommunity.sol deleted file mode 100644 index cd1dde17..00000000 --- a/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3HarnessCommunity.sol +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: MIT - -/** - - This is an extension of the AaveTokenV3 with added getters and view function wrappers needed for - community-written rules - */ - -pragma solidity ^0.8.0; - -import {AaveTokenV3} from '../../src/AaveTokenV3.sol'; - -contract AaveTokenV3Harness is AaveTokenV3 { - function getBalance(address user) public view returns (uint104) { - return _balances[user].balance; - } - - function getDelegatedPropositionBalance(address user) public view returns (uint72) { - return _balances[user].delegatedPropositionBalance; - } - - function getDelegatedVotingBalance(address user) public view returns (uint72) { - return _balances[user].delegatedVotingBalance; - } - - function getDelegatingProposition(address user) public view returns (bool) { - return - _balances[user].delegationState == DelegationState.PROPOSITION_DELEGATED || - _balances[user].delegationState == DelegationState.FULL_POWER_DELEGATED; - } - - function getDelegatingVoting(address user) public view returns (bool) { - return - _balances[user].delegationState == DelegationState.VOTING_DELEGATED || - _balances[user].delegationState == DelegationState.FULL_POWER_DELEGATED; - } - - function getVotingDelegate(address user) public view returns (address) { - return _votingDelegateeV2[user]; - } - - function getPropositionDelegate(address user) public view returns (address) { - return _propositionDelegateeV2[user]; - } - - function getDelegationState(address user) public view returns (DelegationState) { - return _balances[user].delegationState; - } - - function getNonce(address user) public view returns (uint256) { - return _nonces[user]; - } - - function ecrecoverWrapper( - bytes32 hash, - uint8 v, - bytes32 r, - bytes32 s - ) public pure returns (address) { - return ecrecover(hash, v, r, s); - } - - function computeMetaDelegateHash( - address delegator, - address delegatee, - uint256 deadline, - uint256 nonce - ) public view returns (bytes32) { - bytes32 digest = keccak256( - abi.encodePacked( - '\x19\x01', - DOMAIN_SEPARATOR, - keccak256(abi.encode(DELEGATE_TYPEHASH, delegator, delegatee, nonce, deadline)) - ) - ); - return digest; - } - - function computeMetaDelegateByTypeHash( - address delegator, - address delegatee, - GovernancePowerType delegationType, - uint256 deadline, - uint256 nonce - ) public view returns (bytes32) { - bytes32 digest = keccak256( - abi.encodePacked( - '\x19\x01', - DOMAIN_SEPARATOR, - keccak256( - abi.encode( - DELEGATE_BY_TYPE_TYPEHASH, - delegator, - delegatee, - delegationType, - nonce, - deadline - ) - ) - ) - ); - return digest; - } -} diff --git a/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3HarnessStorage.sol b/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3HarnessStorage.sol deleted file mode 100644 index a86db931..00000000 --- a/CVLByExample/aave-token-v3/certora/harness/AaveTokenV3HarnessStorage.sol +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: MIT - -/** - - This is an extension of the harnessed AaveTokenV3 with added getters on the _balances fields. - The imported harnessed AaveTokenV3 contract uses uint8 instead of an enum for delegation state. - - This modification is introduced to bypass a current Certora Prover limitation on accessing - enum fields inside CVL hooks - - */ - -pragma solidity ^0.8.0; - -import {AaveTokenV3} from '../../src/AaveTokenV3.sol'; - -contract AaveTokenV3Harness is AaveTokenV3 { - function getBalance(address user) public view returns (uint104) { - return _balances[user].balance; - } - - function getDelegatedPropositionBalance(address user) public view returns (uint72) { - return _balances[user].delegatedPropositionBalance; - } - - function getDelegatedVotingBalance(address user) public view returns (uint72) { - return _balances[user].delegatedVotingBalance; - } - - function getDelegatingProposition(address user) public view returns (bool) { - DelegationState state = _balances[user].delegationState; - return - state == DelegationState.PROPOSITION_DELEGATED || - state == DelegationState.FULL_POWER_DELEGATED; - } - - function getDelegatingVoting(address user) public view returns (bool) { - DelegationState state = _balances[user].delegationState; - return - state == DelegationState.VOTING_DELEGATED || - state == DelegationState.FULL_POWER_DELEGATED; - } - - function getVotingDelegate(address user) public view returns (address) { - return _votingDelegateeV2[user]; - } - - function getPropositionDelegate(address user) public view returns (address) { - return _propositionDelegateeV2[user]; - } - - function getDelegationState(address user) public view returns (DelegationState) { - return _balances[user].delegationState; - } -} diff --git a/CVLByExample/aave-token-v3/certora/harness/README.md b/CVLByExample/aave-token-v3/certora/harness/README.md deleted file mode 100644 index 2338a7de..00000000 --- a/CVLByExample/aave-token-v3/certora/harness/README.md +++ /dev/null @@ -1,7 +0,0 @@ -We use two harnesses: - -- AaveTokenV3Harness adds a few simple getters to the original AaveTokenV3 code - -- AaveTokenV3HarnessStorage is used to verify general.spec. It changes delegationState field in _balances -to be uint8 instead of DelegationState enum. The harness files are produced by running `make munged` which -patches the original code with `applyHarness.patch` patch. diff --git a/CVLByExample/aave-token-v3/certora/report/Formal Verification Report of AAVE Token V3.md b/CVLByExample/aave-token-v3/certora/report/Formal Verification Report of AAVE Token V3.md deleted file mode 100644 index d96167cd..00000000 --- a/CVLByExample/aave-token-v3/certora/report/Formal Verification Report of AAVE Token V3.md +++ /dev/null @@ -1,924 +0,0 @@ -![Certora logo](https://hackmd.io/_uploads/SkaW6ZXr9.png) - -# Formal Verification Report of AAVE Token V3 - -## Summary - -This document describes the specification and verification of AAVE Token V3 using the Certora Prover. The work was undertaken from July 15th to August 10th, 2022. The latest commit reviewed and run through the Certora Prover was [8bb9f896](https://github.com/bgd-labs/aave-token-v3/commit/8bb9f8966991f8225adbce2b5cd38b5ae3612ecd). - -The scope of this verification is AAVE token V3 code which includes the following contracts: - -* `AaveV3Token.sol` - - -And its parent contracts: - -* `BaseAaveToken.sol` -* `BaseAaveTokenV2.sol` - -This project has been a part of a joint Certora and Aave community program. Contributors from the community have conducted independent formal verification of the code, where Certora has provided an initial setup for writing a specification. - -19 out of the 25 community participants submitted spec files containing formal specifications resulting in 275 properties in total. Out of the 275 correctness rules, 240 quality rules passed our professional review and credited their authors with grants. - -Selected rules written by the community are included in this report in the [_Community_](#Community) section. - -Certora also performed a manual audit of these contracts. - -During this verification process, the Certora Prover discovered issues in the code which are listed in the tables below. - -All the rules and specification files are publicly available and can be found in [AAVE Token V3 repository](https://github.com/bgd-labs/aave-token-v3/tree/certora/certora). - -## List of Main Issues Discovered - -**Severity: **Low**** - -Discovered independently by the following contributors: -https://github.com/Elpacos -https://github.com/himanshu-Bhatt -https://github.com/jessicapointing -and Certora team. - -Discover - -| Issue: | Precision loss during voting power transfer | -| -------- | -------- | -| Description: | When calculating delegated balance on token transfer, the new delegated balance of a delegate was calculated with a small precision loss that violated the property $$delegatee1Power_{t1} = delegatee1Power_{t0} - z / 10^{10} * 10^{10}$$ after a delegator to delegatee1 transfers z amount of tokens. -|Property Violated: | vpTransferWhenOnlyOneIsDelegating (Property #6) and others | -| AAVE Response:| The issue was fixed in commit [a287d134](https://github.com/bgd-labs/aave-token-v3/commit/a287d134903618bed5671d411c66641bfd96002b) and the relevant property was modified to be $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance_{t0} / 10^{10} * 10^{10} + account1Balance_{t1} / 10^{10} * 10^{10}$$ - -## List of Issues Discovered Independently By The Community - -**Severity: **High**** - -Found by the following contributors: -https://github.com/Elpacos - -| Issue: | Wrong parameters order in a `_transferWithDelegation` call | -| -------- | -------- | -| Description: | This issue was present in an intermediary version of the code given to the community to verify, but not in the finalized version that Certora has verified. It was introduced for a short period of time during development, and immediately fixed by the AAVE team. -|Property Violated: | multiple properties | -| AAVE Response:| The issue was fixed in commit [190c03f4](https://github.com/bgd-labs/aave-token-v3/commit/190c03f43208ae85bfcbf7dcb4a0022bb34df169) - - - - - ## Disclaimer - -The Certora Prover takes as input a contract and a specification and formally proves that the contract satisfies the specification in all scenarios. Importantly, the guarantees of the Certora Prover are scoped to the provided specification, and the Certora Prover does not check any cases not covered by the specification. - -We hope that this information is useful, but provide no warranty of any kind, explicit or implied. The contents of this report should not be construed as a complete guarantee that the contract is secure in all dimensions. In no event shall Certora or any of its employees be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the results reported here. - -# Summary of Formal Verification - -## Overview of the AAVE Token V3 - -`AaveV3Token.sol` is the main contract. It inherits from `BaseAaveToken.sol` and `BaseAaveTokenV2.sol`. - -The following description is taken from the token [repository](https://github.com/bgd-labs/aave-token-v3/blob/main/properties.md): - -AAVE is an ERC20 token deployed on Ethereum, which main utility is participating in the Aave governance system via voting on proposals or creating them. - -AAVE is a transparent proxy contract, and its current [implementation](https://etherscan.io/address/0xc13eac3b4f9eed480045113b7af00f7b5655ece8#code) is version 2. - -Together with all the standard ERC20 functionalities, the current implementation includes extra logic mainly for the management and accounting of voting and proposition power. Due to the design/architecture of the Aave governance v2 system, of which AAVE is the main voting asset, the current AAVE implementation makes the token transfers quite gas-consuming, as multiple snapshots of data (voting and proposition power) need to be stored all the time. - -With a new iteration of the Aave governance in the Aave/BGD roadmap down the line, snapshots on the token will not be required anymore for its integration with the governance system. So this new version 3 of AAVE consists mainly of removing the snapshotting, together with adding extra minor meta-transactions capabilities. - -## Assumptions and Simplifications Made During Verification - - - -The invariants in `general.spec` were proven on a slightly modified version of the token code. To bypass a current limitation of the Certora prover, we've refactored the `delegationState` field of the `_balances` struct to be a `uint8` instead of a `DelegationState` enum type. The `AaveV3Token.sol` code was modified to accomodate this change. - -These changes can be seen in the [patch file](https://github.com/bgd-labs/aave-token-v3/blob/certora/certora/applyHarness.patch) in the Certora branch of the token repository. - -To create this harness, we run `make munged` command from the `certora` directory (on the `certora` branch). - -- We unroll loops. Violations that require a loop to execute more than twice will not be detected. - -## Notations - -✔️ indicates the rule is formally verified on the latest reviewed commit. We write ✔️* when the rule was verified on the simplified assumptions described above in "Assumptions and Simplifications Made During Verification". - -❌ indicates the rule was violated under one of the tested versions of the code. - - -🔁 indicates the rule is timing out. - -Our tool uses Hoare triples of the form {p} C {q}, which means that if the execution of program C starts in any state satisfying p, it will end in a state satisfying q. This logical structure is reflected in the included formulae for many of the properties below. Note that p and q here can be thought of as analogous to `require` and `assert` in Solidity. - -The syntax {p} (C1 ~ C2) {q} is a generalization of Hoare rules, called relational properties. {p} is a requirement on the states before C1 and C2, and {q} describes the states after their executions. Notice that C1 and C2 result in different states. As a special case, C1 ~op C2, where op is a getter, indicating that C1 and C2 result in states with the same value for op. - -Our tool consists of a special struct type variable called environment, usually denoted by e. This complex type includes the various block data context accessible by solidity (e.g. block.timestamp, msg.sender, msg.value etc.) -These fields are accessible via the environment variable. - -## Community - -The following properties were written and verified by contributors from the Aave community - -1. **permitIntegrity** -Integrity of permit function - successful permit function increases the nonce of owner by 1 and also changes the allowance of owner to spender. -Contributed by https://github.com/parth-15 -``` - { - nonceBefore = getNonce(owner) - } - < - permit(owner, spender, value, deadline, v, r, s) - > - { - allowance(owner, spender) == value && getNonce(owner) == nonceBefore + 1 - } -``` -2. **addressZeroNoPower** -Address 0 has no voting or proposition power. -Contributed by https://github.com/JayP11 -``` -{ - getPowerCurrent(0, VOTING_POWER) == 0 && getPowerCurrent(0, PROPOSITION_POWER) == && balanceOf(0) == 0 -} -``` - -3. **metaDelegateByTypeOnlyCallableWithProperlySignedArguments** -Verify that `metaDelegateByType` can only be called with a signed request. -Contributed by https://github.com/kustosz -``` - { - ecrecover(v,r,s) != delegator - } - < - metaDelegateByType@withrevert(delegator, delegatee, delegationType, deadline, v, r, s) - > - { - lastReverted == true - } -``` -4. **metaDelegateNonRepeatable** -Verify that it's impossible to use the same arguments to call `metaDalegate` twice. -Contributed by https://github.com/kustosz -``` - { - hash1 = computeMetaDelegateHash(delegator, delegatee, deadline, nonce) - hash2 = computeMetaDelegateHash(delegator, delegatee, deadline, nonce + 1) - ecrecover(hash1, v, r, s) == delegator - } - < - metaDelegate(e1, delegator, delegatee, v, r, s) - metaDelegate@withrevert(e2, delegator, delegatee, delegationType, deadline, v, r, s) - > - { - lastReverted == true - } -``` -5. **delegatingToAnotherUserRemovesPowerFromOldDelegatee** -Power of the previous delegate is removed when the delegatee delegates to another delegate. -Contributed by https://github.com/priyankabhanderi -``` - { - _votingBalance = getDelegatedVotingBalance(alice) - } - < - delegateByType(alice, VOTING_POWER) - delegateByType(bob, VOTING_POWER) - > - { - alice != bob => getDelegatedVotingBalance(alice) == _votingBalance - } -``` -6. **powerChanges** -Voting and proposition power change only as a result of specific functions. -Contributed by https://github.com/top-sekret -``` - { - powerBefore = getPowerCurrent(alice, type) - } - < - f(e, args) - > - { - powerAfter = getPowerCurrent(alice, type) - powerAfter != powerBefore => - f.selector == delegate(address).selector || - f.selector == delegateByType(address, uint8).selector || - f.selector == metaDelegate(address, address, uint256, uint8, bytes32, bytes32).selector || - f.selector == metaDelegateByType(address, address, uint8, uint256, uint8, bytes32, bytes32).selector || - f.selector == transfer(address, uint256).selector || - f.selector == transferFrom(address, address, uint256).selector - } -``` -7. **delegateIndependence** -Changing a delegate of one type doesn't influence the delegate of the other type. -Written by https://github.com/top-sekret -``` - { - delegateBefore = type == 1 ? getPropositionDelegate(e.msg.sender) : getVotingDelegate(e.msg.sender) - } - < - delegateByType(e, delegatee, 1 - type) - > - { - delegateBefore = type == 1 ? getPropositionDelegate(e.msg.sender) : getVotingDelegate(e.msg.sender) - delegateBefore == delegateAfter - } -``` -8. **votingPowerChangesWhileNotBeingADelegatee** -Verify that voting power increases/decreases while not being a voting delegatee yourself. -Contributed by https://github.com/Zarfsec -``` - { - votingPowerBefore = getPowerCurrent(a, VOTING_POWER) - balanceBefore = balanceOf(a) - isVotingDelegatorBefore = getDelegatingVoting(a) - isVotingDelegateeBefore = getDelegatedVotingBalance(a) != 0 - } - < - f(e, args) - > - { - votingPowerAfter = getPowerCurrent(a, VOTING_POWER() - balanceAfter = getBalance(a) - isVotingDelegatorAfter = getDelegatingVoting(a); - isVotingDelegateeAfter = getDelegatedVotingBalance(a) != 0 - - votingPowerBefore < votingPowerAfter <=> - (!isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore < balanceAfter)) || - (isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore != 0)) - && - votingPowerBefore > votingPowerAfter <=> - (!isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore > balanceAfter)) || - (!isVotingDelegatorBefore && isVotingDelegatorAfter && (balanceBefore != 0)) - } -``` - -9. **propositionPowerChangesWhileNotBeingADelegatee** -Verify that proposition power increases/decreases while not being a voting delegatee yourself. -Contributed by https://github.com/Zarfsec -``` - { - propositionPowerBefore = getPowerCurrent(a, PROPOSITION_POWER) - balanceBefore = balanceOf(a) - isPropositionDelegatorBefore = getDelegatingProposition(a) - isPropositionDelegateeBefore = getDelegatedPropositionBalance(a) != 0 - } - < - f(e, args) - > - { - propositionPowerAfter = getPowerCurrent(a, PROPOSITION_POWER() - balanceAfter = getBalance(a) - isPropositionDelegatorAfter = getDelegatingProposition(a); - isPropositionDelegateeAfter = getDelegatedPropositionBalance(a) != 0 - - propositionPowerBefore < propositionPowerAfter <=> - (!isPropositionDelegatorBefore && !isPropositionDelegatorAfter && (balanceBefore < balanceAfter)) || - (isPropositionDelegatorBefore && !isPropositionDelegatorAfter && (balanceBefore != 0)) - && - propositionPowerBefore > propositionPowerAfter <=> - (!isPropositionDelegatorBefore && !isPropositionDelegatorAfter && (balanceBefore > balanceAfter)) || - (!isPropositionDelegatorBefore && isPropositionDelegatorAfter && (balanceBefore != 0)) - } -``` -10. **allowanceStateChange** -Allowance only changes as a result of specific subset of functions. -Contributed by https://github.com/oracleorb -``` - { - allowanceBefore = allowance(owner, spender) - } - < - f(e, args) - > - { - allowance(owner, spender) != allowanceBefore =>f.selector==approve(address,uint256).selector - || f.selector==increaseAllowance(address,uint256).selector - || f.selector==decreaseAllowance(address,uint256).selector - || f.selector==transferFrom(address,address,uint256).selector - || f.selector==permit(address,address,uint256,uint256,uint8,bytes32,bytes32).selector - - } -``` - - -## Formal Properties for AaveTokenV3 -The following properties were written and verified by Certora - -### Delegation Invariants - -1. **delegateCorrectness** ✔️ -User's delegation flag is switched on iff user is delegating to an address other than his own own or 0 -``` - { - (getVotingDelegate(account) == account || getVotingDelegate(account) == 0) <=> !getDelegatingVoting(account) - && - (getPropositionDelegate(account) == account || getPropositionDelegate(account) == 0) <=> !getDelegatingProposition(account) - } -``` - -2. **sumOfVBalancesCorrectness** ✔️ -Sum of delegated voting balances and undelegated voting balances is equal to total supply - -$$\sum balances[u'].delegatedVotingBalance * 10^{10} + \sum balanceOf(u) = totalSupply()$$ - -where getVotingDelegate(u) == 0 - -``` - { - sumDelegatedVotingBalances + sumUndelegatedVotingBalances == totalSupply() - } -``` -3. **sumOfPBalancesCorrectness** ✔️ -Sum of delegated proposition balances and undelegated proposition balances is equal to total supply. -$$\sum balances[u'].delegatedPropositionBalance * 10^{10} + \sum balanceOf(u) = totalSupply()$$ - -where getPropositionDelegate(u) == 0 -``` - { - sumDelegatedPropositionBalances + sumUndelegatedPropositionBalances == totalSupply() - } -``` - -### Delegation Properties - - -4. **powerWhenNotDelegating** ✔️ -If an account is not receiving delegation of power (one type) from anybody, -and that account is not delegating that power to anybody, the power of that account must be equal to its token balance. - -``` - { - dvb = _balances[account].delegatedVotingBalance - votingPower = getPowerCurrent(account, VOTING_POWER) - (dvb == 0 && !isDelegatingVoting(account)) => votingPower == balanceOf(account) - } -``` - -5. **vpTransferWhenBothNotDelegating** ✔️ -When both accounts are not delegating: -On transfer of z amount of tokens from account1 to account2, voting power holds the following properties: -$$account1Power_{t1} = account1Power_{t0} - z$$ $$account2Power_{t1} = account2Power_{t0} + z$$ - -``` - { - !isDelegatingVoting(account1) && !isDelegatingVoting(account2) - account1PowerBefore = getPowerCurrent(account1, VOTING_POWER) - account2PowerBefore = getPowerCurrent(account2, VOTING_POWER) - account3PowerBefore = getPowerCurrent(account3, VOTING_POWER) - } - < - transferFrom(account1, account2, z) - > - { - getPowerCurrent(account1, VOTING_POWER) == account1PowerBefore - z - getPowerCurrent(account2, VOTING_POWER) == account2PowerBefore + z - getPowerCurrent(account3, VOTING_POWER) == account3PowerBefore - } -``` -6. **ppTransferWhenBothNotDelegating** ✔️ -When both account1 and account2 are not delegating: -On transfer of z amount of tokens from account1 to account2, proposition power holds the following properties: -$$account1Power_{t1} = account1Power_{t0} - z$$ $$account2Power_{t1} = account2Power_{t0} + z$$ - -``` - { - !isDelegatingProposition(account1) && !isDelegatingProposition(account2) - account1PowerBefore = getPowerCurrent(account1, PROPOSITION_POWER) - account2PowerBefore = getPowerCurrent(account2, PROPOSITION_POWER) - account3PowerBefore = getPowerCurrent(account3, PROPOSITION_POWER) - } - < - transferFrom(account1, account2, z) - > - { - getPowerCurrent(account1, PROPOSITION_POWER) == account1PowerBefore - z - getPowerCurrent(account2, PROPOSITION_POWER) == account2PowerBefore + z - getPowerCurrent(account3, PROPOSITION_POWER) == account3PowerBefore - } -``` -7. **vpDelegateWhenBothNotDelegating** ✔️ -When both account1 and account2 are not delegating: -After account1 will delegate his voting power to account2 - - $$account1Power_{t1} = account1Power_{t0} - account1Balance$$ - - $$account2Power_{t1} = account2Power_{t0} + account1Balance / 10^{10} * 10^{10}$$ - - $$account1PowerDelegatee_{t1} = account2$$ -``` - { - account1 = e.msg.sender - !isDelegatingVoting(account1) && !isDelegatingVoting(account2) - account1PowerBefore = getPowerCurrent(account1, VOTING_POWER) - account2PowerBefore = getPowerCurrent(account2, VOTING_POWER) - account3PowerBefore = getPowerCurrent(account3, VOTING_POWER) - } - < - delegate(account2) - > - { - getPowerCurrent(account1, VOTING_POWER) == account1PowerBefore - balanceOf(account1) - getPowerCurrent(account2, VOTING_POWER) == account2PowerBefore + balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(account3, VOTING_POWER) == account3PowerBefore - } -``` -8. **ppDelegateWhenBothNotDelegating**✔️ - -When both account1 and account2 are not delegating: -After account1 will delegate his proposition power to account2 - $$account1Power_{t1} = account1Power_{t0} - account1Balance$$ - - $$account2Power_{t1} = account2Power_{t0} + account1Balance / 10^{10} * 10^{10}$$ - - $$account1PowerDelegatee_{t1} = account2$$ -``` - { - account1 = e.msg.sender - !isDelegatingProposition(account1) && !isDelegatingProposition(account2) - account1PowerBefore = getPowerCurrent(account1, PROPOSITION_POWER) - account2PowerBefore = getPowerCurrent(account2, PROPOSITION_POWER) - account3PowerBefore = getPowerCurrent(account3, PROPOSITION_POWER) - } - < - delegate(account2) - > - { - getPowerCurrent(account1, PROPOSITION_POWER) == account1PowerBefore - balanceOf(account1) - getPowerCurrent(account2, PROPOSITION_POWER) == account2PowerBefore + balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(account3, PROPOSITION_POWER) == account3PowerBefore - } -``` - -9. **vpTransferWhenOnlyOneIsDelegating** ✔️ -When account1 is delegating voting power to delegatee1 and account2 is not delegating voting power: -On transfer of z amount of tokens from account1 to account2 -$$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance_{t0} / 10^{10} * 10^{10} + account1Balance_{t1} / 10^{10} * 10^{10}$$ - - $$account2Power_{t1} = account2Power_{t0} + z$$ -``` - { - isDelegatingVoting(account1) && !isDelegatingVoting(account2) - account1PowerBefore = getPowerCurrent(account1, VOTING_POWER) - account2PowerBefore = getPowerCurrent(account2, VOTING_POWER) - account3PowerBefore = getPowerCurrent(account3, VOTING_POWER) - delegatee1PowerBefore = getPowerCurrent(delegatee1, VOTING_POWER) - balanceAccount1Before = balanceOf(account1) - } - < - transferFrom(account1, account2, z) - > - { - getPowerCurrent(account1, VOTING_POWER) == account1PowerBefore == 0 - getPowerCurrent(delegatee1, VOTING_POWER) == delegatee1PowerBefore - balanceAccount1Before / 10^10 * 10^10 + balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(account2, VOTING_POWER) == account2PowerBefore + z - getPowerCurrent(account3, VOTING_POWER) == account3PowerBefore - } -``` -10. **ppTransferWhenOnlyOneIsDelegating** ✔️ -When account1 is delegating proposition power to delegatee1 and account2 is not delegating proposition power: -On transfer of z amount of tokens from account1 to account2 - $$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance_{t0} / 10^{10} * 10^{10} + account1Balance_{t1} / 10^{10} * 10^{10}$$ - - $$account2Power_{t1} = account2Power_{t0} + z$$ -``` - { - isDelegatingProposition(account1) && !isDelegatingProposition(account2) - account1PowerBefore = getPowerCurrent(account1, PROPOSITION_POWER) - account2PowerBefore = getPowerCurrent(account2, PROPOSITION_POWER) - account3PowerBefore = getPowerCurrent(account3, PROPOSITION_POWER) - delegatee1PowerBefore = getPowerCurrent(delegatee1, PROPOSITION_POWER) - balanceAccount1Before = balanceOf(account1) - } - < - transferFrom(account1, account2, z) - > - { - getPowerCurrent(account1, PROPOSITION_POWER) == account1PowerBefore == 0 - getPowerCurrent(delegatee1, PROPOSITION_POWER) == delegatee1PowerBefore - balanceAccount1Before / 10^10 * 10^10 + balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(account2, PROPOSITION_POWER) == account2PowerBefore + z - getPowerCurrent(account3, PROPOSITION_POWER) == account3PowerBefore - } -``` - -11. **vpStopDelegatingWhenOnlyOneIsDelegating** ✔️ -When account1 is delegating voting power to delegatee1 and account2 is not delegating voting power: -After account will stop delegating voting power to delegatee1 - $$account1Power_{t1} = account1Power_{t0} + account1Balance$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance / 10^{10} * 10^{10}$$ - -``` - { - account1 == msg.sender && isDelegatingVoting(account1) - account1PowerBefore = getPowerCurrent(account1, VOTING_POWER) - account2PowerBefore = getPowerCurrent(account2, VOTING_POWER) - account3PowerBefore = getPowerCurrent(account3, VOTING_POWER) - delegatee1PowerBefore = getPowerCurrent(delegatee1, VOTING_POWER) - balanceAccount1Before = balanceOf(account1) - } - < - delegate(0) - > - { - getPowerCurrent(account1, VOTING_POWER) == account1PowerBefore + balanceOfAccount1Before - getPowerCurrent(delegatee1, VOTING_POWER) == delegatee1PowerBefore - balanceAccount1Before / 10^10 * 10^10 - getPowerCurrent(account3, VOTING_POWER) == account3PowerBefore - } -``` - -12. **ppStopDelegatingWhenOnlyOneIsDelegating** ✔️ -When account1 is delegating proposition power to delegatee1 and account2 is not delegating proposition power: -After account will stop delegating proposition power to delegatee1 - $$account1Power_{t1} = account1Power_{t0} + account1Balance$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance / 10^{10} * 10^{10}$$ - -``` - { - account1 == msg.sender && isDelegatingProposition(account1) - account1PowerBefore = getPowerCurrent(account1, PROPOSITION_POWER) - account2PowerBefore = getPowerCurrent(account2, PROPOSITION_POWER) - account3PowerBefore = getPowerCurrent(account3, PROPOSITION_POWER) - delegatee1PowerBefore = getPowerCurrent(delegatee1, PROPOSITION_POWER) - balanceAccount1Before = balanceOf(account1) - } - < - delegate(0) - > - { - getPowerCurrent(account1, PROPOSITION_POWER) == account1PowerBefore + balanceOfAccount1Before - getPowerCurrent(delegatee1, PROPOSITION_POWER) == delegatee1PowerBefore - balanceAccount1Before / 10^10 * 10^10 - getPowerCurrent(account3, PROPOSITION_POWER) == account3PowerBefore - } -``` - -13. **vpChangeDelegateWhenOnlyOneIsDelegating** ✔️ -When account1 is delegating voting power to delegatee1 and account2 is not delegating voting power: -After account1 will delegate power to delegatee2 - - $$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance / 10^{10} * 10^{10}$$ - - $$delegatee2Power_{t1} = delegatee2Power_{t0} + account1Balance / 10^{10} * 10^{10}$$ - - $$account1PowerDelegatee_{t1} = delegatee2$$ -``` - { - account1 == msg.sender && isDelegatingVoting(account1) - account1PowerBefore = getPowerCurrent(account1, VOTING_POWER) - account3PowerBefore = getPowerCurrent(account3, VOTING_POWER) - delegatee1PowerBefore = getPowerCurrent(delegatee1, VOTING_POWER) - delegatee2PowerBefore = getPowerCurrent(delegatee1, VOTING_POWER) - - } - < - delegate(delegatee2) - > - { - getPowerCurrent(account1, VOTING_POWER) == account1PowerBefore == 0 - getPowerCurrent(delegatee1, VOTING_POWER) == delegatee1PowerBefore - balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(delegatee2, VOTING_POWER) == delegatee2PowerBefore + balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(account3, VOTING_POWER) == account3PowerBefore - } -``` - -14. **ppChangeDelegateWhenOnlyOneIsDelegating** ✔️ -When account1 is delegating voting power to delegatee1 and account2 is not delegating voting power: -After account1 will delegate power to delegatee2 - - $$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance / 10^{10} * 10^{10}$$ - - $$delegatee2Power_{t1} = delegatee2Power_{t0} + account1Balance / 10^{10} * 10^{10}$$ - - $$account1PowerDelegatee_{t1} = delegatee2$$ - -``` - { - account1 == msg.sender && isDelegatingProposition(account1) - account1PowerBefore = getPowerCurrent(account1, PROPOSITION_POWER) - account3PowerBefore = getPowerCurrent(account3, PROPOSITION_POWER) - delegatee1PowerBefore = getPowerCurrent(delegatee1, PROPOSITION_POWER) - delegatee2PowerBefore = getPowerCurrent(delegatee1, PROPOSITION_POWER) - - } - < - delegate(delegatee2) - > - { - getPowerCurrent(account1, PROPOSITION_POWER) == account1PowerBefore == 0 - getPowerCurrent(delegatee1, PROPOSITION_POWER) == delegatee1PowerBefore - balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(delegatee2, PROPOSITION_POWER) == delegatee2PowerBefore + balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(account3, PROPOSITION_POWER) == account3PowerBefore - } -``` - -15. **vpOnlyAccount2IsDelegating** ✔️ -Account1 not delegating voting power to anybody, account2 is delegating voting power to delegatee2: -On transfer of z tokens from account1 to account 2 - $$account1Power_{t1} = account1Power_{t0} - z$$ - - $$account2Power_{t1} = account2Power_{t0} = 0$$ - - $$delegatee2Power_{t1}=delegatee2Power_{t0} - account2Balance_{t0} / 10^{10} * 10^{10} + account2Balance_{t1} / 10^{10} * 10^{10}$$ - -``` - { - isDelegatingVoting(account1) && isDelegatingVoting(account2) - delegatee2 == getVotingDelegate(account2) - account1PowerBefore = getPowerCurrent(account1, VOTING_POWER) - account3PowerBefore = getPowerCurrent(account3, VOTING_POWER) - delegatee2PowerBefore = getPowerCurrent(delegatee2, VOTING_POWER) - account2BalanceBefore == balanceOf(account2) - } - < - transferFrom(account1, account2, z) - > - { - getPowerCurrent(account1, VOTING_POWER) == account1PowerBefore - z - getPowerCurrent(account2, VOTING_POWER) == 0 - getPowerCurrent(delegatee2, VOTING_POWER) == delegatee2PowerBefore - account2BalanceBefore / 10^10 *10^10 + balanceOf(account2) / 10^10 * 10^10 - getPowerCurrent(account3, VOTING_POWER) == account3PowerBefore - } -``` - -16. **ppOnlyAccount2IsDelegating** ✔️ -Account1 not delegating proposition power to anybody, account2 is delegating proposition power to delegatee2: -On transfer of z tokens from account1 to account 2 - $$account1Power_{t1} = account1Power_{t0} - z$$ - - $$account2Power_{t1} = account2Power_{t0} = 0$$ - - $$delegatee2Power_{t1}=delegatee2Power_{t0} - account2Balance_{t0} / 10^{10} * 10^{10} + account2Balance_{t1} / 10^{10} * 10^{10}$$ - -``` - { - isDelegatingProposition(account1) && isDelegatingProposition(account2) - account1PowerBefore = getPowerCurrent(account1, PROPOSITION_POWER) - account3PowerBefore = getPowerCurrent(account3, PROPOSITION_POWER) - delegatee2PowerBefore = getPowerCurrent(delegatee2, PROPOSITION_POWER) - account2BalanceBefore == balanceOf(account2) - } - < - transferFrom(account1, account2, z) - > - { - getPowerCurrent(account1, PROPOSITION_POWER) == account1PowerBefore - z - getPowerCurrent(account2, PROPOSITION_POWER) == 0 - getPowerCurrent(delegatee2, PROPOSITION_POWER) == delegatee2PowerBefore - account2BalanceBefore / 10^10 *10^10 + balanceOf(account2) / 10^10 * 10^10 - getPowerCurrent(account3, PROPOSITION_POWER) == account3PowerBefore - } -``` - -17. **vpTransferWhenBothAreDelegating** ✔️ -Account1 is delegating voting power to delegatee1, account2 is delegating voting power to delegatee2: -On transfer of z tokens from account1 to account2 - $$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance_{t0} / 10^{10} * 10^{10} + account1Balance_{t1} / 10^{10} * 10^{10}$$ - - $$account2Power_{t1} = account2Power_{t0} = 0$$ - - $$delegatee2Power_{t1}=delegatee2Power_{t0} - account2Balance_{t0} / 10^{10} * 10^{10} + account2Balance_{t1} / 10^{10} * 10^{10}$$ - -``` - { - isDelegatingVoting(account1) && isDelegatingVoting(account2) - account1PowerBefore = getPowerCurrent(account1, VOTING_POWER) - account2PowerBefore = getPowerCurrent(account2, VOTING_POWER) - account3PowerBefore = getPowerCurrent(account3, VOTING_POWER) - delegatee1PowerBefore = getPowerCurrent(delegatee1, VOTING_POWER) - delegatee2PowerBefore = getPowerCurrent(delegatee2, VOTING_POWER) - account1BalanceBefore = balanceOf(account1) - account2BalanceBefore = balanceOf(account2) - } - < - transferFrom(account1, account2, z) - > - { - getPowerCurrent(account1, VOTING_POWER) == account1PowerBefore == 0 - getPowerCurrent(account2, VOTING_POWER) == account2PowerBefore == 0 - getPowerCurrent(delegatee1, VOTING_POWER) == delegatee1PowerBefore - account1BalanceBefore / 10^10 * 10^10 + balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(delegatee2, VOTING_POWER) == delegatee2PowerBefore - account2BalanceBefore / 10^10 * 10^10 + balanceOf(account2) / 10^10 * 10^10 - } -``` - -18. **ppTransferWhenBothAreDelegating** ✔️ -Account1 is delegating proposition power to delegatee1, account2 is delegating proposition power to delegatee2: -On transfer of z tokens from account1 to account2 - $$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance_{t0} / 10^{10} * 10^{10} + account1Balance_{t1} / 10^{10} * 10^{10}$$ - - $$account2Power_{t1} = account2Power_{t0} = 0$$ - - $$delegatee2Power_{t1}=delegatee2Power_{t0} - account2Balance_{t0} / 10^{10} * 10^{10} + account2Balance_{t1} / 10^{10} * 10^{10}$$ - -``` - { - isDelegatingProposition(account1) && isDelegatingProposition(account2) - account1PowerBefore = getPowerCurrent(account1, PROPOSITION_POWER) - account2PowerBefore = getPowerCurrent(account2, PROPOSITION_POWER) - account3PowerBefore = getPowerCurrent(account3, PROPOSITION_POWER) - delegatee1PowerBefore = getPowerCurrent(delegatee1, PROPOSITION_POWER) - delegatee2PowerBefore = getPowerCurrent(delegatee2, PROPOSITION_POWER) - account1BalanceBefore = balanceOf(account1) - account2BalanceBefore = balanceOf(account2) - } - < - transferFrom(account1, account2, z) - > - { - getPowerCurrent(account1, PROPOSITION_POWER) == account1PowerBefore == 0 - getPowerCurrent(account2, PROPOSITION_POWER) == account2PowerBefore == 0 - getPowerCurrent(delegatee1, PROPOSITION_POWER) == delegatee1PowerBefore - account1BalanceBefore / 10^10 * 10^10 + balanceOf(account1) / 10^10 * 10^10 - getPowerCurrent(delegatee2, PROPOSITION_POWER) == delegatee2PowerBefore - account2BalanceBefore / 10^10 * 10^10 + balanceOf(account2) / 10^10 * 10^10 - } -``` - -19. **delegationTypeIndependence** ✔️ -Only delegate() and metaDelegate() may change both voting and -proposition delegates of an account at once. -``` - { - delegateVBefore = getVotingDelegate(account) - delegatePBefore = getPropositionDelegate(account) - } - < - f(e, args) - > - { - delegateVAfter = getVotingDelegate(account) - delegatePAfter = getPropositionDelegate(account) - (delegateVBefore == delegateVAfter || delegatePBefore == delegatePAfter) || (f.selector == delegate(address).selector || f.selector == metaDelegate(address,address,uint256,uint8,bytes32,bytes32).selector) - } -``` - -20. **cantDelegateTwice** ✔️ -Delegating twice to the same delegate _delegate changes the delegate's voting power only once. - -``` - { - votingPowerBefore = getPowerCurrent(_delegate, VOTING_POWER) - propositionPowerBefore = getPowerCurrent(_delegate, PROPOSITION_POWER) - } - < - delegate(_delegate) - votingPowerAfter = getPowerCurrent(_delegate, VOTING_POWER) - propositionPowerAfter = getPowerCurrent(_delegate, PROPOSITION_POWER) - delegate(_delegate) - > - { - getPowerCurrent(_delegate, VOTING_POWER) == votingPowerAfter - getPowerCurrent(_delegate, PROPOSITION_POWER) == propositionPowerAfter - } -``` - -### ERC20 Properties - -21. **transferCorrect** ✔️ -Token transfer works correctly. Balances are updated if not reverted. -If reverted then the transfer amount was too high, or the recipient is 0. -``` - { - balanceFromBefore = balanceOf(msg.sender) - balanceToBefore = balanceOf(to) - } - < - transfer(to, amount) - > - { - lastReverted => to = 0 || amount > balanceOf(msg.sender) - !lastReverted => balanceOf(to) = balanceToBefore + amount && - balanceOf(msg.sender) = balanceFromBefore - amount - } -``` - -22. **transferFromCorrect** ✔️ -Token transferFrom function works correctly. Balances are updated if not reverted. If reverted then the transfer amount was too high, or the recipient is 0, or the allowance was not sufficient -``` - { - balanceFromBefore = balanceOf(from) - balanceToBefore = balanceOf(to) - } - < - transferFrom(from, to, amount) - > - { - lastreverted => to = 0 || amount > balanceOf(from) - !lastreverted => balanceOf(to) = balanceToBefore + amount && - balanceOf(from) = balanceFromBefore - amount - } -``` - -23. **zeroAddressNoBalance** ✔️ -Balance of address 0 is always 0 -``` -{ balanceOf(0) = 0 } -``` - -24. **NoChangeTotalSupply** ✔️ -Contract calls don't change token total supply. -``` - { - supplyBefore = totalSupply() - } - < f(e, args)> - { - supplyAfter = totalSupply() - supplyBefore == supplyAfter - } -``` - -25. **ChangingAllowance** ✔️ -Allowance changes correctly as a result of calls to approve, transfer, increaseAllowance, decreaseAllowance -``` - { - allowanceBefore = allowance(from, spender) - } - < - f(e, args) - > - { - f.selector = approve(spender, amount) => allowance(from, spender) = amount - f.selector = transferFrom(from, spender, amount) => allowance(from, spender) = allowanceBefore - amount - f.selector = decreaseAllowance(spender, delta) => allowance(from, spender) = allowanceBefore - delta - f.selector = increaseAllowance(spender, delta) => allowance(from, spender) = allowanceBefore + delta - generic f.selector => allowance(from, spender) == allowanceBefore - } -``` - -26. **TransferSumOfFromAndToBalancesStaySame** ✔️ -Transfer from msg.sender to b doesn't change the sum of their balances -``` - { - balancesBefore = balanceOf(msg.sender) + balanceOf(b) - } - < - transfer(b, amount) - > - { - balancesBefore == balanceOf(msg.sender) + balanceOf(b) - } -``` - -27. **TransferFromSumOfFromAndToBalancesStaySame** ✔️ -transferFrom from a to b doesn't change the sum of their balances -``` - { - balancesBefore = balanceOf(a) + balanceOf(b) - } - < - transferFrom(a, b) - > - { - balancesBefore == balanceOf(a) + balanceOf(b) - } -``` - -28. **TransferDoesntChangeOtherBalance** ✔️ -Transfer from msg.sender to alice doesn't change the balance of other addresses -``` - { - balanceBefore = balanceOf(charlie) - } - < - transfer(alice, amount) - > - { - balanceOf(charlie) == balanceBefore - } -``` - -29. **TransferFromDoesntChangeOtherBalance** ✔️ -``` - { - balanceBefore = balanceOf(charlie) - } - < - transferFrom(alice, bob, amount) - > - { - balanceOf(charlie) = balanceBefore - } -``` - -30. **OtherBalanceOnlyGoesUp** ✔️ -Balance of an address, who is not a sender or a recipient in transfer functions, doesn't decrease as a result of contract calls -``` - { - balanceBefore = balanceOf(charlie) - } - < - f(e, args) - > - { - f.selector != transfer && f.selector != transferFrom => balanceOf(charlie) == balanceBefore - } -``` - - diff --git a/CVLByExample/aave-token-v3/certora/report/Formal Verification Report of AAVE Token V3.pdf b/CVLByExample/aave-token-v3/certora/report/Formal Verification Report of AAVE Token V3.pdf deleted file mode 100644 index 556c81ba..00000000 Binary files a/CVLByExample/aave-token-v3/certora/report/Formal Verification Report of AAVE Token V3.pdf and /dev/null differ diff --git a/CVLByExample/aave-token-v3/certora/scripts/erc20.sh b/CVLByExample/aave-token-v3/certora/scripts/erc20.sh deleted file mode 100644 index 29631e54..00000000 --- a/CVLByExample/aave-token-v3/certora/scripts/erc20.sh +++ /dev/null @@ -1,13 +0,0 @@ -if [[ "$1" ]] -then - RULE="--rule $1" -fi - -certoraRun certora/harness/AaveTokenV3Harness.sol:AaveTokenV3Harness \ - --verify AaveTokenV3Harness:certora/specs/erc20.spec \ - $RULE \ - --solc solc8.13 \ - --optimistic_loop \ - --cloud \ - --msg "AaveTokenV3:erc20.spec $1" - \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/certora/scripts/verifyCommunity.sh b/CVLByExample/aave-token-v3/certora/scripts/verifyCommunity.sh deleted file mode 100644 index 2925a2d6..00000000 --- a/CVLByExample/aave-token-v3/certora/scripts/verifyCommunity.sh +++ /dev/null @@ -1,14 +0,0 @@ -if [[ "$1" ]] -then - RULE="--rule $1" -fi - -certoraRun certora/harness/AaveTokenV3HarnessCommunity.sol:AaveTokenV3Harness \ - --verify AaveTokenV3Harness:certora/specs/community.spec \ - $RULE \ - --solc solc8.13 \ - --optimistic_loop \ - --cloud \ - --msg "AaveTokenV3HarnessCommunity:community.spec $1" -# --sanity - \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/certora/scripts/verifyDelegate.sh b/CVLByExample/aave-token-v3/certora/scripts/verifyDelegate.sh deleted file mode 100755 index f0869cba..00000000 --- a/CVLByExample/aave-token-v3/certora/scripts/verifyDelegate.sh +++ /dev/null @@ -1,14 +0,0 @@ -if [[ "$1" ]] -then - RULE="--rule $1" -fi - -certoraRun certora/harness/AaveTokenV3Harness.sol:AaveTokenV3Harness \ - --verify AaveTokenV3Harness:certora/specs/delegate.spec \ - $RULE \ - --solc solc8.13 \ - --optimistic_loop \ - --cloud \ - --msg "AaveTokenV3Harness:delegate.spec $1" -# --sanity - \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/certora/scripts/verifyGeneral.sh b/CVLByExample/aave-token-v3/certora/scripts/verifyGeneral.sh deleted file mode 100644 index 4bd18744..00000000 --- a/CVLByExample/aave-token-v3/certora/scripts/verifyGeneral.sh +++ /dev/null @@ -1,14 +0,0 @@ -if [[ "$1" ]] -then - RULE="--rule $1" -fi - -certoraRun certora/harness/AaveTokenV3HarnessStorage.sol:AaveTokenV3Harness \ - --verify AaveTokenV3Harness:certora/specs/general.spec \ - $RULE \ - --solc solc8.13 \ - --optimistic_loop \ - --settings -smt_bitVectorTheory=true \ - --cloud \ - --msg "AaveTokenV3:general.spec $1" - \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/certora/specs/base.spec b/CVLByExample/aave-token-v3/certora/specs/base.spec deleted file mode 100644 index 5173075d..00000000 --- a/CVLByExample/aave-token-v3/certora/specs/base.spec +++ /dev/null @@ -1,81 +0,0 @@ -/* - This is a base spec file that includes methods declarations, definitions - and functions to be included in other spec. There are no rules in this file. - For more information, visit: https://www.certora.com/ - -*/ - -/* - - Declaration of methods of the Aave token contract (and harness) - -*/ - -methods { - function totalSupply() external returns (uint256) envfree; - function balanceOf(address) external returns (uint256) envfree; - function allowance(address,address) external returns (uint256) envfree; - function increaseAllowance(address, uint256) external; - function decreaseAllowance(address, uint256) external; - function transfer(address,uint256) external; - function transferFrom(address,address,uint256) external; - function permit(address,address,uint256,uint256,uint8,bytes32,bytes32) external; - - function delegate(address delegatee) external; - function metaDelegate(address,address,uint256,uint8,bytes32,bytes32) external; - function metaDelegateByType(address,address,uint8,uint256,uint8,bytes32,bytes32) external; - function getPowerCurrent(address, AaveTokenV3Harness.GovernancePowerType) external returns (uint256) envfree; - - function getBalance(address user) external returns (uint104) envfree; - function getDelegatedPropositionBalance(address user) external returns (uint72) envfree; - function getDelegatedVotingBalance(address user) external returns (uint72) envfree; - function getDelegatingProposition(address user) external returns (bool) envfree; - function getDelegatingVoting(address user) external returns (bool) envfree; - function getVotingDelegate(address user) external returns (address) envfree; - function getPropositionDelegate(address user) external returns (address) envfree; - function getDelegationState(address user) external returns (AaveTokenV3Harness.DelegationState) envfree; -} - -definition VOTING_POWER() returns AaveTokenV3Harness.GovernancePowerType = AaveTokenV3Harness.GovernancePowerType.VOTING; -definition PROPOSITION_POWER() returns AaveTokenV3Harness.GovernancePowerType = AaveTokenV3Harness.GovernancePowerType.PROPOSITION; -definition DELEGATED_POWER_DIVIDER() returns uint256 = 10^10; - -/** - - Definitions of delegation states - -*/ -definition NO_DELEGATION() returns AaveTokenV3Harness.DelegationState = AaveTokenV3Harness.DelegationState.NO_DELEGATION; -definition VOTING_DELEGATED() returns AaveTokenV3Harness.DelegationState = AaveTokenV3Harness.DelegationState.VOTING_DELEGATED; -definition PROPOSITION_DELEGATED() returns AaveTokenV3Harness.DelegationState = AaveTokenV3Harness.DelegationState.PROPOSITION_DELEGATED; -definition FULL_POWER_DELEGATED() returns AaveTokenV3Harness.DelegationState = AaveTokenV3Harness.DelegationState.FULL_POWER_DELEGATED; -definition DELEGATING_VOTING(AaveTokenV3Harness.DelegationState state) returns bool = - state == VOTING_DELEGATED() || state == FULL_POWER_DELEGATED(); -definition DELEGATING_PROPOSITION(AaveTokenV3Harness.DelegationState state) returns bool = - state == PROPOSITION_DELEGATED() || state == FULL_POWER_DELEGATED(); - -definition AAVE_MAX_SUPPLY() returns uint256 = 16000000 * 10^18; -definition SCALED_MAX_SUPPLY() returns mathint = AAVE_MAX_SUPPLY() / DELEGATED_POWER_DIVIDER(); - - -/** - - Functions - -*/ - -function normalize(uint256 amount) returns mathint { - return amount / DELEGATED_POWER_DIVIDER() * DELEGATED_POWER_DIVIDER(); -} - -function validDelegationState(address user) returns bool { - AaveTokenV3Harness.DelegationState state = getDelegationState(user); - return state == AaveTokenV3Harness.DelegationState.NO_DELEGATION || - state == AaveTokenV3Harness.DelegationState.VOTING_DELEGATED || - state == AaveTokenV3Harness.DelegationState.PROPOSITION_DELEGATED || - state == AaveTokenV3Harness.DelegationState.FULL_POWER_DELEGATED; -} - -function validAmount(uint256 amt) returns bool { - return amt < AAVE_MAX_SUPPLY(); -} diff --git a/CVLByExample/aave-token-v3/certora/specs/community.spec b/CVLByExample/aave-token-v3/certora/specs/community.spec deleted file mode 100644 index 5248f53f..00000000 --- a/CVLByExample/aave-token-v3/certora/specs/community.spec +++ /dev/null @@ -1,493 +0,0 @@ -/* - This is a specification file for the verification of AaveTokenV3.sol - smart contract using the Certora prover. The rules in this spec have been - contributed by the community. Individual attribution is given in the comments - to each rule. - - For more information, visit: https://www.certora.com/ - - This file is run with scripts/verifyCommunity.sh - On AaveTokenV3Harness.sol - - Run results: https://prover.certora.com/output/67509/d36b2357623beec546c1?anonymousKey=f6fb866df18e6bc9ed880806375e7861cde8274f - -*/ - -import "base.spec"; - -methods { - function ecrecoverWrapper(bytes32, uint8, bytes32, bytes32) external returns (address) envfree; - function computeMetaDelegateHash(address delegator, address delegatee, uint256 deadline, uint256 nonce) external returns (bytes32) envfree; - function computeMetaDelegateByTypeHash(address delegator, address delegatee, AaveTokenV3Harness.GovernancePowerType delegationType, uint256 deadline, uint256 nonce) external returns (bytes32) envfree; - function _nonces(address addr) external returns (uint256) envfree; - function getNonce(address) external returns (uint256) envfree; -} - -definition ZERO_ADDRESS() returns address = 0; - - -/* - @Rule - - @Description: - Integrity of permit function - Successful permit function increases the nonce of owner by 1 and also changes the allowance of owner to spender - - @Formula: - { - nonceBefore = getNonce(owner) - } - < - permit(owner, spender, value, deadline, v, r, s) - > - { - allowance(owner, spender) == value && getNonce(owner) == nonceBefore + 1 - } - - @Note: - Written by https://github.com/parth-15 - - @Link: -*/ -rule permitIntegrity() { - env e; - address owner; - address spender; - uint256 value; - uint256 deadline; - uint8 v; - bytes32 r; - bytes32 s; - - uint256 allowanceBefore = allowance(owner, spender); - mathint nonceBefore = getNonce(owner); - - //checking this because function is using unchecked math and such a high nonce is unrealistic - require nonceBefore < max_uint; - - permit(e, owner, spender, value, deadline, v, r, s); - - uint256 allowanceAfter = allowance(owner, spender); - mathint nonceAfter = getNonce(owner); - - assert allowanceAfter == value, "permit increases allowance of owner to spender on success"; - assert nonceAfter == nonceBefore + 1, "successful call to permit function increases nonce of owner by 1"; -} - - -/* - @Rule - - @Description: - Address 0 has no voting or proposition power - - @Formula: - { - getPowerCurrent(0, VOTING_POWER) == 0 && getPowerCurrent(0, PROPOSITION_POWER) == && balanceOf(0) == 0 - } - - @Note: - Written by https://github.com/JayP11 - - @Link: -*/ -invariant addressZeroNoPower() - getPowerCurrent(0, VOTING_POWER()) == 0 && getPowerCurrent(0, PROPOSITION_POWER()) == 0 && balanceOf(0) == 0; - - -/* - @Rule - - @Description: - Verify that `metaDelegateByType` can only be called with a signed request. - - @Formula: - { - ecrecover(v,r,s) != delegator - } - < - metaDelegateByType@withrevert(delegator, delegatee, delegationType, deadline, v, r, s) - > - { - lastReverted == true - } - - @Note: - Written by https://github.com/kustosz - - @Link: -*/ -rule metaDelegateByTypeOnlyCallableWithProperlySignedArguments(env e, address delegator, address delegatee, AaveTokenV3Harness.GovernancePowerType delegationType, uint256 deadline, uint8 v, bytes32 r, bytes32 s) { - require ecrecoverWrapper(computeMetaDelegateByTypeHash(delegator, delegatee, delegationType, deadline, _nonces(delegator)), v, r, s) != delegator; - metaDelegateByType@withrevert(e, delegator, delegatee, delegationType, deadline, v, r, s); - assert lastReverted; -} - - /* - @Rule - - @Description: - Verify that it's impossible to use the same arguments to call `metaDalegate` twice. - - @Formula: - { - hash1 = computeMetaDelegateHash(delegator, delegatee, deadline, nonce) - hash2 = computeMetaDelegateHash(delegator, delegatee, deadline, nonce + 1) - ecrecover(hash1, v, r, s) == delegator - } - < - metaDelegate(e1, delegator, delegatee, v, r, s) - metaDelegate@withrevert(e2, delegator, delegatee, delegationType, deadline, v, r, s) - > - { - lastReverted == true - } - - @Note: - Written by https://github.com/kustosz - - @Link: -*/ -rule metaDelegateNonRepeatable(env e1, env e2, address delegator, address delegatee, uint256 deadline, uint8 v, bytes32 r, bytes32 s) { - uint256 nonce = _nonces(delegator); - bytes32 hash1 = computeMetaDelegateHash(delegator, delegatee, deadline, nonce); - bytes32 hash2 = computeMetaDelegateHash(delegator, delegatee, deadline, require_uint256(nonce+1)); - // assume no hash collisions - require hash1 != hash2; - // assume first call is properly signed - require ecrecoverWrapper(hash1, v, r, s) == delegator; - // assume ecrecover is sane: cannot sign two different messages with the same (v,r,s) - require ecrecoverWrapper(hash2, v, r, s) != ecrecoverWrapper(hash1, v, r, s); - metaDelegate(e1, delegator, delegatee, deadline, v, r, s); - metaDelegate@withrevert(e2, delegator, delegatee, deadline, v, r, s); - assert lastReverted; -} - - -/* - @Rule - - @Description: - Power of the previous delegate is removed when the delegatee delegates to another delegate - - @Formula: - { - _votingBalance = getDelegatedVotingBalance(alice) - } - < - delegateByType(alice, VOTING_POWER) - delegateByType(bob, VOTING_POWER) - > - { - alice != bob => getDelegatedVotingBalance(alice) == _votingBalance - } - - @Note: - Written by https://github.com/priyankabhanderi - - @Link: -*/ -rule delegatingToAnotherUserRemovesPowerFromOldDelegatee(env e, address alice, address bob) { - - require e.msg.sender != ZERO_ADDRESS(); - require e.msg.sender != alice && e.msg.sender != bob; - require alice != ZERO_ADDRESS() && bob != ZERO_ADDRESS(); - - require getVotingDelegate(e.msg.sender) != alice; - - uint72 _votingBalance = getDelegatedVotingBalance(alice); - - delegateByType(e, alice, VOTING_POWER()); - - assert getVotingDelegate(e.msg.sender) == alice; - - delegateByType(e, bob, VOTING_POWER()); - - assert getVotingDelegate(e.msg.sender) == bob; - uint72 votingBalance_ = getDelegatedVotingBalance(alice); - assert alice != bob => votingBalance_ == _votingBalance; -} - -/* - @Rule - - @Description: - Voting and proposition power change only as a result of specific functions - - @Formula: - { - powerBefore = getPowerCurrent(alice, type) - } - < - f(e, args) - > - { - powerAfter = getPowerCurrent(alice, type) - powerAfter != powerBefore => - f.selector == sig:delegate(address).selector || - f.selector == sig:delegateByType(address, uint8).selector || - f.selector == sig:metaDelegate(address, address, uint256, uint8, bytes32, bytes32).selector || - f.selector == sig:metaDelegateByType(address, address, uint8, uint256, uint8, bytes32, bytes32).selector || - f.selector == sig:transfer(address, uint256).selector || - f.selector == sig:transferFrom(address, address, uint256).selector - } - - @Note: - Written by https://github.com/top-sekret - - @Link: -*/ - -rule powerChanges(address alice, method f) { - env e; - calldataarg args; - - AaveTokenV3Harness.GovernancePowerType type; - uint256 powerBefore = getPowerCurrent(alice, type); - - f(e, args); - - uint256 powerAfter = getPowerCurrent(alice, type); - - assert powerBefore != powerAfter => - f.selector == sig:delegate(address).selector || - f.selector == sig:delegateByType(address, AaveTokenV3Harness.GovernancePowerType).selector || - f.selector == sig:metaDelegate(address, address, uint256, uint8, bytes32, bytes32).selector || - f.selector == sig:metaDelegateByType(address, address, AaveTokenV3Harness.GovernancePowerType, uint256, uint8, bytes32, bytes32).selector || - f.selector == sig:transfer(address, uint256).selector || - f.selector == sig:transferFrom(address, address, uint256).selector; -} - - - -/* - @Rule - - @Description: - Changing a delegate of one type doesn't influence the delegate of the other type - - @Formula: - { - delegateBefore = type == 1 ? getPropositionDelegate(e.msg.sender) : getVotingDelegate(e.msg.sender) - } - < - delegateByType(e, delegatee, 1 - type) - > - { - delegateBefore = type == 1 ? getPropositionDelegate(e.msg.sender) : getVotingDelegate(e.msg.sender) - delegateBefore == delegateAfter - } - - @Note: - Written by https://github.com/top-sekret - - @Link: -*/ -rule delegateIndependence(method f) { - env e; - - AaveTokenV3Harness.GovernancePowerType type; - - address delegateBefore = type == AaveTokenV3Harness.GovernancePowerType.PROPOSITION ? getPropositionDelegate(e.msg.sender) : getVotingDelegate(e.msg.sender); - - AaveTokenV3Harness.GovernancePowerType otherType = type == AaveTokenV3Harness.GovernancePowerType.PROPOSITION ? AaveTokenV3Harness.GovernancePowerType.VOTING : AaveTokenV3Harness.GovernancePowerType.PROPOSITION; - delegateByType(e, _, otherType); - - address delegateAfter = type == AaveTokenV3Harness.GovernancePowerType.PROPOSITION ? getPropositionDelegate(e.msg.sender) : getVotingDelegate(e.msg.sender); - - assert delegateBefore == delegateAfter; -} - -/* - @Rule - - @Description: - Verifying voting power increases/decreases while not being a voting delegatee yourself - - @Formula: - { - votingPowerBefore = getPowerCurrent(a, VOTING_POWER) - balanceBefore = balanceOf(a) - isVotingDelegatorBefore = getDelegatingVoting(a) - isVotingDelegateeBefore = getDelegatedVotingBalance(a) != 0 - } - < - f(e, args) - > - { - votingPowerAfter = getPowerCurrent(a, VOTING_POWER() - balanceAfter = getBalance(a) - isVotingDelegatorAfter = getDelegatingVoting(a); - isVotingDelegateeAfter = getDelegatedVotingBalance(a) != 0 - - votingPowerBefore < votingPowerAfter <=> - (!isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore < balanceAfter)) || - (isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore != 0)) - && - votingPowerBefore > votingPowerAfter <=> - (!isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore > balanceAfter)) || - (!isVotingDelegatorBefore && isVotingDelegatorAfter && (balanceBefore != 0)) - } - - @Note: - Written by https://github.com/Zarfsec - - @Link: -*/ -rule votingPowerChangesWhileNotBeingADelegatee(address a) { - require a != 0; - - uint256 votingPowerBefore = getPowerCurrent(a, VOTING_POWER()); - uint256 balanceBefore = getBalance(a); - bool isVotingDelegatorBefore = getDelegatingVoting(a); - bool isVotingDelegateeBefore = getDelegatedVotingBalance(a) != 0; - - method f; - env e; - calldataarg args; - f(e, args); - - uint256 votingPowerAfter = getPowerCurrent(a, VOTING_POWER()); - uint256 balanceAfter = getBalance(a); - bool isVotingDelegatorAfter = getDelegatingVoting(a); - bool isVotingDelegateeAfter = getDelegatedVotingBalance(a) != 0; - - require !isVotingDelegateeBefore && !isVotingDelegateeAfter; - - /* - If you're not a delegatee, your voting power only increases when - 1. You're not delegating and your balance increases - 2. You're delegating and stop delegating and your balanceBefore != 0 - */ - assert votingPowerBefore < votingPowerAfter <=> - (!isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore < balanceAfter)) || - (isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore != 0)); - - /* - If you're not a delegatee, your voting power only decreases when - 1. You're not delegating and your balance decreases - 2. You're not delegating and start delegating and your balanceBefore != 0 - */ - assert votingPowerBefore > votingPowerAfter <=> - (!isVotingDelegatorBefore && !isVotingDelegatorAfter && (balanceBefore > balanceAfter)) || - (!isVotingDelegatorBefore && isVotingDelegatorAfter && (balanceBefore != 0)); -} - -/* - @Rule - - @Description: - Verifying proposition power increases/decreases while not being a proposition delegatee yourself - - @Formula: - { - propositionPowerBefore = getPowerCurrent(a, PROPOSITION_POWER) - balanceBefore = balanceOf(a) - isPropositionDelegatorBefore = getDelegatingProposition(a) - isPropositionDelegateeBefore = getDelegatedPropositionBalance(a) != 0 - } - < - f(e, args) - > - { - propositionPowerAfter = getPowerCurrent(a, PROPOSITION_POWER() - balanceAfter = getBalance(a) - isPropositionDelegatorAfter = getDelegatingProposition(a); - isPropositionDelegateeAfter = getDelegatedPropositionBalance(a) != 0 - - propositionPowerBefore < propositionPowerAfter <=> - (!isPropositionDelegatorBefore && !isPropositionDelegatorAfter && (balanceBefore < balanceAfter)) || - (isPropositionDelegatorBefore && !isPropositionDelegatorAfter && (balanceBefore != 0)) - && - propositionPowerBefore > propositionPowerAfter <=> - (!isPropositionDelegatorBefore && !isPropositionDelegatorAfter && (balanceBefore > balanceAfter)) || - (!isPropositionDelegatorBefore && isPropositionDelegatorAfter && (balanceBefore != 0)) - } - - @Note: - Written by https://github.com/Zarfsec - - @Link: -*/ -rule propositionPowerChangesWhileNotBeingADelegatee(address a) { - require a != 0; - - uint256 propositionPowerBefore = getPowerCurrent(a, PROPOSITION_POWER()); - uint256 balanceBefore = getBalance(a); - bool isPropositionDelegatorBefore = getDelegatingProposition(a); - bool isPropositionDelegateeBefore = getDelegatedPropositionBalance(a) != 0; - - method f; - env e; - calldataarg args; - f(e, args); - - uint256 propositionPowerAfter = getPowerCurrent(a, PROPOSITION_POWER()); - uint256 balanceAfter = getBalance(a); - bool isPropositionDelegatorAfter = getDelegatingProposition(a); - bool isPropositionDelegateeAfter = getDelegatedPropositionBalance(a) != 0; - - require !isPropositionDelegateeBefore && !isPropositionDelegateeAfter; - - /* - If you're not a delegatee, your proposition power only increases when - 1. You're not delegating and your balance increases - 2. You're delegating and stop delegating and your balanceBefore != 0 - */ - assert propositionPowerBefore < propositionPowerAfter <=> - (!isPropositionDelegatorBefore && !isPropositionDelegatorAfter && (balanceBefore < balanceAfter)) || - (isPropositionDelegatorBefore && !isPropositionDelegatorAfter && (balanceBefore != 0)); - - /* - If you're not a delegatee, your proposition power only decreases when - 1. You're not delegating and your balance decreases - 2. You're not delegating and start delegating and your balanceBefore != 0 - */ - assert propositionPowerBefore > propositionPowerAfter <=> - (!isPropositionDelegatorBefore && !isPropositionDelegatorBefore && (balanceBefore > balanceAfter)) || - (!isPropositionDelegatorBefore && isPropositionDelegatorAfter && (balanceBefore != 0)); -} - -/* - @Rule - - @Description: - Allowance only changes as a result of specific subset of functions - - @Formula: - { - allowanceBefore = allowance(owner, spender) - } - < - f(e, args) - > - { - allowance(owner, spender) != allowanceBefore =>f.selector==sig:approve(address,uint256).selector - || f.selector==sig:increaseAllowance(address,uint256).selector - || f.selector==sig:decreaseAllowance(address,uint256).selector - || f.selector==sig:transferFrom(address,address,uint256).selector - || f.selector==sig:permit(address,address,uint256,uint256,uint8,bytes32,bytes32).selector - - } - - @Note: - Written by https://github.com/oracleorb - - @Link: -*/ -rule allowanceStateChange(env e){ - address owner; - address user; - method f; - calldataarg args; - - uint256 allowanceBefore=allowance(owner,user); - f(e, args); - uint256 allowanceAfter=allowance(owner,user); - - assert allowanceBefore!=allowanceAfter => f.selector==sig:approve(address,uint256).selector - || f.selector==sig:increaseAllowance(address,uint256).selector - || f.selector==sig:decreaseAllowance(address,uint256).selector - || f.selector==sig:transferFrom(address,address,uint256).selector - || f.selector==sig:permit(address,address,uint256,uint256,uint8,bytes32,bytes32).selector; -} diff --git a/CVLByExample/aave-token-v3/certora/specs/delegate.spec b/CVLByExample/aave-token-v3/certora/specs/delegate.spec deleted file mode 100644 index bcb29b9a..00000000 --- a/CVLByExample/aave-token-v3/certora/specs/delegate.spec +++ /dev/null @@ -1,817 +0,0 @@ - -/* - This is a specification file for the verification of delegation - features of AaveTokenV3.sol smart contract using the Certora prover. - For more information, visit: https://www.certora.com/ - - This file is run with scripts/verifyDelegate.sh - On AaveTokenV3Harness.sol - - Sanity check results: https://prover.certora.com/output/67509/021f59de6995d82ecf18/?anonymousKey=84f18dc61532a37fabfd59655fe7fe43989f1a8e - -*/ - -import "base.spec"; - - -/* - @Rule - - @Description: - If an account is not receiving delegation of power (one type) from anybody, - and that account is not delegating that power to anybody, the power of that account - must be equal to its token balance. - - @Note: - - @Link: -*/ - -rule powerWhenNotDelegating(address account) { - mathint balance = balanceOf(account); - bool isDelegatingVoting = getDelegatingVoting(account); - bool isDelegatingProposition = getDelegatingProposition(account); - uint72 dvb = getDelegatedVotingBalance(account); - uint72 dpb = getDelegatedPropositionBalance(account); - - mathint votingPower = getPowerCurrent(account, VOTING_POWER()); - mathint propositionPower = getPowerCurrent(account, PROPOSITION_POWER()); - - assert dvb == 0 && !isDelegatingVoting => votingPower == balance; - assert dpb == 0 && !isDelegatingProposition => propositionPower == balance; -} - - -/** - Account1 and account2 are not delegating power -*/ - -/* - @Rule - - @Description: - Verify correct voting power on token transfers, when both accounts are not delegating - - @Note: - - @Link: -*/ - -rule vpTransferWhenBothNotDelegating(address alice, address bob, address charlie, uint256 amount) { - env e; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegatingVoting = getDelegatingVoting(alice); - bool isBobDelegatingVoting = getDelegatingVoting(bob); - - // both accounts are not delegating - require !isAliceDelegatingVoting && !isBobDelegatingVoting; - - mathint alicePowerBefore = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerBefore = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, VOTING_POWER()); - - transferFrom(e, alice, bob, amount); - - mathint alicePowerAfter = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, VOTING_POWER()); - - assert alicePowerAfter == alicePowerBefore - amount; - assert bobPowerAfter == bobPowerBefore + amount; - assert charliePowerAfter == charliePowerBefore; -} - -/* - @Rule - - @Description: - Verify correct proposition power on token transfers, when both accounts are not delegating - - @Note: - - @Link: -*/ - -rule ppTransferWhenBothNotDelegating(address alice, address bob, address charlie, uint256 amount) { - env e; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegatingProposition = getDelegatingProposition(alice); - bool isBobDelegatingProposition = getDelegatingProposition(bob); - - require !isAliceDelegatingProposition && !isBobDelegatingProposition; - - mathint alicePowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerBefore = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, PROPOSITION_POWER()); - - transferFrom(e, alice, bob, amount); - - mathint alicePowerAfter = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, PROPOSITION_POWER()); - - assert alicePowerAfter == alicePowerBefore - amount; - assert bobPowerAfter == bobPowerBefore + amount; - assert charliePowerAfter == charliePowerBefore; -} - -/* - @Rule - - @Description: - Verify correct voting power after Alice delegates to Bob, when - both accounts were not delegating - - @Note: - - @Link: -*/ - -rule vpDelegateWhenBothNotDelegating(address alice, address bob, address charlie) { - env e; - require alice == e.msg.sender; - require alice != 0 && bob != 0 && charlie != 0; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegatingVoting = getDelegatingVoting(alice); - bool isBobDelegatingVoting = getDelegatingVoting(bob); - - require !isAliceDelegatingVoting && !isBobDelegatingVoting; - - mathint aliceBalance = balanceOf(alice); - mathint bobBalance = balanceOf(bob); - - mathint alicePowerBefore = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerBefore = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, VOTING_POWER()); - - delegate(e, bob); - - mathint alicePowerAfter = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, VOTING_POWER()); - - assert alicePowerAfter == alicePowerBefore - aliceBalance; - assert bobPowerAfter == bobPowerBefore + (aliceBalance / DELEGATED_POWER_DIVIDER()) * DELEGATED_POWER_DIVIDER(); - assert getVotingDelegate(alice) == bob; - assert charliePowerAfter == charliePowerBefore; -} - -/* - @Rule - - @Description: - Verify correct proposition power after Alice delegates to Bob, when - both accounts were not delegating - - @Note: - - @Link: -*/ - -rule ppDelegateWhenBothNotDelegating(address alice, address bob, address charlie) { - env e; - require alice == e.msg.sender; - require alice != 0 && bob != 0 && charlie != 0; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegatingProposition = getDelegatingProposition(alice); - bool isBobDelegatingProposition = getDelegatingProposition(bob); - - require !isAliceDelegatingProposition && !isBobDelegatingProposition; - - mathint aliceBalance = balanceOf(alice); - mathint bobBalance = balanceOf(bob); - - mathint alicePowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerBefore = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, PROPOSITION_POWER()); - - delegate(e, bob); - - mathint alicePowerAfter = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, PROPOSITION_POWER()); - - assert alicePowerAfter == alicePowerBefore - aliceBalance; - assert bobPowerAfter == bobPowerBefore + (aliceBalance / DELEGATED_POWER_DIVIDER()) * DELEGATED_POWER_DIVIDER(); - assert getPropositionDelegate(alice) == bob; - assert charliePowerAfter == charliePowerBefore; -} - -/** - Account1 is delegating power to delegatee1, account2 is not delegating power to anybody -*/ - -/* - @Rule - - @Description: - Verify correct voting power after a token transfer from Alice to Bob, when - Alice was delegating and Bob wasn't - - @Note: - - @Link: -*/ - -rule vpTransferWhenOnlyOneIsDelegating(address alice, address bob, address charlie, uint256 amount) { - env e; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegatingVoting = getDelegatingVoting(alice); - bool isBobDelegatingVoting = getDelegatingVoting(bob); - address aliceDelegate = getVotingDelegate(alice); - require aliceDelegate != alice && aliceDelegate != 0 && aliceDelegate != bob && aliceDelegate != charlie; - - require isAliceDelegatingVoting && !isBobDelegatingVoting; - - mathint alicePowerBefore = getPowerCurrent(alice, VOTING_POWER()); - // no delegation of anyone to Alice - require alicePowerBefore == 0; - - mathint bobPowerBefore = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, VOTING_POWER()); - mathint aliceDelegatePowerBefore = getPowerCurrent(aliceDelegate, VOTING_POWER()); - uint256 aliceBalanceBefore = balanceOf(alice); - - transferFrom(e, alice, bob, amount); - - mathint alicePowerAfter = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, VOTING_POWER()); - mathint aliceDelegatePowerAfter = getPowerCurrent(aliceDelegate, VOTING_POWER()); - uint256 aliceBalanceAfter = balanceOf(alice); - - assert alicePowerBefore == alicePowerAfter; - assert aliceDelegatePowerAfter == - aliceDelegatePowerBefore - normalize(aliceBalanceBefore) + normalize(aliceBalanceAfter); - assert bobPowerAfter == bobPowerBefore + amount; - assert charliePowerBefore == charliePowerAfter; -} - -/* - @Rule - - @Description: - Verify correct proposition power after a token transfer from Alice to Bob, when - Alice was delegating and Bob wasn't - - @Note: - - @Link: -*/ - -rule ppTransferWhenOnlyOneIsDelegating(address alice, address bob, address charlie, uint256 amount) { - env e; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegatingProposition = getDelegatingProposition(alice); - bool isBobDelegatingProposition = getDelegatingProposition(bob); - address aliceDelegate = getPropositionDelegate(alice); - require aliceDelegate != alice && aliceDelegate != 0 && aliceDelegate != bob && aliceDelegate != charlie; - - require isAliceDelegatingProposition && !isBobDelegatingProposition; - - mathint alicePowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - // no delegation of anyone to Alice - require alicePowerBefore == 0; - - mathint bobPowerBefore = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint aliceDelegatePowerBefore = getPowerCurrent(aliceDelegate, PROPOSITION_POWER()); - uint256 aliceBalanceBefore = balanceOf(alice); - - transferFrom(e, alice, bob, amount); - - mathint alicePowerAfter = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint aliceDelegatePowerAfter = getPowerCurrent(aliceDelegate, PROPOSITION_POWER()); - uint256 aliceBalanceAfter = balanceOf(alice); - - // still zero - assert alicePowerBefore == alicePowerAfter; - assert aliceDelegatePowerAfter == - aliceDelegatePowerBefore - normalize(aliceBalanceBefore) + normalize(aliceBalanceAfter); - assert bobPowerAfter == bobPowerBefore + amount; - assert charliePowerBefore == charliePowerAfter; -} - - -/* - @Rule - - @Description: - Verify correct voting power after Alice stops delegating, when - Alice was delegating and Bob wasn't - - @Note: - - @Link: -*/ -rule vpStopDelegatingWhenOnlyOneIsDelegating(address alice, address charlie) { - env e; - require alice != charlie; - require alice == e.msg.sender; - - bool isAliceDelegatingVoting = getDelegatingVoting(alice); - address aliceDelegate = getVotingDelegate(alice); - - require isAliceDelegatingVoting && aliceDelegate != alice && aliceDelegate != 0 && aliceDelegate != charlie; - - mathint alicePowerBefore = getPowerCurrent(alice, VOTING_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, VOTING_POWER()); - mathint aliceDelegatePowerBefore = getPowerCurrent(aliceDelegate, VOTING_POWER()); - - delegate(e, 0); - - mathint alicePowerAfter = getPowerCurrent(alice, VOTING_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, VOTING_POWER()); - mathint aliceDelegatePowerAfter = getPowerCurrent(aliceDelegate, VOTING_POWER()); - - assert alicePowerAfter == alicePowerBefore + balanceOf(alice); - assert aliceDelegatePowerAfter == aliceDelegatePowerBefore - normalize(balanceOf(alice)); - assert charliePowerAfter == charliePowerBefore; -} - -/* - @Rule - - @Description: - Verify correct proposition power after Alice stops delegating, when - Alice was delegating and Bob wasn't - - @Note: - - @Link: -*/ -rule ppStopDelegatingWhenOnlyOneIsDelegating(address alice, address charlie) { - env e; - require alice != charlie; - require alice == e.msg.sender; - - bool isAliceDelegatingProposition = getDelegatingProposition(alice); - address aliceDelegate = getPropositionDelegate(alice); - - require isAliceDelegatingProposition && aliceDelegate != alice && aliceDelegate != 0 && aliceDelegate != charlie; - - mathint alicePowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint aliceDelegatePowerBefore = getPowerCurrent(aliceDelegate, PROPOSITION_POWER()); - - delegate(e, 0); - - mathint alicePowerAfter = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint aliceDelegatePowerAfter = getPowerCurrent(aliceDelegate, PROPOSITION_POWER()); - - assert alicePowerAfter == alicePowerBefore + balanceOf(alice); - assert aliceDelegatePowerAfter == aliceDelegatePowerBefore - normalize(balanceOf(alice)); - assert charliePowerAfter == charliePowerBefore; -} - -/* - @Rule - - @Description: - Verify correct voting power after Alice delegates - - @Note: - - @Link: -*/ -rule vpChangeDelegateWhenOnlyOneIsDelegating(address alice, address delegate2, address charlie) { - env e; - require alice != charlie && alice != delegate2 && charlie != delegate2; - require alice == e.msg.sender; - - bool isAliceDelegatingVoting = getDelegatingVoting(alice); - address aliceDelegate = getVotingDelegate(alice); - require aliceDelegate != alice && aliceDelegate != 0 && aliceDelegate != delegate2 && - delegate2 != 0 && delegate2 != charlie && aliceDelegate != charlie; - - require isAliceDelegatingVoting; - - mathint alicePowerBefore = getPowerCurrent(alice, VOTING_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, VOTING_POWER()); - mathint aliceDelegatePowerBefore = getPowerCurrent(aliceDelegate, VOTING_POWER()); - mathint delegate2PowerBefore = getPowerCurrent(delegate2, VOTING_POWER()); - - delegate(e, delegate2); - - mathint alicePowerAfter = getPowerCurrent(alice, VOTING_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, VOTING_POWER()); - mathint aliceDelegatePowerAfter = getPowerCurrent(aliceDelegate, VOTING_POWER()); - mathint delegate2PowerAfter = getPowerCurrent(delegate2, VOTING_POWER()); - address aliceDelegateAfter = getVotingDelegate(alice); - - assert alicePowerBefore == alicePowerAfter; - assert aliceDelegatePowerAfter == aliceDelegatePowerBefore - normalize(balanceOf(alice)); - assert delegate2PowerAfter == delegate2PowerBefore + normalize(balanceOf(alice)); - assert aliceDelegateAfter == delegate2; - assert charliePowerAfter == charliePowerBefore; -} - -/* - @Rule - - @Description: - Verify correct proposition power after Alice delegates - - @Note: - - @Link: -*/ -rule ppChangeDelegateWhenOnlyOneIsDelegating(address alice, address delegate2, address charlie) { - env e; - require alice != charlie && alice != delegate2 && charlie != delegate2; - require alice == e.msg.sender; - - bool isAliceDelegatingVoting = getDelegatingProposition(alice); - address aliceDelegate = getPropositionDelegate(alice); - require aliceDelegate != alice && aliceDelegate != 0 && aliceDelegate != delegate2 && - delegate2 != 0 && delegate2 != charlie && aliceDelegate != charlie; - - require isAliceDelegatingVoting; - - mathint alicePowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint aliceDelegatePowerBefore = getPowerCurrent(aliceDelegate, PROPOSITION_POWER()); - mathint delegate2PowerBefore = getPowerCurrent(delegate2, PROPOSITION_POWER()); - - delegate(e, delegate2); - - mathint alicePowerAfter = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint aliceDelegatePowerAfter = getPowerCurrent(aliceDelegate, PROPOSITION_POWER()); - mathint delegate2PowerAfter = getPowerCurrent(delegate2, PROPOSITION_POWER()); - address aliceDelegateAfter = getPropositionDelegate(alice); - - assert alicePowerBefore == alicePowerAfter; - assert aliceDelegatePowerAfter == aliceDelegatePowerBefore - normalize(balanceOf(alice)); - assert delegate2PowerAfter == delegate2PowerBefore + normalize(balanceOf(alice)); - assert aliceDelegateAfter == delegate2; - assert charliePowerAfter == charliePowerBefore; -} - -/* - @Rule - - @Description: - Verify correct voting power after Alice transfers to Bob, when only Bob was delegating - - @Note: - - @Link: -*/ - -rule vpOnlyAccount2IsDelegating(address alice, address bob, address charlie, uint256 amount) { - env e; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegatingVoting = getDelegatingVoting(alice); - bool isBobDelegatingVoting = getDelegatingVoting(bob); - address bobDelegate = getVotingDelegate(bob); - require bobDelegate != bob && bobDelegate != 0 && bobDelegate != alice && bobDelegate != charlie; - - require !isAliceDelegatingVoting && isBobDelegatingVoting; - - mathint alicePowerBefore = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerBefore = getPowerCurrent(bob, VOTING_POWER()); - require bobPowerBefore == 0; - mathint charliePowerBefore = getPowerCurrent(charlie, VOTING_POWER()); - mathint bobDelegatePowerBefore = getPowerCurrent(bobDelegate, VOTING_POWER()); - uint256 bobBalanceBefore = balanceOf(bob); - - transferFrom(e, alice, bob, amount); - - mathint alicePowerAfter = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, VOTING_POWER()); - mathint bobDelegatePowerAfter = getPowerCurrent(bobDelegate, VOTING_POWER()); - uint256 bobBalanceAfter = balanceOf(bob); - - assert alicePowerAfter == alicePowerBefore - amount; - assert bobPowerAfter == 0; - assert bobDelegatePowerAfter == bobDelegatePowerBefore - normalize(bobBalanceBefore) + normalize(bobBalanceAfter); - - assert charliePowerAfter == charliePowerBefore; -} - -/* - @Rule - - @Description: - Verify correct proposition power after Alice transfers to Bob, when only Bob was delegating - - @Note: - - @Link: -*/ - -rule ppOnlyAccount2IsDelegating(address alice, address bob, address charlie, uint256 amount) { - env e; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegating = getDelegatingProposition(alice); - bool isBobDelegating = getDelegatingProposition(bob); - address bobDelegate = getPropositionDelegate(bob); - require bobDelegate != bob && bobDelegate != 0 && bobDelegate != alice && bobDelegate != charlie; - - require !isAliceDelegating && isBobDelegating; - - mathint alicePowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerBefore = getPowerCurrent(bob, PROPOSITION_POWER()); - require bobPowerBefore == 0; - mathint charliePowerBefore = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint bobDelegatePowerBefore = getPowerCurrent(bobDelegate, PROPOSITION_POWER()); - uint256 bobBalanceBefore = balanceOf(bob); - - transferFrom(e, alice, bob, amount); - - mathint alicePowerAfter = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint bobDelegatePowerAfter = getPowerCurrent(bobDelegate, PROPOSITION_POWER()); - uint256 bobBalanceAfter = balanceOf(bob); - - assert alicePowerAfter == alicePowerBefore - amount; - assert bobPowerAfter == 0; - assert bobDelegatePowerAfter == bobDelegatePowerBefore - normalize(bobBalanceBefore) + normalize(bobBalanceAfter); - - assert charliePowerAfter == charliePowerBefore; -} - - -/* - @Rule - - @Description: - Verify correct voting power after Alice transfers to Bob, when both Alice - and Bob were delegating - - @Note: - - @Link: -*/ -rule vpTransferWhenBothAreDelegating(address alice, address bob, address charlie, uint256 amount) { - env e; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegatingVoting = getDelegatingVoting(alice); - bool isBobDelegatingVoting = getDelegatingVoting(bob); - require isAliceDelegatingVoting && isBobDelegatingVoting; - address aliceDelegate = getVotingDelegate(alice); - address bobDelegate = getVotingDelegate(bob); - require aliceDelegate != alice && aliceDelegate != 0 && aliceDelegate != bob && aliceDelegate != charlie; - require bobDelegate != bob && bobDelegate != 0 && bobDelegate != alice && bobDelegate != charlie; - require aliceDelegate != bobDelegate; - - mathint alicePowerBefore = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerBefore = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, VOTING_POWER()); - mathint aliceDelegatePowerBefore = getPowerCurrent(aliceDelegate, VOTING_POWER()); - mathint bobDelegatePowerBefore = getPowerCurrent(bobDelegate, VOTING_POWER()); - uint256 aliceBalanceBefore = balanceOf(alice); - uint256 bobBalanceBefore = balanceOf(bob); - - transferFrom(e, alice, bob, amount); - - mathint alicePowerAfter = getPowerCurrent(alice, VOTING_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, VOTING_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, VOTING_POWER()); - mathint aliceDelegatePowerAfter = getPowerCurrent(aliceDelegate, VOTING_POWER()); - mathint bobDelegatePowerAfter = getPowerCurrent(bobDelegate, VOTING_POWER()); - uint256 aliceBalanceAfter = balanceOf(alice); - uint256 bobBalanceAfter = balanceOf(bob); - - assert alicePowerAfter == alicePowerBefore; - assert bobPowerAfter == bobPowerBefore; - assert aliceDelegatePowerAfter == aliceDelegatePowerBefore - normalize(aliceBalanceBefore) - + normalize(aliceBalanceAfter); - - mathint normalizedBalanceBefore = normalize(bobBalanceBefore); - mathint normalizedBalanceAfter = normalize(bobBalanceAfter); - assert bobDelegatePowerAfter == bobDelegatePowerBefore - normalizedBalanceBefore + normalizedBalanceAfter; -} - -/* - @Rule - - @Description: - Verify correct proposition power after Alice transfers to Bob, when both Alice - and Bob were delegating - - @Note: - - @Link: -*/ -rule ppTransferWhenBothAreDelegating(address alice, address bob, address charlie, uint256 amount) { - env e; - require alice != bob && bob != charlie && alice != charlie; - - bool isAliceDelegating = getDelegatingProposition(alice); - bool isBobDelegating = getDelegatingProposition(bob); - require isAliceDelegating && isBobDelegating; - address aliceDelegate = getPropositionDelegate(alice); - address bobDelegate = getPropositionDelegate(bob); - require aliceDelegate != alice && aliceDelegate != 0 && aliceDelegate != bob && aliceDelegate != charlie; - require bobDelegate != bob && bobDelegate != 0 && bobDelegate != alice && bobDelegate != charlie; - require aliceDelegate != bobDelegate; - - mathint alicePowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerBefore = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerBefore = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint aliceDelegatePowerBefore = getPowerCurrent(aliceDelegate, PROPOSITION_POWER()); - mathint bobDelegatePowerBefore = getPowerCurrent(bobDelegate, PROPOSITION_POWER()); - uint256 aliceBalanceBefore = balanceOf(alice); - uint256 bobBalanceBefore = balanceOf(bob); - - transferFrom(e, alice, bob, amount); - - mathint alicePowerAfter = getPowerCurrent(alice, PROPOSITION_POWER()); - mathint bobPowerAfter = getPowerCurrent(bob, PROPOSITION_POWER()); - mathint charliePowerAfter = getPowerCurrent(charlie, PROPOSITION_POWER()); - mathint aliceDelegatePowerAfter = getPowerCurrent(aliceDelegate, PROPOSITION_POWER()); - mathint bobDelegatePowerAfter = getPowerCurrent(bobDelegate, PROPOSITION_POWER()); - uint256 aliceBalanceAfter = balanceOf(alice); - uint256 bobBalanceAfter = balanceOf(bob); - - assert alicePowerAfter == alicePowerBefore; - assert bobPowerAfter == bobPowerBefore; - assert aliceDelegatePowerAfter == aliceDelegatePowerBefore - normalize(aliceBalanceBefore) - + normalize(aliceBalanceAfter); - - mathint normalizedBalanceBefore = normalize(bobBalanceBefore); - mathint normalizedBalanceAfter = normalize(bobBalanceAfter); - assert bobDelegatePowerAfter == bobDelegatePowerBefore - normalizedBalanceBefore + normalizedBalanceAfter; -} - -/* - @Rule - - @Description: - Verify that an account's delegate changes only as a result of a call to - the delegation functions - - @Note: - - @Link: -*/ -rule votingDelegateChanges(address alice, method f) { - env e; - calldataarg args; - - address aliceVotingDelegateBefore = getVotingDelegate(alice); - address alicePropDelegateBefore = getPropositionDelegate(alice); - - f(e, args); - - address aliceVotingDelegateAfter = getVotingDelegate(alice); - address alicePropDelegateAfter = getPropositionDelegate(alice); - - // only these four function may change the delegate of an address - assert aliceVotingDelegateAfter != aliceVotingDelegateBefore || alicePropDelegateBefore != alicePropDelegateAfter => - f.selector == sig:delegate(address).selector || - f.selector == sig:delegateByType(address,AaveTokenV3Harness.GovernancePowerType).selector || - f.selector == sig:metaDelegate(address,address,uint256,uint8,bytes32,bytes32).selector || - f.selector == sig:metaDelegateByType(address,address,AaveTokenV3Harness.GovernancePowerType,uint256,uint8,bytes32,bytes32).selector; -} - -/* - @Rule - - @Description: - Verify that an account's voting and proposition power changes only as a result of a call to - the delegation and transfer functions - - @Note: - - @Link: -*/ -rule votingPowerChanges(address alice, method f) { - env e; - calldataarg args; - - uint aliceVotingPowerBefore = getPowerCurrent(alice, VOTING_POWER()); - uint alicePropPowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - - f(e, args); - - uint aliceVotingPowerAfter = getPowerCurrent(alice, VOTING_POWER()); - uint alicePropPowerAfter = getPowerCurrent(alice, PROPOSITION_POWER()); - - // only these four function may change the power of an address - assert aliceVotingPowerAfter != aliceVotingPowerBefore || alicePropPowerAfter != alicePropPowerBefore => - f.selector == sig:delegate(address).selector || - f.selector == sig:delegateByType(address,AaveTokenV3Harness.GovernancePowerType).selector || - f.selector == sig:metaDelegate(address,address,uint256,uint8,bytes32,bytes32).selector || - f.selector == sig:metaDelegateByType(address,address,AaveTokenV3Harness.GovernancePowerType,uint256,uint8,bytes32,bytes32).selector || - f.selector == sig:transfer(address,uint256).selector || - f.selector == sig:transferFrom(address,address,uint256).selector; -} - -/* - @Rule - - @Description: - Verify that only delegate() and metaDelegate() may change both voting and - proposition delegates of an account at once. - - @Note: - - @Link: -*/ -rule delegationTypeIndependence(address who, method f) filtered { f -> !f.isView } { - address _delegateeV = getVotingDelegate(who); - address _delegateeP = getPropositionDelegate(who); - - env e; - calldataarg arg; - f(e, arg); - - address delegateeV_ = getVotingDelegate(who); - address delegateeP_ = getPropositionDelegate(who); - assert _delegateeV != delegateeV_ && _delegateeP != delegateeP_ => - (f.selector == sig:delegate(address).selector || - f.selector == sig:metaDelegate(address,address,uint256,uint8,bytes32,bytes32).selector), - "one delegatee type stays the same, unless delegate or delegateBySig was called"; -} - -/* - @Rule - - @Description: - Verifies that delegating twice to the same delegate changes the delegate's - voting power only once. - - @Note: - - @Link: -*/ -rule cantDelegateTwice(address _delegate) { - env e; - - address delegateBeforeV = getVotingDelegate(e.msg.sender); - address delegateBeforeP = getPropositionDelegate(e.msg.sender); - require delegateBeforeV != _delegate && delegateBeforeV != e.msg.sender && delegateBeforeV != 0; - require delegateBeforeP != _delegate && delegateBeforeP != e.msg.sender && delegateBeforeP != 0; - require _delegate != e.msg.sender && _delegate != 0 && e.msg.sender != 0; - require getDelegationState(e.msg.sender) == FULL_POWER_DELEGATED(); - - mathint votingPowerBefore = getPowerCurrent(_delegate, VOTING_POWER()); - mathint propPowerBefore = getPowerCurrent(_delegate, PROPOSITION_POWER()); - - delegate(e, _delegate); - - mathint votingPowerAfter = getPowerCurrent(_delegate, VOTING_POWER()); - mathint propPowerAfter = getPowerCurrent(_delegate, PROPOSITION_POWER()); - - delegate(e, _delegate); - - mathint votingPowerAfter2 = getPowerCurrent(_delegate, VOTING_POWER()); - mathint propPowerAfter2 = getPowerCurrent(_delegate, PROPOSITION_POWER()); - - assert votingPowerAfter == votingPowerBefore + normalize(balanceOf(e.msg.sender)); - assert propPowerAfter == propPowerBefore + normalize(balanceOf(e.msg.sender)); - assert votingPowerAfter2 == votingPowerAfter && propPowerAfter2 == propPowerAfter; -} - -/* - @Rule - - @Description: - transfer and transferFrom change voting/proposition power identically - - @Note: - - @Link: -*/ -rule transferAndTransferFromPowerEquivalence(address bob, uint amount) { - env e1; - env e2; - storage init = lastStorage; - - address alice; - require alice == e1.msg.sender; - - uint aliceVotingPowerBefore = getPowerCurrent(alice, VOTING_POWER()); - uint alicePropPowerBefore = getPowerCurrent(alice, PROPOSITION_POWER()); - - transfer(e1, bob, amount); - - uint aliceVotingPowerAfterTransfer = getPowerCurrent(alice, VOTING_POWER()); - uint alicePropPowerAfterTransfer = getPowerCurrent(alice, PROPOSITION_POWER()); - - transferFrom(e2, alice, bob, amount) at init; - - uint aliceVotingPowerAfterTransferFrom = getPowerCurrent(alice, VOTING_POWER()); - uint alicePropPowerAfterTransferFrom = getPowerCurrent(alice, PROPOSITION_POWER()); - - assert aliceVotingPowerAfterTransfer == aliceVotingPowerAfterTransferFrom && - alicePropPowerAfterTransfer == alicePropPowerAfterTransferFrom; - -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/certora/specs/erc20.spec b/CVLByExample/aave-token-v3/certora/specs/erc20.spec deleted file mode 100644 index e9fb5ac4..00000000 --- a/CVLByExample/aave-token-v3/certora/specs/erc20.spec +++ /dev/null @@ -1,558 +0,0 @@ -/* - This is a specification file for the verification of general ERC20 - features of AaveTokenV3.sol smart contract using the Certora prover. - For more information, visit: https://www.certora.com/ - - This file is run with scripts/erc20.sh - On the token harness AaveTokenV3Harness.sol - - Sanity run: - https://prover.certora.com/output/67509/a5d16a31a49b9c9a7b71/?anonymousKey=bd108549122fd97450428a26c4ed52458793b898 -*/ -import "base.spec"; - -function doesntChangeBalance(method f) returns bool { - return f.selector != sig:transfer(address,uint256).selector && - f.selector != sig:transferFrom(address,address,uint256).selector; -} - - - -/* - @Rule - - - @Description: - Verify that there is no fee on transferFrom() (like potentially on USDT) - - @Formula: - { - balances[bob] = y - allowance(alice, msg.sender) >= amount - } - < - transferFrom(alice, bob, amount) - > - { - balances[bob] = y + amount - } - - @Notes: - - - @Link: - -*/ -rule noFeeOnTransferFrom(address alice, address bob, uint256 amount) { - env e; - calldataarg args; - require alice != bob; - require allowance(alice, e.msg.sender) >= amount; - mathint balanceBefore = balanceOf(bob); - - transferFrom(e, alice, bob, amount); - - mathint balanceAfter = balanceOf(bob); - assert balanceAfter == balanceBefore + amount; -} - -/* - @Rule - - @Description: - Verify that there is no fee on transfer() (like potentially on USDT) - - @Formula: - { - balances[bob] = y - balances[msg.sender] >= amount - } - < - transfer(bob, amount) - > - { - balances[bob] = y + amount - } - - @Notes: - - @Link: - - -*/ -rule noFeeOnTransfer(address bob, uint256 amount) { - env e; - calldataarg args; - require bob != e.msg.sender; - mathint balanceSenderBefore = balanceOf(e.msg.sender); - mathint balanceBefore = balanceOf(bob); - - transfer(e, bob, amount); - - mathint balanceAfter = balanceOf(bob); - mathint balanceSenderAfter = balanceOf(e.msg.sender); - assert balanceAfter == balanceBefore + amount; -} - -/* - @Rule - - - @Description: - Token transfer works correctly. Balances are updated if not reverted. - If reverted then the transfer amount was too high, or the recipient is 0. - - @Formula: - { - balanceFromBefore = balanceOf(msg.sender) - balanceToBefore = balanceOf(to) - } - < - transfer(to, amount) - > - { - lastReverted => to = 0 || amount > balanceOf(msg.sender) - !lastReverted => balanceOf(to) = balanceToBefore + amount && - balanceOf(msg.sender) = balanceFromBefore - amount - } - - @Notes: - This rule fails on tokens with a blacklist function, like USDC and USDT. - The prover finds a counterexample of a reverted transfer to a blacklisted address or a transfer in a paused state. - - @Link: - -*/ - - -rule transferCorrect(address to, uint256 amount) { - env e; - require e.msg.value == 0 && e.msg.sender != 0; - uint256 fromBalanceBefore = balanceOf(e.msg.sender); - uint256 toBalanceBefore = balanceOf(to); - require fromBalanceBefore + toBalanceBefore < AAVE_MAX_SUPPLY() / 100; - - // proven elsewhere - address v_delegateTo = getVotingDelegate(to); - mathint dvbTo = getDelegatedVotingBalance(v_delegateTo); - require dvbTo >= balanceOf(to) / DELEGATED_POWER_DIVIDER() && - dvbTo < SCALED_MAX_SUPPLY() - amount / DELEGATED_POWER_DIVIDER(); - address p_delegateTo = getPropositionDelegate(to); - mathint pvbTo = getDelegatedPropositionBalance(p_delegateTo); - require pvbTo >= balanceOf(to) / DELEGATED_POWER_DIVIDER() && - pvbTo < SCALED_MAX_SUPPLY() - amount / DELEGATED_POWER_DIVIDER(); - - // proven elsewhere - address v_delegateFrom = getVotingDelegate(e.msg.sender); - address p_delegateFrom = getPropositionDelegate(e.msg.sender); - mathint dvbFrom = getDelegatedVotingBalance(v_delegateFrom); - mathint pvbFrom = getDelegatedPropositionBalance(p_delegateFrom); - require dvbFrom >= balanceOf(e.msg.sender) / DELEGATED_POWER_DIVIDER(); - require pvbFrom >= balanceOf(e.msg.sender) / DELEGATED_POWER_DIVIDER(); - - require ! ( (getDelegatingVoting(to) && v_delegateTo == to) || - (getDelegatingProposition(to) && p_delegateTo == to)); - - // to not overcomplicate the constraints on dvbTo and dvbFrom - require v_delegateFrom != v_delegateTo && p_delegateFrom != p_delegateTo; - - transfer@withrevert(e, to, amount); - bool reverted = lastReverted; - if (!reverted) { - if (e.msg.sender == to) { - assert balanceOf(e.msg.sender) == fromBalanceBefore; - } else { - assert to_mathint(balanceOf(e.msg.sender)) == fromBalanceBefore - amount; - assert to_mathint(balanceOf(to)) == toBalanceBefore + amount; - } - } else { - assert amount > fromBalanceBefore || to == 0; - } -} - -/* - @Rule - - - @Description: - Test that transferFrom works correctly. Balances are updated if not reverted. - If reverted, it means the transfer amount was too high, or the recipient is 0 - - @Formula: - { - balanceFromBefore = balanceOf(from) - balanceToBefore = balanceOf(to) - } - < - transferFrom(from, to, amount) - > - { - lastreverted => to = 0 || amount > balanceOf(from) - !lastreverted => balanceOf(to) = balanceToBefore + amount && - balanceOf(from) = balanceFromBefore - amount - } - - @Notes: - This rule fails on tokens with a blacklist and or pause function, like USDC and USDT. - The prover finds a counterexample of a reverted transfer to a blacklisted address or a transfer in a paused state. - - @Link: - -*/ - -rule transferFromCorrect(address from, address to, uint256 amount) { - env e; - require e.msg.value == 0; - uint256 fromBalanceBefore = balanceOf(from); - uint256 toBalanceBefore = balanceOf(to); - uint256 allowanceBefore = allowance(from, e.msg.sender); - require fromBalanceBefore + toBalanceBefore < to_mathint(AAVE_MAX_SUPPLY()); - - transferFrom(e, from, to, amount); - - assert from != to => - to_mathint(balanceOf(from)) == fromBalanceBefore - amount && - to_mathint(balanceOf(to)) == toBalanceBefore + amount && - (to_mathint(allowance(from, e.msg.sender)) == allowanceBefore - amount || - allowance(from, e.msg.sender) == max_uint256); -} - -/* - @Rule - - @Description: - Balance of address 0 is always 0 - - @Formula: - { balanceOf[0] = 0 } - - @Notes: - - - @Link: - -*/ -invariant ZeroAddressNoBalance() - balanceOf(0) == 0; - - -/* - @Rule - - @Description: - Contract calls don't change token total supply. - - @Formula: - { - supplyBefore = totalSupply() - } - < f(e, args)> - { - supplyAfter = totalSupply() - supplyBefore == supplyAfter - } - - @Notes: - This rule should fail for any token that has functions that change totalSupply(), like mint() and burn(). - It's still important to run the rule and see if it fails in functions that _aren't_ supposed to modify totalSupply() - - @Link: - -*/ -rule NoChangeTotalSupply(method f) { - // require f.selector != sig:burn(uint256).selector && f.selector != sig:mint(address, uint256).selector; - uint256 totalSupplyBefore = totalSupply(); - env e; - calldataarg args; - f(e, args); - assert totalSupply() == totalSupplyBefore; -} - -/* - The two rules cover the same ground as NoChangeTotalSupply. - - The split into two rules is in order to make the burn/mint features of a tested token even more obvious -*/ -rule noBurningTokens(method f) { - uint256 totalSupplyBefore = totalSupply(); - env e; - calldataarg args; - f(e, args); - assert totalSupply() >= totalSupplyBefore; -} - -rule noMintingTokens(method f) { - uint256 totalSupplyBefore = totalSupply(); - env e; - calldataarg args; - f(e, args); - assert totalSupply() <= totalSupplyBefore; -} - -/* - @Rule - - @Description: - Allowance changes correctly as a result of calls to approve, transfer, increaseAllowance, decreaseAllowance - - @Formula: - { - allowanceBefore = allowance(from, spender) - } - < - f(e, args) - > - { - f.selector = approve(spender, amount) => allowance(from, spender) = amount - f.selector = transferFrom(from, spender, amount) => allowance(from, spender) = allowanceBefore - amount - f.selector = decreaseAllowance(spender, delta) => allowance(from, spender) = allowanceBefore - delta - f.selector = increaseAllowance(spender, delta) => allowance(from, spender) = allowanceBefore + delta - generic f.selector => allowance(from, spender) == allowanceBefore - } - - @Notes: - Some ERC20 tokens have functions like permit() that change allowance via a signature. - The rule will fail on such functions. - - @Link: - -*/ -rule ChangingAllowance(method f, address from, address spender) { - uint256 allowanceBefore = allowance(from, spender); - env e; - if (f.selector == sig:approve(address, uint256).selector) { - address spender_; - uint256 amount; - approve(e, spender_, amount); - if (from == e.msg.sender && spender == spender_) { - assert allowance(from, spender) == amount; - } else { - assert allowance(from, spender) == allowanceBefore; - } - } else if (f.selector == sig:transferFrom(address,address,uint256).selector) { - address from_; - address to; - uint256 amount; - transferFrom(e, from_, to, amount); - mathint allowanceAfter = allowance(from, spender); - if (from == from_ && spender == e.msg.sender) { - assert from == to || allowanceBefore == max_uint256 || allowanceAfter == allowanceBefore - amount; - } else { - assert allowance(from, spender) == allowanceBefore; - } - } else if (f.selector == sig:decreaseAllowance(address, uint256).selector) { - address spender_; - uint256 amount; - require amount <= allowanceBefore; - decreaseAllowance(e, spender_, amount); - if (from == e.msg.sender && spender == spender_) { - assert to_mathint(allowance(from, spender)) == allowanceBefore - amount; - } else { - assert allowance(from, spender) == allowanceBefore; - } - } else if (f.selector == sig:increaseAllowance(address, uint256).selector) { - address spender_; - uint256 amount; - require amount + allowanceBefore < max_uint256; - increaseAllowance(e, spender_, amount); - if (from == e.msg.sender && spender == spender_) { - assert to_mathint(allowance(from, spender)) == allowanceBefore + amount; - } else { - assert allowance(from, spender) == allowanceBefore; - } - } - else - { - calldataarg args; - f(e, args); - assert allowance(from, spender) == allowanceBefore || - f.selector == sig:permit(address,address,uint256,uint256,uint8,bytes32,bytes32).selector; - } -} - -/* - @Rule - - @Description: - Transfer from a to b doesn't change the sum of their balances - - @Formula: - { - balancesBefore = balanceOf(msg.sender) + balanceOf(b) - } - < - transfer(b, amount) - > - { - balancesBefore == balanceOf(msg.sender) + balanceOf(b) - } - - @Notes: - - @Link: - -*/ -rule TransferSumOfFromAndToBalancesStaySame(address to, uint256 amount) { - env e; - mathint sum = balanceOf(e.msg.sender) + balanceOf(to); - require sum < max_uint256; - transfer(e, to, amount); - assert balanceOf(e.msg.sender) + balanceOf(to) == sum; -} - -/* - @Rule - - @Description: - Transfer using transferFrom() from a to b doesn't change the sum of their balances - - @Formula: - { - balancesBefore = balanceOf(a) + balanceOf(b) - } - < - transferFrom(a, b) - > - { - balancesBefore == balanceOf(a) + balanceOf(b) - } - - @Notes: - - @Link: - -*/ -rule TransferFromSumOfFromAndToBalancesStaySame(address from, address to, uint256 amount) { - env e; - mathint sum = balanceOf(from) + balanceOf(to); - require sum < max_uint256; - transferFrom(e, from, to, amount); - assert balanceOf(from) + balanceOf(to) == sum; -} - -/* - @Rule - - @Description: - Transfer from msg.sender to alice doesn't change the balance of other addresses - - @Formula: - { - balanceBefore = balanceOf(bob) - } - < - transfer(alice, amount) - > - { - balanceOf(bob) == balanceBefore - } - - @Notes: - - @Link: - -*/ -rule TransferDoesntChangeOtherBalance(address to, uint256 amount, address other) { - env e; - require other != e.msg.sender; - require other != to && other != currentContract; - uint256 balanceBefore = balanceOf(other); - transfer(e, to, amount); - assert balanceBefore == balanceOf(other); -} - -/* - @Rule - - @Description: - Transfer from alice to bob using transferFrom doesn't change the balance of other addresses - - @Formula: - { - balanceBefore = balanceOf(charlie) - } - < - transferFrom(alice, bob, amount) - > - { - balanceOf(charlie) = balanceBefore - } - - @Notes: - - @Link: - -*/ -rule TransferFromDoesntChangeOtherBalance(address from, address to, uint256 amount, address other) { - env e; - require other != from; - require other != to; - uint256 balanceBefore = balanceOf(other); - transferFrom(e, from, to, amount); - assert balanceBefore == balanceOf(other); -} - -/* - @Rule - - @Description: - Balance of an address, who is not a sender or a recipient in transfer functions, doesn't decrease - as a result of contract calls - - @Formula: - { - balanceBefore = balanceOf(charlie) - } - < - f(e, args) - > - { - f.selector != transfer && f.selector != transferFrom => balanceOf(charlie) == balanceBefore - } - - @Notes: - USDC token has functions like transferWithAuthorization that use a signed message for allowance. - FTT token has a burnFrom that lets an approved spender to burn owner's token. - Certora prover finds these counterexamples to this rule. - In general, the rule will fail on all functions other than transfer/transferFrom that change a balance of an address. - - @Link: - -*/ -rule OtherBalanceOnlyGoesUp(address other, method f) { - env e; - require other != currentContract; - uint256 balanceBefore = balanceOf(other); - - if (f.selector == sig:transferFrom(address, address, uint256).selector) { - address from; - address to; - uint256 amount; - require(other != from); - require balanceOf(from) + balanceBefore < max_uint256; - transferFrom(e, from, to, amount); - } else if (f.selector == sig:transfer(address, uint256).selector) { - require other != e.msg.sender; - require balanceOf(e.msg.sender) + balanceBefore < max_uint256; - calldataarg args; - f(e, args); - } else { - require other != e.msg.sender; - calldataarg args; - f(e, args); - } - - assert balanceOf(other) >= balanceBefore; -} - -rule noRebasing(method f, address alice) { - env e; - calldataarg args; - - require doesntChangeBalance(f); - - uint256 balanceBefore = balanceOf(alice); - f(e, args); - uint256 balanceAfter = balanceOf(alice); - assert balanceBefore == balanceAfter; -} diff --git a/CVLByExample/aave-token-v3/certora/specs/general.spec b/CVLByExample/aave-token-v3/certora/specs/general.spec deleted file mode 100644 index de87e70a..00000000 --- a/CVLByExample/aave-token-v3/certora/specs/general.spec +++ /dev/null @@ -1,213 +0,0 @@ -/* - This is a specification file for the verification of delegation invariants - of AaveTokenV3.sol smart contract using the Certora prover. - For more information, visit: https://www.certora.com/ - - This file is run with scripts/verifyGeneral.sh - On a version with some minimal code modifications - AaveTokenV3HarnessStorage.sol - - Sanity check results: https://prover.certora.com/output/67509/8cee7c95432ede6b3f9f/?anonymousKey=78d297585a2b2edc38f6c513e0ce12df10e47b82 -*/ - -import "base.spec"; - - -/** - - Ghosts - -*/ - -// sum of all user balances -ghost mathint sumBalances { - init_state axiom sumBalances == 0; -} - -// tracking voting delegation status for each address -ghost mapping(address => bool) isDelegatingVoting { - init_state axiom forall address a. isDelegatingVoting[a] == false; -} - -// tracking voting delegation status for each address -ghost mapping(address => bool) isDelegatingProposition { - init_state axiom forall address a. isDelegatingProposition[a] == false; -} - -// sum of all voting delegated balances -ghost mathint sumDelegatedBalancesV { - init_state axiom sumDelegatedBalancesV == 0; -} - -// sum of all proposition undelegated balances -ghost mathint sumUndelegatedBalancesV { - init_state axiom sumUndelegatedBalancesV == 0; -} - -// sum of all proposition delegated balances -ghost mathint sumDelegatedBalancesP { - init_state axiom sumDelegatedBalancesP == 0; -} - -// sum of all voting undelegated balances -ghost mathint sumUndelegatedBalancesP { - init_state axiom sumUndelegatedBalancesP == 0; -} - -// token balances of each address -ghost mapping(address => mathint) balances { - init_state axiom forall address a. balances[a] == 0; -} - -/* - - Hooks - -*/ - - -/* - - This hook updates the sum of delegated and undelegated balances on each change of delegation state. - If the user moves from not delegating to delegating, their balance is moved from undelegated to delegating, - and etc. - -*/ -hook Sstore _balances[KEY address user].delegationState AaveTokenV3Harness.DelegationState new_state (AaveTokenV3Harness.DelegationState old_state) STORAGE { - - bool willDelegateP = !DELEGATING_PROPOSITION(old_state) && DELEGATING_PROPOSITION(new_state); - bool wasDelegatingP = DELEGATING_PROPOSITION(old_state) && !DELEGATING_PROPOSITION(new_state); - - // we cannot use if statements inside hooks, hence the ternary operator - sumUndelegatedBalancesP = willDelegateP ? (sumUndelegatedBalancesP - balances[user]) : sumUndelegatedBalancesP; - sumUndelegatedBalancesP = wasDelegatingP ? (sumUndelegatedBalancesP + balances[user]) : sumUndelegatedBalancesP; - sumDelegatedBalancesP = willDelegateP ? (sumDelegatedBalancesP + balances[user]) : sumDelegatedBalancesP; - sumDelegatedBalancesP = wasDelegatingP ? (sumDelegatedBalancesP - balances[user]) : sumDelegatedBalancesP; - - // change the delegating state only if a change is stored - - isDelegatingProposition[user] = new_state == old_state - ? isDelegatingProposition[user] - : new_state == PROPOSITION_DELEGATED() || new_state == FULL_POWER_DELEGATED(); - - - bool willDelegateV = !DELEGATING_VOTING(old_state) && DELEGATING_VOTING(new_state); - bool wasDelegatingV = DELEGATING_VOTING(old_state) && !DELEGATING_VOTING(new_state); - sumUndelegatedBalancesV = willDelegateV ? (sumUndelegatedBalancesV - balances[user]) : sumUndelegatedBalancesV; - sumUndelegatedBalancesV = wasDelegatingV ? (sumUndelegatedBalancesV + balances[user]) : sumUndelegatedBalancesV; - sumDelegatedBalancesV = willDelegateV ? (sumDelegatedBalancesV + balances[user]) : sumDelegatedBalancesV; - sumDelegatedBalancesV = wasDelegatingV ? (sumDelegatedBalancesV - balances[user]) : sumDelegatedBalancesV; - - // change the delegating state only if a change is stored - - isDelegatingVoting[user] = new_state == old_state - ? isDelegatingVoting[user] - : new_state == VOTING_DELEGATED() || new_state == FULL_POWER_DELEGATED(); -} - - -/* - - This hook updates the sum of delegated and undelegated balances on each change of user balance. - Depending on the delegation state, either the delegated or the undelegated balance get updated. - -*/ -hook Sstore _balances[KEY address user].balance uint104 balance (uint104 old_balance) STORAGE { - balances[user] = balances[user] - old_balance + balance; - // we cannot use if statements inside hooks, hence the ternary operator - sumDelegatedBalancesV = isDelegatingVoting[user] - ? sumDelegatedBalancesV + to_mathint(balance) - to_mathint(old_balance) - : sumDelegatedBalancesV; - sumUndelegatedBalancesV = !isDelegatingVoting[user] - ? sumUndelegatedBalancesV + to_mathint(balance) - to_mathint(old_balance) - : sumUndelegatedBalancesV; - sumDelegatedBalancesP = isDelegatingProposition[user] - ? sumDelegatedBalancesP + to_mathint(balance) - to_mathint(old_balance) - : sumDelegatedBalancesP; - sumUndelegatedBalancesP = !isDelegatingProposition[user] - ? sumUndelegatedBalancesP + to_mathint(balance) - to_mathint(old_balance) - : sumUndelegatedBalancesP; - -} - -/* - @Rule - - @Description: - User's delegation flag is switched on iff user is delegating to an address - other than his own own or 0 - - @Notes: - - - @Link: - -*/ -invariant delegateCorrectness(address user) - ((getVotingDelegate(user) == user || getVotingDelegate(user) == 0) <=> !getDelegatingVoting(user)) - && - ((getPropositionDelegate(user) == user || getPropositionDelegate(user) == 0) <=> !getDelegatingProposition(user)); - -/* - @Rule - - @Description: - Sum of delegated voting balances and undelegated balances is equal to total supply - - @Notes: - - - @Link: - -*/ -invariant sumOfVBalancesCorrectness() sumDelegatedBalancesV + sumUndelegatedBalancesV == to_mathint(totalSupply()); - -/* - @Rule - - @Description: - Sum of delegated proposition balances and undelegated balances is equal to total supply - - @Notes: - - - @Link: - -*/ -invariant sumOfPBalancesCorrectness() sumDelegatedBalancesP + sumUndelegatedBalancesP == to_mathint(totalSupply()); - -/* - @Rule - - @Description: - Transfers don't change voting delegation state - - @Notes: - - - @Link: - -*/ -rule transferDoesntChangeDelegationState() { - env e; - address from; address to; address charlie; - require (charlie != from && charlie != to); - uint amount; - - AaveTokenV3Harness.DelegationState stateFromBefore = getDelegationState(from); - AaveTokenV3Harness.DelegationState stateToBefore = getDelegationState(to); - AaveTokenV3Harness.DelegationState stateCharlieBefore = getDelegationState(charlie); - - bool testFromBefore = isDelegatingVoting[from]; - bool testToBefore = isDelegatingVoting[to]; - - transferFrom(e, from, to, amount); - - AaveTokenV3Harness.DelegationState stateFromAfter = getDelegationState(from); - AaveTokenV3Harness.DelegationState stateToAfter = getDelegationState(to); - bool testFromAfter = isDelegatingVoting[from]; - bool testToAfter = isDelegatingVoting[to]; - - assert testFromBefore == testFromAfter && testToBefore == testToAfter; - assert getDelegationState(charlie) == stateCharlieBefore; -} diff --git a/CVLByExample/aave-token-v3/foundry.toml b/CVLByExample/aave-token-v3/foundry.toml deleted file mode 100644 index 534da712..00000000 --- a/CVLByExample/aave-token-v3/foundry.toml +++ /dev/null @@ -1,9 +0,0 @@ -[default] -src = 'src' -out = 'out' -libs = ['lib'] -remappings = [ - 'openzeppelin-contracts/=lib/openzeppelin-contracts/contracts' -] - -# See more config options https://github.com/gakonst/foundry/tree/master/config \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/.gitignore b/CVLByExample/aave-token-v3/lib/aave-token-v2/.gitignore deleted file mode 100644 index 1d025e5f..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -.env -#Buidler files -cache -artifacts - -node_modules -dist/ -build/ -.vscode - -types/ -coverage -.coverage_artifacts -.coverage_cache -.coverage_contracts -deployed-contracts.json diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/.gitlab-ci.yml b/CVLByExample/aave-token-v3/lib/aave-token-v2/.gitlab-ci.yml deleted file mode 100644 index 56a093b2..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/.gitlab-ci.yml +++ /dev/null @@ -1,46 +0,0 @@ -stages: - - prepare - - test - - deploy - -variables: - IMAGE: ${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHA} - -prepare: - stage: prepare - tags: - - docker-builder - script: - - docker build -t ${IMAGE} . - - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY - - docker push ${IMAGE} -test: - stage: test - tags: - - aave-build-runner - before_script: - - docker-compose -p ${CI_JOB_ID} -f docker-compose.test.yml build - script: - - docker-compose -p ${CI_JOB_ID} -f docker-compose.test.yml run contracts-env npm run test - after_script: - - docker-compose -p ${CI_JOB_ID} -f docker-compose.test.yml run contracts-env npm run ci:clean - - docker-compose -p ${CI_JOB_ID} -f docker-compose.test.yml down - -.image_step: - image: ${IMAGE} - tags: - - docker - -deploy: - extends: .image_step - stage: deploy - script: - - echo @aave-tech:registry=https://gitlab.com/api/v4/packages/npm/ >> .npmrc - - echo //gitlab.com/api/v4/packages/npm/:_authToken=${CI_JOB_TOKEN} >> .npmrc - - echo //gitlab.com/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN} >> .npmrc - - ${VERSION} - - npm --no-git-tag-version version prerelease --preid=beta-$CI_COMMIT_SHORT_SHA - - npm --tag $CI_COMMIT_REF_NAME publish - only: - - master - - merge_requests diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/.prettierrc b/CVLByExample/aave-token-v3/lib/aave-token-v2/.prettierrc deleted file mode 100644 index e81a9fe7..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/.prettierrc +++ /dev/null @@ -1,17 +0,0 @@ -{ - "printWidth": 100, - "trailingComma": "es5", - "semi": true, - "singleQuote": true, - "tabWidth": 2, - "overrides": [ - { - "files": "*.sol", - "options": { - "semi": true, - "printWidth": 100 - } - } - ] - } - \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/.solcover.js b/CVLByExample/aave-token-v3/lib/aave-token-v2/.solcover.js deleted file mode 100644 index 11608506..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/.solcover.js +++ /dev/null @@ -1,14 +0,0 @@ -const accounts = require(`./test-wallets.js`).accounts; - -module.exports = { - skipFiles: ["open-zeppelin/"], - mocha: { - enableTimeouts: false, - }, - providerOptions: { - accounts, - _chainId: 1337, - _chainIdRpc: 1337, - network_id: 1337, - }, -}; diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/Dockerfile b/CVLByExample/aave-token-v3/lib/aave-token-v2/Dockerfile deleted file mode 100644 index 143997e0..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/Dockerfile +++ /dev/null @@ -1,4 +0,0 @@ -FROM ethereum/solc:0.7.5 as build-deps - -FROM node:13 -COPY --from=build-deps /usr/bin/solc /usr/bin/solc diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/Dockerfile_test b/CVLByExample/aave-token-v3/lib/aave-token-v2/Dockerfile_test deleted file mode 100644 index 1c378377..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/Dockerfile_test +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:14 -ARG GITLAB_ACCESS_TOKEN - -WORKDIR /app - -ADD ./package-lock.json ./package.json /app/ - -RUN npm ci - -ADD ./ /app/ \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/LICENSE.md b/CVLByExample/aave-token-v3/lib/aave-token-v2/LICENSE.md deleted file mode 100644 index eb2444d7..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/LICENSE.md +++ /dev/null @@ -1,9 +0,0 @@ - - -Aave Token - -Copyright (C) 2020 Aave - -This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. - -This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/README.md b/CVLByExample/aave-token-v3/lib/aave-token-v2/README.md deleted file mode 100644 index c00e3f30..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/README.md +++ /dev/null @@ -1,115 +0,0 @@ -# Aave Token design - -AAVE is an ERC-20 compatible token. It implements governance-inspired features, and will allow Aave to bootstrap the rewards program for safety and ecosystem growth. -The following document explains the main features of AAVE, it’s monetary policy, and the redemption process from LEND. - -## Roles - -The initial AAVE token implementation does not have any admin roles configured. The contract will be proxied using the Openzeppelin implementation of the EIP-1967 Transparent Proxy pattern. The proxy has an Admin role, and the Admin of the proxy contract will be set upon deployment to the Aave governance contracts. - -## ERC-20 - -The AAVE token implements the standard methods of the ERC-20 interface. A balance snapshot feature has been added to keep track of the balances of the users at specific block heights. This will help with the Aave governance integration of AAVE. -AAVE also integrates the EIP 2612 `permit` function, that will allow gasless transaction and one tx approval/transfer. - -# LendToAaveMigrator - -Smart contract for LEND token holders to execute the migration to the AAVE token, using part of the initial emission of AAVE for it. - -The contract is covered by a proxy, whose owner will be the AAVE governance. Once the governance passes the corresponding proposal, the proxy will be connected to the implementation and LEND holders will be able to call the `migrateFromLend()` function, which, after LEND approval, will pull LEND from the holder wallet and transfer back an equivalent AAVE amount defined by the `LEND_AAVE_RATIO` constant. - -One tradeOff of `migrateFromLend()` is that, as the AAVE total supply will be lower than LEND, the `LEND_AAVE_RATIO` will be always > 1, causing a loss of precision for amounts of LEND that are not multiple of `LEND_AAVE_RATIO`. E.g. a person sending 1.000000000000000022 LEND, with a `LEND_AAVE_RATIO` == 100, will receive 0.01 AAVE, losing the value of the last 22 small units of LEND. -Taking into account the current value of LEND and the future value of AAVE, a lack of precision for less than LEND_AAVE_RATIO small units represents a value several orders of magnitude smaller than 0.01\$. We evaluated some potential solutions for this, specifically: - -1. Rounding half up the amount of AAVE returned from the migration. This opens up to potential attacks where users might purposely migrate less than LEND_AAVE_RATIO to obtain more AAVE as a result of the round up. -2. Returning back the excess LEND: this would leave LEND in circulation forever, which is not the expected end result of the migration. -3. Require the users to migrate only amounts that are multiple of LEND_AAVE_RATIO: This presents considerable UX friction. - -None of those present a better outcome than the implemented solution. - -## The Redemption process - -The first step to bootstrap the AAVE emission is to deploy the AAVE token contract and the  LendToAaveMigrator contract. This task will be performed by the Aave team. Upon deployment, the ownership of the Proxy of the AAVE contract and the LendToAaveMigrator will be set to the Aave Governance. To start the LEND redemption process at that point, the Aave team will create an AIP (Aave Improvement Proposal) and submit a proposal to the Aave governance. The proposal will, once approved, activate the LEND/AAVE redemption process and the ecosystem incentives, which will mark the initial emission of AAVE on the market. -The result of the migration procedure will see the supply of LEND being progressively locked within the new AAVE smart contract, while at the same time an equivalent amount of AAVE is being issued.   -The amount of AAVE equivalent to the LEND tokens burned in the initial phase of the AAVE protocol will remain locked in the LendToAaveMigrator contract. - -## Technical implementation - -### Changes to the Openzeppelin original contracts - -In the context of this implementation, we needed apply the following changes to the OpenZepplin implementation: - -- In `/contracts/open-zeppelin/ERC20.sol`, line 44 and 45, `_name` and `_symbol` have been changed from `private` to `internal` -- We extended the original `Initializable` class from the Openzeppelin contracts and created a `VersionedInitializable` contract. The main differences compared to the `Initializable` are: - -1. The boolean `initialized` has been replaced with a `uint256 latestInitializedRevision`. -2. The `initializer()` modifier fetch the revision of the implementation using a `getRevision()` function defined in the implementation contract. The `initializer` modifier forces that an implementation -3. with a bigger revision number than the current one is being initialized - -The change allows us to call `initialize()` on multiple implementations, that was not possible with the original `Initializable` implementation from OZ. - -### \_beforeTokenTransfer hook - -We override the \_beforeTokenTransfer function on the OZ base ERC20 implementation in order to include the following features: - -1. Snapshotting of balances every time an action involved a transfer happens (mint, burn, transfer or transferFrom). If the account does a transfer to itself, no new snapshot is done. -2. Call to the Aave governance contract forwarding the same input parameters of the `_beforeTokenTransfer` hook. Its an assumption that the Aave governance contract is a trustable party, being its responsibility to control all potential reentrancies if calling back the AaveToken. If the account does a transfer to itself, no interaction with the Aave governance contract should happen. - -## Development deployment - -For development purposes, you can deploy AaveToken and LendToAaveMigrator to a local network via the following command: - -``` -npm run dev:deployment -``` - -For any other network, you can run the deployment in the following way - -``` -npm run ropsten:deployment -``` - -You can also set an optional `$AAVE_ADMIN` enviroment variable to set an ETH address as the admin of the AaveToken and LendToAaveMigrator proxies. If not set, the deployment will set the second account of the `accounts` network configuration at `buidler.config.ts`. - -## Mainnet deployment - -You can deploy AaveToken and LendToAaveMigrator to the mainnet network via the following command: - -``` -AAVE_ADMIN=governance_or_ETH_address -LEND_TOKEN=lend_token_address -npm run main:deployment -``` - -The `$AAVE_ADMIN` enviroment variable is required to run, set an ETH address as the admin of the AaveToken and LendToAaveMigrator proxies. Check `buidler.config.ts` for more required enviroment variables for Mainnet deployment. - -The proxies will be initialized during the deployment with the `$AAVE_ADMIN` address, but the smart contracts implementations will not be initialized. - -## Enviroment Variables - -| Variable | Description | -| ----------------------- | ----------------------------------------------------------------------------------- | -| \$AAVE_ADMIN | ETH Address of the admin of Proxy contracts. Optional for development. | -| \$LEND_TOKEN | ETH Address of the LEND token. Optional for development. | -| \$INFURA_KEY | Infura key, only required when using a network different than local network. | -| \$MNEMONIC\_\ | Mnemonic phrase, only required when using a network different than local network. | -| \$ETHERESCAN_KEY | Etherscan key, not currently used, but will be required for contracts verification. | - -## Audits v1 - -The Solidity code in this repository has undergone 2 traditional smart contracts' audits by Consensys Diligence and Certik, and properties' verification process by Certora. The reports are: -- [Consensys Diligence](https://diligence.consensys.net/audits/2020/07/aave-token/) -- [Certik](audits/AaveTokenReport_CertiK.pdf) -- [Certora](audits/AaveTokenVerification_by_Certora.pdf) - -## Audits v2 - -The new StakedAaveV2 implementation has been audited by Peckshield and property checked by Certora. - -## Credits - -For the proxy-related contracts, we have used the implementation of our friend from [OpenZeppelin](https://github.com/OpenZeppelin/openzeppelin-sdk/). - -## License - -The contents of this repository are under the AGPLv3 license. diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/audits/AaveTokenReport_CertiK.pdf b/CVLByExample/aave-token-v3/lib/aave-token-v2/audits/AaveTokenReport_CertiK.pdf deleted file mode 100644 index c481f552..00000000 Binary files a/CVLByExample/aave-token-v3/lib/aave-token-v2/audits/AaveTokenReport_CertiK.pdf and /dev/null differ diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/audits/AaveTokenVerification_by_Certora.pdf b/CVLByExample/aave-token-v3/lib/aave-token-v2/audits/AaveTokenVerification_by_Certora.pdf deleted file mode 100644 index 12bc4de2..00000000 Binary files a/CVLByExample/aave-token-v3/lib/aave-token-v2/audits/AaveTokenVerification_by_Certora.pdf and /dev/null differ diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IERC20.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IERC20.sol deleted file mode 100644 index a9211a4b..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IERC20.sol +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20 { - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `recipient`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address recipient, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `sender` to `recipient` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); - - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IERC20Detailed.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IERC20Detailed.sol deleted file mode 100644 index 46f3942e..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IERC20Detailed.sol +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -import {IERC20} from "./IERC20.sol"; - -interface IERC20Detailed is IERC20 { - function name() external view returns(string memory); - function symbol() external view returns(string memory); - function decimals() external view returns(uint8); -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IGovernancePowerDelegationToken.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IGovernancePowerDelegationToken.sol deleted file mode 100644 index 52098968..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/IGovernancePowerDelegationToken.sol +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -interface IGovernancePowerDelegationToken { - - enum DelegationType {VOTING_POWER, PROPOSITION_POWER} - - /** - * @dev emitted when a user delegates to another - * @param delegator the delegator - * @param delegatee the delegatee - * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) - **/ - event DelegateChanged( - address indexed delegator, - address indexed delegatee, - DelegationType delegationType - ); - - /** - * @dev emitted when an action changes the delegated power of a user - * @param user the user which delegated power has changed - * @param amount the amount of delegated power for the user - * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) - **/ - event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); - - /** - * @dev delegates the specific power to a delegatee - * @param delegatee the user which delegated power has changed - * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) - **/ - function delegateByType(address delegatee, DelegationType delegationType) external virtual; - /** - * @dev delegates all the powers to a specific user - * @param delegatee the user to which the power will be delegated - **/ - function delegate(address delegatee) external virtual; - /** - * @dev returns the delegatee of an user - * @param delegator the address of the delegator - **/ - function getDelegateeByType(address delegator, DelegationType delegationType) - external - virtual - view - returns (address); - - /** - * @dev returns the current delegated power of a user. The current power is the - * power delegated at the time of the last snapshot - * @param user the user - **/ - function getPowerCurrent(address user, DelegationType delegationType) - external - virtual - view - returns (uint256); - - /** - * @dev returns the delegated power of a user at a certain block - * @param user the user - **/ - function getPowerAtBlock( - address user, - uint256 blockNumber, - DelegationType delegationType - ) external virtual view returns (uint256); - - /** - * @dev returns the total supply at a certain block number - **/ - function totalSupplyAt(uint256 blockNumber) external virtual view returns (uint256); -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/ITransferHook.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/ITransferHook.sol deleted file mode 100644 index 7819ac23..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/interfaces/ITransferHook.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -interface ITransferHook { - function onTransfer(address from, address to, uint256 amount) external; -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Address.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Address.sol deleted file mode 100644 index ae830617..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Address.sol +++ /dev/null @@ -1,58 +0,0 @@ -pragma solidity ^0.7.5; - -/** - * @dev Collection of functions related to the address type - */ -library Address { - /** - * @dev Returns true if `account` is a contract. - * - * [IMPORTANT] - * ==== - * It is unsafe to assume that an address for which this function returns - * false is an externally-owned account (EOA) and not a contract. - * - * Among others, `isContract` will return false for the following - * types of addresses: - * - * - an externally-owned account - * - a contract in construction - * - an address where a contract will be created - * - an address where a contract lived, but was destroyed - * ==== - */ - function isContract(address account) internal view returns (bool) { - // According to EIP-1052, 0x0 is the value returned for not-yet created accounts - // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned - // for accounts without code, i.e. `keccak256('')` - bytes32 codehash; - bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; - // solhint-disable-next-line no-inline-assembly - assembly { codehash := extcodehash(account) } - return (codehash != accountHash && codehash != 0x0); - } - - /** - * @dev Replacement for Solidity's `transfer`: sends `amount` wei to - * `recipient`, forwarding all available gas and reverting on errors. - * - * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost - * of certain opcodes, possibly making contracts go over the 2300 gas limit - * imposed by `transfer`, making them unable to receive funds via - * `transfer`. {sendValue} removes this limitation. - * - * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. - * - * IMPORTANT: because control is transferred to `recipient`, care must be - * taken to not create reentrancy vulnerabilities. Consider using - * {ReentrancyGuard} or the - * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. - */ - function sendValue(address payable recipient, uint256 amount) internal { - require(address(this).balance >= amount, "Address: insufficient balance"); - - // solhint-disable-next-line avoid-low-level-calls, avoid-call-value - (bool success, ) = recipient.call{ value: amount }(""); - require(success, "Address: unable to send value, recipient may have reverted"); - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/BaseAdminUpgradeabilityProxy.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/BaseAdminUpgradeabilityProxy.sol deleted file mode 100644 index b49562c9..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/BaseAdminUpgradeabilityProxy.sol +++ /dev/null @@ -1,120 +0,0 @@ -pragma solidity ^0.7.5; - -import './UpgradeabilityProxy.sol'; - -/** - * @title BaseAdminUpgradeabilityProxy - * @dev This contract combines an upgradeability proxy with an authorization - * mechanism for administrative tasks. - * All external functions in this contract must be guarded by the - * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity - * feature proposal that would enable this to be done automatically. - */ -contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { - /** - * @dev Emitted when the administration has been transferred. - * @param previousAdmin Address of the previous admin. - * @param newAdmin Address of the new admin. - */ - event AdminChanged(address previousAdmin, address newAdmin); - - /** - * @dev Storage slot with the admin of the contract. - * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is - * validated in the constructor. - */ - - bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; - - /** - * @dev Modifier to check whether the `msg.sender` is the admin. - * If it is, it will run the function. Otherwise, it will delegate the call - * to the implementation. - */ - modifier ifAdmin() { - if (msg.sender == _admin()) { - _; - } else { - _fallback(); - } - } - - /** - * @return The address of the proxy admin. - */ - function admin() external ifAdmin returns (address) { - return _admin(); - } - - /** - * @return The address of the implementation. - */ - function implementation() external ifAdmin returns (address) { - return _implementation(); - } - - /** - * @dev Changes the admin of the proxy. - * Only the current admin can call this function. - * @param newAdmin Address to transfer proxy administration to. - */ - function changeAdmin(address newAdmin) external ifAdmin { - require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); - emit AdminChanged(_admin(), newAdmin); - _setAdmin(newAdmin); - } - - /** - * @dev Upgrade the backing implementation of the proxy. - * Only the admin can call this function. - * @param newImplementation Address of the new implementation. - */ - function upgradeTo(address newImplementation) external ifAdmin { - _upgradeTo(newImplementation); - } - - /** - * @dev Upgrade the backing implementation of the proxy and call a function - * on the new implementation. - * This is useful to initialize the proxied contract. - * @param newImplementation Address of the new implementation. - * @param data Data to send as msg.data in the low level call. - * It should include the signature and the parameters of the function to be called, as described in - * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. - */ - function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { - _upgradeTo(newImplementation); - (bool success,) = newImplementation.delegatecall(data); - require(success); - } - - /** - * @return adm The admin slot. - */ - function _admin() internal view returns (address adm) { - bytes32 slot = ADMIN_SLOT; - assembly { - adm := sload(slot) - } - } - - /** - * @dev Sets the address of the proxy admin. - * @param newAdmin Address of the new proxy admin. - */ - function _setAdmin(address newAdmin) internal { - bytes32 slot = ADMIN_SLOT; - - assembly { - sstore(slot, newAdmin) - } - } - - /** - * @dev Only fall back when the sender is not the admin. - */ - function _willFallback() internal override virtual { - require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); - super._willFallback(); - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/BaseUpgradeabilityProxy.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/BaseUpgradeabilityProxy.sol deleted file mode 100644 index 18497bb9..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/BaseUpgradeabilityProxy.sol +++ /dev/null @@ -1,59 +0,0 @@ -pragma solidity ^0.7.5; - -import './Proxy.sol'; -import './Address.sol'; - -/** - * @title BaseUpgradeabilityProxy - * @dev This contract implements a proxy that allows to change the - * implementation address to which it will delegate. - * Such a change is called an implementation upgrade. - */ -contract BaseUpgradeabilityProxy is Proxy { - /** - * @dev Emitted when the implementation is upgraded. - * @param implementation Address of the new implementation. - */ - event Upgraded(address indexed implementation); - - /** - * @dev Storage slot with the address of the current implementation. - * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is - * validated in the constructor. - */ - bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - - /** - * @dev Returns the current implementation. - * @return impl Address of the current implementation - */ - function _implementation() internal override view returns (address impl) { - bytes32 slot = IMPLEMENTATION_SLOT; - assembly { - impl := sload(slot) - } - } - - /** - * @dev Upgrades the proxy to a new implementation. - * @param newImplementation Address of the new implementation. - */ - function _upgradeTo(address newImplementation) internal { - _setImplementation(newImplementation); - emit Upgraded(newImplementation); - } - - /** - * @dev Sets the implementation address of the proxy. - * @param newImplementation Address of the new implementation. - */ - function _setImplementation(address newImplementation) internal { - require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); - - bytes32 slot = IMPLEMENTATION_SLOT; - - assembly { - sstore(slot, newImplementation) - } - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Context.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Context.sol deleted file mode 100644 index 335e8305..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Context.sol +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.7.5; - -/* - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with GSN meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract Context { - function _msgSender() internal view virtual returns (address payable) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes memory) { - this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 - return msg.data; - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/ERC20.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/ERC20.sol deleted file mode 100644 index ad3ca30a..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/ERC20.sol +++ /dev/null @@ -1,307 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.7.5; - -import "./Context.sol"; -import "../interfaces/IERC20.sol"; -import "./SafeMath.sol"; -import "./Address.sol"; - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20PresetMinterPauser}. - * - * TIP: For a detailed writeup see our guide - * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * We have followed general OpenZeppelin guidelines: functions revert instead - * of returning `false` on failure. This behavior is nonetheless conventional - * and does not conflict with the expectations of ERC20 applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -contract ERC20 is Context, IERC20 { - using SafeMath for uint256; - using Address for address; - - mapping (address => uint256) private _balances; - - mapping (address => mapping (address => uint256)) private _allowances; - - uint256 private _totalSupply; - - string internal _name; - string internal _symbol; - uint8 private _decimals; - - /** - * @dev Sets the values for {name} and {symbol}, initializes {decimals} with - * a default value of 18. - * - * To select a different value for {decimals}, use {_setupDecimals}. - * - * All three of these values are immutable: they can only be set once during - * construction. - */ - constructor (string memory name, string memory symbol) public { - _name = name; - _symbol = symbol; - _decimals = 18; - } - - /** - * @dev Returns the name of the token. - */ - function name() public view returns (string memory) { - return _name; - } - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() public view returns (string memory) { - return _symbol; - } - - /** - * @dev Returns the number of decimals used to get its user representation. - * For example, if `decimals` equals `2`, a balance of `505` tokens should - * be displayed to a user as `5,05` (`505 / 10 ** 2`). - * - * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is - * called. - * - * NOTE: This information is only used for _display_ purposes: it in - * no way affects any of the arithmetic of the contract, including - * {IERC20-balanceOf} and {IERC20-transfer}. - */ - function decimals() public view returns (uint8) { - return _decimals; - } - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view override returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view override returns (uint256) { - return _balances[account]; - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `recipient` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address recipient, uint256 amount) public virtual override returns (bool) { - _transfer(_msgSender(), recipient, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view virtual override returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public virtual override returns (bool) { - _approve(_msgSender(), spender, amount); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}; - * - * Requirements: - * - `sender` and `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - * - the caller must have allowance for ``sender``'s tokens of at least - * `amount`. - */ - function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { - _transfer(sender, recipient, amount); - _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); - return true; - } - - /** - * @dev Atomically increases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { - _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); - return true; - } - - /** - * @dev Atomically decreases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `spender` must have allowance for the caller of at least - * `subtractedValue`. - */ - function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { - _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); - return true; - } - - /** - * @dev Moves tokens `amount` from `sender` to `recipient`. - * - * This is internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * Requirements: - * - * - `sender` cannot be the zero address. - * - `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - */ - function _transfer(address sender, address recipient, uint256 amount) internal virtual { - require(sender != address(0), "ERC20: transfer from the zero address"); - require(recipient != address(0), "ERC20: transfer to the zero address"); - - _beforeTokenTransfer(sender, recipient, amount); - - _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); - _balances[recipient] = _balances[recipient].add(amount); - emit Transfer(sender, recipient, amount); - } - - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * Requirements - * - * - `to` cannot be the zero address. - */ - function _mint(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: mint to the zero address"); - - _beforeTokenTransfer(address(0), account, amount); - - _totalSupply = _totalSupply.add(amount); - _balances[account] = _balances[account].add(amount); - emit Transfer(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * Requirements - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - */ - function _burn(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: burn from the zero address"); - - _beforeTokenTransfer(account, address(0), amount); - - _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); - _totalSupply = _totalSupply.sub(amount); - emit Transfer(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. - * - * This is internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve(address owner, address spender, uint256 amount) internal virtual { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Sets {decimals} to a value other than the default one of 18. - * - * WARNING: This function should only be called from the constructor. Most - * applications that interact with token contracts will not expect - * {decimals} to ever change, and may work incorrectly if it does. - */ - function _setupDecimals(uint8 decimals_) internal { - _decimals = decimals_; - } - - /** - * @dev Hook that is called before any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be to transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/InitializableAdminUpgradeabilityProxy.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/InitializableAdminUpgradeabilityProxy.sol deleted file mode 100644 index 9e34cc65..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/InitializableAdminUpgradeabilityProxy.sol +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity ^0.7.5; - -import "./BaseAdminUpgradeabilityProxy.sol"; -import "./InitializableUpgradeabilityProxy.sol"; - -/** - * @title InitializableAdminUpgradeabilityProxy - * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for - * initializing the implementation, admin, and init data. - */ -contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { - /** - * Contract initializer. - * @param _logic address of the initial implementation. - * @param _admin Address of the proxy administrator. - * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. - * It should include the signature and the parameters of the function to be called, as described in - * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. - * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. - */ - function initialize(address _logic, address _admin, bytes memory _data) public payable { - require(_implementation() == address(0)); - InitializableUpgradeabilityProxy.initialize(_logic, _data); - assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); - _setAdmin(_admin); - } - - /** - * @dev Only fall back when the sender is not the admin. - */ - function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { - BaseAdminUpgradeabilityProxy._willFallback(); - } - -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/InitializableUpgradeabilityProxy.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/InitializableUpgradeabilityProxy.sol deleted file mode 100644 index 27eeb244..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/InitializableUpgradeabilityProxy.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity ^0.7.5; - -import "./BaseUpgradeabilityProxy.sol"; - -/** - * @title InitializableUpgradeabilityProxy - * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing - * implementation and init data. - */ -contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { - /** - * @dev Contract initializer. - * @param _logic Address of the initial implementation. - * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. - * It should include the signature and the parameters of the function to be called, as described in - * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. - * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. - */ - function initialize(address _logic, bytes memory _data) public payable { - require(_implementation() == address(0)); - assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); - _setImplementation(_logic); - if (_data.length > 0) { - (bool success, ) = _logic.delegatecall(_data); - require(success); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Proxy.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Proxy.sol deleted file mode 100644 index b04b6a3d..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/Proxy.sol +++ /dev/null @@ -1,67 +0,0 @@ -pragma solidity ^0.7.5; - -/** - * @title Proxy - * @dev Implements delegation of calls to other contracts, with proper - * forwarding of return values and bubbling of failures. - * It defines a fallback function that delegates all calls to the address - * returned by the abstract _implementation() internal function. - */ -abstract contract Proxy { - /** - * @dev Fallback function. - * Implemented entirely in `_fallback`. - */ - fallback () payable external { - _fallback(); - } - - /** - * @return The Address of the implementation. - */ - function _implementation() internal virtual view returns (address); - - /** - * @dev Delegates execution to an implementation contract. - * This is a low level function that doesn't return to its internal call site. - * It will return to the external caller whatever the implementation returns. - * @param implementation Address to delegate. - */ - function _delegate(address implementation) internal { - assembly { - // Copy msg.data. We take full control of memory in this inline assembly - // block because it will not return to Solidity code. We overwrite the - // Solidity scratch pad at memory position 0. - calldatacopy(0, 0, calldatasize()) - - // Call the implementation. - // out and outsize are 0 because we don't know the size yet. - let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) - - // Copy the returned data. - returndatacopy(0, 0, returndatasize()) - - switch result - // delegatecall returns 0 on error. - case 0 { revert(0, returndatasize()) } - default { return(0, returndatasize()) } - } - } - - /** - * @dev Function that is run as the first thing in the fallback function. - * Can be redefined in derived contracts to add functionality. - * Redefinitions must call super._willFallback(). - */ - function _willFallback() internal virtual { - } - - /** - * @dev fallback implementation. - * Extracted to enable manual triggering. - */ - function _fallback() internal { - _willFallback(); - _delegate(_implementation()); - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/SafeMath.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/SafeMath.sol deleted file mode 100644 index 23e61b53..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/SafeMath.sol +++ /dev/null @@ -1,150 +0,0 @@ -pragma solidity ^0.7.5; - -/** - * @dev Wrappers over Solidity's arithmetic operations with added overflow - * checks. - * - * Arithmetic operations in Solidity wrap on overflow. This can easily result - * in bugs, because programmers usually assume that an overflow raises an - * error, which is the standard behavior in high level programming languages. - * `SafeMath` restores this intuition by reverting the transaction when an - * operation overflows. - * - * Using this library instead of the unchecked operations eliminates an entire - * class of bugs, so it's recommended to use it always. - */ -library SafeMath { - /** - * @dev Returns the addition of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `+` operator. - * - * Requirements: - * - Addition cannot overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256) { - uint256 c = a + b; - require(c >= a, "SafeMath: addition overflow"); - - return c; - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - return sub(a, b, "SafeMath: subtraction overflow"); - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting with custom message on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b <= a, errorMessage); - uint256 c = a - b; - - return c; - } - - /** - * @dev Returns the multiplication of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `*` operator. - * - * Requirements: - * - Multiplication cannot overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256) { - // Gas optimization: this is cheaper than requiring 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 - if (a == 0) { - return 0; - } - - uint256 c = a * b; - require(c / a == b, "SafeMath: multiplication overflow"); - - return c; - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - return div(a, b, "SafeMath: division by zero"); - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts with custom message on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - // Solidity only automatically asserts when dividing by 0 - require(b > 0, errorMessage); - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - - return c; - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b) internal pure returns (uint256) { - return mod(a, b, "SafeMath: modulo by zero"); - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts with custom message when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b != 0, errorMessage); - return a % b; - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/UpgradeabilityProxy.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/UpgradeabilityProxy.sol deleted file mode 100644 index 06a299d0..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/open-zeppelin/UpgradeabilityProxy.sol +++ /dev/null @@ -1,27 +0,0 @@ -pragma solidity ^0.7.5; - -import './BaseUpgradeabilityProxy.sol'; - -/** - * @title UpgradeabilityProxy - * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing - * implementation and init data. - */ -contract UpgradeabilityProxy is BaseUpgradeabilityProxy { - /** - * @dev Contract constructor. - * @param _logic Address of the initial implementation. - * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. - * It should include the signature and the parameters of the function to be called, as described in - * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. - * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. - */ - constructor(address _logic, bytes memory _data) public payable { - assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); - _setImplementation(_logic); - if(_data.length > 0) { - (bool success,) = _logic.delegatecall(_data); - require(success); - } - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/AaveToken.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/AaveToken.sol deleted file mode 100644 index e0b5d0f3..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/AaveToken.sol +++ /dev/null @@ -1,200 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -import {ERC20} from '../open-zeppelin/ERC20.sol'; -import {ITransferHook} from '../interfaces/ITransferHook.sol'; -import {VersionedInitializable} from '../utils/VersionedInitializable.sol'; -import {SafeMath} from '../open-zeppelin/SafeMath.sol'; - -/** - * @notice implementation of the AAVE token contract - * @author Aave - */ -contract AaveToken is ERC20, VersionedInitializable { - using SafeMath for uint256; - - /// @dev snapshot of a value on a specific block, used for balances - struct Snapshot { - uint128 blockNumber; - uint128 value; - } - - string internal constant NAME = 'Aave Token'; - string internal constant SYMBOL = 'AAVE'; - uint8 internal constant DECIMALS = 18; - - /// @dev the amount being distributed for the LEND -> AAVE migration - uint256 internal constant MIGRATION_AMOUNT = 13000000 ether; - - /// @dev the amount being distributed for the PSI and PEI - uint256 internal constant DISTRIBUTION_AMOUNT = 3000000 ether; - - uint256 public constant REVISION = 1; - - /// @dev owner => next valid nonce to submit with permit() - mapping(address => uint256) public _nonces; - - mapping(address => mapping(uint256 => Snapshot)) public _snapshots; - - mapping(address => uint256) public _countsSnapshots; - - /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer - /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility - /// to control all potential reentrancies by calling back the AaveToken - ITransferHook public _aaveGovernance; - - bytes32 public DOMAIN_SEPARATOR; - bytes public constant EIP712_REVISION = bytes('1'); - bytes32 internal constant EIP712_DOMAIN = keccak256( - 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' - ); - bytes32 public constant PERMIT_TYPEHASH = keccak256( - 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' - ); - - event SnapshotDone(address owner, uint128 oldValue, uint128 newValue); - - constructor() public ERC20(NAME, SYMBOL) {} - - /** - * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy - * @param migrator the address of the LEND -> AAVE migration contract - * @param distributor the address of the AAVE distribution contract - */ - function initialize( - address migrator, - address distributor, - ITransferHook aaveGovernance - ) external initializer { - uint256 chainId; - - //solium-disable-next-line - assembly { - chainId := chainid() - } - - DOMAIN_SEPARATOR = keccak256( - abi.encode( - EIP712_DOMAIN, - keccak256(bytes(NAME)), - keccak256(EIP712_REVISION), - chainId, - address(this) - ) - ); - _name = NAME; - _symbol = SYMBOL; - _setupDecimals(DECIMALS); - _aaveGovernance = aaveGovernance; - _mint(migrator, MIGRATION_AMOUNT); - _mint(distributor, DISTRIBUTION_AMOUNT); - } - - /** - * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md - * @param owner the owner of the funds - * @param spender the spender - * @param value the amount - * @param deadline the deadline timestamp, type(uint256).max for no deadline - * @param v signature param - * @param s signature param - * @param r signature param - */ - - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external { - require(owner != address(0), 'INVALID_OWNER'); - //solium-disable-next-line - require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); - uint256 currentValidNonce = _nonces[owner]; - bytes32 digest = keccak256( - abi.encodePacked( - '\x19\x01', - DOMAIN_SEPARATOR, - keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) - ) - ); - - require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); - _nonces[owner] = currentValidNonce.add(1); - _approve(owner, spender, value); - } - - /** - * @dev returns the revision of the implementation contract - */ - function getRevision() internal override pure returns (uint256) { - return REVISION; - } - - /** - * @dev Writes a snapshot for an owner of tokens - * @param owner The owner of the tokens - * @param oldValue The value before the operation that is gonna be executed after the snapshot - * @param newValue The value after the operation - */ - function _writeSnapshot( - address owner, - uint128 oldValue, - uint128 newValue - ) internal { - uint128 currentBlock = uint128(block.number); - - uint256 ownerCountOfSnapshots = _countsSnapshots[owner]; - mapping(uint256 => Snapshot) storage snapshotsOwner = _snapshots[owner]; - - // Doing multiple operations in the same block - if ( - ownerCountOfSnapshots != 0 && - snapshotsOwner[ownerCountOfSnapshots - 1].blockNumber == currentBlock - ) { - snapshotsOwner[ownerCountOfSnapshots - 1].value = newValue; - } else { - snapshotsOwner[ownerCountOfSnapshots] = Snapshot(currentBlock, newValue); - _countsSnapshots[owner] = ownerCountOfSnapshots + 1; - } - - emit SnapshotDone(owner, oldValue, newValue); - } - - /** - * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn - * - On _transfer, it writes snapshots for both "from" and "to" - * - On _mint, only for _to - * - On _burn, only for _from - * @param from the from address - * @param to the to address - * @param amount the amount to transfer - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal override { - if (from == to) { - return; - } - - if (from != address(0)) { - uint256 fromBalance = balanceOf(from); - _writeSnapshot(from, uint128(fromBalance), uint128(fromBalance.sub(amount))); - } - if (to != address(0)) { - uint256 toBalance = balanceOf(to); - _writeSnapshot(to, uint128(toBalance), uint128(toBalance.add(amount))); - } - - // caching the aave governance address to avoid multiple state loads - ITransferHook aaveGovernance = _aaveGovernance; - if (aaveGovernance != ITransferHook(0)) { - aaveGovernance.onTransfer(from, to, amount); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/AaveTokenV2.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/AaveTokenV2.sol deleted file mode 100644 index 88b66057..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/AaveTokenV2.sol +++ /dev/null @@ -1,220 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -import {ERC20} from '../open-zeppelin/ERC20.sol'; -import {ITransferHook} from '../interfaces/ITransferHook.sol'; -import {VersionedInitializable} from '../utils/VersionedInitializable.sol'; -import {GovernancePowerDelegationERC20} from './base/GovernancePowerDelegationERC20.sol'; -import {SafeMath} from '../open-zeppelin/SafeMath.sol'; - -/** - * @notice implementation of the AAVE token contract - * @author Aave - */ -contract AaveTokenV2 is GovernancePowerDelegationERC20, VersionedInitializable { - using SafeMath for uint256; - - string internal constant NAME = 'Aave Token'; - string internal constant SYMBOL = 'AAVE'; - uint8 internal constant DECIMALS = 18; - - uint256 public constant REVISION = 2; - - /// @dev owner => next valid nonce to submit with permit() - mapping(address => uint256) public _nonces; - - mapping(address => mapping(uint256 => Snapshot)) public _votingSnapshots; - - mapping(address => uint256) public _votingSnapshotsCounts; - - /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer - /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility - /// to control all potential reentrancies by calling back the AaveToken - ITransferHook public _aaveGovernance; - - bytes32 public DOMAIN_SEPARATOR; - bytes public constant EIP712_REVISION = bytes('1'); - bytes32 internal constant EIP712_DOMAIN = keccak256( - 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' - ); - bytes32 public constant PERMIT_TYPEHASH = keccak256( - 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' - ); - - mapping(address => address) internal _votingDelegates; - - mapping(address => mapping(uint256 => Snapshot)) internal _propositionPowerSnapshots; - mapping(address => uint256) internal _propositionPowerSnapshotsCounts; - - mapping(address => address) internal _propositionPowerDelegates; - - constructor() public ERC20(NAME, SYMBOL) {} - - /** - * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy - */ - function initialize() external initializer {} - - /** - * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md - * @param owner the owner of the funds - * @param spender the spender - * @param value the amount - * @param deadline the deadline timestamp, type(uint256).max for no deadline - * @param v signature param - * @param s signature param - * @param r signature param - */ - - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external { - require(owner != address(0), 'INVALID_OWNER'); - //solium-disable-next-line - require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); - uint256 currentValidNonce = _nonces[owner]; - bytes32 digest = keccak256( - abi.encodePacked( - '\x19\x01', - DOMAIN_SEPARATOR, - keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) - ) - ); - - require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); - _nonces[owner] = currentValidNonce.add(1); - _approve(owner, spender, value); - } - - /** - * @dev returns the revision of the implementation contract - */ - function getRevision() internal override pure returns (uint256) { - return REVISION; - } - - /** - * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn - * - On _transfer, it writes snapshots for both "from" and "to" - * - On _mint, only for _to - * - On _burn, only for _from - * @param from the from address - * @param to the to address - * @param amount the amount to transfer - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal override { - address votingFromDelegatee = _getDelegatee(from, _votingDelegates); - address votingToDelegatee = _getDelegatee(to, _votingDelegates); - - _moveDelegatesByType( - votingFromDelegatee, - votingToDelegatee, - amount, - DelegationType.VOTING_POWER - ); - - address propPowerFromDelegatee = _getDelegatee(from, _propositionPowerDelegates); - address propPowerToDelegatee = _getDelegatee(to, _propositionPowerDelegates); - - _moveDelegatesByType( - propPowerFromDelegatee, - propPowerToDelegatee, - amount, - DelegationType.PROPOSITION_POWER - ); - - // caching the aave governance address to avoid multiple state loads - ITransferHook aaveGovernance = _aaveGovernance; - if (aaveGovernance != ITransferHook(0)) { - aaveGovernance.onTransfer(from, to, amount); - } - } - - function _getDelegationDataByType(DelegationType delegationType) - internal - override - view - returns ( - mapping(address => mapping(uint256 => Snapshot)) storage, //snapshots - mapping(address => uint256) storage, //snapshots count - mapping(address => address) storage //delegatees list - ) - { - if (delegationType == DelegationType.VOTING_POWER) { - return (_votingSnapshots, _votingSnapshotsCounts, _votingDelegates); - } else { - return ( - _propositionPowerSnapshots, - _propositionPowerSnapshotsCounts, - _propositionPowerDelegates - ); - } - } - - /** - * @dev Delegates power from signatory to `delegatee` - * @param delegatee The address to delegate votes to - * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) - * @param nonce The contract state required to match the signature - * @param expiry The time at which to expire the signature - * @param v The recovery byte of the signature - * @param r Half of the ECDSA signature pair - * @param s Half of the ECDSA signature pair - */ - function delegateByTypeBySig( - address delegatee, - DelegationType delegationType, - uint256 nonce, - uint256 expiry, - uint8 v, - bytes32 r, - bytes32 s - ) public { - bytes32 structHash = keccak256( - abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) - ); - bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash)); - address signatory = ecrecover(digest, v, r, s); - require(signatory != address(0), 'INVALID_SIGNATURE'); - require(nonce == _nonces[signatory]++, 'INVALID_NONCE'); - require(block.timestamp <= expiry, 'INVALID_EXPIRATION'); - _delegateByType(signatory, delegatee, delegationType); - } - - /** - * @dev Delegates power from signatory to `delegatee` - * @param delegatee The address to delegate votes to - * @param nonce The contract state required to match the signature - * @param expiry The time at which to expire the signature - * @param v The recovery byte of the signature - * @param r Half of the ECDSA signature pair - * @param s Half of the ECDSA signature pair - */ - function delegateBySig( - address delegatee, - uint256 nonce, - uint256 expiry, - uint8 v, - bytes32 r, - bytes32 s - ) public { - bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); - bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash)); - address signatory = ecrecover(digest, v, r, s); - require(signatory != address(0), 'INVALID_SIGNATURE'); - require(nonce == _nonces[signatory]++, 'INVALID_NONCE'); - require(block.timestamp <= expiry, 'INVALID_EXPIRATION'); - _delegateByType(signatory, delegatee, DelegationType.VOTING_POWER); - _delegateByType(signatory, delegatee, DelegationType.PROPOSITION_POWER); - } -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/LendToAaveMigrator.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/LendToAaveMigrator.sol deleted file mode 100644 index 784e7e80..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/LendToAaveMigrator.sol +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -import {IERC20} from "../interfaces/IERC20.sol"; -import {SafeMath} from "../open-zeppelin/SafeMath.sol"; -import {VersionedInitializable} from "../utils/VersionedInitializable.sol"; - - -/** -* @title LendToAaveMigrator -* @notice This contract implements the migration from LEND to AAVE token -* @author Aave -*/ -contract LendToAaveMigrator is VersionedInitializable { - using SafeMath for uint256; - - IERC20 public immutable AAVE; - IERC20 public immutable LEND; - uint256 public immutable LEND_AAVE_RATIO; - uint256 public constant REVISION = 1; - - uint256 public _totalLendMigrated; - - /** - * @dev emitted on migration - * @param sender the caller of the migration - * @param amount the amount being migrated - */ - event LendMigrated(address indexed sender, uint256 indexed amount); - - /** - * @param aave the address of the AAVE token - * @param lend the address of the LEND token - * @param lendAaveRatio the exchange rate between LEND and AAVE - */ - constructor(IERC20 aave, IERC20 lend, uint256 lendAaveRatio) public { - AAVE = aave; - LEND = lend; - LEND_AAVE_RATIO = lendAaveRatio; - } - - /** - * @dev initializes the implementation - */ - function initialize() public initializer { - } - - /** - * @dev returns true if the migration started - */ - function migrationStarted() external view returns(bool) { - return lastInitializedRevision != 0; - } - - - /** - * @dev executes the migration from LEND to AAVE. Users need to give allowance to this contract to transfer LEND before executing - * this transaction. - * @param amount the amount of LEND to be migrated - */ - function migrateFromLEND(uint256 amount) external { - require(lastInitializedRevision != 0, "MIGRATION_NOT_STARTED"); - - _totalLendMigrated = _totalLendMigrated.add(amount); - LEND.transferFrom(msg.sender, address(this), amount); - AAVE.transfer(msg.sender, amount.div(LEND_AAVE_RATIO)); - emit LendMigrated(msg.sender, amount); - } - - /** - * @dev returns the implementation revision - * @return the implementation revision - */ - function getRevision() internal pure override returns (uint256) { - return REVISION; - } - -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/base/GovernancePowerDelegationERC20.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/base/GovernancePowerDelegationERC20.sol deleted file mode 100644 index 7deac8e3..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/token/base/GovernancePowerDelegationERC20.sol +++ /dev/null @@ -1,313 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -import {SafeMath} from '../../open-zeppelin/SafeMath.sol'; -import {ERC20} from '../../open-zeppelin/ERC20.sol'; -import { - IGovernancePowerDelegationToken -} from '../../interfaces/IGovernancePowerDelegationToken.sol'; - -/** - * @notice implementation of the AAVE token contract - * @author Aave - */ -abstract contract GovernancePowerDelegationERC20 is ERC20, IGovernancePowerDelegationToken { - using SafeMath for uint256; - /// @notice The EIP-712 typehash for the delegation struct used by the contract - bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( - 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' - ); - - bytes32 public constant DELEGATE_TYPEHASH = keccak256( - 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' - ); - - /// @dev snapshot of a value on a specific block, used for votes - struct Snapshot { - uint128 blockNumber; - uint128 value; - } - - /** - * @dev delegates one specific power to a delegatee - * @param delegatee the user which delegated power has changed - * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) - **/ - function delegateByType(address delegatee, DelegationType delegationType) external override { - _delegateByType(msg.sender, delegatee, delegationType); - } - - /** - * @dev delegates all the powers to a specific user - * @param delegatee the user to which the power will be delegated - **/ - function delegate(address delegatee) external override { - _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); - _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); - } - - /** - * @dev returns the delegatee of an user - * @param delegator the address of the delegator - **/ - function getDelegateeByType(address delegator, DelegationType delegationType) - external - override - view - returns (address) - { - (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); - - return _getDelegatee(delegator, delegates); - } - - /** - * @dev returns the current delegated power of a user. The current power is the - * power delegated at the time of the last snapshot - * @param user the user - **/ - function getPowerCurrent(address user, DelegationType delegationType) - external - override - view - returns (uint256) - { - ( - mapping(address => mapping(uint256 => Snapshot)) storage snapshots, - mapping(address => uint256) storage snapshotsCounts, - - ) = _getDelegationDataByType(delegationType); - - return _searchByBlockNumber(snapshots, snapshotsCounts, user, block.number); - } - - /** - * @dev returns the delegated power of a user at a certain block - * @param user the user - **/ - function getPowerAtBlock( - address user, - uint256 blockNumber, - DelegationType delegationType - ) external override view returns (uint256) { - ( - mapping(address => mapping(uint256 => Snapshot)) storage snapshots, - mapping(address => uint256) storage snapshotsCounts, - - ) = _getDelegationDataByType(delegationType); - - return _searchByBlockNumber(snapshots, snapshotsCounts, user, blockNumber); - } - - /** - * @dev returns the total supply at a certain block number - * used by the voting strategy contracts to calculate the total votes needed for threshold/quorum - * In this initial implementation with no AAVE minting, simply returns the current supply - * A snapshots mapping will need to be added in case a mint function is added to the AAVE token in the future - **/ - function totalSupplyAt(uint256 blockNumber) external override view returns (uint256) { - return super.totalSupply(); - } - - /** - * @dev delegates the specific power to a delegatee - * @param delegatee the user which delegated power has changed - * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) - **/ - function _delegateByType( - address delegator, - address delegatee, - DelegationType delegationType - ) internal { - require(delegatee != address(0), 'INVALID_DELEGATEE'); - - (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); - - uint256 delegatorBalance = balanceOf(delegator); - - address previousDelegatee = _getDelegatee(delegator, delegates); - - delegates[delegator] = delegatee; - - _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); - emit DelegateChanged(delegator, delegatee, delegationType); - } - - /** - * @dev moves delegated power from one user to another - * @param from the user from which delegated power is moved - * @param to the user that will receive the delegated power - * @param amount the amount of delegated power to be moved - * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) - **/ - function _moveDelegatesByType( - address from, - address to, - uint256 amount, - DelegationType delegationType - ) internal { - if (from == to) { - return; - } - - ( - mapping(address => mapping(uint256 => Snapshot)) storage snapshots, - mapping(address => uint256) storage snapshotsCounts, - - ) = _getDelegationDataByType(delegationType); - - if (from != address(0)) { - uint256 previous = 0; - uint256 fromSnapshotsCount = snapshotsCounts[from]; - - if (fromSnapshotsCount != 0) { - previous = snapshots[from][fromSnapshotsCount - 1].value; - } else { - previous = balanceOf(from); - } - - _writeSnapshot( - snapshots, - snapshotsCounts, - from, - uint128(previous), - uint128(previous.sub(amount)) - ); - - emit DelegatedPowerChanged(from, previous.sub(amount), delegationType); - } - if (to != address(0)) { - uint256 previous = 0; - uint256 toSnapshotsCount = snapshotsCounts[to]; - if (toSnapshotsCount != 0) { - previous = snapshots[to][toSnapshotsCount - 1].value; - } else { - previous = balanceOf(to); - } - - _writeSnapshot( - snapshots, - snapshotsCounts, - to, - uint128(previous), - uint128(previous.add(amount)) - ); - - emit DelegatedPowerChanged(to, previous.add(amount), delegationType); - } - } - - /** - * @dev searches a snapshot by block number. Uses binary search. - * @param snapshots the snapshots mapping - * @param snapshotsCounts the number of snapshots - * @param user the user for which the snapshot is being searched - * @param blockNumber the block number being searched - **/ - function _searchByBlockNumber( - mapping(address => mapping(uint256 => Snapshot)) storage snapshots, - mapping(address => uint256) storage snapshotsCounts, - address user, - uint256 blockNumber - ) internal view returns (uint256) { - require(blockNumber <= block.number, 'INVALID_BLOCK_NUMBER'); - - uint256 snapshotsCount = snapshotsCounts[user]; - - if (snapshotsCount == 0) { - return balanceOf(user); - } - - // First check most recent balance - if (snapshots[user][snapshotsCount - 1].blockNumber <= blockNumber) { - return snapshots[user][snapshotsCount - 1].value; - } - - // Next check implicit zero balance - if (snapshots[user][0].blockNumber > blockNumber) { - return 0; - } - - uint256 lower = 0; - uint256 upper = snapshotsCount - 1; - while (upper > lower) { - uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow - Snapshot memory snapshot = snapshots[user][center]; - if (snapshot.blockNumber == blockNumber) { - return snapshot.value; - } else if (snapshot.blockNumber < blockNumber) { - lower = center; - } else { - upper = center - 1; - } - } - return snapshots[user][lower].value; - } - - /** - * @dev returns the delegation data (snapshot, snapshotsCount, list of delegates) by delegation type - * NOTE: Ideal implementation would have mapped this in a struct by delegation type. Unfortunately, - * the AAVE token and StakeToken already include a mapping for the snapshots, so we require contracts - * who inherit from this to provide access to the delegation data by overriding this method. - * @param delegationType the type of delegation - **/ - function _getDelegationDataByType(DelegationType delegationType) - internal - virtual - view - returns ( - mapping(address => mapping(uint256 => Snapshot)) storage, //snapshots - mapping(address => uint256) storage, //snapshots count - mapping(address => address) storage //delegatees list - ); - - /** - * @dev Writes a snapshot for an owner of tokens - * @param owner The owner of the tokens - * @param oldValue The value before the operation that is gonna be executed after the snapshot - * @param newValue The value after the operation - */ - function _writeSnapshot( - mapping(address => mapping(uint256 => Snapshot)) storage snapshots, - mapping(address => uint256) storage snapshotsCounts, - address owner, - uint128 oldValue, - uint128 newValue - ) internal { - uint128 currentBlock = uint128(block.number); - - uint256 ownerSnapshotsCount = snapshotsCounts[owner]; - mapping(uint256 => Snapshot) storage snapshotsOwner = snapshots[owner]; - - // Doing multiple operations in the same block - if ( - ownerSnapshotsCount != 0 && - snapshotsOwner[ownerSnapshotsCount - 1].blockNumber == currentBlock - ) { - snapshotsOwner[ownerSnapshotsCount - 1].value = newValue; - } else { - snapshotsOwner[ownerSnapshotsCount] = Snapshot(currentBlock, newValue); - snapshotsCounts[owner] = ownerSnapshotsCount + 1; - } - } - - /** - * @dev returns the user delegatee. If a user never performed any delegation, - * his delegated address will be 0x0. In that case we simply return the user itself - * @param delegator the address of the user for which return the delegatee - * @param delegates the array of delegates for a particular type of delegation - **/ - function _getDelegatee(address delegator, mapping(address => address) storage delegates) - internal - view - returns (address) - { - address previousDelegatee = delegates[delegator]; - - if (previousDelegatee == address(0)) { - return delegator; - } - - return previousDelegatee; - } -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/DoubleTransferHelper.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/DoubleTransferHelper.sol deleted file mode 100644 index 309393ce..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/DoubleTransferHelper.sol +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -import "../interfaces/IERC20.sol"; - -contract DoubleTransferHelper { - - IERC20 public immutable AAVE; - - constructor(IERC20 aave) public { - AAVE = aave; - } - - function doubleSend(address to, uint256 amount1, uint256 amount2) external { - AAVE.transfer(to, amount1); - AAVE.transfer(to, amount2); - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/MintableErc20.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/MintableErc20.sol deleted file mode 100644 index 23c6e4f4..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/MintableErc20.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -import "../open-zeppelin/ERC20.sol"; - -/** - * @title ERC20Mintable - * @dev ERC20 minting logic - */ -contract MintableErc20 is ERC20 { - constructor(string memory name, string memory symbol, uint8 decimals) ERC20(name, symbol) public { - _setupDecimals(decimals); - } - /** - * @dev Function to mint tokens - * @param value The amount of tokens to mint. - * @return A boolean that indicates if the operation was successful. - */ - function mint(uint256 value) public returns (bool) { - _mint(msg.sender, value); - return true; - } -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/MockTransferHook.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/MockTransferHook.sol deleted file mode 100644 index b91c8e4f..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/MockTransferHook.sol +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -import {ITransferHook} from "../interfaces/ITransferHook.sol"; - -contract MockTransferHook is ITransferHook { - event MockHookEvent(); - - function onTransfer(address from, address to, uint256 amount) external override { - emit MockHookEvent(); - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/VersionedInitializable.sol b/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/VersionedInitializable.sol deleted file mode 100644 index c1f54761..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/contracts/utils/VersionedInitializable.sol +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity 0.7.5; - -/** - * @title VersionedInitializable - * - * @dev Helper contract to support initializer functions. To use it, replace - * the constructor with a function that has the `initializer` modifier. - * WARNING: Unlike constructors, initializer functions must be manually - * invoked. This applies both to deploying an Initializable contract, as well - * as extending an Initializable contract via inheritance. - * WARNING: When used with inheritance, manual care must be taken to not invoke - * a parent initializer twice, or ensure that all initializers are idempotent, - * because this is not dealt with automatically as with constructors. - * - * @author Aave, inspired by the OpenZeppelin Initializable contract - */ -abstract contract VersionedInitializable { - /** - * @dev Indicates that the contract has been initialized. - */ - uint256 internal lastInitializedRevision = 0; - - /** - * @dev Modifier to use in the initializer function of a contract. - */ - modifier initializer() { - uint256 revision = getRevision(); - require(revision > lastInitializedRevision, "Contract instance has already been initialized"); - - lastInitializedRevision = revision; - - _; - - } - - /// @dev returns the revision number of the contract. - /// Needs to be defined in the inherited class as a constant. - function getRevision() internal pure virtual returns(uint256); - - - // Reserved storage space to allow for layout changes in the future. - uint256[50] private ______gap; -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/coverage.json b/CVLByExample/aave-token-v3/lib/aave-token-v2/coverage.json deleted file mode 100644 index 0acd72ab..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/coverage.json +++ /dev/null @@ -1 +0,0 @@ -{"contracts/interfaces/IERC20.sol":{"l":{},"path":"/home/kartojal/aave/aave-token/contracts/interfaces/IERC20.sol","s":{},"b":{},"f":{},"fnMap":{},"statementMap":{},"branchMap":{}},"contracts/interfaces/IERC20Detailed.sol":{"l":{},"path":"/home/kartojal/aave/aave-token/contracts/interfaces/IERC20Detailed.sol","s":{},"b":{},"f":{},"fnMap":{},"statementMap":{},"branchMap":{}},"contracts/interfaces/IGovernancePowerDelegationToken.sol":{"l":{},"path":"/home/kartojal/aave/aave-token/contracts/interfaces/IGovernancePowerDelegationToken.sol","s":{},"b":{},"f":{},"fnMap":{},"statementMap":{},"branchMap":{}},"contracts/interfaces/ITransferHook.sol":{"l":{},"path":"/home/kartojal/aave/aave-token/contracts/interfaces/ITransferHook.sol","s":{},"b":{},"f":{},"fnMap":{},"statementMap":{},"branchMap":{}},"contracts/token/AaveToken.sol":{"l":{"65":1,"68":1,"72":1,"79":1,"80":1,"81":1,"82":1,"83":1,"84":1,"107":7,"109":6,"110":4,"111":4,"120":4,"121":2,"122":2,"129":1,"139":16,"141":16,"142":16,"145":16,"146":2,"148":14,"149":14,"152":16,"165":10,"166":1,"169":9,"170":7,"171":7,"173":9,"174":9,"175":9,"179":9,"180":9,"181":9},"path":"/home/kartojal/aave/aave-token/contracts/token/AaveToken.sol","s":{"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":7,"10":6,"11":4,"12":4,"13":4,"14":2,"15":2,"16":1,"17":16,"18":16,"19":16,"20":16,"21":2,"22":14,"23":14,"24":16,"25":10,"26":1,"27":9,"28":7,"29":7,"30":9,"31":9,"32":9,"33":9,"34":9,"35":9},"b":{"1":[6,1],"2":[4,2],"3":[2,2],"4":[2,14],"5":[1,9],"6":[7,2],"7":[9,0],"8":[9,0]},"f":{"1":3,"2":1,"3":7,"4":1,"5":16,"6":10},"fnMap":{"1":{"name":"constructor","line":52,"loc":{"start":{"line":52,"column":4},"end":{"line":52,"column":46}}},"2":{"name":"initialize","line":63,"loc":{"start":{"line":59,"column":4},"end":{"line":85,"column":4}}},"3":{"name":"permit","line":98,"loc":{"start":{"line":98,"column":4},"end":{"line":123,"column":4}}},"4":{"name":"getRevision","line":128,"loc":{"start":{"line":128,"column":4},"end":{"line":130,"column":4}}},"5":{"name":"_writeSnapshot","line":138,"loc":{"start":{"line":138,"column":4},"end":{"line":153,"column":4}}},"6":{"name":"_beforeTokenTransfer","line":164,"loc":{"start":{"line":164,"column":4},"end":{"line":183,"column":4}}}},"statementMap":{"1":{"start":{"line":65,"column":8},"end":{"line":65,"column":23}},"2":{"start":{"line":72,"column":8},"end":{"line":72,"column":2610}},"3":{"start":{"line":79,"column":8},"end":{"line":79,"column":19}},"4":{"start":{"line":80,"column":8},"end":{"line":80,"column":23}},"5":{"start":{"line":81,"column":8},"end":{"line":81,"column":31}},"6":{"start":{"line":82,"column":8},"end":{"line":82,"column":39}},"7":{"start":{"line":83,"column":8},"end":{"line":83,"column":40}},"8":{"start":{"line":84,"column":8},"end":{"line":84,"column":46}},"9":{"start":{"line":107,"column":8},"end":{"line":107,"column":52}},"10":{"start":{"line":109,"column":8},"end":{"line":109,"column":65}},"11":{"start":{"line":110,"column":8},"end":{"line":110,"column":50}},"12":{"start":{"line":111,"column":8},"end":{"line":111,"column":3882}},"13":{"start":{"line":120,"column":8},"end":{"line":120,"column":72}},"14":{"start":{"line":121,"column":8},"end":{"line":121,"column":48}},"15":{"start":{"line":122,"column":8},"end":{"line":122,"column":38}},"16":{"start":{"line":129,"column":8},"end":{"line":129,"column":23}},"17":{"start":{"line":139,"column":8},"end":{"line":139,"column":52}},"18":{"start":{"line":141,"column":8},"end":{"line":141,"column":63}},"19":{"start":{"line":142,"column":8},"end":{"line":142,"column":80}},"20":{"start":{"line":145,"column":8},"end":{"line":145,"column":5153}},"21":{"start":{"line":146,"column":12},"end":{"line":146,"column":72}},"22":{"start":{"line":148,"column":12},"end":{"line":148,"column":83}},"23":{"start":{"line":149,"column":12},"end":{"line":149,"column":65}},"24":{"start":{"line":152,"column":8},"end":{"line":152,"column":52}},"25":{"start":{"line":165,"column":8},"end":{"line":165,"column":6046}},"26":{"start":{"line":166,"column":12},"end":{"line":166,"column":18}},"27":{"start":{"line":169,"column":8},"end":{"line":169,"column":6103}},"28":{"start":{"line":170,"column":12},"end":{"line":170,"column":49}},"29":{"start":{"line":171,"column":12},"end":{"line":171,"column":87}},"30":{"start":{"line":173,"column":8},"end":{"line":173,"column":6288}},"31":{"start":{"line":174,"column":12},"end":{"line":174,"column":45}},"32":{"start":{"line":175,"column":12},"end":{"line":175,"column":81}},"33":{"start":{"line":179,"column":8},"end":{"line":179,"column":54}},"34":{"start":{"line":180,"column":8},"end":{"line":180,"column":6595}},"35":{"start":{"line":181,"column":12},"end":{"line":181,"column":54}}},"branchMap":{"1":{"line":107,"type":"if","locations":[{"start":{"line":107,"column":8},"end":{"line":107,"column":8}},{"start":{"line":107,"column":8},"end":{"line":107,"column":8}}]},"2":{"line":109,"type":"if","locations":[{"start":{"line":109,"column":8},"end":{"line":109,"column":8}},{"start":{"line":109,"column":8},"end":{"line":109,"column":8}}]},"3":{"line":120,"type":"if","locations":[{"start":{"line":120,"column":8},"end":{"line":120,"column":8}},{"start":{"line":120,"column":8},"end":{"line":120,"column":8}}]},"4":{"line":145,"type":"if","locations":[{"start":{"line":145,"column":8},"end":{"line":145,"column":8}},{"start":{"line":145,"column":8},"end":{"line":145,"column":8}}]},"5":{"line":165,"type":"if","locations":[{"start":{"line":165,"column":8},"end":{"line":165,"column":8}},{"start":{"line":165,"column":8},"end":{"line":165,"column":8}}]},"6":{"line":169,"type":"if","locations":[{"start":{"line":169,"column":8},"end":{"line":169,"column":8}},{"start":{"line":169,"column":8},"end":{"line":169,"column":8}}]},"7":{"line":173,"type":"if","locations":[{"start":{"line":173,"column":8},"end":{"line":173,"column":8}},{"start":{"line":173,"column":8},"end":{"line":173,"column":8}}]},"8":{"line":180,"type":"if","locations":[{"start":{"line":180,"column":8},"end":{"line":180,"column":8}},{"start":{"line":180,"column":8},"end":{"line":180,"column":8}}]}}},"contracts/token/AaveTokenV2.sol":{"l":{"77":7,"79":6,"80":4,"81":4,"89":4,"90":2,"91":2,"98":2,"118":8,"119":8,"121":8,"122":6,"124":8,"125":4,"128":8,"130":8,"131":8,"133":8,"134":6,"136":8,"137":4,"140":8,"143":8,"144":8,"145":8,"159":121,"160":65,"162":56,"189":5,"190":5,"191":5,"192":5,"193":4,"194":3,"195":2,"215":4,"216":4,"217":4,"218":4,"219":3,"220":2,"221":1,"222":1},"path":"/home/kartojal/aave/aave-token/contracts/token/AaveTokenV2.sol","s":{"1":7,"2":6,"3":4,"4":4,"5":4,"6":2,"7":2,"8":2,"9":8,"10":8,"11":8,"12":6,"13":8,"14":4,"15":8,"16":8,"17":8,"18":8,"19":6,"20":8,"21":4,"22":8,"23":8,"24":8,"25":8,"26":121,"27":65,"28":56,"29":5,"30":5,"31":5,"32":5,"33":4,"34":3,"35":2,"36":4,"37":4,"38":4,"39":4,"40":3,"41":2,"42":1,"43":1},"b":{"1":[6,1],"2":[4,2],"3":[2,2],"4":[6,2],"5":[4,4],"6":[6,2],"7":[4,4],"8":[8,0],"9":[65,56],"10":[4,1],"11":[3,1],"12":[2,1],"13":[3,1],"14":[2,1],"15":[1,1]},"f":{"1":6,"2":2,"3":7,"4":2,"5":8,"6":121,"7":5,"8":4},"fnMap":{"1":{"name":"constructor","line":50,"loc":{"start":{"line":50,"column":2},"end":{"line":50,"column":44}}},"2":{"name":"initialize","line":55,"loc":{"start":{"line":55,"column":2},"end":{"line":55,"column":46}}},"3":{"name":"permit","line":68,"loc":{"start":{"line":68,"column":2},"end":{"line":92,"column":2}}},"4":{"name":"getRevision","line":97,"loc":{"start":{"line":97,"column":2},"end":{"line":99,"column":2}}},"5":{"name":"_beforeTokenTransfer","line":112,"loc":{"start":{"line":112,"column":2},"end":{"line":147,"column":2}}},"6":{"name":"_getDelegationDataByType","line":149,"loc":{"start":{"line":149,"column":2},"end":{"line":168,"column":2}}},"7":{"name":"delegateBySig","line":180,"loc":{"start":{"line":180,"column":2},"end":{"line":196,"column":2}}},"8":{"name":"delegateAllBySig","line":207,"loc":{"start":{"line":207,"column":2},"end":{"line":223,"column":2}}}},"statementMap":{"1":{"start":{"line":77,"column":4},"end":{"line":77,"column":48}},"2":{"start":{"line":79,"column":4},"end":{"line":79,"column":61}},"3":{"start":{"line":80,"column":4},"end":{"line":80,"column":46}},"4":{"start":{"line":81,"column":4},"end":{"line":81,"column":2911}},"5":{"start":{"line":89,"column":4},"end":{"line":89,"column":68}},"6":{"start":{"line":90,"column":4},"end":{"line":90,"column":44}},"7":{"start":{"line":91,"column":4},"end":{"line":91,"column":34}},"8":{"start":{"line":98,"column":4},"end":{"line":98,"column":19}},"9":{"start":{"line":118,"column":4},"end":{"line":118,"column":56}},"10":{"start":{"line":119,"column":4},"end":{"line":119,"column":52}},"11":{"start":{"line":121,"column":4},"end":{"line":121,"column":4034}},"12":{"start":{"line":122,"column":6},"end":{"line":122,"column":31}},"13":{"start":{"line":124,"column":4},"end":{"line":124,"column":4117}},"14":{"start":{"line":125,"column":6},"end":{"line":125,"column":27}},"15":{"start":{"line":128,"column":4},"end":{"line":128,"column":94}},"16":{"start":{"line":130,"column":4},"end":{"line":130,"column":69}},"17":{"start":{"line":131,"column":4},"end":{"line":131,"column":65}},"18":{"start":{"line":133,"column":4},"end":{"line":133,"column":4433}},"19":{"start":{"line":134,"column":6},"end":{"line":134,"column":34}},"20":{"start":{"line":136,"column":4},"end":{"line":136,"column":4522}},"21":{"start":{"line":137,"column":6},"end":{"line":137,"column":30}},"22":{"start":{"line":140,"column":4},"end":{"line":140,"column":105}},"23":{"start":{"line":143,"column":4},"end":{"line":143,"column":50}},"24":{"start":{"line":144,"column":4},"end":{"line":144,"column":4840}},"25":{"start":{"line":145,"column":6},"end":{"line":145,"column":48}},"26":{"start":{"line":159,"column":4},"end":{"line":159,"column":5271}},"27":{"start":{"line":160,"column":6},"end":{"line":160,"column":73}},"28":{"start":{"line":162,"column":6},"end":{"line":162,"column":5421}},"29":{"start":{"line":189,"column":4},"end":{"line":189,"column":116}},"30":{"start":{"line":190,"column":4},"end":{"line":190,"column":90}},"31":{"start":{"line":191,"column":4},"end":{"line":191,"column":50}},"32":{"start":{"line":192,"column":4},"end":{"line":192,"column":56}},"33":{"start":{"line":193,"column":4},"end":{"line":193,"column":58}},"34":{"start":{"line":194,"column":4},"end":{"line":194,"column":47}},"35":{"start":{"line":195,"column":4},"end":{"line":195,"column":50}},"36":{"start":{"line":215,"column":4},"end":{"line":215,"column":94}},"37":{"start":{"line":216,"column":4},"end":{"line":216,"column":90}},"38":{"start":{"line":217,"column":4},"end":{"line":217,"column":50}},"39":{"start":{"line":218,"column":4},"end":{"line":218,"column":56}},"40":{"start":{"line":219,"column":4},"end":{"line":219,"column":58}},"41":{"start":{"line":220,"column":4},"end":{"line":220,"column":47}},"42":{"start":{"line":221,"column":4},"end":{"line":221,"column":63}},"43":{"start":{"line":222,"column":4},"end":{"line":222,"column":68}}},"branchMap":{"1":{"line":77,"type":"if","locations":[{"start":{"line":77,"column":4},"end":{"line":77,"column":4}},{"start":{"line":77,"column":4},"end":{"line":77,"column":4}}]},"2":{"line":79,"type":"if","locations":[{"start":{"line":79,"column":4},"end":{"line":79,"column":4}},{"start":{"line":79,"column":4},"end":{"line":79,"column":4}}]},"3":{"line":89,"type":"if","locations":[{"start":{"line":89,"column":4},"end":{"line":89,"column":4}},{"start":{"line":89,"column":4},"end":{"line":89,"column":4}}]},"4":{"line":121,"type":"if","locations":[{"start":{"line":121,"column":4},"end":{"line":121,"column":4}},{"start":{"line":121,"column":4},"end":{"line":121,"column":4}}]},"5":{"line":124,"type":"if","locations":[{"start":{"line":124,"column":4},"end":{"line":124,"column":4}},{"start":{"line":124,"column":4},"end":{"line":124,"column":4}}]},"6":{"line":133,"type":"if","locations":[{"start":{"line":133,"column":4},"end":{"line":133,"column":4}},{"start":{"line":133,"column":4},"end":{"line":133,"column":4}}]},"7":{"line":136,"type":"if","locations":[{"start":{"line":136,"column":4},"end":{"line":136,"column":4}},{"start":{"line":136,"column":4},"end":{"line":136,"column":4}}]},"8":{"line":144,"type":"if","locations":[{"start":{"line":144,"column":4},"end":{"line":144,"column":4}},{"start":{"line":144,"column":4},"end":{"line":144,"column":4}}]},"9":{"line":159,"type":"if","locations":[{"start":{"line":159,"column":4},"end":{"line":159,"column":4}},{"start":{"line":159,"column":4},"end":{"line":159,"column":4}}]},"10":{"line":192,"type":"if","locations":[{"start":{"line":192,"column":4},"end":{"line":192,"column":4}},{"start":{"line":192,"column":4},"end":{"line":192,"column":4}}]},"11":{"line":193,"type":"if","locations":[{"start":{"line":193,"column":4},"end":{"line":193,"column":4}},{"start":{"line":193,"column":4},"end":{"line":193,"column":4}}]},"12":{"line":194,"type":"if","locations":[{"start":{"line":194,"column":4},"end":{"line":194,"column":4}},{"start":{"line":194,"column":4},"end":{"line":194,"column":4}}]},"13":{"line":218,"type":"if","locations":[{"start":{"line":218,"column":4},"end":{"line":218,"column":4}},{"start":{"line":218,"column":4},"end":{"line":218,"column":4}}]},"14":{"line":219,"type":"if","locations":[{"start":{"line":219,"column":4},"end":{"line":219,"column":4}},{"start":{"line":219,"column":4},"end":{"line":219,"column":4}}]},"15":{"line":220,"type":"if","locations":[{"start":{"line":220,"column":4},"end":{"line":220,"column":4}},{"start":{"line":220,"column":4},"end":{"line":220,"column":4}}]}}},"contracts/token/base/GovernancePowerDelegationERC20.sol":{"l":{"35":5,"43":5,"44":5,"57":11,"59":11,"73":44,"79":44,"91":16,"97":16,"99":16,"112":19,"114":19,"116":19,"118":19,"119":6,"122":19,"124":19,"125":19,"141":35,"142":4,"145":31,"151":31,"152":31,"153":31,"155":31,"156":28,"158":3,"161":31,"169":31,"171":31,"172":30,"173":30,"174":30,"175":20,"177":10,"180":30,"188":30,"205":60,"207":58,"209":58,"210":6,"214":52,"215":42,"219":10,"220":2,"223":8,"224":8,"225":8,"226":15,"227":15,"228":15,"229":3,"231":5,"233":7,"236":5,"269":61,"271":61,"272":61,"275":61,"279":4,"281":57,"282":57,"293":1},"path":"/home/kartojal/aave/aave-token/contracts/token/base/GovernancePowerDelegationERC20.sol","s":{"1":5,"2":5,"3":5,"4":11,"5":11,"6":44,"7":44,"8":16,"9":16,"10":16,"11":19,"12":19,"13":19,"14":19,"15":6,"16":19,"17":19,"18":19,"19":35,"20":4,"21":31,"22":31,"23":31,"24":31,"25":31,"26":28,"27":3,"28":31,"29":31,"30":31,"31":30,"32":30,"33":30,"34":20,"35":10,"36":30,"37":30,"38":60,"39":58,"40":58,"41":6,"42":52,"43":42,"44":10,"45":2,"46":8,"47":8,"48":8,"49":15,"50":15,"51":15,"52":3,"53":12,"54":5,"55":7,"56":5,"57":61,"58":61,"59":61,"60":61,"61":4,"62":57,"63":57,"64":1},"b":{"1":[6,13],"2":[4,31],"3":[31,0],"4":[28,3],"5":[30,1],"6":[20,10],"7":[58,2],"8":[6,52],"9":[42,10],"10":[2,8],"11":[3,12],"12":[5,7],"13":[4,57]},"f":{"1":5,"2":5,"3":11,"4":44,"5":16,"6":19,"7":35,"8":60,"9":61,"10":1},"fnMap":{"1":{"name":"delegate","line":34,"loc":{"start":{"line":34,"column":2},"end":{"line":36,"column":2}}},"2":{"name":"delegateAll","line":42,"loc":{"start":{"line":42,"column":2},"end":{"line":45,"column":2}}},"3":{"name":"getDelegatee","line":51,"loc":{"start":{"line":51,"column":2},"end":{"line":60,"column":2}}},"4":{"name":"getPowerCurrent","line":67,"loc":{"start":{"line":67,"column":2},"end":{"line":80,"column":2}}},"5":{"name":"getPowerAtBlock","line":86,"loc":{"start":{"line":86,"column":2},"end":{"line":100,"column":2}}},"6":{"name":"_delegate","line":107,"loc":{"start":{"line":107,"column":2},"end":{"line":126,"column":2}}},"7":{"name":"_moveDelegates","line":135,"loc":{"start":{"line":135,"column":2},"end":{"line":190,"column":2}}},"8":{"name":"_searchByBlockNumber","line":199,"loc":{"start":{"line":199,"column":2},"end":{"line":237,"column":2}}},"9":{"name":"_writeSnapshot","line":262,"loc":{"start":{"line":262,"column":2},"end":{"line":284,"column":2}}},"10":{"name":"totalSupplyAt","line":292,"loc":{"start":{"line":292,"column":2},"end":{"line":294,"column":2}}}},"statementMap":{"1":{"start":{"line":35,"column":4},"end":{"line":35,"column":51}},"2":{"start":{"line":43,"column":4},"end":{"line":43,"column":64}},"3":{"start":{"line":44,"column":4},"end":{"line":44,"column":69}},"4":{"start":{"line":57,"column":4},"end":{"line":57,"column":98}},"5":{"start":{"line":59,"column":4},"end":{"line":59,"column":31}},"6":{"start":{"line":73,"column":4},"end":{"line":73,"column":2329}},"7":{"start":{"line":79,"column":4},"end":{"line":79,"column":79}},"8":{"start":{"line":91,"column":4},"end":{"line":91,"column":2864}},"9":{"start":{"line":97,"column":4},"end":{"line":97,"column":50}},"10":{"start":{"line":99,"column":4},"end":{"line":99,"column":78}},"11":{"start":{"line":112,"column":4},"end":{"line":112,"column":98}},"12":{"start":{"line":114,"column":4},"end":{"line":114,"column":51}},"13":{"start":{"line":116,"column":4},"end":{"line":116,"column":52}},"14":{"start":{"line":118,"column":4},"end":{"line":118,"column":3692}},"15":{"start":{"line":119,"column":6},"end":{"line":119,"column":34}},"16":{"start":{"line":122,"column":4},"end":{"line":122,"column":35}},"17":{"start":{"line":124,"column":4},"end":{"line":124,"column":81}},"18":{"start":{"line":125,"column":4},"end":{"line":125,"column":63}},"19":{"start":{"line":141,"column":4},"end":{"line":141,"column":4441}},"20":{"start":{"line":142,"column":6},"end":{"line":142,"column":12}},"21":{"start":{"line":145,"column":4},"end":{"line":145,"column":4528}},"22":{"start":{"line":151,"column":4},"end":{"line":151,"column":4675}},"23":{"start":{"line":152,"column":6},"end":{"line":152,"column":26}},"24":{"start":{"line":153,"column":6},"end":{"line":153,"column":56}},"25":{"start":{"line":155,"column":6},"end":{"line":155,"column":4796}},"26":{"start":{"line":156,"column":8},"end":{"line":156,"column":69}},"27":{"start":{"line":158,"column":8},"end":{"line":158,"column":33}},"28":{"start":{"line":161,"column":6},"end":{"line":161,"column":4965}},"29":{"start":{"line":169,"column":6},"end":{"line":169,"column":76}},"30":{"start":{"line":171,"column":4},"end":{"line":171,"column":5200}},"31":{"start":{"line":172,"column":6},"end":{"line":172,"column":26}},"32":{"start":{"line":173,"column":6},"end":{"line":173,"column":52}},"33":{"start":{"line":174,"column":6},"end":{"line":174,"column":5314}},"34":{"start":{"line":175,"column":8},"end":{"line":175,"column":65}},"35":{"start":{"line":177,"column":8},"end":{"line":177,"column":31}},"36":{"start":{"line":180,"column":6},"end":{"line":180,"column":5475}},"37":{"start":{"line":188,"column":6},"end":{"line":188,"column":74}},"38":{"start":{"line":205,"column":4},"end":{"line":205,"column":63}},"39":{"start":{"line":207,"column":4},"end":{"line":207,"column":50}},"40":{"start":{"line":209,"column":4},"end":{"line":209,"column":6372}},"41":{"start":{"line":210,"column":6},"end":{"line":210,"column":28}},"42":{"start":{"line":214,"column":4},"end":{"line":214,"column":6479}},"43":{"start":{"line":215,"column":6},"end":{"line":215,"column":54}},"44":{"start":{"line":219,"column":4},"end":{"line":219,"column":6656}},"45":{"start":{"line":220,"column":6},"end":{"line":220,"column":14}},"46":{"start":{"line":223,"column":4},"end":{"line":223,"column":21}},"47":{"start":{"line":224,"column":4},"end":{"line":224,"column":38}},"48":{"start":{"line":225,"column":4},"end":{"line":225,"column":6798}},"49":{"start":{"line":226,"column":6},"end":{"line":226,"column":50}},"50":{"start":{"line":227,"column":6},"end":{"line":227,"column":56}},"51":{"start":{"line":228,"column":6},"end":{"line":228,"column":6967}},"52":{"start":{"line":229,"column":8},"end":{"line":229,"column":29}},"53":{"start":{"line":230,"column":13},"end":{"line":230,"column":7054}},"54":{"start":{"line":231,"column":8},"end":{"line":231,"column":21}},"55":{"start":{"line":233,"column":8},"end":{"line":233,"column":25}},"56":{"start":{"line":236,"column":4},"end":{"line":236,"column":39}},"57":{"start":{"line":269,"column":4},"end":{"line":269,"column":48}},"58":{"start":{"line":271,"column":4},"end":{"line":271,"column":56}},"59":{"start":{"line":272,"column":4},"end":{"line":272,"column":74}},"60":{"start":{"line":275,"column":4},"end":{"line":275,"column":8735}},"61":{"start":{"line":279,"column":6},"end":{"line":279,"column":64}},"62":{"start":{"line":281,"column":6},"end":{"line":281,"column":75}},"63":{"start":{"line":282,"column":6},"end":{"line":282,"column":56}},"64":{"start":{"line":293,"column":4},"end":{"line":293,"column":30}}},"branchMap":{"1":{"line":118,"type":"if","locations":[{"start":{"line":118,"column":4},"end":{"line":118,"column":4}},{"start":{"line":118,"column":4},"end":{"line":118,"column":4}}]},"2":{"line":141,"type":"if","locations":[{"start":{"line":141,"column":4},"end":{"line":141,"column":4}},{"start":{"line":141,"column":4},"end":{"line":141,"column":4}}]},"3":{"line":151,"type":"if","locations":[{"start":{"line":151,"column":4},"end":{"line":151,"column":4}},{"start":{"line":151,"column":4},"end":{"line":151,"column":4}}]},"4":{"line":155,"type":"if","locations":[{"start":{"line":155,"column":6},"end":{"line":155,"column":6}},{"start":{"line":155,"column":6},"end":{"line":155,"column":6}}]},"5":{"line":171,"type":"if","locations":[{"start":{"line":171,"column":4},"end":{"line":171,"column":4}},{"start":{"line":171,"column":4},"end":{"line":171,"column":4}}]},"6":{"line":174,"type":"if","locations":[{"start":{"line":174,"column":6},"end":{"line":174,"column":6}},{"start":{"line":174,"column":6},"end":{"line":174,"column":6}}]},"7":{"line":205,"type":"if","locations":[{"start":{"line":205,"column":4},"end":{"line":205,"column":4}},{"start":{"line":205,"column":4},"end":{"line":205,"column":4}}]},"8":{"line":209,"type":"if","locations":[{"start":{"line":209,"column":4},"end":{"line":209,"column":4}},{"start":{"line":209,"column":4},"end":{"line":209,"column":4}}]},"9":{"line":214,"type":"if","locations":[{"start":{"line":214,"column":4},"end":{"line":214,"column":4}},{"start":{"line":214,"column":4},"end":{"line":214,"column":4}}]},"10":{"line":219,"type":"if","locations":[{"start":{"line":219,"column":4},"end":{"line":219,"column":4}},{"start":{"line":219,"column":4},"end":{"line":219,"column":4}}]},"11":{"line":228,"type":"if","locations":[{"start":{"line":228,"column":6},"end":{"line":228,"column":6}},{"start":{"line":228,"column":6},"end":{"line":228,"column":6}}]},"12":{"line":230,"type":"if","locations":[{"start":{"line":230,"column":13},"end":{"line":230,"column":13}},{"start":{"line":230,"column":13},"end":{"line":230,"column":13}}]},"13":{"line":275,"type":"if","locations":[{"start":{"line":275,"column":4},"end":{"line":275,"column":4}},{"start":{"line":275,"column":4},"end":{"line":275,"column":4}}]}}},"contracts/token/LendToAaveMigrator.sol":{"l":{"37":3,"38":3,"39":3,"52":2,"62":7,"64":6,"65":6,"66":6,"67":6,"75":4},"path":"/home/kartojal/aave/aave-token/contracts/token/LendToAaveMigrator.sol","s":{"1":3,"2":3,"3":3,"4":2,"5":7,"6":6,"7":6,"8":6,"9":6,"10":4},"b":{"1":[6,1]},"f":{"1":3,"2":4,"3":2,"4":7,"5":4},"fnMap":{"1":{"name":"constructor","line":36,"loc":{"start":{"line":36,"column":4},"end":{"line":40,"column":4}}},"2":{"name":"initialize","line":45,"loc":{"start":{"line":45,"column":4},"end":{"line":46,"column":4}}},"3":{"name":"migrationStarted","line":51,"loc":{"start":{"line":51,"column":4},"end":{"line":53,"column":4}}},"4":{"name":"migrateFromLEND","line":61,"loc":{"start":{"line":61,"column":4},"end":{"line":68,"column":4}}},"5":{"name":"getRevision","line":74,"loc":{"start":{"line":74,"column":4},"end":{"line":76,"column":4}}}},"statementMap":{"1":{"start":{"line":37,"column":8},"end":{"line":37,"column":18}},"2":{"start":{"line":38,"column":8},"end":{"line":38,"column":18}},"3":{"start":{"line":39,"column":8},"end":{"line":39,"column":38}},"4":{"start":{"line":52,"column":8},"end":{"line":52,"column":43}},"5":{"start":{"line":62,"column":8},"end":{"line":62,"column":69}},"6":{"start":{"line":64,"column":8},"end":{"line":64,"column":58}},"7":{"start":{"line":65,"column":8},"end":{"line":65,"column":59}},"8":{"start":{"line":66,"column":8},"end":{"line":66,"column":61}},"9":{"start":{"line":67,"column":8},"end":{"line":67,"column":45}},"10":{"start":{"line":75,"column":8},"end":{"line":75,"column":23}}},"branchMap":{"1":{"line":62,"type":"if","locations":[{"start":{"line":62,"column":8},"end":{"line":62,"column":8}},{"start":{"line":62,"column":8},"end":{"line":62,"column":8}}]}}},"contracts/utils/DoubleTransferHelper.sol":{"l":{"11":6,"15":2,"16":2},"path":"/home/kartojal/aave/aave-token/contracts/utils/DoubleTransferHelper.sol","s":{"1":6,"2":2,"3":2},"b":{},"f":{"1":6,"2":2},"fnMap":{"1":{"name":"constructor","line":10,"loc":{"start":{"line":10,"column":4},"end":{"line":12,"column":4}}},"2":{"name":"doubleSend","line":14,"loc":{"start":{"line":14,"column":4},"end":{"line":17,"column":4}}}},"statementMap":{"1":{"start":{"line":11,"column":8},"end":{"line":11,"column":18}},"2":{"start":{"line":15,"column":8},"end":{"line":15,"column":33}},"3":{"start":{"line":16,"column":8},"end":{"line":16,"column":33}}},"branchMap":{}},"contracts/utils/MintableErc20.sol":{"l":{"12":3,"20":6,"21":6},"path":"/home/kartojal/aave/aave-token/contracts/utils/MintableErc20.sol","s":{"1":3,"2":6,"3":6},"b":{},"f":{"1":3,"2":6},"fnMap":{"1":{"name":"constructor","line":11,"loc":{"start":{"line":11,"column":4},"end":{"line":13,"column":4}}},"2":{"name":"mint","line":19,"loc":{"start":{"line":19,"column":4},"end":{"line":22,"column":4}}}},"statementMap":{"1":{"start":{"line":12,"column":8},"end":{"line":12,"column":31}},"2":{"start":{"line":20,"column":8},"end":{"line":20,"column":31}},"3":{"start":{"line":21,"column":8},"end":{"line":21,"column":19}}},"branchMap":{}},"contracts/utils/MockTransferHook.sol":{"l":{"10":17},"path":"/home/kartojal/aave/aave-token/contracts/utils/MockTransferHook.sol","s":{"1":17},"b":{},"f":{"1":17},"fnMap":{"1":{"name":"onTransfer","line":9,"loc":{"start":{"line":9,"column":4},"end":{"line":11,"column":4}}}},"statementMap":{"1":{"start":{"line":10,"column":8},"end":{"line":10,"column":28}}},"branchMap":{}},"contracts/utils/VersionedInitializable.sol":{"l":{"28":7,"29":7,"31":7,"33":7},"path":"/home/kartojal/aave/aave-token/contracts/utils/VersionedInitializable.sol","s":{"1":7,"2":7,"3":7},"b":{"1":[7,0]},"f":{"1":7},"fnMap":{"1":{"name":"initializer","line":27,"loc":{"start":{"line":27,"column":4},"end":{"line":35,"column":4}}}},"statementMap":{"1":{"start":{"line":28,"column":8},"end":{"line":28,"column":40}},"2":{"start":{"line":29,"column":8},"end":{"line":29,"column":100}},"3":{"start":{"line":31,"column":8},"end":{"line":31,"column":41}}},"branchMap":{"1":{"line":29,"type":"if","locations":[{"start":{"line":29,"column":8},"end":{"line":29,"column":8}},{"start":{"line":29,"column":8},"end":{"line":29,"column":8}}]}}}} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/docker-compose.test.yml b/CVLByExample/aave-token-v3/lib/aave-token-v2/docker-compose.test.yml deleted file mode 100644 index b1fbbcd9..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/docker-compose.test.yml +++ /dev/null @@ -1,10 +0,0 @@ -version: '3.5' -services: - contracts-env: - build: - context: ./ - dockerfile: ./Dockerfile_test - args: - GITLAB_ACCESS_TOKEN: ${CI_JOB_TOKEN} - environment: - GITLAB_ACCESS_TOKEN: ${CI_JOB_TOKEN} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/docker-compose.yml b/CVLByExample/aave-token-v3/lib/aave-token-v2/docker-compose.yml deleted file mode 100644 index 43f982bf..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/docker-compose.yml +++ /dev/null @@ -1,17 +0,0 @@ -version: '3.5' - -services: - contracts-env: - env_file: - - .env - build: - context: ./ - working_dir: /src - command: npm run run-env - volumes: - - ./:/src - environment: - MNEMONIC: ${MNEMONIC} - ETHERSCAN_KEY: ${ETHERSCAN_KEY} - INFURA_KEY: ${INFURA_KEY} - ALCHEMY_KEY: ${ALCHEMY_KEY} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/hardhat.config.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/hardhat.config.ts deleted file mode 100644 index 92c518d8..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/hardhat.config.ts +++ /dev/null @@ -1,128 +0,0 @@ -import {eEthereumNetwork} from './helpers/types-common'; -// @ts-ignore -import {accounts} from './test-wallets.js'; -import {BUIDLEREVM_CHAINID, COVERAGE_CHAINID} from './helpers/constants'; -import {HardhatUserConfig} from 'hardhat/config'; - -import 'hardhat-typechain'; -import 'solidity-coverage'; -import '@nomiclabs/hardhat-waffle'; -import '@nomiclabs/hardhat-etherscan'; -import path from 'path'; -import fs from 'fs'; - -const SKIP_LOAD = process.env.SKIP_LOAD === 'true'; - -// Prevent to load scripts before compilation and typechain -if (!SKIP_LOAD) { - ['misc', 'migrations', 'deployments'].forEach((folder) => { - const tasksPath = path.join(__dirname, 'tasks', folder); - fs.readdirSync(tasksPath) - .filter((pth) => pth.includes('.ts')) - .forEach((task) => { - require(`${tasksPath}/${task}`); - }); - }); -} - -const DEFAULT_BLOCK_GAS_LIMIT = 12500000; -const DEFAULT_GAS_PRICE = 50000000000; // 50 gwei -const HARDFORK = 'istanbul'; -const INFURA_KEY = process.env.INFURA_KEY || ''; -const ALCHEMY_KEY = process.env.ALCHEMY_KEY || ''; -const ETHERSCAN_KEY = process.env.ETHERSCAN_KEY || ''; -const MNEMONIC_PATH = "m/44'/60'/0'/0"; -const MNEMONIC = process.env.MNEMONIC || ''; -const MAINNET_FORK = process.env.MAINNET_FORK === 'true'; - -const mainnetFork = MAINNET_FORK - ? { - blockNumber: 11366117, - url: ALCHEMY_KEY - ? `https://eth-mainnet.alchemyapi.io/v2/${ALCHEMY_KEY}` - : `https://main.infura.io/v3/${INFURA_KEY}`, - } - : undefined; - -const getCommonNetworkConfig = (networkName: eEthereumNetwork, networkId: number) => { - return { - url: ALCHEMY_KEY - ? `https://eth-${ - networkName === 'main' ? 'mainnet' : networkName - }.alchemyapi.io/v2/${ALCHEMY_KEY}` - : `https://${networkName}.infura.io/v3/${INFURA_KEY}`, - hardfork: HARDFORK, - blockGasLimit: DEFAULT_BLOCK_GAS_LIMIT, - gasMultiplier: DEFAULT_GAS_PRICE, - chainId: networkId, - accounts: { - mnemonic: MNEMONIC, - path: MNEMONIC_PATH, - initialIndex: 0, - count: 20, - }, - }; -}; - -const config: HardhatUserConfig = { - solidity: { - version: '0.7.5', - settings: { - optimizer: {enabled: true, runs: 200}, - evmVersion: 'istanbul', - }, - }, - typechain: { - outDir: 'types', - }, - etherscan: { - apiKey: ETHERSCAN_KEY, - }, - mocha: { - timeout: 0, - }, - networks: { - kovan: getCommonNetworkConfig(eEthereumNetwork.kovan, 42), - ropsten: getCommonNetworkConfig(eEthereumNetwork.ropsten, 3), - main: getCommonNetworkConfig(eEthereumNetwork.main, 1), - hardhat: { - hardfork: 'istanbul', - blockGasLimit: DEFAULT_BLOCK_GAS_LIMIT, - gas: DEFAULT_BLOCK_GAS_LIMIT, - gasPrice: DEFAULT_GAS_PRICE, - chainId: BUIDLEREVM_CHAINID, - throwOnTransactionFailures: true, - throwOnCallFailures: true, - accounts: accounts.map(({secretKey, balance}: {secretKey: string; balance: string}) => ({ - privateKey: secretKey, - balance, - })), - forking: mainnetFork, - }, - buidlerevm_docker: { - hardfork: 'istanbul', - blockGasLimit: 9500000, - gas: 9500000, - gasPrice: 8000000000, - chainId: BUIDLEREVM_CHAINID, - throwOnTransactionFailures: true, - throwOnCallFailures: true, - url: 'http://localhost:8545', - }, - ganache: { - url: 'http://ganache:8545', - accounts: { - mnemonic: 'fox sight canyon orphan hotel grow hedgehog build bless august weather swarm', - path: "m/44'/60'/0'/0", - initialIndex: 0, - count: 20, - }, - }, - coverage: { - url: 'http://localhost:8555', - chainId: COVERAGE_CHAINID, - }, - }, -}; - -export default config; diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/constants.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/constants.ts deleted file mode 100644 index 6a29fbf8..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/constants.ts +++ /dev/null @@ -1,56 +0,0 @@ -import {tEthereumAddress} from './types'; -import {getParamPerNetwork} from './misc-utils'; -import {eEthereumNetwork} from './types-common'; - -export const BUIDLEREVM_CHAINID = 31337; -export const COVERAGE_CHAINID = 1337; - -export const ZERO_ADDRESS: tEthereumAddress = '0x0000000000000000000000000000000000000000'; -export const ONE_ADDRESS = '0x0000000000000000000000000000000000000001'; -export const MAX_UINT_AMOUNT = - '115792089237316195423570985008687907853269984665640564039457584007913129639935'; -export const MOCK_ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'; -export const WAD = Math.pow(10, 18).toString(); - -export const SUPPORTED_ETHERSCAN_NETWORKS = ['main', 'ropsten', 'kovan']; - -export const getAaveTokenDomainSeparatorPerNetwork = ( - network: eEthereumNetwork -): tEthereumAddress => - getParamPerNetwork( - { - [eEthereumNetwork.coverage]: - '0x6334ce07fc771d21f0634439a587b364f00756c209bb425d2c4873b672e6d265', - [eEthereumNetwork.hardhat]: - '0xd76d40d21133f42fdacea0d02807309902f26a87ff5b55bb55ac77f881143cc4', - [eEthereumNetwork.kovan]: '', - [eEthereumNetwork.ropsten]: '', - [eEthereumNetwork.main]: '', - }, - network - ); - -// AaveProtoGovernance address as admin of AaveToken and Migrator -export const getAaveAdminPerNetwork = (network: eEthereumNetwork): tEthereumAddress => - getParamPerNetwork( - { - [eEthereumNetwork.coverage]: ZERO_ADDRESS, - [eEthereumNetwork.hardhat]: ZERO_ADDRESS, - [eEthereumNetwork.kovan]: '0x8134929c3dcb1b8b82f27f53424b959fb82182f2', - [eEthereumNetwork.ropsten]: '0xEd93e49A2d75beA505fD4D1A0Dff745f69F2E997', - [eEthereumNetwork.main]: '0x8a2Efd9A790199F4c94c6effE210fce0B4724f52', - }, - network - ); - -export const getLendTokenPerNetwork = (network: eEthereumNetwork): tEthereumAddress => - getParamPerNetwork( - { - [eEthereumNetwork.coverage]: ZERO_ADDRESS, - [eEthereumNetwork.hardhat]: ZERO_ADDRESS, - [eEthereumNetwork.kovan]: '0x690eaca024935aaff9b14b9ff9e9c8757a281f3c', - [eEthereumNetwork.ropsten]: '0xb47f338ec1e3857bb188e63569aebab036ee67c6', - [eEthereumNetwork.main]: '0x80fB784B7eD66730e8b1DBd9820aFD29931aab03', - }, - network - ); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/contracts-helpers.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/contracts-helpers.ts deleted file mode 100644 index c3760366..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/contracts-helpers.ts +++ /dev/null @@ -1,371 +0,0 @@ -import {Contract, Signer, utils, ethers} from 'ethers'; - -import {getDb, DRE, waitForTx} from './misc-utils'; -import {tEthereumAddress, eContractid, tStringTokenSmallUnits} from './types'; -import {Artifact} from 'hardhat/types'; -import {MOCK_ETH_ADDRESS, SUPPORTED_ETHERSCAN_NETWORKS} from './constants'; -import BigNumber from 'bignumber.js'; -import {Ierc20Detailed} from '../types/Ierc20Detailed'; -import {InitializableAdminUpgradeabilityProxy} from '../types/InitializableAdminUpgradeabilityProxy'; -import {MintableErc20} from '../types/MintableErc20'; -import {signTypedData_v4, TypedData} from 'eth-sig-util'; -import {fromRpcSig, ECDSASignature} from 'ethereumjs-util'; -import {DoubleTransferHelper} from '../types/DoubleTransferHelper'; -import {MockTransferHook} from '../types/MockTransferHook'; -import {verifyContract} from './etherscan-verification'; -import {AaveToken} from '../types/AaveToken'; -import {AaveTokenV2} from '../types/AaveTokenV2'; -import {LendToAaveMigrator} from '../types/LendToAaveMigrator'; - -export const registerContractInJsonDb = async (contractId: string, contractInstance: Contract) => { - const currentNetwork = DRE.network.name; - if (currentNetwork !== 'hardhat' && currentNetwork !== 'coverage') { - console.log(`\n\t *** ${contractId} ***\n`); - console.log(`\t Network: ${currentNetwork}`); - console.log(`\t tx: ${contractInstance.deployTransaction.hash}`); - console.log(`\t contract address: ${contractInstance.address}`); - console.log(`\t deployer address: ${contractInstance.deployTransaction.from}`); - console.log(`\t gas price: ${contractInstance.deployTransaction.gasPrice}`); - console.log(`\t gas used: ${contractInstance.deployTransaction.gasLimit}`); - console.log(`\t ******`); - console.log(); - } - - await getDb() - .set(`${contractId}.${currentNetwork}`, { - address: contractInstance.address, - deployer: contractInstance.deployTransaction.from, - }) - .write(); -}; - -export const insertContractAddressInDb = async (id: eContractid, address: tEthereumAddress) => - await getDb() - .set(`${id}.${DRE.network.name}`, { - address, - }) - .write(); - -export const getEthersSigners = async (): Promise => - await Promise.all(await DRE.ethers.getSigners()); - -export const getEthersSignersAddresses = async (): Promise => - await Promise.all((await DRE.ethers.getSigners()).map((signer) => signer.getAddress())); - -export const getCurrentBlock = async () => { - return DRE.ethers.provider.getBlockNumber(); -}; - -export const decodeAbiNumber = (data: string): number => - parseInt(utils.defaultAbiCoder.decode(['uint256'], data).toString()); - -const deployContract = async ( - contractName: string, - args: any[] -): Promise => { - const contract = (await (await DRE.ethers.getContractFactory(contractName)).deploy( - ...args - )) as ContractType; - await waitForTx(contract.deployTransaction); - await registerContractInJsonDb(contractName, contract); - return contract; -}; - -export const getContract = async ( - contractName: string, - address: string -): Promise => (await DRE.ethers.getContractAt(contractName, address)) as ContractType; - -export const deployAaveToken = async (verify?: boolean) => { - const id = eContractid.AaveToken; - const args: string[] = []; - const instance = await deployContract(id, args); - await instance.deployTransaction.wait(); - if (verify) { - await verifyContract(id, instance.address, args); - } - return instance; -}; - -export const deployAaveTokenV2 = async (verify?: boolean): Promise => { - const id = eContractid.AaveTokenV2; - const args: string[] = []; - const instance = await deployContract(id, args); - await instance.deployTransaction.wait(); - if (verify) { - await verifyContract(id, instance.address, args); - } - return instance; -}; - -export const deployLendToAaveMigrator = async ( - [aaveToken, lendToken, aaveLendRatio]: [tEthereumAddress, tEthereumAddress, string], - verify?: boolean -) => { - const id = eContractid.LendToAaveMigrator; - const args: string[] = [aaveToken, lendToken, aaveLendRatio]; - const instance = await deployContract(id, args); - await instance.deployTransaction.wait(); - if (verify) { - await verifyContract(id, instance.address, args); - } - return instance; -}; - -export const deployMintableErc20 = async ([name, symbol, decimals]: [string, string, number]) => - await deployContract(eContractid.MintableErc20, [name, symbol, decimals]); - -export const deployDoubleTransferHelper = async (aaveToken: tEthereumAddress, verify?: boolean) => { - const id = eContractid.DoubleTransferHelper; - const args = [aaveToken]; - const instance = await deployContract(id, args); - await instance.deployTransaction.wait(); - if (verify) { - await verifyContract(id, instance.address, args); - } - return instance; -}; - -export const deployMockTransferHook = async () => - await deployContract(eContractid.MockTransferHook, []); - -export const deployInitializableAdminUpgradeabilityProxy = async (verify?: boolean) => { - const id = eContractid.InitializableAdminUpgradeabilityProxy; - const args: string[] = []; - const instance = await deployContract(id, args); - await instance.deployTransaction.wait(); - if (verify) { - await verifyContract(id, instance.address, args); - } - return instance; -}; - -export const getAaveToken = async (address?: tEthereumAddress) => { - return await getContract( - eContractid.AaveToken, - address || (await getDb().get(`${eContractid.AaveToken}.${DRE.network.name}`).value()).address - ); -}; - -export const getAaveTokenImpl = async (address?: tEthereumAddress) => { - return await getContract( - eContractid.AaveToken, - address || - (await getDb().get(`${eContractid.AaveTokenImpl}.${DRE.network.name}`).value()).address - ); -}; - -export const getLendToken = async (address?: tEthereumAddress) => { - return await getContract( - eContractid.MintableErc20, - address || - (await getDb().get(`${eContractid.MintableErc20}.${DRE.network.name}`).value()).address - ); -}; - -export const getLendToAaveMigratorImpl = async (address?: tEthereumAddress) => { - return await getContract( - eContractid.LendToAaveMigrator, - address || - (await getDb().get(`${eContractid.LendToAaveMigratorImpl}.${DRE.network.name}`).value()) - .address - ); -}; - -export const getLendToAaveMigrator = async (address?: tEthereumAddress) => { - return await getContract( - eContractid.LendToAaveMigrator, - address || - (await getDb().get(`${eContractid.LendToAaveMigrator}.${DRE.network.name}`).value()).address - ); -}; - -export const getMintableErc20 = async (address: tEthereumAddress) => { - return await getContract( - eContractid.MintableErc20, - address || - (await getDb().get(`${eContractid.MintableErc20}.${DRE.network.name}`).value()).address - ); -}; - -export const getDoubleTransferHelper = async (address: tEthereumAddress) => { - return await getContract( - eContractid.DoubleTransferHelper, - address || - (await getDb().get(`${eContractid.DoubleTransferHelper}.${DRE.network.name}`).value()).address - ); -}; - -export const getMockTransferHook = async (address?: tEthereumAddress) => { - return await getContract( - eContractid.MockTransferHook, - address || - (await getDb().get(`${eContractid.MockTransferHook}.${DRE.network.name}`).value()).address - ); -}; - -export const getIErc20Detailed = async (address: tEthereumAddress) => { - return await getContract( - eContractid.IERC20Detailed, - address || - (await getDb().get(`${eContractid.IERC20Detailed}.${DRE.network.name}`).value()).address - ); -}; - -export const getInitializableAdminUpgradeabilityProxy = async (address: tEthereumAddress) => { - return await getContract( - eContractid.InitializableAdminUpgradeabilityProxy, - address || - ( - await getDb() - .get(`${eContractid.InitializableAdminUpgradeabilityProxy}.${DRE.network.name}`) - .value() - ).address - ); -}; - -export const convertToCurrencyDecimals = async (tokenAddress: tEthereumAddress, amount: string) => { - const isEth = tokenAddress === MOCK_ETH_ADDRESS; - let decimals = '18'; - - if (!isEth) { - const token = await getIErc20Detailed(tokenAddress); - decimals = (await token.decimals()).toString(); - } - - return ethers.utils.parseUnits(amount, decimals); -}; - -export const convertToCurrencyUnits = async (tokenAddress: string, amount: string) => { - const isEth = tokenAddress === MOCK_ETH_ADDRESS; - - let decimals = new BigNumber(18); - if (!isEth) { - const token = await getIErc20Detailed(tokenAddress); - decimals = new BigNumber(await token.decimals()); - } - const currencyUnit = new BigNumber(10).pow(decimals); - const amountInCurrencyUnits = new BigNumber(amount).div(currencyUnit); - return amountInCurrencyUnits.toFixed(); -}; - -export const buildPermitParams = ( - chainId: number, - aaveToken: tEthereumAddress, - owner: tEthereumAddress, - spender: tEthereumAddress, - nonce: number, - deadline: string, - value: tStringTokenSmallUnits -) => ({ - types: { - EIP712Domain: [ - {name: 'name', type: 'string'}, - {name: 'version', type: 'string'}, - {name: 'chainId', type: 'uint256'}, - {name: 'verifyingContract', type: 'address'}, - ], - Permit: [ - {name: 'owner', type: 'address'}, - {name: 'spender', type: 'address'}, - {name: 'value', type: 'uint256'}, - {name: 'nonce', type: 'uint256'}, - {name: 'deadline', type: 'uint256'}, - ], - }, - primaryType: 'Permit' as const, - domain: { - name: 'Aave Token', - version: '1', - chainId: chainId, - verifyingContract: aaveToken, - }, - message: { - owner, - spender, - value, - nonce, - deadline, - }, -}); - -export const buildDelegateByTypeParams = ( - chainId: number, - aaveToken: tEthereumAddress, - delegatee: tEthereumAddress, - type: string, - nonce: string, - expiry: string -) => ({ - types: { - EIP712Domain: [ - {name: 'name', type: 'string'}, - {name: 'version', type: 'string'}, - {name: 'chainId', type: 'uint256'}, - {name: 'verifyingContract', type: 'address'}, - ], - DelegateByType: [ - {name: 'delegatee', type: 'address'}, - {name: 'type', type: 'uint256'}, - {name: 'nonce', type: 'uint256'}, - {name: 'expiry', type: 'uint256'}, - ], - }, - primaryType: 'DelegateByType' as const, - domain: { - name: 'Aave Token', - version: '1', - chainId: chainId, - verifyingContract: aaveToken, - }, - message: { - delegatee, - type, - nonce, - expiry, - }, -}); - -export const buildDelegateParams = ( - chainId: number, - aaveToken: tEthereumAddress, - delegatee: tEthereumAddress, - nonce: string, - expiry: string -) => ({ - types: { - EIP712Domain: [ - {name: 'name', type: 'string'}, - {name: 'version', type: 'string'}, - {name: 'chainId', type: 'uint256'}, - {name: 'verifyingContract', type: 'address'}, - ], - Delegate: [ - {name: 'delegatee', type: 'address'}, - {name: 'nonce', type: 'uint256'}, - {name: 'expiry', type: 'uint256'}, - ], - }, - primaryType: 'Delegate' as const, - domain: { - name: 'Aave Token', - version: '1', - chainId: chainId, - verifyingContract: aaveToken, - }, - message: { - delegatee, - nonce, - expiry, - }, -}); - -export const getSignatureFromTypedData = ( - privateKey: string, - typedData: any // TODO: should be TypedData, from eth-sig-utils, but TS doesn't accept it -): ECDSASignature => { - const signature = signTypedData_v4(Buffer.from(privateKey.substring(2, 66), 'hex'), { - data: typedData, - }); - return fromRpcSig(signature); -}; diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/etherscan-verification.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/etherscan-verification.ts deleted file mode 100644 index 02fe6c52..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/etherscan-verification.ts +++ /dev/null @@ -1,121 +0,0 @@ -import {exit} from 'process'; -import fs from 'fs'; -import globby from 'globby'; -import {file} from 'tmp-promise'; -import {DRE} from './misc-utils'; - -const listSolidityFiles = (dir: string) => globby(`${dir}/**/*.sol`); - -const fatalErrors = [ - `The address provided as argument contains a contract, but its bytecode`, - `Daily limit of 100 source code submissions reached`, -]; - -export const SUPPORTED_ETHERSCAN_NETWORKS = ['main', 'ropsten', 'kovan']; - -export const getEtherscanPath = async (contractName: string) => { - const paths = await listSolidityFiles(DRE.config.paths.sources); - const path = paths.find((p) => p.includes(contractName)); - if (!path) { - throw new Error( - `Contract path not found for ${contractName}. Check if smart contract file is equal to contractName input.` - ); - } - - return `${path}:${contractName}`; -}; - -function delay(ms: number) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -export const verifyContract = async ( - contractName: string, - address: string, - constructorArguments: (string | string[])[], - libraries?: string -) => { - const currentNetwork = DRE.network.name; - - if (!process.env.ETHERSCAN_KEY) { - throw Error('Missing process.env.ETHERSCAN_KEY.'); - } - if (!SUPPORTED_ETHERSCAN_NETWORKS.includes(currentNetwork)) { - throw Error( - `Current network ${currentNetwork} not supported. Please change to one of the next networks: ${SUPPORTED_ETHERSCAN_NETWORKS.toString()}` - ); - } - const etherscanPath = await getEtherscanPath(contractName); - - try { - console.log( - '[ETHERSCAN][WARNING] Delaying Etherscan verification due their API can not find newly deployed contracts' - ); - const msDelay = 3000; - const times = 15; - // Write a temporal file to host complex parameters for buidler-etherscan https://github.com/nomiclabs/buidler/tree/development/packages/buidler-etherscan#complex-arguments - const {fd, path, cleanup} = await file({ - prefix: 'verify-params-', - postfix: '.js', - }); - fs.writeSync(fd, `module.exports = ${JSON.stringify([...constructorArguments])};`); - - const params = { - contractName: etherscanPath, - address: address, - libraries, - constructorArgs: path, - }; - await runTaskWithRetry('verify', params, times, msDelay, cleanup); - } catch (error) {} -}; - -export const runTaskWithRetry = async ( - task: string, - params: any, - times: number, - msDelay: number, - cleanup: () => void -) => { - let counter = times; - await delay(msDelay); - - try { - if (times) { - await DRE.run(task, params); - cleanup(); - } else { - cleanup(); - console.error( - '[ETHERSCAN][ERROR] Errors after all the retries, check the logs for more information.' - ); - } - } catch (error) { - counter--; - console.info(`[ETHERSCAN][[INFO] Retrying attemps: ${counter}.`); - console.error('[ETHERSCAN][[ERROR]', error.message); - - if (fatalErrors.some((fatalError) => error.message.includes(fatalError))) { - console.error( - '[ETHERSCAN][[ERROR] Fatal error detected, skip retries and resume deployment.' - ); - return; - } - - await runTaskWithRetry(task, params, counter, msDelay, cleanup); - } -}; - -export const checkVerification = () => { - const currentNetwork = DRE.network.name; - if (!process.env.ETHERSCAN_KEY) { - console.error('Missing process.env.ETHERSCAN_KEY.'); - exit(3); - } - if (!SUPPORTED_ETHERSCAN_NETWORKS.includes(currentNetwork)) { - console.error( - `Current network ${currentNetwork} not supported. Please change to one of the next networks: ${SUPPORTED_ETHERSCAN_NETWORKS.toString()}` - ); - exit(5); - } -}; diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/misc-utils.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/misc-utils.ts deleted file mode 100644 index e3a59431..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/misc-utils.ts +++ /dev/null @@ -1,64 +0,0 @@ -import BigNumber from 'bignumber.js'; -import BN = require('bn.js'); -import low from 'lowdb'; -import FileSync from 'lowdb/adapters/FileSync'; -import {WAD} from './constants'; -import {Wallet, ContractTransaction} from 'ethers'; -import {HardhatRuntimeEnvironment} from 'hardhat/types'; -import {iParamsPerNetwork} from './types'; -import {eEthereumNetwork} from './types-common'; - -export const toWad = (value: string | number) => new BigNumber(value).times(WAD).toFixed(); - -export const bnToBigNumber = (amount: BN): BigNumber => new BigNumber(amount); -export const stringToBigNumber = (amount: string): BigNumber => new BigNumber(amount); - -export const getDb = () => low(new FileSync('./deployed-contracts.json')); - -export let DRE: HardhatRuntimeEnvironment = {} as HardhatRuntimeEnvironment; -export const setDRE = (_DRE: HardhatRuntimeEnvironment) => { - DRE = _DRE; -}; - -export const getParamPerNetwork = ( - {kovan, ropsten, main, hardhat, coverage}: iParamsPerNetwork, - network: eEthereumNetwork -) => { - switch (network) { - case eEthereumNetwork.coverage: - return coverage; - case eEthereumNetwork.hardhat: - return hardhat; - case eEthereumNetwork.kovan: - return kovan; - case eEthereumNetwork.ropsten: - return ropsten; - case eEthereumNetwork.main: - return main; - default: - return main; - } -}; - -export const sleep = (milliseconds: number) => { - return new Promise((resolve) => setTimeout(resolve, milliseconds)); -}; - -export const createRandomAddress = () => Wallet.createRandom().address; - -export const waitForTx = async (tx: ContractTransaction) => await tx.wait(); - -export const evmSnapshot = async () => await DRE.ethers.provider.send('evm_snapshot', []); - -export const evmRevert = async (id: string) => DRE.ethers.provider.send('evm_revert', [id]); - -export const timeLatest = async () => { - const block = await DRE.ethers.provider.getBlock('latest'); - return new BigNumber(block.timestamp); -}; - -export const advanceBlock = async (timestamp: number) => - await DRE.ethers.provider.send('evm_mine', [timestamp]); - -export const increaseTime = async (secondsToIncrease: number) => - await DRE.ethers.provider.send('evm_increaseTime', [secondsToIncrease]); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/types-common.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/types-common.ts deleted file mode 100644 index e2d660e8..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/types-common.ts +++ /dev/null @@ -1,7 +0,0 @@ -export enum eEthereumNetwork { - coverage = 'coverage', - hardhat = 'hardhat', - kovan = 'kovan', - ropsten = 'ropsten', - main = 'main', -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/types.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/types.ts deleted file mode 100644 index 97e259b8..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/helpers/types.ts +++ /dev/null @@ -1,32 +0,0 @@ -import BigNumber from 'bignumber.js'; -import {eEthereumNetwork} from './types-common'; - -export enum eContractid { - AaveToken = 'AaveToken', - AaveTokenV2 = 'AaveTokenV2', - AaveTokenImpl = 'AaveTokenImpl', - LendToAaveMigrator = 'LendToAaveMigrator', - IERC20Detailed = 'IERC20Detailed', - AdminUpgradeabilityProxy = 'AdminUpgradeabilityProxy', - InitializableAdminUpgradeabilityProxy = 'InitializableAdminUpgradeabilityProxy', - MintableErc20 = 'MintableErc20', - LendToAaveMigratorImpl = 'LendToAaveMigratorImpl', - DoubleTransferHelper = 'DoubleTransferHelper', - MockTransferHook = 'MockTransferHook', -} - -export enum ProtocolErrors {} - -export type tEthereumAddress = string; -export type tStringTokenBigUnits = string; // 1 ETH, or 10e6 USDC or 10e18 DAI -export type tBigNumberTokenBigUnits = BigNumber; -export type tStringTokenSmallUnits = string; // 1 wei, or 1 basic unit of USDC, or 1 basic unit of DAI -export type tBigNumberTokenSmallUnits = BigNumber; - -export interface iParamsPerNetwork { - [eEthereumNetwork.coverage]: T; - [eEthereumNetwork.hardhat]: T; - [eEthereumNetwork.kovan]: T; - [eEthereumNetwork.ropsten]: T; - [eEthereumNetwork.main]: T; -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/package.json b/CVLByExample/aave-token-v3/lib/aave-token-v2/package.json deleted file mode 100644 index ecd6b3ac..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/package.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "name": "@aave-tech/aave-token-v2", - "version": "1.0.0", - "description": "Aave ERC20 token", - "files": [ - "/contracts/**/*.sol" - ], - "scripts": { - "run-env": "npm i && tail -f /dev/null", - "hardhat": "hardhat", - "hardhat-kovan": "hardhat --network kovan", - "hardhat-ropsten": "hardhat --network ropsten", - "hardhat-main": "hardhat --network main", - "hardhat-docker": "hardhat --network hardhatevm_docker", - "hardhat help": "hardhat help", - "compile": "SKIP_LOAD=true hardhat compile", - "compile:force": "npm run compile -- --force", - "compile:force:quiet": "npm run compile:force -- --quiet", - "types-gen": "hardhat typechain", - "test": "npm run compile:force:quiet && TS_NODE_TRANSPILE_ONLY=1 hardhat test", - "coverage": "SKIP_LOAD=true npx hardhat typechain && node --max_old_space_size=6144 node_modules/.bin/hardhat coverage", - "dev:deployment": "hardhat dev-deployment --admin ${AAVE_ADMIN:-''} --lend-token-address ${LEND_TOKEN:-''}", - "docker:deployment": "npm run hardhat-docker -- dev-deployment --admin ${AAVE_ADMIN:-''} --lend-token-address ${LEND_TOKEN:-''}", - "dev:main:deployment": "hardhat main-deployment", - "dev:deploy-AaveToken": "hardhat deploy-AaveToken", - "dev:deploy-LendToAaveMigrator": "hardhat deploy-LendToAaveMigrator", - "dev:initialize-AaveToken": "hardhat initialize-AaveToken --admin ${AAVE_ADMIN:-''}", - "dev:initialize-LendToAaveMigrator": "hardhat initialize-LendToAaveMigrator --admin ${AAVE_ADMIN:-''}", - "kovan:deployment": "npm run hardhat-kovan -- testnet-deployment --verify", - "kovan:deploy-AaveToken": "npm run hardhat-kovan deploy-AaveToken", - "kovan:deploy-v2": "hardhat --network kovan deploy-v2 --verify", - "kovan:deploy-LendToAaveMigrator": "npm run hardhat-kovan deploy-LendToAaveMigrator", - "kovan:initialize-AaveToken": "npm run hardhat-kovan -- initialize-AaveToken --admin ${AAVE_ADMIN:-''}", - "kovan:initialize-LendToAaveMigrator": "npm run hardhat-kovan -- initialize-LendToAaveMigrator --admin ${AAVE_ADMIN:-''}", - "ropsten:deployment": "npm run hardhat-ropsten -- testnet-deployment --verify", - "ropsten:deploy-AaveToken": "npm run hardhat-ropsten deploy-AaveToken", - "ropsten:deploy-LendToAaveMigrator": "npm run hardhat-ropsten deploy-LendToAaveMigrator", - "ropsten:initialize-AaveToken": "npm run hardhat-ropsten -- initialize-AaveToken --admin ${AAVE_ADMIN:-''}", - "ropsten:initialize-LendToAaveMigrator": "npm run hardhat-ropsten -- initialize-LendToAaveMigrator --admin ${AAVE_ADMIN:-''}", - "main:deployment": "npm run hardhat-main -- main-deployment --verify", - "main:deploy-AaveTokenV2": "npm run hardhat-main deploy-AaveTokenV2 --verify", - "main:deploy-AaveToken": "npm run hardhat-main deploy-AaveToken", - "main:deploy-LendToAaveMigrator": "npm run hardhat-main -- deploy-LendToAaveMigrator --lend-token-address ${LEND_TOKEN:-''}", - "main:initialize-AaveToken": "npm run hardhat-main -- initialize-AaveToken --admin ${AAVE_ADMIN:-''} --onlyProxy", - "main:initialize-LendToAaveMigrator": "npm run hardhat-main -- initialize-LendToAaveMigrator --admin ${AAVE_ADMIN:-''} --onlyProxy", - "ci:clean": "rm -rf ./artifacts ./cache ./types" - }, - "devDependencies": { - "@nomiclabs/hardhat-ethers": "^2.0.1", - "@nomiclabs/hardhat-etherscan": "^2.1.0", - "@nomiclabs/hardhat-waffle": "^2.0.1", - "@openzeppelin/contracts": "3.0.1", - "@typechain/ethers-v5": "^4.0.0", - "@types/chai": "4.2.11", - "@types/lowdb": "1.0.9", - "@types/mocha": "7.0.2", - "@types/node": "14.0.5", - "bignumber.js": "9.0.0", - "buidler-typechain": "0.1.1", - "chai": "4.2.0", - "chai-bignumber": "3.0.0", - "eth-sig-util": "2.5.3", - "ethereum-waffle": "^3.2.1", - "ethereumjs-util": "7.0.2", - "ethers": "^5.0.8", - "hardhat": "^2.0.4", - "hardhat-typechain": "^0.3.3", - "husky": "^4.2.5", - "lowdb": "1.0.0", - "prettier": "^2.0.5", - "prettier-plugin-solidity": "^1.0.0-alpha.53", - "solidity-coverage": "^0.7.13", - "ts-generator": "^0.1.1", - "ts-node": "^9.1.0", - "typechain": "^3.0.0", - "typescript": "^4.1.2" - }, - "author": "Aave", - "contributors": [ - { - "name": "Ernesto Boado", - "email": "ernesto@aave.com" - }, - { - "name": "Emilio Frangella", - "email": "emilio@aave.com" - }, - { - "name": "Andrey Kozlov", - "email": "andrey@aave.com" - }, - { - "name": "David Racero", - "email": "david.k@aave.com" - }, - { - "name": "Hadrien Charlanes", - "email": "hadrien@aave.com" - } - ], - "license": "AGPLv3", - "dependencies": { - "tmp-promise": "^3.0.2" - }, - "publishConfig": { - "@aave-tech:registry": "https://gitlab.com/api/v4/projects/19392283/packages/npm/" - } -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-AaveToken.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-AaveToken.ts deleted file mode 100644 index a95807a2..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-AaveToken.ts +++ /dev/null @@ -1,31 +0,0 @@ -import {task} from 'hardhat/config'; -import {eContractid} from '../../helpers/types'; -import { - registerContractInJsonDb, - deployAaveToken, - deployInitializableAdminUpgradeabilityProxy, -} from '../../helpers/contracts-helpers'; - -const {AaveToken, AaveTokenImpl} = eContractid; - -task(`deploy-${AaveToken}`, `Deploys the ${AaveToken} contract`) - .addFlag('verify', 'Proceed with the Etherscan verification') - .setAction(async ({verify}, localBRE) => { - await localBRE.run('set-dre'); - - if (!localBRE.network.config.chainId) { - throw new Error('INVALID_CHAIN_ID'); - } - - console.log(`\n- ${AaveToken} deployment`); - - console.log(`\tDeploying ${AaveToken} implementation ...`); - const aaveTokenImpl = await deployAaveToken(verify); - await registerContractInJsonDb(AaveTokenImpl, aaveTokenImpl); - - console.log(`\tDeploying ${AaveToken} Transparent Proxy ...`); - const aaveTokenProxy = await deployInitializableAdminUpgradeabilityProxy(verify); - await registerContractInJsonDb(AaveToken, aaveTokenProxy); - - console.log(`\tFinished ${AaveToken} proxy and implementation deployment`); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-AaveTokenV2.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-AaveTokenV2.ts deleted file mode 100644 index e8ea1db0..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-AaveTokenV2.ts +++ /dev/null @@ -1,28 +0,0 @@ -import {task} from 'hardhat/config'; -import {eContractid} from '../../helpers/types'; -import { - registerContractInJsonDb, - deployAaveToken, - deployInitializableAdminUpgradeabilityProxy, - deployAaveTokenV2, -} from '../../helpers/contracts-helpers'; - -const {AaveTokenV2, AaveTokenImpl} = eContractid; - -task(`deploy-${AaveTokenV2}`, `Deploys the ${AaveTokenV2} contract`) - .addFlag('verify', 'Proceed with the Etherscan verification') - .setAction(async ({verify}, localBRE) => { - await localBRE.run('set-dre'); - - if (!localBRE.network.config.chainId) { - throw new Error('INVALID_CHAIN_ID'); - } - - console.log(`\n- ${AaveTokenV2} deployment`); - - console.log(`\tDeploying ${AaveTokenV2} implementation ...`); - const aaveTokenImpl = await deployAaveTokenV2(verify); - await registerContractInJsonDb(AaveTokenImpl, aaveTokenImpl); - - console.log(`\tFinished ${AaveTokenV2} proxy and implementation deployment`); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-LendToAaveMigrator.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-LendToAaveMigrator.ts deleted file mode 100644 index 0dd199e0..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/deploy-LendToAaveMigrator.ts +++ /dev/null @@ -1,57 +0,0 @@ -import {task} from 'hardhat/config'; -import {eContractid} from '../../helpers/types'; -import { - registerContractInJsonDb, - deployLendToAaveMigrator, - deployInitializableAdminUpgradeabilityProxy, - getAaveToken, - getLendToken, - deployMintableErc20, -} from '../../helpers/contracts-helpers'; -import {verify} from 'crypto'; - -const {LendToAaveMigrator, LendToAaveMigratorImpl, MintableErc20} = eContractid; - -task(`deploy-${LendToAaveMigrator}`, `Deploys ${LendToAaveMigrator} contract`) - .addOptionalParam( - 'lendTokenAddress', - 'The address of the LEND token. If not set, a mocked Mintable token will be deployed.' - ) - .addFlag('verify', 'Proceed with the Etherscan verification') - .setAction(async ({lendTokenAddress, verify}, localBRE) => { - await localBRE.run('set-dre'); - - if (!localBRE.network.config.chainId) { - throw new Error('INVALID_CHAIN_ID'); - } - - console.log(`\n- ${LendToAaveMigrator} deployment`); - - if (!lendTokenAddress) { - console.log(`\tDeploying ${MintableErc20} to mock LEND token...`); - const mockedLend = await deployMintableErc20(['LEND token', 'LEND', 18]); - await mockedLend.deployTransaction.wait(); - } - - const aaveTokenProxy = await getAaveToken(); - const lendToken = lendTokenAddress || (await getLendToken()).address; - - console.log(`\tUsing ${lendToken} address for Lend Token input parameter`); - - console.log(`\tDeploying ${LendToAaveMigrator} Implementation...`); - - const constructorParameters: [string, string, string] = [ - aaveTokenProxy.address, - lendToken, - '100', - ]; - const lendToAaveMigratorImpl = await deployLendToAaveMigrator(constructorParameters, verify); - await registerContractInJsonDb(LendToAaveMigratorImpl, lendToAaveMigratorImpl); - - console.log(`\tDeploying ${LendToAaveMigrator} Transparent Proxy...`); - - const lendToAaveMigratorProxy = await deployInitializableAdminUpgradeabilityProxy(verify); - await registerContractInJsonDb(LendToAaveMigrator, lendToAaveMigratorProxy); - - console.log(`\tFinished ${LendToAaveMigrator} proxy and implementation deployment`); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/initialize-AaveToken.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/initialize-AaveToken.ts deleted file mode 100644 index 14608368..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/initialize-AaveToken.ts +++ /dev/null @@ -1,66 +0,0 @@ -import {task} from 'hardhat/config'; -import {eContractid} from '../../helpers/types'; -import { - getAaveToken, - getLendToAaveMigrator, - getAaveTokenImpl, - getContract, -} from '../../helpers/contracts-helpers'; -import {waitForTx} from '../../helpers/misc-utils'; -import {ZERO_ADDRESS} from '../../helpers/constants'; -import {InitializableAdminUpgradeabilityProxy} from '../../types/InitializableAdminUpgradeabilityProxy'; - -const {AaveToken} = eContractid; - -task(`initialize-${AaveToken}`, `Initialize the ${AaveToken} proxy contract`) - .addParam('admin', `The address to be added as an Admin role in ${AaveToken} Transparent Proxy.`) - .addFlag('onlyProxy', 'Initialize only the proxy contract, not the implementation contract') - .setAction(async ({admin: aaveAdmin, onlyProxy}, localBRE) => { - await localBRE.run('set-dre'); - - if (!aaveAdmin) { - throw new Error( - `Missing --admin parameter to add the Admin Role to ${AaveToken} Transparent Proxy` - ); - } - - if (!localBRE.network.config.chainId) { - throw new Error('INVALID_CHAIN_ID'); - } - - console.log(`\n- ${AaveToken} initialization`); - - const aaveTokenImpl = await getAaveTokenImpl(); - const aaveToken = await getAaveToken(); - const lendToAaveMigratorProxy = await getLendToAaveMigrator(); - - const aaveTokenProxy = await getContract( - eContractid.InitializableAdminUpgradeabilityProxy, - aaveToken.address - ); - - if (onlyProxy) { - console.log( - `\tWARNING: Not initializing the ${AaveToken} implementation, only set AAVE_ADMIN to Transparent Proxy contract.` - ); - await waitForTx(await aaveTokenProxy.initialize(aaveTokenImpl.address, aaveAdmin, '0x')); - console.log( - `\tFinished ${AaveToken} Proxy initialization, but not ${AaveToken} implementation.` - ); - return; - } - - console.log('\tInitializing Aave Token and Transparent Proxy'); - // If any other testnet, initialize for development purposes - const aaveTokenEncodedInitialize = aaveTokenImpl.interface.encodeFunctionData('initialize', [ - lendToAaveMigratorProxy.address, - aaveAdmin, - ZERO_ADDRESS, - ]); - - await waitForTx( - await aaveTokenProxy.initialize(aaveTokenImpl.address, aaveAdmin, aaveTokenEncodedInitialize) - ); - - console.log('\tFinished Aave Token and Transparent Proxy initialization'); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/initialize-LendToAaveMigrator.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/initialize-LendToAaveMigrator.ts deleted file mode 100644 index 93c69023..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/initialize-LendToAaveMigrator.ts +++ /dev/null @@ -1,66 +0,0 @@ -import {task} from 'hardhat/config'; -import {eContractid} from '../../helpers/types'; -import { - getLendToAaveMigratorImpl, - getContract, - getLendToAaveMigrator, -} from '../../helpers/contracts-helpers'; -import {waitForTx} from '../../helpers/misc-utils'; - -const {LendToAaveMigrator} = eContractid; - -task(`initialize-${LendToAaveMigrator}`, `Initialize the ${LendToAaveMigrator} proxy contract`) - .addParam('admin', 'The address to be added as an Admin role in Aave Token Transparent Proxy.') - .addFlag('onlyProxy', 'Initialize only the proxy contract, not the implementation contract') - .setAction(async ({admin: aaveAdmin, onlyProxy}, localBRE) => { - await localBRE.run('set-dre'); - - if (!aaveAdmin) { - throw new Error( - `Missing --admin parameter to add the Admin Role to ${LendToAaveMigrator} Transparent Proxy` - ); - } - - if (!localBRE.network.config.chainId) { - throw new Error('INVALID_CHAIN_ID'); - } - - console.log(`\n- ${LendToAaveMigrator} initialization`); - - const lendToAaveMigratorImpl = await getLendToAaveMigratorImpl(); - const lendToAaveMigrator = await getLendToAaveMigrator(); - - const lendToAaveMigratorProxy = await getContract( - eContractid.InitializableAdminUpgradeabilityProxy, - lendToAaveMigrator.address - ); - - const lendToAaveMigratorInitializeEncoded = lendToAaveMigratorImpl.interface.encodeFunctionData( - 'initialize' - ); - - if (onlyProxy) { - console.log( - `\tWARNING: Not initializing the ${LendToAaveMigrator} implementation, only set AAVE_ADMIN to Transparent Proxy contract.` - ); - await waitForTx( - await lendToAaveMigratorProxy.initialize(lendToAaveMigratorImpl.address, aaveAdmin, '0x') - ); - console.log( - `\tFinished ${LendToAaveMigrator} Proxy initialization, but not ${LendToAaveMigrator} implementation.` - ); - return; - } - - console.log('\tInitializing LendToAaveMigrator Proxy and Implementation '); - - await waitForTx( - await lendToAaveMigratorProxy.initialize( - lendToAaveMigratorImpl.address, - aaveAdmin, - lendToAaveMigratorInitializeEncoded - ) - ); - - console.log('\tFinished LendToAaveMigrator Proxy and Implementation initialization.'); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/migrate-LendToAave-migrations.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/migrate-LendToAave-migrations.ts deleted file mode 100644 index 647def60..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/deployments/migrate-LendToAave-migrations.ts +++ /dev/null @@ -1,39 +0,0 @@ -import {task} from 'hardhat/config'; -import BigNumber from 'bignumber.js'; -import { - getLendToAaveMigrator, - getLendToken, - getEthersSigners, -} from '../../helpers/contracts-helpers'; - -task(`Lend-Migration`, `Create migration to test the contracts`).setAction(async (_, localBRE) => { - console.log(`\n- Lend Migration started`); - await localBRE.run('set-dre'); - - if (!localBRE.network.config.chainId) { - throw new Error('INVALID_CHAIN_ID'); - } - - const [, , user1, user2] = await getEthersSigners(); - - const mockLend = await getLendToken(); - const lendToAaveMigrator = await getLendToAaveMigrator(); - - const lendAmount = 1000; - const lendTokenAmount = new BigNumber(lendAmount).times(new BigNumber(10).pow(18)).toFixed(0); - const halfLendTokenAmount = new BigNumber(lendAmount / 2) - .times(new BigNumber(10).pow(18)) - .toFixed(0); - - await mockLend.connect(user1).mint(lendTokenAmount); - await mockLend.connect(user2).mint(lendTokenAmount); - - await mockLend.connect(user1).approve(lendToAaveMigrator.address, lendTokenAmount); - await mockLend.connect(user2).approve(lendToAaveMigrator.address, lendTokenAmount); - - await lendToAaveMigrator.connect(user1).migrateFromLEND(halfLendTokenAmount); - await lendToAaveMigrator.connect(user1).migrateFromLEND(halfLendTokenAmount); - await lendToAaveMigrator.connect(user2).migrateFromLEND(lendTokenAmount); - - console.log(`\n- Finished migrating lend balances`); -}); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/deploy-AaveTokenV2.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/deploy-AaveTokenV2.ts deleted file mode 100644 index c81f09a1..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/deploy-AaveTokenV2.ts +++ /dev/null @@ -1,33 +0,0 @@ -import {task} from 'hardhat/config'; -import {HardhatRuntimeEnvironment} from 'hardhat/types'; - -import {eEthereumNetwork} from '../../helpers/types-common'; -import {eContractid} from '../../helpers/types'; -import {checkVerification} from '../../helpers/etherscan-verification'; -import {getAaveAdminPerNetwork, getLendTokenPerNetwork} from '../../helpers/constants'; - -task('deploy-v2', 'Deployment of the Aave token V2') - .addFlag( - 'verify', - 'Verify AaveTokenV2 contract.' - ) - .setAction(async ({verify}, localBRE) => { - const DRE: HardhatRuntimeEnvironment = await localBRE.run('set-dre'); - const network = DRE.network.name as eEthereumNetwork; - const aaveAdmin = getAaveAdminPerNetwork(network); - - if (!aaveAdmin) { - throw Error( - 'The --admin parameter must be set for mainnet network. Set an Ethereum address as --admin parameter input.' - ); - } - - // If Etherscan verification is enabled, check needed environments to prevent loss of gas in failed deployments. - if (verify) { - checkVerification(); - } - - await DRE.run(`deploy-${eContractid.AaveTokenV2}`, {verify}); - - console.log('\n✔️ Finished the deployment of the Aave Token V2 Mainnet Environment. ✔️'); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/dev-deployment.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/dev-deployment.ts deleted file mode 100644 index 6b2f838f..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/dev-deployment.ts +++ /dev/null @@ -1,51 +0,0 @@ -import {task} from 'hardhat/config'; -import {HardhatRuntimeEnvironment} from 'hardhat/types'; - -import {eContractid} from '../../helpers/types'; -import {getEthersSigners} from '../../helpers/contracts-helpers'; -import {checkVerification} from '../../helpers/etherscan-verification'; - -task('dev-deployment', 'Deployment in hardhat') - .addOptionalParam( - 'admin', - `The address to be added as an Admin role in Aave Token and LendToAaveMigrator Transparent Proxies.` - ) - .addOptionalParam('lendTokenAddress', 'The address of the LEND token smart contract.') - .addFlag( - 'verify', - 'Verify AaveToken, LendToAaveMigrator, and InitializableAdminUpgradeabilityProxy contract.' - ) - .setAction(async ({admin, lendTokenAddress, verify}, localBRE) => { - const DRE: HardhatRuntimeEnvironment = await localBRE.run('set-dre'); - - // If admin parameter is NOT set, the Aave Admin will be the - // second account provided via buidler config. - const [, secondaryWallet] = await getEthersSigners(); - const aaveAdmin = admin || (await secondaryWallet.getAddress()); - - console.log('AAVE ADMIN', aaveAdmin); - - // If Etherscan verification is enabled, check needed enviroments to prevent loss of gas in failed deployments. - if (verify) { - checkVerification(); - } - - await DRE.run(`deploy-${eContractid.AaveToken}`, {verify}); - - await DRE.run(`deploy-${eContractid.LendToAaveMigrator}`, { - lendTokenAddress, - verify, - }); - - await DRE.run(`initialize-${eContractid.AaveToken}`, { - admin: aaveAdmin, - }); - - await DRE.run(`initialize-${eContractid.LendToAaveMigrator}`, { - admin: aaveAdmin, - }); - - await DRE.run(`Lend-Migration`, {}); - - console.log('\n👷 Finished the deployment of the Aave Token Development Enviroment. 👷'); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/mainnet-deployment.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/mainnet-deployment.ts deleted file mode 100644 index 34f83a91..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/mainnet-deployment.ts +++ /dev/null @@ -1,52 +0,0 @@ -import {task} from 'hardhat/config'; -import {HardhatRuntimeEnvironment} from 'hardhat/types'; - -import {eEthereumNetwork} from '../../helpers/types-common'; -import {eContractid} from '../../helpers/types'; -import {checkVerification} from '../../helpers/etherscan-verification'; -import {getAaveAdminPerNetwork, getLendTokenPerNetwork} from '../../helpers/constants'; - -task('main-deployment', 'Deployment in mainnet network') - .addFlag( - 'verify', - 'Verify AaveToken, LendToAaveMigrator, and InitializableAdminUpgradeabilityProxy contract.' - ) - .setAction(async ({verify}, localBRE) => { - const DRE: HardhatRuntimeEnvironment = await localBRE.run('set-dre'); - const network = DRE.network.name as eEthereumNetwork; - const aaveAdmin = getAaveAdminPerNetwork(network); - const lendTokenAddress = getLendTokenPerNetwork(network); - - if (!aaveAdmin) { - throw Error( - 'The --admin parameter must be set for mainnet network. Set an Ethereum address as --admin parameter input.' - ); - } - - // If Etherscan verification is enabled, check needed enviroments to prevent loss of gas in failed deployments. - if (verify) { - checkVerification(); - } - - console.log('AAVE ADMIN', aaveAdmin); - await DRE.run(`deploy-${eContractid.AaveToken}`, {verify}); - - await DRE.run(`deploy-${eContractid.LendToAaveMigrator}`, { - lendTokenAddress, - verify, - }); - - // The task will only initialize the proxy contract, not implementation - await DRE.run(`initialize-${eContractid.AaveToken}`, { - admin: aaveAdmin, - onlyProxy: true, - }); - - // The task will only initialize the proxy contract, not implementation - await DRE.run(`initialize-${eContractid.LendToAaveMigrator}`, { - admin: aaveAdmin, - onlyProxy: true, - }); - - console.log('\n✔️ Finished the deployment of the Aave Token Mainnet Enviroment. ✔️'); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/testnet-deployment.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/testnet-deployment.ts deleted file mode 100644 index 444a7a69..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/migrations/testnet-deployment.ts +++ /dev/null @@ -1,50 +0,0 @@ -import {task} from 'hardhat/config'; -import {HardhatRuntimeEnvironment} from 'hardhat/types'; - -import {eContractid} from '../../helpers/types'; -import {eEthereumNetwork} from '../../helpers/types-common'; -import {getAaveAdminPerNetwork, getLendTokenPerNetwork} from '../../helpers/constants'; -import {checkVerification} from '../../helpers/etherscan-verification'; - -task('testnet-deployment', 'Deployment in mainnet network') - .addFlag( - 'verify', - 'Verify AaveToken, LendToAaveMigrator, and InitializableAdminUpgradeabilityProxy contract.' - ) - .setAction(async ({verify}, localBRE) => { - const DRE: HardhatRuntimeEnvironment = await localBRE.run('set-dre'); - const network = DRE.network.name as eEthereumNetwork; - const aaveAdmin = getAaveAdminPerNetwork(network); - const lendTokenAddress = getLendTokenPerNetwork(network); - - if (!aaveAdmin) { - throw Error( - 'The --admin parameter must be set for mainnet network. Set an Ethereum address as --admin parameter input.' - ); - } - - // If Etherscan verification is enabled, check needed enviroments to prevent loss of gas in failed deployments. - if (verify) { - checkVerification(); - } - - console.log('AAVE ADMIN', aaveAdmin); - await DRE.run(`deploy-${eContractid.AaveToken}`, {verify}); - - await DRE.run(`deploy-${eContractid.LendToAaveMigrator}`, { - lendTokenAddress, - verify, - }); - - await DRE.run(`initialize-${eContractid.AaveToken}`, { - admin: aaveAdmin, - onlyProxy: true, - }); - - await DRE.run(`initialize-${eContractid.LendToAaveMigrator}`, { - admin: aaveAdmin, - onlyProxy: true, - }); - - console.log('\n✔️ Finished the deployment of the Aave Token Testnet Enviroment. ✔️'); - }); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/misc/set-dre.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/misc/set-dre.ts deleted file mode 100644 index 9d05b7be..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/misc/set-dre.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {task} from 'hardhat/config'; -import {setDRE} from '../../helpers/misc-utils'; - -task(`set-dre`, `Inits the DRE, to have access to all the plugins' objects`).setAction( - async (_, _BRE) => { - await setDRE(_BRE); - return _BRE; - } -); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/misc/verify-sc.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/misc/verify-sc.ts deleted file mode 100644 index c3cec1d6..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tasks/misc/verify-sc.ts +++ /dev/null @@ -1,35 +0,0 @@ -import {task} from 'hardhat/config'; -import {verifyContract, checkVerification} from '../../helpers/etherscan-verification'; - -interface VerifyParams { - contractName: string; - address: string; - constructorArguments: string[]; - libraries: string; -} - -task('verify-sc', 'Inits the DRE, to have access to all the plugins') - .addParam('contractName', 'Name of the Solidity smart contract') - .addParam('address', 'Ethereum address of the smart contract') - .addOptionalParam( - 'libraries', - 'Stringified JSON object in format of {library1: "0x2956356cd2a2bf3202f771f50d3d14a367b48071"}' - ) - .addOptionalVariadicPositionalParam( - 'constructorArguments', - 'arguments for contract constructor', - [] - ) - .setAction( - async ( - {contractName, address, constructorArguments = [], libraries}: VerifyParams, - localBRE - ) => { - await localBRE.run('set-dre'); - - checkVerification(); - - const result = await verifyContract(contractName, address, constructorArguments, libraries); - return result; - } - ); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/test-wallets.js b/CVLByExample/aave-token-v3/lib/aave-token-v2/test-wallets.js deleted file mode 100644 index 10813cb7..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/test-wallets.js +++ /dev/null @@ -1,45 +0,0 @@ - -module.exports = { - accounts: [ - { - secretKey: - "0xc5e8f61d1ab959b397eecc0a37a6517b8e67a0e7cf1f4bce5591f3ed80199122", - balance: "1000000000000000000000000", - }, - { - secretKey: - "0xd49743deccbccc5dc7baa8e69e5be03298da8688a15dd202e20f15d5e0e9a9fb", - balance: "1000000000000000000000000", - }, - { - secretKey: - "0x23c601ae397441f3ef6f1075dcb0031ff17fb079837beadaf3c84d96c6f3e569", - balance: "1000000000000000000000000", - }, - { - secretKey: - "0xee9d129c1997549ee09c0757af5939b2483d80ad649a0eda68e8b0357ad11131", - balance: "1000000000000000000000000", - }, - { - secretKey: - "0x87630b2d1de0fbd5044eb6891b3d9d98c34c8d310c852f98550ba774480e47cc", - balance: "1000000000000000000000000", - }, - { - secretKey: - "0x275cc4a2bfd4f612625204a20a2280ab53a6da2d14860c47a9f5affe58ad86d4", - balance: "1000000000000000000000000", - }, - { - secretKey: - "0xaee25d55ce586148a853ca83fdfacaf7bc42d5762c6e7187e6f8e822d8e6a650", - balance: "1000000000000000000000000", - }, - { - secretKey: - "0xa2e0097c961c67ec197b6865d7ecea6caffc68ebeb00e6050368c8f67fc9c588", - balance: "1000000000000000000000000", - }, - ], -}; diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/__setup.spec.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/test/__setup.spec.ts deleted file mode 100644 index 76b58147..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/__setup.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -import rawBRE from 'hardhat'; - -import { - getEthersSigners, - deployLendToAaveMigrator, - deployAaveToken, - deployInitializableAdminUpgradeabilityProxy, - deployMintableErc20, - insertContractAddressInDb, - registerContractInJsonDb, - deployMockTransferHook, -} from '../helpers/contracts-helpers'; - -import path from 'path'; -import fs from 'fs'; - -import {Signer} from 'ethers'; - -import {initializeMakeSuite} from './helpers/make-suite'; -import {waitForTx, DRE} from '../helpers/misc-utils'; -import {eContractid} from '../helpers/types'; - -['misc', 'deployments', 'migrations'].forEach((folder) => { - const tasksPath = path.join(__dirname, '../tasks', folder); - fs.readdirSync(tasksPath).forEach((task) => require(`${tasksPath}/${task}`)); -}); - -const buildTestEnv = async (deployer: Signer, secondaryWallet: Signer) => { - console.time('setup'); - - const aaveAdmin = await secondaryWallet.getAddress(); - - const aaveTokenImpl = await deployAaveToken(); - - const aaveTokenProxy = await deployInitializableAdminUpgradeabilityProxy(); - - const mockLendToken = await deployMintableErc20(['LEND token', 'LEND', 18]); - await registerContractInJsonDb('LEND', mockLendToken); - - const lendToAaveMigratorImpl = await deployLendToAaveMigrator([ - aaveTokenProxy.address, - mockLendToken.address, - '1000', - ]); - - const lendToAaveMigratorProxy = await deployInitializableAdminUpgradeabilityProxy(); - - const mockTransferHook = await deployMockTransferHook(); - - const aaveTokenEncodedInitialize = aaveTokenImpl.interface.encodeFunctionData('initialize', [ - lendToAaveMigratorProxy.address, - aaveAdmin, - mockTransferHook.address, - ]); - - await waitForTx( - await aaveTokenProxy['initialize(address,address,bytes)']( - aaveTokenImpl.address, - aaveAdmin, - aaveTokenEncodedInitialize - ) - ); - - //we will not run the initialize on the migrator - will be executed by the governance to bootstrap the migration - await waitForTx( - await lendToAaveMigratorProxy['initialize(address,address,bytes)']( - lendToAaveMigratorImpl.address, - aaveAdmin, - '0x' - ) - ); - - await insertContractAddressInDb(eContractid.AaveToken, aaveTokenProxy.address); - - await insertContractAddressInDb(eContractid.LendToAaveMigrator, lendToAaveMigratorProxy.address); - - await insertContractAddressInDb(eContractid.MintableErc20, mockLendToken.address); - - await insertContractAddressInDb(eContractid.MockTransferHook, mockTransferHook.address); - - await insertContractAddressInDb( - eContractid.LendToAaveMigratorImpl, - lendToAaveMigratorImpl.address - ); - - console.timeEnd('setup'); -}; - -before(async () => { - await rawBRE.run('set-dre'); - const [deployer, secondaryWallet] = await getEthersSigners(); - console.log('-> Deploying test environment...'); - await buildTestEnv(deployer, secondaryWallet); - await initializeMakeSuite(); - console.log('\n***************'); - console.log('Setup and snapshot finished'); - console.log('***************\n'); -}); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/aaveToken.spec.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/test/aaveToken.spec.ts deleted file mode 100644 index 06ee2c19..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/aaveToken.spec.ts +++ /dev/null @@ -1,518 +0,0 @@ -import {fail} from 'assert'; -import {ethers} from 'ethers'; -import BigNumber from 'bignumber.js'; -import {TestEnv, makeSuite} from './helpers/make-suite'; -import {ProtocolErrors} from '../helpers/types'; -import {eEthereumNetwork} from '../helpers/types-common'; -import {waitForTx, DRE} from '../helpers/misc-utils'; -import { - getInitializableAdminUpgradeabilityProxy, - buildPermitParams, - getSignatureFromTypedData, - deployDoubleTransferHelper, -} from '../helpers/contracts-helpers'; -import { - getAaveTokenDomainSeparatorPerNetwork, - BUIDLEREVM_CHAINID, - ZERO_ADDRESS, - MAX_UINT_AMOUNT, -} from '../helpers/constants'; - -const {expect} = require('chai'); - -makeSuite('AAVE token', (testEnv: TestEnv) => { - const {} = ProtocolErrors; - - it('Checks initial configuration', async () => { - const {aaveToken} = testEnv; - - expect(await aaveToken.name()).to.be.equal('Aave Token', 'Invalid token name'); - - expect(await aaveToken.symbol()).to.be.equal('AAVE', 'Invalid token symbol'); - - expect((await aaveToken.decimals()).toString()).to.be.equal('18', 'Invalid token decimals'); - }); - - it('Checks the domain separator', async () => { - const network = DRE.network.name; - const DOMAIN_SEPARATOR_ENCODED = getAaveTokenDomainSeparatorPerNetwork( - network as eEthereumNetwork - ); - const {aaveToken} = testEnv; - - const separator = await aaveToken.DOMAIN_SEPARATOR(); - expect(separator).to.be.equal(DOMAIN_SEPARATOR_ENCODED, 'Invalid domain separator'); - }); - - it('Checks the revision', async () => { - const {aaveToken} = testEnv; - - const revision = await aaveToken.REVISION(); - - expect(revision.toString()).to.be.equal('1', 'Invalid revision'); - }); - - it('Checks the allocation of the initial AAVE supply', async () => { - const expectedMigratorBalance = new BigNumber(13000000).times(new BigNumber(10).pow(18)); - const expectedlDistributorBalance = new BigNumber(3000000).times(new BigNumber(10).pow(18)); - const {aaveToken, lendToAaveMigrator} = testEnv; - const migratorBalance = await aaveToken.balanceOf(lendToAaveMigrator.address); - const distributorBalance = await aaveToken.balanceOf(testEnv.users[0].address); - - expect(migratorBalance.toString()).to.be.equal( - expectedMigratorBalance.toFixed(0), - 'Invalid migrator balance' - ); - expect(distributorBalance.toString()).to.be.equal( - expectedlDistributorBalance.toFixed(0), - 'Invalid migrator balance' - ); - }); - - it('Starts the migration', async () => { - const {lendToAaveMigrator, lendToAaveMigratorImpl, users} = testEnv; - - const lendToAaveMigratorInitializeEncoded = lendToAaveMigratorImpl.interface.encodeFunctionData( - 'initialize' - ); - - const migratorAsProxy = await getInitializableAdminUpgradeabilityProxy( - lendToAaveMigrator.address - ); - - await migratorAsProxy - .connect(users[0].signer) - .upgradeToAndCall(lendToAaveMigratorImpl.address, lendToAaveMigratorInitializeEncoded); - }); - - it('Checks the snapshots emitted after the initial allocation', async () => { - const {aaveToken, users} = testEnv; - - const userCountOfSnapshots = await aaveToken._countsSnapshots(users[0].address); - const snapshot = await aaveToken._snapshots(users[0].address, userCountOfSnapshots.sub(1)); - expect(userCountOfSnapshots.toString()).to.be.equal('1', 'INVALID_SNAPSHOT_COUNT'); - expect(snapshot.value.toString()).to.be.equal( - ethers.utils.parseEther('3000000'), - 'INVALID_SNAPSHOT_VALUE' - ); - }); - - it('Record correctly snapshot on migration', async () => { - const {aaveToken, lendToAaveMigrator, deployer, lendToken} = testEnv; - - await waitForTx(await lendToken.mint(ethers.utils.parseEther('2000'))); - await waitForTx( - await lendToken.approve(lendToAaveMigrator.address, ethers.utils.parseEther('2000')) - ); - await waitForTx(await lendToAaveMigrator.migrateFromLEND(ethers.utils.parseEther('2000'))); - - expect((await aaveToken.balanceOf(deployer.address)).toString()).to.be.equal( - ethers.utils.parseEther('2'), - 'INVALID_BALANCE_AFTER_MIGRATION' - ); - - const userCountOfSnapshots = await aaveToken._countsSnapshots(deployer.address); - const snapshot = await aaveToken._snapshots(deployer.address, userCountOfSnapshots.sub(1)); - expect(userCountOfSnapshots.toString()).to.be.equal('1', 'INVALID_SNAPSHOT_COUNT'); - expect(snapshot.value.toString()).to.be.equal( - ethers.utils.parseEther('2'), - 'INVALID_SNAPSHOT_VALUE' - ); - }); - - it('Record correctly snapshot on transfer', async () => { - const {aaveToken, deployer, users} = testEnv; - const from = deployer.address; - const to = users[1].address; - await waitForTx(await aaveToken.transfer(to, ethers.utils.parseEther('1'))); - const fromCountOfSnapshots = await aaveToken._countsSnapshots(from); - const fromLastSnapshot = await aaveToken._snapshots(from, fromCountOfSnapshots.sub(1)); - const fromPreviousSnapshot = await aaveToken._snapshots(from, fromCountOfSnapshots.sub(2)); - - const toCountOfSnapshots = await aaveToken._countsSnapshots(to); - const toSnapshot = await aaveToken._snapshots(to, toCountOfSnapshots.sub(1)); - - expect(fromCountOfSnapshots.toString()).to.be.equal('2', 'INVALID_SNAPSHOT_COUNT'); - expect(fromLastSnapshot.value.toString()).to.be.equal( - ethers.utils.parseEther('1'), - 'INVALID_SNAPSHOT_VALUE' - ); - expect(fromPreviousSnapshot.value.toString()).to.be.equal( - ethers.utils.parseEther('2'), - 'INVALID_SNAPSHOT_VALUE' - ); - - expect(toCountOfSnapshots.toString()).to.be.equal('1', 'INVALID_SNAPSHOT_COUNT'); - expect(toSnapshot.value.toString()).to.be.equal( - ethers.utils.parseEther('1'), - 'INVALID_SNAPSHOT_VALUE' - ); - }); - - it('Reverts submitting a permit with 0 expiration', async () => { - const {aaveToken, deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const expiration = 0; - const nonce = (await aaveToken._nonces(owner)).toNumber(); - const permitAmount = ethers.utils.parseEther('2').toString(); - const msgParams = buildPermitParams( - chainId, - aaveToken.address, - owner, - spender, - nonce, - permitAmount, - expiration.toFixed() - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - expect((await aaveToken.allowance(owner, spender)).toString()).to.be.equal( - '0', - 'INVALID_ALLOWANCE_BEFORE_PERMIT' - ); - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveToken.connect(users[1].signer).permit(owner, spender, permitAmount, expiration, v, r, s) - ).to.be.revertedWith('INVALID_EXPIRATION'); - - expect((await aaveToken.allowance(owner, spender)).toString()).to.be.equal( - '0', - 'INVALID_ALLOWANCE_AFTER_PERMIT' - ); - }); - - it('Submits a permit with maximum expiration length', async () => { - const {aaveToken, deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - const configChainId = DRE.network.config.chainId; - expect(configChainId).to.be.equal(chainId); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const deadline = MAX_UINT_AMOUNT; - const nonce = (await aaveToken._nonces(owner)).toNumber(); - const permitAmount = ethers.utils.parseEther('2').toString(); - const msgParams = buildPermitParams( - chainId, - aaveToken.address, - owner, - spender, - nonce, - deadline, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - expect((await aaveToken.allowance(owner, spender)).toString()).to.be.equal( - '0', - 'INVALID_ALLOWANCE_BEFORE_PERMIT' - ); - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await waitForTx( - await aaveToken - .connect(users[1].signer) - .permit(owner, spender, permitAmount, deadline, v, r, s) - ); - - expect((await aaveToken._nonces(owner)).toNumber()).to.be.equal(1); - }); - - it('Cancels the previous permit', async () => { - const {aaveToken, deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const deadline = MAX_UINT_AMOUNT; - const nonce = (await aaveToken._nonces(owner)).toNumber(); - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveToken.address, - owner, - spender, - nonce, - deadline, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - expect((await aaveToken.allowance(owner, spender)).toString()).to.be.equal( - ethers.utils.parseEther('2'), - 'INVALID_ALLOWANCE_BEFORE_PERMIT' - ); - - await waitForTx( - await aaveToken - .connect(users[1].signer) - .permit(owner, spender, permitAmount, deadline, v, r, s) - ); - expect((await aaveToken.allowance(owner, spender)).toString()).to.be.equal( - permitAmount, - 'INVALID_ALLOWANCE_AFTER_PERMIT' - ); - - expect((await aaveToken._nonces(owner)).toNumber()).to.be.equal(2); - }); - - it('Tries to submit a permit with invalid nonce', async () => { - const {aaveToken, deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const deadline = MAX_UINT_AMOUNT; - const nonce = 1000; - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveToken.address, - owner, - spender, - nonce, - deadline, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveToken.connect(users[1].signer).permit(owner, spender, permitAmount, deadline, v, r, s) - ).to.be.revertedWith('INVALID_SIGNATURE'); - }); - - it('Tries to submit a permit with invalid expiration (previous to the current block)', async () => { - const {aaveToken, deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const expiration = '1'; - const nonce = (await aaveToken._nonces(owner)).toNumber(); - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveToken.address, - owner, - spender, - nonce, - expiration, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveToken.connect(users[1].signer).permit(owner, spender, expiration, permitAmount, v, r, s) - ).to.be.revertedWith('INVALID_EXPIRATION'); - }); - - it('Tries to submit a permit with invalid signature', async () => { - const {aaveToken, deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const deadline = MAX_UINT_AMOUNT; - const nonce = (await aaveToken._nonces(owner)).toNumber(); - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveToken.address, - owner, - spender, - nonce, - deadline, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveToken - .connect(users[1].signer) - .permit(owner, ZERO_ADDRESS, permitAmount, deadline, v, r, s) - ).to.be.revertedWith('INVALID_SIGNATURE'); - }); - - it('Tries to submit a permit with invalid owner', async () => { - const {aaveToken, deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const expiration = MAX_UINT_AMOUNT; - const nonce = (await aaveToken._nonces(owner)).toNumber(); - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveToken.address, - owner, - spender, - nonce, - expiration, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveToken - .connect(users[1].signer) - .permit(ZERO_ADDRESS, spender, expiration, permitAmount, v, r, s) - ).to.be.revertedWith('INVALID_OWNER'); - }); - - it('Correct snapshotting on double action in the same block', async () => { - const {aaveToken, deployer, users} = testEnv; - - const doubleTransferHelper = await deployDoubleTransferHelper(aaveToken.address); - - const receiver = users[2].address; - - await waitForTx( - await aaveToken.transfer( - doubleTransferHelper.address, - (await aaveToken.balanceOf(deployer.address)).toString() - ) - ); - - await waitForTx( - await doubleTransferHelper.doubleSend( - receiver, - ethers.utils.parseEther('0.2'), - ethers.utils.parseEther('0.8') - ) - ); - - const countSnapshotsReceiver = (await aaveToken._countsSnapshots(receiver)).toString(); - - const snapshotReceiver = await aaveToken._snapshots(doubleTransferHelper.address, 0); - - const countSnapshotsSender = ( - await aaveToken._countsSnapshots(doubleTransferHelper.address) - ).toString(); - - expect(countSnapshotsSender).to.be.equal('2', 'INVALID_COUNT_SNAPSHOTS_SENDER'); - const snapshotsSender = [ - await aaveToken._snapshots(doubleTransferHelper.address, 0), - await aaveToken._snapshots(doubleTransferHelper.address, 1), - ]; - - expect(snapshotsSender[0].value.toString()).to.be.equal( - ethers.utils.parseEther('1'), - 'INVALID_SENDER_SNAPSHOT' - ); - expect(snapshotsSender[1].value.toString()).to.be.equal( - ethers.utils.parseEther('0'), - 'INVALID_SENDER_SNAPSHOT' - ); - - expect(countSnapshotsReceiver).to.be.equal('1', 'INVALID_COUNT_SNAPSHOTS_RECEIVER'); - expect(snapshotReceiver.value.toString()).to.be.equal(ethers.utils.parseEther('1')); - }); - - it('Emits correctly mock event of the _beforeTokenTransfer hook', async () => { - const {aaveToken, mockTransferHook, users} = testEnv; - - const recipient = users[2].address; - - await expect(aaveToken.connect(users[1].signer).transfer(recipient, 1)).to.emit( - mockTransferHook, - 'MockHookEvent' - ); - }); - - it("Don't record snapshot when sending funds to itself", async () => { - const {aaveToken, deployer, users} = testEnv; - const from = users[2].address; - const to = from; - await waitForTx( - await aaveToken.connect(users[2].signer).transfer(to, ethers.utils.parseEther('1')) - ); - const fromCountOfSnapshots = await aaveToken._countsSnapshots(from); - const fromLastSnapshot = await aaveToken._snapshots(from, fromCountOfSnapshots.sub(1)); - const fromPreviousSnapshot = await aaveToken._snapshots(from, fromCountOfSnapshots.sub(2)); - - const toCountOfSnapshots = await aaveToken._countsSnapshots(to); - const toSnapshot = await aaveToken._snapshots(to, toCountOfSnapshots.sub(1)); - - expect(fromCountOfSnapshots.toString()).to.be.equal('2', 'INVALID_SNAPSHOT_COUNT'); - expect(fromLastSnapshot.value.toString()).to.be.equal( - '1000000000000000001', - 'INVALID_SNAPSHOT_VALUE' - ); - expect(fromPreviousSnapshot.value.toString()).to.be.equal( - ethers.utils.parseEther('1'), - 'INVALID_SNAPSHOT_VALUE' - ); - - expect(toCountOfSnapshots.toString()).to.be.equal('2', 'INVALID_SNAPSHOT_COUNT'); - expect(toSnapshot.value.toString()).to.be.equal( - '1000000000000000001', - 'INVALID_SNAPSHOT_VALUE' - ); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/aaveTokenV2.spec.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/test/aaveTokenV2.spec.ts deleted file mode 100644 index e4e3a0e1..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/aaveTokenV2.spec.ts +++ /dev/null @@ -1,386 +0,0 @@ -import {fail} from 'assert'; -import {ethers} from 'ethers'; -import BigNumber from 'bignumber.js'; -import {TestEnv, makeSuite} from './helpers/make-suite'; -import {eContractid, ProtocolErrors} from '../helpers/types'; -import {eEthereumNetwork} from '../helpers/types-common'; -import {waitForTx, DRE} from '../helpers/misc-utils'; -import { - getInitializableAdminUpgradeabilityProxy, - buildPermitParams, - getSignatureFromTypedData, - deployDoubleTransferHelper, - deployAaveTokenV2, - getContract, -} from '../helpers/contracts-helpers'; -import { - ZERO_ADDRESS, - MAX_UINT_AMOUNT, - getAaveTokenDomainSeparatorPerNetwork, -} from '../helpers/constants'; -import {AaveTokenV2} from '../types/AaveTokenV2'; -import {parseEther} from 'ethers/lib/utils'; - -const {expect} = require('chai'); - -makeSuite('AAVE token V2', (testEnv: TestEnv) => { - let aaveTokenV2: AaveTokenV2; - - it('Updates the implementation of the AAVE token to V2', async () => { - const {aaveToken, users} = testEnv; - - //getting the proxy contract from the aave token address - const aaveTokenProxy = await getContract( - eContractid.InitializableAdminUpgradeabilityProxy, - aaveToken.address - ); - - const AAVEv2 = await deployAaveTokenV2(); - - const encodedIntialize = AAVEv2.interface.encodeFunctionData('initialize'); - - await aaveTokenProxy - .connect(users[0].signer) - .upgradeToAndCall(AAVEv2.address, encodedIntialize); - - aaveTokenV2 = await getContract(eContractid.AaveTokenV2, aaveTokenProxy.address); - }); - - it('Checks initial configuration', async () => { - expect(await aaveTokenV2.name()).to.be.equal('Aave Token', 'Invalid token name'); - - expect(await aaveTokenV2.symbol()).to.be.equal('AAVE', 'Invalid token symbol'); - - expect((await aaveTokenV2.decimals()).toString()).to.be.equal('18', 'Invalid token decimals'); - }); - - it('Checks the domain separator', async () => { - const network = DRE.network.name; - const DOMAIN_SEPARATOR_ENCODED = getAaveTokenDomainSeparatorPerNetwork( - network as eEthereumNetwork - ); - - const separator = await aaveTokenV2.DOMAIN_SEPARATOR(); - expect(separator).to.be.equal(DOMAIN_SEPARATOR_ENCODED, 'Invalid domain separator'); - }); - - it('Checks the revision', async () => { - const revision = await aaveTokenV2.REVISION(); - - expect(revision.toString()).to.be.equal('2', 'Invalid revision'); - }); - - it('Checks the allocation of the initial AAVE supply', async () => { - const expectedMigratorBalance = new BigNumber(13000000).times(new BigNumber(10).pow(18)); - const expectedlDistributorBalance = new BigNumber(3000000).times(new BigNumber(10).pow(18)); - const {lendToAaveMigrator} = testEnv; - const migratorBalance = await aaveTokenV2.balanceOf(lendToAaveMigrator.address); - const distributorBalance = await aaveTokenV2.balanceOf(testEnv.users[0].address); - - expect(migratorBalance.toString()).to.be.equal( - expectedMigratorBalance.toFixed(0), - 'Invalid migrator balance' - ); - expect(distributorBalance.toString()).to.be.equal( - expectedlDistributorBalance.toFixed(0), - 'Invalid migrator balance' - ); - }); - - it('Starts the migration', async () => { - const {lendToAaveMigrator, lendToAaveMigratorImpl, users} = testEnv; - - const lendToAaveMigratorInitializeEncoded = lendToAaveMigratorImpl.interface.encodeFunctionData( - 'initialize' - ); - - const migratorAsProxy = await getInitializableAdminUpgradeabilityProxy( - lendToAaveMigrator.address - ); - - await migratorAsProxy - .connect(users[0].signer) - .upgradeToAndCall(lendToAaveMigratorImpl.address, lendToAaveMigratorInitializeEncoded); - }); - - it('Reverts submitting a permit with 0 expiration', async () => { - const {deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const expiration = 0; - const nonce = (await aaveTokenV2._nonces(owner)).toNumber(); - const permitAmount = ethers.utils.parseEther('2').toString(); - const msgParams = buildPermitParams( - chainId, - aaveTokenV2.address, - owner, - spender, - nonce, - permitAmount, - expiration.toFixed() - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - expect((await aaveTokenV2.allowance(owner, spender)).toString()).to.be.equal( - '0', - 'INVALID_ALLOWANCE_BEFORE_PERMIT' - ); - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveTokenV2.connect(users[1].signer).permit(owner, spender, permitAmount, expiration, v, r, s) - ).to.be.revertedWith('INVALID_EXPIRATION'); - - expect((await aaveTokenV2.allowance(owner, spender)).toString()).to.be.equal( - '0', - 'INVALID_ALLOWANCE_AFTER_PERMIT' - ); - }); - - it('Submits a permit with maximum expiration length', async () => { - const {deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - const configChainId = DRE.network.config.chainId; - expect(configChainId).to.be.equal(chainId); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const deadline = MAX_UINT_AMOUNT; - const nonce = (await aaveTokenV2._nonces(owner)).toNumber(); - const permitAmount = ethers.utils.parseEther('2').toString(); - const msgParams = buildPermitParams( - chainId, - aaveTokenV2.address, - owner, - spender, - nonce, - deadline, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - expect((await aaveTokenV2.allowance(owner, spender)).toString()).to.be.equal( - '0', - 'INVALID_ALLOWANCE_BEFORE_PERMIT' - ); - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await waitForTx( - await aaveTokenV2 - .connect(users[1].signer) - .permit(owner, spender, permitAmount, deadline, v, r, s) - ); - - expect((await aaveTokenV2._nonces(owner)).toNumber()).to.be.equal(1); - }); - - it('Cancels the previous permit', async () => { - const {deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const deadline = MAX_UINT_AMOUNT; - const nonce = (await aaveTokenV2._nonces(owner)).toNumber(); - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveTokenV2.address, - owner, - spender, - nonce, - deadline, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - expect((await aaveTokenV2.allowance(owner, spender)).toString()).to.be.equal( - ethers.utils.parseEther('2'), - 'INVALID_ALLOWANCE_BEFORE_PERMIT' - ); - - await waitForTx( - await aaveTokenV2 - .connect(users[1].signer) - .permit(owner, spender, permitAmount, deadline, v, r, s) - ); - expect((await aaveTokenV2.allowance(owner, spender)).toString()).to.be.equal( - permitAmount, - 'INVALID_ALLOWANCE_AFTER_PERMIT' - ); - - expect((await aaveTokenV2._nonces(owner)).toNumber()).to.be.equal(2); - }); - - it('Tries to submit a permit with invalid nonce', async () => { - const {deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const deadline = MAX_UINT_AMOUNT; - const nonce = 1000; - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveTokenV2.address, - owner, - spender, - nonce, - deadline, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveTokenV2.connect(users[1].signer).permit(owner, spender, permitAmount, deadline, v, r, s) - ).to.be.revertedWith('INVALID_SIGNATURE'); - }); - - it('Tries to submit a permit with invalid expiration (previous to the current block)', async () => { - const {deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const expiration = '1'; - const nonce = (await aaveTokenV2._nonces(owner)).toNumber(); - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveTokenV2.address, - owner, - spender, - nonce, - expiration, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveTokenV2.connect(users[1].signer).permit(owner, spender, expiration, permitAmount, v, r, s) - ).to.be.revertedWith('INVALID_EXPIRATION'); - }); - - it('Tries to submit a permit with invalid signature', async () => { - const {deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const deadline = MAX_UINT_AMOUNT; - const nonce = (await aaveTokenV2._nonces(owner)).toNumber(); - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveTokenV2.address, - owner, - spender, - nonce, - deadline, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveTokenV2 - .connect(users[1].signer) - .permit(owner, ZERO_ADDRESS, permitAmount, deadline, v, r, s) - ).to.be.revertedWith('INVALID_SIGNATURE'); - }); - - it('Tries to submit a permit with invalid owner', async () => { - const {deployer, users} = testEnv; - const owner = deployer.address; - const spender = users[1].address; - - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const expiration = MAX_UINT_AMOUNT; - const nonce = (await aaveTokenV2._nonces(owner)).toNumber(); - const permitAmount = '0'; - const msgParams = buildPermitParams( - chainId, - aaveTokenV2.address, - owner, - spender, - nonce, - expiration, - permitAmount - ); - - const ownerPrivateKey = require('../test-wallets.js').accounts[0].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - await expect( - aaveTokenV2 - .connect(users[1].signer) - .permit(ZERO_ADDRESS, spender, expiration, permitAmount, v, r, s) - ).to.be.revertedWith('INVALID_OWNER'); - }); - - it('Checks the total supply', async () => { - const totalSupply = await aaveTokenV2.totalSupplyAt('0'); // Supply remains constant due no more mints - expect(totalSupply).equal(parseEther('16000000')); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/delegation.spec.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/test/delegation.spec.ts deleted file mode 100644 index ca579b3b..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/delegation.spec.ts +++ /dev/null @@ -1,1012 +0,0 @@ -import chai, {expect} from 'chai'; -import {fail} from 'assert'; -import {solidity} from 'ethereum-waffle'; -import {TestEnv, makeSuite} from './helpers/make-suite'; -import {ProtocolErrors, eContractid} from '../helpers/types'; -import {DRE, advanceBlock, timeLatest, waitForTx} from '../helpers/misc-utils'; -import { - buildDelegateParams, - buildDelegateByTypeParams, - deployAaveTokenV2, - deployDoubleTransferHelper, - getContract, - getCurrentBlock, - getSignatureFromTypedData, -} from '../helpers/contracts-helpers'; -import {AaveTokenV2} from '../types/AaveTokenV2'; -import {MAX_UINT_AMOUNT, ZERO_ADDRESS} from '../helpers/constants'; -import {parseEther} from 'ethers/lib/utils'; - -chai.use(solidity); - -makeSuite('Delegation', (testEnv: TestEnv) => { - const {} = ProtocolErrors; - let aaveInstance = {} as AaveTokenV2; - let firstActionBlockNumber = 0; - let secondActionBlockNumber = 0; - - it('Updates the implementation of the AAVE token to V2', async () => { - const {aaveToken, users} = testEnv; - - //getting the proxy contract from the aave token address - const aaveTokenProxy = await getContract( - eContractid.InitializableAdminUpgradeabilityProxy, - aaveToken.address - ); - - const AAVEv2 = await deployAaveTokenV2(); - - const encodedIntialize = AAVEv2.interface.encodeFunctionData('initialize'); - - await aaveTokenProxy - .connect(users[0].signer) - .upgradeToAndCall(AAVEv2.address, encodedIntialize); - - aaveInstance = await getContract(eContractid.AaveTokenV2, aaveTokenProxy.address); - }); - - // Blocked by https://github.com/nomiclabs/hardhat/issues/1081 - xit('ZERO_ADDRESS tries to delegate voting power to user1 but delegatee should still be ZERO_ADDRESS', async () => { - const { - users: [, user1], - } = testEnv; - await DRE.network.provider.request({ - method: 'hardhat_impersonateAccount', - params: ['0x0000000000000000000000000000000000000000'], - }); - const zeroUser = await DRE.ethers.provider.getSigner( - '0x0000000000000000000000000000000000000000' - ); - await user1.signer.sendTransaction({to: ZERO_ADDRESS, value: parseEther('1')}); - - await aaveInstance.connect(zeroUser).delegateByType(user1.address, '0'); - - const delegatee = await aaveInstance.getDelegateeByType(ZERO_ADDRESS, '0'); - - expect(delegatee.toString()).to.be.equal(ZERO_ADDRESS); - }); - - it('User 1 tries to delegate voting power to user 2', async () => { - const {users} = testEnv; - - await aaveInstance.connect(users[1].signer).delegateByType(users[2].address, '0'); - - const delegatee = await aaveInstance.getDelegateeByType(users[1].address, '0'); - - expect(delegatee.toString()).to.be.equal(users[2].address); - }); - - it('User 1 tries to delegate proposition power to user 3', async () => { - const {users} = testEnv; - - await aaveInstance.connect(users[1].signer).delegateByType(users[3].address, '1'); - - const delegatee = await aaveInstance.getDelegateeByType(users[1].address, '1'); - - expect(delegatee.toString()).to.be.equal(users[3].address); - }); - - it('Starts the migration', async () => { - const {lendToAaveMigrator, lendToAaveMigratorImpl} = testEnv; - - const lendToAaveMigratorInitializeEncoded = lendToAaveMigratorImpl.interface.encodeFunctionData( - 'initialize' - ); - - const migratorAsProxy = await getContract( - eContractid.InitializableAdminUpgradeabilityProxy, - lendToAaveMigrator.address - ); - - await migratorAsProxy - .connect(testEnv.users[0].signer) - .upgradeToAndCall(lendToAaveMigratorImpl.address, lendToAaveMigratorInitializeEncoded); - }); - - it('User1 tries to delegate voting power to ZERO_ADDRESS', async () => { - const { - users: [, , , , , user], - lendToken, - lendToAaveMigrator, - } = testEnv; - const lendBalance = parseEther('1000'); - const aaveBalance = parseEther('1'); - - // Mint LEND and migrate - await lendToken.connect(user.signer).mint(lendBalance); - await lendToken.connect(user.signer).approve(lendToAaveMigrator.address, lendBalance); - await lendToAaveMigrator.connect(user.signer).migrateFromLEND(lendBalance); - - // Track current power - const priorPowerUser = await aaveInstance.getPowerCurrent(user.address, '0'); - const priorPowerUserZeroAddress = await aaveInstance.getPowerCurrent(ZERO_ADDRESS, '0'); - - await expect( - aaveInstance.connect(user.signer).delegateByType(ZERO_ADDRESS, '0') - ).to.be.revertedWith('INVALID_DELEGATEE'); - }); - - it('User 1 migrates 1000 LEND; checks voting and proposition power of user 2 and 3', async () => { - const {lendToAaveMigrator, lendToken, users} = testEnv; - const user1 = users[1]; - const user2 = users[2]; - const user3 = users[3]; - - const lendBalance = parseEther('1000'); - const expectedAaveBalanceAfterMigration = parseEther('1'); - - await lendToken.connect(user1.signer).mint(lendBalance); - - await lendToken.connect(user1.signer).approve(lendToAaveMigrator.address, lendBalance); - - await lendToAaveMigrator.connect(user1.signer).migrateFromLEND(lendBalance); - - const lendBalanceAfterMigration = await lendToken.balanceOf(user1.address); - const aaveBalanceAfterMigration = await aaveInstance.balanceOf(user1.address); - - firstActionBlockNumber = await getCurrentBlock(); - - const user1PropPower = await aaveInstance.getPowerCurrent(user1.address, '0'); - const user1VotingPower = await aaveInstance.getPowerCurrent(user1.address, '1'); - - const user2VotingPower = await aaveInstance.getPowerCurrent(user2.address, '0'); - const user2PropPower = await aaveInstance.getPowerCurrent(user2.address, '1'); - - const user3VotingPower = await aaveInstance.getPowerCurrent(user3.address, '0'); - const user3PropPower = await aaveInstance.getPowerCurrent(user3.address, '1'); - - expect(user1PropPower.toString()).to.be.equal('0', 'Invalid prop power for user 1'); - expect(user1VotingPower.toString()).to.be.equal('0', 'Invalid voting power for user 1'); - - expect(user2PropPower.toString()).to.be.equal('0', 'Invalid prop power for user 2'); - expect(user2VotingPower.toString()).to.be.equal( - expectedAaveBalanceAfterMigration.toString(), - 'Invalid voting power for user 2' - ); - - expect(user3PropPower.toString()).to.be.equal( - expectedAaveBalanceAfterMigration.toString(), - 'Invalid prop power for user 3' - ); - expect(user3VotingPower.toString()).to.be.equal('0', 'Invalid voting power for user 3'); - - expect(lendBalanceAfterMigration.toString()).to.be.equal('0'); - expect(aaveBalanceAfterMigration.toString()).to.be.equal(expectedAaveBalanceAfterMigration); - }); - - it('User 2 migrates 1000 LEND; checks voting and proposition power of user 2', async () => { - const {lendToAaveMigrator, lendToken, users} = testEnv; - const user2 = users[2]; - - const lendBalance = parseEther('1000'); - const expectedAaveBalanceAfterMigration = parseEther('1'); - - await lendToken.connect(user2.signer).mint(lendBalance); - - await lendToken.connect(user2.signer).approve(lendToAaveMigrator.address, lendBalance); - - await lendToAaveMigrator.connect(user2.signer).migrateFromLEND(lendBalance); - - const user2VotingPower = await aaveInstance.getPowerCurrent(user2.address, '0'); - const user2PropPower = await aaveInstance.getPowerCurrent(user2.address, '1'); - - expect(user2PropPower.toString()).to.be.equal( - expectedAaveBalanceAfterMigration.toString(), - 'Invalid prop power for user 3' - ); - expect(user2VotingPower.toString()).to.be.equal( - expectedAaveBalanceAfterMigration.mul('2').toString(), - 'Invalid voting power for user 3' - ); - }); - - it('User 3 migrates 1000 LEND; checks voting and proposition power of user 3', async () => { - const {lendToAaveMigrator, lendToken, users} = testEnv; - const user3 = users[3]; - - const lendBalance = parseEther('1000'); - const expectedAaveBalanceAfterMigration = parseEther('1'); - - await lendToken.connect(user3.signer).mint(lendBalance); - - await lendToken.connect(user3.signer).approve(lendToAaveMigrator.address, lendBalance); - - await lendToAaveMigrator.connect(user3.signer).migrateFromLEND(lendBalance); - - const user3VotingPower = await aaveInstance.getPowerCurrent(user3.address, '0'); - const user3PropPower = await aaveInstance.getPowerCurrent(user3.address, '1'); - - expect(user3PropPower.toString()).to.be.equal( - expectedAaveBalanceAfterMigration.mul('2').toString(), - 'Invalid prop power for user 3' - ); - expect(user3VotingPower.toString()).to.be.equal( - expectedAaveBalanceAfterMigration.toString(), - 'Invalid voting power for user 3' - ); - }); - - it('User 2 delegates voting and prop power to user 3', async () => { - const {users} = testEnv; - const user2 = users[2]; - const user3 = users[3]; - - const expectedDelegatedVotingPower = parseEther('2'); - const expectedDelegatedPropPower = parseEther('3'); - - await aaveInstance.connect(user2.signer).delegate(user3.address); - - const user3VotingPower = await aaveInstance.getPowerCurrent(user3.address, '0'); - const user3PropPower = await aaveInstance.getPowerCurrent(user3.address, '1'); - - expect(user3VotingPower.toString()).to.be.equal( - expectedDelegatedVotingPower.toString(), - 'Invalid voting power for user 3' - ); - expect(user3PropPower.toString()).to.be.equal( - expectedDelegatedPropPower.toString(), - 'Invalid prop power for user 3' - ); - }); - - it('User 1 removes voting and prop power to user 2 and 3', async () => { - const {users} = testEnv; - const user1 = users[1]; - const user2 = users[2]; - const user3 = users[3]; - - await aaveInstance.connect(user1.signer).delegate(user1.address); - - const user2VotingPower = await aaveInstance.getPowerCurrent(user2.address, '0'); - const user2PropPower = await aaveInstance.getPowerCurrent(user2.address, '1'); - - const user3VotingPower = await aaveInstance.getPowerCurrent(user3.address, '0'); - const user3PropPower = await aaveInstance.getPowerCurrent(user3.address, '1'); - - const expectedUser2DelegatedVotingPower = '0'; - const expectedUser2DelegatedPropPower = '0'; - - const expectedUser3DelegatedVotingPower = parseEther('2'); - const expectedUser3DelegatedPropPower = parseEther('2'); - - expect(user2VotingPower.toString()).to.be.equal( - expectedUser2DelegatedVotingPower.toString(), - 'Invalid voting power for user 3' - ); - expect(user2PropPower.toString()).to.be.equal( - expectedUser2DelegatedPropPower.toString(), - 'Invalid prop power for user 3' - ); - - expect(user3VotingPower.toString()).to.be.equal( - expectedUser3DelegatedVotingPower.toString(), - 'Invalid voting power for user 3' - ); - expect(user3PropPower.toString()).to.be.equal( - expectedUser3DelegatedPropPower.toString(), - 'Invalid prop power for user 3' - ); - }); - - it('Checks the delegation at the block of the first action', async () => { - const {users} = testEnv; - - const user1 = users[1]; - const user2 = users[2]; - const user3 = users[3]; - - const user1VotingPower = await aaveInstance.getPowerAtBlock( - user1.address, - firstActionBlockNumber, - '0' - ); - const user1PropPower = await aaveInstance.getPowerAtBlock( - user1.address, - firstActionBlockNumber, - '1' - ); - - const user2VotingPower = await aaveInstance.getPowerAtBlock( - user2.address, - firstActionBlockNumber, - '0' - ); - const user2PropPower = await aaveInstance.getPowerAtBlock( - user2.address, - firstActionBlockNumber, - '1' - ); - - const user3VotingPower = await aaveInstance.getPowerAtBlock( - user3.address, - firstActionBlockNumber, - '0' - ); - const user3PropPower = await aaveInstance.getPowerAtBlock( - user3.address, - firstActionBlockNumber, - '1' - ); - - const expectedUser1DelegatedVotingPower = '0'; - const expectedUser1DelegatedPropPower = '0'; - - const expectedUser2DelegatedVotingPower = parseEther('1'); - const expectedUser2DelegatedPropPower = '0'; - - const expectedUser3DelegatedVotingPower = '0'; - const expectedUser3DelegatedPropPower = parseEther('1'); - - expect(user1VotingPower.toString()).to.be.equal( - expectedUser1DelegatedPropPower, - 'Invalid voting power for user 1' - ); - expect(user1PropPower.toString()).to.be.equal( - expectedUser1DelegatedVotingPower, - 'Invalid prop power for user 1' - ); - - expect(user2VotingPower.toString()).to.be.equal( - expectedUser2DelegatedVotingPower, - 'Invalid voting power for user 2' - ); - expect(user2PropPower.toString()).to.be.equal( - expectedUser2DelegatedPropPower, - 'Invalid prop power for user 2' - ); - - expect(user3VotingPower.toString()).to.be.equal( - expectedUser3DelegatedVotingPower, - 'Invalid voting power for user 3' - ); - expect(user3PropPower.toString()).to.be.equal( - expectedUser3DelegatedPropPower, - 'Invalid prop power for user 3' - ); - }); - - it('Ensure that getting the power at the current block is the same as using getPowerCurrent', async () => { - const {users} = testEnv; - - const user1 = users[1]; - - const currTime = await timeLatest(); - - await advanceBlock(currTime.toNumber() + 1); - - const currentBlock = await getCurrentBlock(); - - const votingPowerAtPreviousBlock = await aaveInstance.getPowerAtBlock( - user1.address, - currentBlock - 1, - '0' - ); - const votingPowerCurrent = await aaveInstance.getPowerCurrent(user1.address, '0'); - - const propPowerAtPreviousBlock = await aaveInstance.getPowerAtBlock( - user1.address, - currentBlock - 1, - '1' - ); - const propPowerCurrent = await aaveInstance.getPowerCurrent(user1.address, '1'); - - expect(votingPowerAtPreviousBlock.toString()).to.be.equal( - votingPowerCurrent.toString(), - 'Invalid voting power for user 1' - ); - expect(propPowerAtPreviousBlock.toString()).to.be.equal( - propPowerCurrent.toString(), - 'Invalid voting power for user 1' - ); - }); - - it("Checks you can't fetch power at a block in the future", async () => { - const {users} = testEnv; - - const user1 = users[1]; - - const currentBlock = await getCurrentBlock(); - - await expect( - aaveInstance.getPowerAtBlock(user1.address, currentBlock + 1, '0') - ).to.be.revertedWith('INVALID_BLOCK_NUMBER'); - await expect( - aaveInstance.getPowerAtBlock(user1.address, currentBlock + 1, '1') - ).to.be.revertedWith('INVALID_BLOCK_NUMBER'); - }); - - it('User 1 transfers value to himself. Ensures nothing changes in the delegated power', async () => { - const {users} = testEnv; - - const user1 = users[1]; - - const user1VotingPowerBefore = await aaveInstance.getPowerCurrent(user1.address, '0'); - const user1PropPowerBefore = await aaveInstance.getPowerCurrent(user1.address, '1'); - - const balance = await aaveInstance.balanceOf(user1.address); - - await aaveInstance.connect(user1.signer).transfer(user1.address, balance); - - const user1VotingPowerAfter = await aaveInstance.getPowerCurrent(user1.address, '0'); - const user1PropPowerAfter = await aaveInstance.getPowerCurrent(user1.address, '1'); - - expect(user1VotingPowerBefore.toString()).to.be.equal( - user1VotingPowerAfter, - 'Invalid voting power for user 1' - ); - expect(user1PropPowerBefore.toString()).to.be.equal( - user1PropPowerAfter, - 'Invalid prop power for user 1' - ); - }); - it('User 1 delegates voting power to User 2 via signature', async () => { - const { - users: [, user1, user2], - } = testEnv; - - // Calculate expected voting power - const user2VotPower = await aaveInstance.getPowerCurrent(user2.address, '1'); - const expectedVotingPower = (await aaveInstance.getPowerCurrent(user1.address, '1')).add( - user2VotPower - ); - - // Check prior delegatee is still user1 - const priorDelegatee = await aaveInstance.getDelegateeByType(user1.address, '0'); - expect(priorDelegatee.toString()).to.be.equal(user1.address); - - // Prepare params to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const nonce = (await aaveInstance._nonces(user1.address)).toString(); - const expiration = MAX_UINT_AMOUNT; - const msgParams = buildDelegateByTypeParams( - chainId, - aaveInstance.address, - user2.address, - '0', - nonce, - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[2].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit message via delegateByTypeBySig - const tx = await aaveInstance - .connect(user1.signer) - .delegateByTypeBySig(user2.address, '0', nonce, expiration, v, r, s); - - // Check tx success and DelegateChanged - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegateChanged') - .withArgs(user1.address, user2.address, 0); - - // Check DelegatedPowerChanged event: users[1] power should drop to zero - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegatedPowerChanged') - .withArgs(user1.address, 0, 0); - - // Check DelegatedPowerChanged event: users[2] power should increase to expectedVotingPower - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegatedPowerChanged') - .withArgs(user2.address, expectedVotingPower, 0); - - // Check internal state - const delegatee = await aaveInstance.getDelegateeByType(user1.address, '0'); - expect(delegatee.toString()).to.be.equal(user2.address, 'Delegatee should be user 2'); - - const user2VotingPower = await aaveInstance.getPowerCurrent(user2.address, '0'); - expect(user2VotingPower).to.be.equal( - expectedVotingPower, - 'Delegatee should have voting power from user 1' - ); - }); - - it('User 1 delegates proposition to User 3 via signature', async () => { - const { - users: [, user1, , user3], - } = testEnv; - - // Calculate expected proposition power - const user3PropPower = await aaveInstance.getPowerCurrent(user3.address, '1'); - const expectedPropPower = (await aaveInstance.getPowerCurrent(user1.address, '1')).add( - user3PropPower - ); - - // Check prior proposition delegatee is still user1 - const priorDelegatee = await aaveInstance.getDelegateeByType(user1.address, '1'); - expect(priorDelegatee.toString()).to.be.equal( - user1.address, - 'expected proposition delegatee to be user1' - ); - - // Prepare parameters to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const nonce = (await aaveInstance._nonces(user1.address)).toString(); - const expiration = MAX_UINT_AMOUNT; - const msgParams = buildDelegateByTypeParams( - chainId, - aaveInstance.address, - user3.address, - '1', - nonce, - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[2].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit tx via delegateByTypeBySig - const tx = await aaveInstance - .connect(user1.signer) - .delegateByTypeBySig(user3.address, '1', nonce, expiration, v, r, s); - - // Check tx success and DelegateChanged - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegateChanged') - .withArgs(user1.address, user3.address, 1); - - // Check DelegatedPowerChanged event: users[1] power should drop to zero - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegatedPowerChanged') - .withArgs(user1.address, 0, 1); - - // Check DelegatedPowerChanged event: users[2] power should increase to expectedVotingPower - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegatedPowerChanged') - .withArgs(user3.address, expectedPropPower, 1); - - // Check internal state matches events - const delegatee = await aaveInstance.getDelegateeByType(user1.address, '1'); - expect(delegatee.toString()).to.be.equal(user3.address, 'Delegatee should be user 3'); - - const user3PropositionPower = await aaveInstance.getPowerCurrent(user3.address, '1'); - expect(user3PropositionPower).to.be.equal( - expectedPropPower, - 'Delegatee should have propostion power from user 1' - ); - - // Save current block - secondActionBlockNumber = await getCurrentBlock(); - }); - - it('User 2 delegates all to User 4 via signature', async () => { - const { - users: [, user1, user2, , user4], - } = testEnv; - - await aaveInstance.connect(user2.signer).delegate(user2.address); - - // Calculate expected powers - const user4PropPower = await aaveInstance.getPowerCurrent(user4.address, '1'); - const expectedPropPower = (await aaveInstance.getPowerCurrent(user2.address, '1')).add( - user4PropPower - ); - - const user1VotingPower = await aaveInstance.balanceOf(user1.address); - const user4VotPower = await aaveInstance.getPowerCurrent(user4.address, '0'); - const user2ExpectedVotPower = user1VotingPower; - const user4ExpectedVotPower = (await aaveInstance.getPowerCurrent(user2.address, '0')) - .add(user4VotPower) - .sub(user1VotingPower); // Delegation does not delegate votes others from other delegations - - // Check prior proposition delegatee is still user1 - const priorPropDelegatee = await aaveInstance.getDelegateeByType(user2.address, '1'); - expect(priorPropDelegatee.toString()).to.be.equal( - user2.address, - 'expected proposition delegatee to be user1' - ); - - const priorVotDelegatee = await aaveInstance.getDelegateeByType(user2.address, '0'); - expect(priorVotDelegatee.toString()).to.be.equal( - user2.address, - 'expected proposition delegatee to be user1' - ); - - // Prepare parameters to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const nonce = (await aaveInstance._nonces(user2.address)).toString(); - const expiration = MAX_UINT_AMOUNT; - const msgParams = buildDelegateParams( - chainId, - aaveInstance.address, - user4.address, - nonce, - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[3].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit tx via delegateByTypeBySig - const tx = await aaveInstance - .connect(user2.signer) - .delegateBySig(user4.address, nonce, expiration, v, r, s); - - // Check tx success and DelegateChanged for voting - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegateChanged') - .withArgs(user2.address, user4.address, 1); - // Check tx success and DelegateChanged for proposition - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegateChanged') - .withArgs(user2.address, user4.address, 0); - - // Check DelegatedPowerChanged event: users[2] power should drop to zero - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegatedPowerChanged') - .withArgs(user2.address, 0, 1); - - // Check DelegatedPowerChanged event: users[4] power should increase to expectedVotingPower - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegatedPowerChanged') - .withArgs(user4.address, expectedPropPower, 1); - - // Check DelegatedPowerChanged event: users[2] power should drop to zero - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegatedPowerChanged') - .withArgs(user2.address, user2ExpectedVotPower, 0); - - // Check DelegatedPowerChanged event: users[4] power should increase to expectedVotingPower - await expect(Promise.resolve(tx)) - .to.emit(aaveInstance, 'DelegatedPowerChanged') - .withArgs(user4.address, user4ExpectedVotPower, 0); - - // Check internal state matches events - const propDelegatee = await aaveInstance.getDelegateeByType(user2.address, '1'); - expect(propDelegatee.toString()).to.be.equal( - user4.address, - 'Proposition delegatee should be user 4' - ); - - const votDelegatee = await aaveInstance.getDelegateeByType(user2.address, '0'); - expect(votDelegatee.toString()).to.be.equal(user4.address, 'Voting delegatee should be user 4'); - - const user4PropositionPower = await aaveInstance.getPowerCurrent(user4.address, '1'); - expect(user4PropositionPower).to.be.equal( - expectedPropPower, - 'Delegatee should have propostion power from user 2' - ); - const user4VotingPower = await aaveInstance.getPowerCurrent(user4.address, '0'); - expect(user4VotingPower).to.be.equal( - user4ExpectedVotPower, - 'Delegatee should have votinh power from user 2' - ); - - const user2PropositionPower = await aaveInstance.getPowerCurrent(user2.address, '1'); - expect(user2PropositionPower).to.be.equal('0', 'User 2 should have zero prop power'); - const user2VotingPower = await aaveInstance.getPowerCurrent(user2.address, '0'); - expect(user2VotingPower).to.be.equal( - user2ExpectedVotPower, - 'User 2 should still have voting power from user 1 delegation' - ); - }); - - it('User 1 should not be able to delegate with bad signature', async () => { - const { - users: [, user1, user2], - } = testEnv; - - // Prepare params to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const nonce = (await aaveInstance._nonces(user1.address)).toString(); - const expiration = MAX_UINT_AMOUNT; - const msgParams = buildDelegateByTypeParams( - chainId, - aaveInstance.address, - user2.address, - '0', - nonce, - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[1].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit message via delegateByTypeBySig - await expect( - aaveInstance - .connect(user1.signer) - .delegateByTypeBySig(user2.address, '0', nonce, expiration, 0, r, s) - ).to.be.revertedWith('INVALID_SIGNATURE'); - }); - - it('User 1 should not be able to delegate with bad nonce', async () => { - const { - users: [, user1, user2], - } = testEnv; - - // Prepare params to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const expiration = MAX_UINT_AMOUNT; - const msgParams = buildDelegateByTypeParams( - chainId, - aaveInstance.address, - user2.address, - '0', - MAX_UINT_AMOUNT, // bad nonce - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[1].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit message via delegateByTypeBySig - await expect( - aaveInstance - .connect(user1.signer) - .delegateByTypeBySig(user2.address, '0', MAX_UINT_AMOUNT, expiration, v, r, s) - ).to.be.revertedWith('INVALID_NONCE'); - }); - - it('User 1 should not be able to delegate if signature expired', async () => { - const { - users: [, user1, user2], - } = testEnv; - - // Prepare params to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const nonce = (await aaveInstance._nonces(user1.address)).toString(); - const expiration = '0'; - const msgParams = buildDelegateByTypeParams( - chainId, - aaveInstance.address, - user2.address, - '0', - nonce, - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[2].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit message via delegateByTypeBySig - await expect( - aaveInstance - .connect(user1.signer) - .delegateByTypeBySig(user2.address, '0', nonce, expiration, v, r, s) - ).to.be.revertedWith('INVALID_EXPIRATION'); - }); - - it('User 2 should not be able to delegate all with bad signature', async () => { - const { - users: [, , user2, , user4], - } = testEnv; - // Prepare parameters to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const nonce = (await aaveInstance._nonces(user2.address)).toString(); - const expiration = MAX_UINT_AMOUNT; - const msgParams = buildDelegateParams( - chainId, - aaveInstance.address, - user4.address, - nonce, - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[3].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit tx via delegateBySig - await expect( - aaveInstance.connect(user2.signer).delegateBySig(user4.address, nonce, expiration, '0', r, s) - ).to.be.revertedWith('INVALID_SIGNATURE'); - }); - - it('User 2 should not be able to delegate all with bad nonce', async () => { - const { - users: [, , user2, , user4], - } = testEnv; - // Prepare parameters to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const nonce = MAX_UINT_AMOUNT; - const expiration = MAX_UINT_AMOUNT; - const msgParams = buildDelegateParams( - chainId, - aaveInstance.address, - user4.address, - nonce, - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[3].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit tx via delegateByTypeBySig - await expect( - aaveInstance.connect(user2.signer).delegateBySig(user4.address, nonce, expiration, v, r, s) - ).to.be.revertedWith('INVALID_NONCE'); - }); - - it('User 2 should not be able to delegate all if signature expired', async () => { - const { - users: [, , user2, , user4], - } = testEnv; - // Prepare parameters to sign message - const {chainId} = await DRE.ethers.provider.getNetwork(); - if (!chainId) { - fail("Current network doesn't have CHAIN ID"); - } - const nonce = (await aaveInstance._nonces(user2.address)).toString(); - const expiration = '0'; - const msgParams = buildDelegateParams( - chainId, - aaveInstance.address, - user4.address, - nonce, - expiration - ); - const ownerPrivateKey = require('../test-wallets.js').accounts[3].secretKey; - if (!ownerPrivateKey) { - throw new Error('INVALID_OWNER_PK'); - } - const {v, r, s} = getSignatureFromTypedData(ownerPrivateKey, msgParams); - - // Transmit tx via delegateByTypeBySig - await expect( - aaveInstance.connect(user2.signer).delegateBySig(user4.address, nonce, expiration, v, r, s) - ).to.be.revertedWith('INVALID_EXPIRATION'); - }); - - it('Checks the delegation at the block of the second saved action', async () => { - const {users} = testEnv; - - const user1 = users[1]; - const user2 = users[2]; - const user3 = users[3]; - - const user1VotingPower = await aaveInstance.getPowerAtBlock( - user1.address, - secondActionBlockNumber, - '0' - ); - const user1PropPower = await aaveInstance.getPowerAtBlock( - user1.address, - secondActionBlockNumber, - '1' - ); - - const user2VotingPower = await aaveInstance.getPowerAtBlock( - user2.address, - secondActionBlockNumber, - '0' - ); - const user2PropPower = await aaveInstance.getPowerAtBlock( - user2.address, - secondActionBlockNumber, - '1' - ); - - const user3VotingPower = await aaveInstance.getPowerAtBlock( - user3.address, - secondActionBlockNumber, - '0' - ); - const user3PropPower = await aaveInstance.getPowerAtBlock( - user3.address, - secondActionBlockNumber, - '1' - ); - - const expectedUser1DelegatedVotingPower = '0'; - const expectedUser1DelegatedPropPower = '0'; - - const expectedUser2DelegatedVotingPower = parseEther('1'); - const expectedUser2DelegatedPropPower = '0'; - - const expectedUser3DelegatedVotingPower = parseEther('2'); - const expectedUser3DelegatedPropPower = parseEther('3'); - - expect(user1VotingPower.toString()).to.be.equal( - expectedUser1DelegatedPropPower, - 'Invalid voting power for user 1' - ); - expect(user1PropPower.toString()).to.be.equal( - expectedUser1DelegatedVotingPower, - 'Invalid prop power for user 1' - ); - - expect(user2VotingPower.toString()).to.be.equal( - expectedUser2DelegatedVotingPower, - 'Invalid voting power for user 2' - ); - expect(user2PropPower.toString()).to.be.equal( - expectedUser2DelegatedPropPower, - 'Invalid prop power for user 2' - ); - - expect(user3VotingPower.toString()).to.be.equal( - expectedUser3DelegatedVotingPower, - 'Invalid voting power for user 3' - ); - expect(user3PropPower.toString()).to.be.equal( - expectedUser3DelegatedPropPower, - 'Invalid prop power for user 3' - ); - }); - - it('Correct proposal and voting snapshotting on double action in the same block', async () => { - const { - users: [, user1, receiver], - } = testEnv; - - // Reset delegations - await aaveInstance.connect(user1.signer).delegate(user1.address); - await aaveInstance.connect(receiver.signer).delegate(receiver.address); - - const user1PriorBalance = await aaveInstance.balanceOf(user1.address); - const receiverPriorPower = await aaveInstance.getPowerCurrent(receiver.address, '0'); - const user1PriorPower = await aaveInstance.getPowerCurrent(user1.address, '0'); - - // Deploy double transfer helper - const doubleTransferHelper = await deployDoubleTransferHelper(aaveInstance.address); - - await waitForTx( - await aaveInstance - .connect(user1.signer) - .transfer(doubleTransferHelper.address, user1PriorBalance) - ); - - // Do double transfer - await waitForTx( - await doubleTransferHelper - .connect(user1.signer) - .doubleSend(receiver.address, user1PriorBalance.sub(parseEther('1')), parseEther('1')) - ); - - const receiverCurrentPower = await aaveInstance.getPowerCurrent(receiver.address, '0'); - const user1CurrentPower = await aaveInstance.getPowerCurrent(user1.address, '0'); - - expect(receiverCurrentPower).to.be.equal( - user1PriorPower.add(receiverPriorPower), - 'Receiver should have added the user1 power after double transfer' - ); - expect(user1CurrentPower).to.be.equal( - '0', - 'User1 power should be zero due transfered all the funds' - ); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/helpers/make-suite.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/test/helpers/make-suite.ts deleted file mode 100644 index 56ae73b6..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/helpers/make-suite.ts +++ /dev/null @@ -1,85 +0,0 @@ -import {evmRevert, evmSnapshot, DRE} from '../../helpers/misc-utils'; -import {Signer} from 'ethers'; -import { - getEthersSigners, - getAaveToken, - getLendToken, - getLendToAaveMigrator, - getLendToAaveMigratorImpl, - getMockTransferHook, -} from '../../helpers/contracts-helpers'; -import {tEthereumAddress} from '../../helpers/types'; - -import chai from 'chai'; -// @ts-ignore -import bignumberChai from 'chai-bignumber'; -import {AaveToken} from '../../types/AaveToken'; -import {LendToAaveMigrator} from '../../types/LendToAaveMigrator'; -import {MintableErc20} from '../../types/MintableErc20'; -import {MockTransferHook} from '../../types/MockTransferHook'; - -chai.use(bignumberChai()); - -export interface SignerWithAddress { - signer: Signer; - address: tEthereumAddress; -} -export interface TestEnv { - deployer: SignerWithAddress; - users: SignerWithAddress[]; - aaveToken: AaveToken; - lendToken: MintableErc20; - lendToAaveMigrator: LendToAaveMigrator; - lendToAaveMigratorImpl: LendToAaveMigrator; - mockTransferHook: MockTransferHook; -} - -let buidlerevmSnapshotId: string = '0x1'; -const setBuidlerevmSnapshotId = (id: string) => { - if (DRE.network.name === 'hardhat') { - buidlerevmSnapshotId = id; - } -}; - -const testEnv: TestEnv = { - deployer: {} as SignerWithAddress, - users: [] as SignerWithAddress[], - aaveToken: {} as AaveToken, - lendToken: {} as MintableErc20, - lendToAaveMigrator: {} as LendToAaveMigrator, - lendToAaveMigratorImpl: {} as LendToAaveMigrator, - mockTransferHook: {} as MockTransferHook, -} as TestEnv; - -export async function initializeMakeSuite() { - const [_deployer, ...restSigners] = await getEthersSigners(); - const deployer: SignerWithAddress = { - address: await _deployer.getAddress(), - signer: _deployer, - }; - - for (const signer of restSigners) { - testEnv.users.push({ - signer, - address: await signer.getAddress(), - }); - } - testEnv.deployer = deployer; - testEnv.aaveToken = await getAaveToken(); - testEnv.lendToAaveMigrator = await getLendToAaveMigrator(); - testEnv.lendToken = await getLendToken(); - testEnv.lendToAaveMigratorImpl = await getLendToAaveMigratorImpl(); - testEnv.mockTransferHook = await getMockTransferHook(); -} - -export function makeSuite(name: string, tests: (testEnv: TestEnv) => void) { - describe(name, () => { - before(async () => { - setBuidlerevmSnapshotId(await evmSnapshot()); - }); - tests(testEnv); - after(async () => { - await evmRevert(buidlerevmSnapshotId); - }); - }); -} diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/migrator.spec.ts b/CVLByExample/aave-token-v3/lib/aave-token-v2/test/migrator.spec.ts deleted file mode 100644 index 0b2e57a8..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/test/migrator.spec.ts +++ /dev/null @@ -1,74 +0,0 @@ -import rawBRE from 'hardhat'; -import {expect} from 'chai'; -import {TestEnv, makeSuite} from './helpers/make-suite'; -import {ProtocolErrors, eContractid} from '../helpers/types'; -import {getContract} from '../helpers/contracts-helpers'; -import BigNumber from 'bignumber.js'; - -makeSuite('LEND migrator', (testEnv: TestEnv) => { - const {} = ProtocolErrors; - - it('Check the constructor is executed properly', async () => { - const {lendToAaveMigrator, aaveToken, lendToken} = testEnv; - - expect(await lendToAaveMigrator.AAVE()).to.be.equal(aaveToken.address, 'Invalid AAVE Address'); - - expect(await lendToAaveMigrator.LEND()).to.be.equal(lendToken.address, 'Invalid LEND address'); - - expect(await lendToAaveMigrator.LEND_AAVE_RATIO()).to.be.equal('1000', 'Invalid ratio'); - }); - - it("Check migration isn't started", async () => { - const {lendToAaveMigrator, lendToAaveMigratorImpl} = testEnv; - - const migrationStarted = await lendToAaveMigrator.migrationStarted(); - - expect(migrationStarted.toString()).to.be.eq('false'); - await expect(lendToAaveMigrator.migrateFromLEND('1000')).to.be.revertedWith( - 'MIGRATION_NOT_STARTED' - ); - }); - - it('Starts the migration', async () => { - const {lendToAaveMigrator, lendToAaveMigratorImpl} = testEnv; - - const lendToAaveMigratorInitializeEncoded = lendToAaveMigratorImpl.interface.encodeFunctionData( - 'initialize' - ); - - const migratorAsProxy = await getContract( - eContractid.InitializableAdminUpgradeabilityProxy, - lendToAaveMigrator.address - ); - - await migratorAsProxy - .connect(testEnv.users[0].signer) - .upgradeToAndCall(lendToAaveMigratorImpl.address, lendToAaveMigratorInitializeEncoded); - - const migrationStarted = await lendToAaveMigrator.migrationStarted(); - - expect(migrationStarted.toString()).to.be.eq('true'); - }); - - it('Migrates 1000 LEND', async () => { - const {lendToAaveMigrator, lendToken, aaveToken} = testEnv; - const user = testEnv.users[2]; - - const lendBalance = new BigNumber(1000).times(new BigNumber(10).pow(18)).toFixed(0); - const expectedAaveBalanceAfterMigration = new BigNumber(10).pow(18); - - await lendToken.connect(user.signer).mint(lendBalance); - - await lendToken.connect(user.signer).approve(lendToAaveMigrator.address, lendBalance); - - await lendToAaveMigrator.connect(user.signer).migrateFromLEND(lendBalance); - - const lendBalanceAfterMigration = await lendToken.balanceOf(user.address); - const aaveBalanceAfterMigration = await aaveToken.balanceOf(user.address); - - expect(lendBalanceAfterMigration.toString()).to.be.eq('0'); - expect(aaveBalanceAfterMigration.toString()).to.be.eq( - expectedAaveBalanceAfterMigration.toFixed(0) - ); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/aave-token-v2/tsconfig.json b/CVLByExample/aave-token-v3/lib/aave-token-v2/tsconfig.json deleted file mode 100644 index 8d2bf2a2..00000000 --- a/CVLByExample/aave-token-v3/lib/aave-token-v2/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ - { - "compilerOptions": { - "target": "es5", - "module": "commonjs", - "strict": true, - "esModuleInterop": true, - "outDir": "dist", - "resolveJsonModule": true - }, - "include": ["./scripts", "./test"], - "files": ["./hardhat.config.ts"] - } \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/forge-std/.github/workflows/tests.yml b/CVLByExample/aave-token-v3/lib/forge-std/.github/workflows/tests.yml deleted file mode 100644 index 08ab66e9..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/.github/workflows/tests.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Tests -on: [push, pull_request] - -jobs: - check: - name: Foundry project - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - submodules: recursive - - - name: Install Foundry - uses: onbjerg/foundry-toolchain@v1 - with: - version: nightly - - - name: Install dependencies - run: forge install - - name: Run tests - run: forge test -vvv - - name: Build Test with older solc versions - run: | - forge build --contracts src/Test.sol --use solc:0.8.0 - forge build --contracts src/Test.sol --use solc:0.7.0 - forge build --contracts src/Test.sol --use solc:0.6.0 diff --git a/CVLByExample/aave-token-v3/lib/forge-std/.gitignore b/CVLByExample/aave-token-v3/lib/forge-std/.gitignore deleted file mode 100644 index d8a1d071..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -cache/ -out/ diff --git a/CVLByExample/aave-token-v3/lib/forge-std/.gitmodules b/CVLByExample/aave-token-v3/lib/forge-std/.gitmodules deleted file mode 100644 index e1247196..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "lib/ds-test"] - path = lib/ds-test - url = https://github.com/dapphub/ds-test diff --git a/CVLByExample/aave-token-v3/lib/forge-std/LICENSE-APACHE b/CVLByExample/aave-token-v3/lib/forge-std/LICENSE-APACHE deleted file mode 100644 index 83000445..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/LICENSE-APACHE +++ /dev/null @@ -1,203 +0,0 @@ -Copyright (c) 2021 Brock Elmore - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/CVLByExample/aave-token-v3/lib/forge-std/LICENSE-MIT b/CVLByExample/aave-token-v3/lib/forge-std/LICENSE-MIT deleted file mode 100644 index 3bbce32e..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2021 Brock Elmore - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE O THE USE OR OTHER -DEALINGS IN THE SOFTWARE.R diff --git a/CVLByExample/aave-token-v3/lib/forge-std/README.md b/CVLByExample/aave-token-v3/lib/forge-std/README.md deleted file mode 100644 index 2cf73384..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/README.md +++ /dev/null @@ -1,246 +0,0 @@ -# Forge Standard Library • [![tests](https://github.com/brockelmore/forge-std/actions/workflows/tests.yml/badge.svg)](https://github.com/brockelmore/forge-std/actions/workflows/tests.yml) - -Forge Standard Library is a collection of helpful contracts for use with [`forge` and `foundry`](https://github.com/foundry-rs/foundry). It leverages `forge`'s cheatcodes to make writing tests easier and faster, while improving the UX of cheatcodes. - -**Learn how to use Forge Std with the [📖 Foundry Book (Forge Std Guide)](https://book.getfoundry.sh/forge/forge-std.html).** - -## Install - -```bash -forge install foundry-rs/forge-std -``` - -## Contracts -### stdError - -This is a helper contract for errors and reverts. In `forge`, this contract is particularly helpful for the `expectRevert` cheatcode, as it provides all compiler builtin errors. - -See the contract itself for all error codes. - -#### Example usage - -```solidity - -import "forge-std/Test.sol"; - -contract TestContract is Test { - ErrorsTest test; - - function setUp() public { - test = new ErrorsTest(); - } - - function testExpectArithmetic() public { - vm.expectRevert(stdError.arithmeticError); - test.arithmeticError(10); - } -} - -contract ErrorsTest { - function arithmeticError(uint256 a) public { - uint256 a = a - 100; - } -} -``` - -### stdStorage - -This is a rather large contract due to all of the overloading to make the UX decent. Primarily, it is a wrapper around the `record` and `accesses` cheatcodes. It can *always* find and write the storage slot(s) associated with a particular variable without knowing the storage layout. The one _major_ caveat to this is while a slot can be found for packed storage variables, we can't write to that variable safely. If a user tries to write to a packed slot, the execution throws an error, unless it is uninitialized (`bytes32(0)`). - -This works by recording all `SLOAD`s and `SSTORE`s during a function call. If there is a single slot read or written to, it immediately returns the slot. Otherwise, behind the scenes, we iterate through and check each one (assuming the user passed in a `depth` parameter). If the variable is a struct, you can pass in a `depth` parameter which is basically the field depth. - -I.e.: -```solidity -struct T { - // depth 0 - uint256 a; - // depth 1 - uint256 b; -} -``` - -#### Example usage - -```solidity -import "forge-std/Test.sol"; - -contract TestContract is Test { - using stdStorage for StdStorage; - - Storage test; - - function setUp() public { - test = new Storage(); - } - - function testFindExists() public { - // Lets say we want to find the slot for the public - // variable `exists`. We just pass in the function selector - // to the `find` command - uint256 slot = stdstore.target(address(test)).sig("exists()").find(); - assertEq(slot, 0); - } - - function testWriteExists() public { - // Lets say we want to write to the slot for the public - // variable `exists`. We just pass in the function selector - // to the `checked_write` command - stdstore.target(address(test)).sig("exists()").checked_write(100); - assertEq(test.exists(), 100); - } - - // It supports arbitrary storage layouts, like assembly based storage locations - function testFindHidden() public { - // `hidden` is a random hash of a bytes, iteration through slots would - // not find it. Our mechanism does - // Also, you can use the selector instead of a string - uint256 slot = stdstore.target(address(test)).sig(test.hidden.selector).find(); - assertEq(slot, uint256(keccak256("my.random.var"))); - } - - // If targeting a mapping, you have to pass in the keys necessary to perform the find - // i.e.: - function testFindMapping() public { - uint256 slot = stdstore - .target(address(test)) - .sig(test.map_addr.selector) - .with_key(address(this)) - .find(); - // in the `Storage` constructor, we wrote that this address' value was 1 in the map - // so when we load the slot, we expect it to be 1 - assertEq(uint(vm.load(address(test), bytes32(slot))), 1); - } - - // If the target is a struct, you can specify the field depth: - function testFindStruct() public { - // NOTE: see the depth parameter - 0 means 0th field, 1 means 1st field, etc. - uint256 slot_for_a_field = stdstore - .target(address(test)) - .sig(test.basicStruct.selector) - .depth(0) - .find(); - - uint256 slot_for_b_field = stdstore - .target(address(test)) - .sig(test.basicStruct.selector) - .depth(1) - .find(); - - assertEq(uint(vm.load(address(test), bytes32(slot_for_a_field))), 1); - assertEq(uint(vm.load(address(test), bytes32(slot_for_b_field))), 2); - } -} - -// A complex storage contract -contract Storage { - struct UnpackedStruct { - uint256 a; - uint256 b; - } - - constructor() { - map_addr[msg.sender] = 1; - } - - uint256 public exists = 1; - mapping(address => uint256) public map_addr; - // mapping(address => Packed) public map_packed; - mapping(address => UnpackedStruct) public map_struct; - mapping(address => mapping(address => uint256)) public deep_map; - mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct; - UnpackedStruct public basicStruct = UnpackedStruct({ - a: 1, - b: 2 - }); - - function hidden() public view returns (bytes32 t) { - // an extremely hidden storage slot - bytes32 slot = keccak256("my.random.var"); - assembly { - t := sload(slot) - } - } -} -``` - -### stdCheats - -This is a wrapper over miscellaneous cheatcodes that need wrappers to be more dev friendly. Currently there are only functions related to `prank`. In general, users may expect ETH to be put into an address on `prank`, but this is not the case for safety reasons. Explicitly this `hoax` function should only be used for address that have expected balances as it will get overwritten. If an address already has ETH, you should just use `prank`. If you want to change that balance explicitly, just use `deal`. If you want to do both, `hoax` is also right for you. - - -#### Example usage: -```solidity - -// SPDX-License-Identifier: Unlicense -pragma solidity ^0.8.0; - -import "forge-std/Test.sol"; - -// Inherit the stdCheats -contract StdCheatsTest is Test { - Bar test; - function setUp() public { - test = new Bar(); - } - - function testHoax() public { - // we call `hoax`, which gives the target address - // eth and then calls `prank` - hoax(address(1337)); - test.bar{value: 100}(address(1337)); - - // overloaded to allow you to specify how much eth to - // initialize the address with - hoax(address(1337), 1); - test.bar{value: 1}(address(1337)); - } - - function testStartHoax() public { - // we call `startHoax`, which gives the target address - // eth and then calls `startPrank` - // - // it is also overloaded so that you can specify an eth amount - startHoax(address(1337)); - test.bar{value: 100}(address(1337)); - test.bar{value: 100}(address(1337)); - vm.stopPrank(); - test.bar(address(this)); - } -} - -contract Bar { - function bar(address expectedSender) public payable { - require(msg.sender == expectedSender, "!prank"); - } -} -``` - -### Std Assertions - -Expand upon the assertion functions from the `DSTest` library. - -### `console.log` - -Usage follows the same format as [Hardhat](https://hardhat.org/hardhat-network/reference/#console-log). -It's recommended to use `console2.sol` as shown below, as this will show the decoded logs in Forge traces. - -```solidity -// import it indirectly via Test.sol -import "forge-std/Test.sol"; -// or directly import it -import "forge-std/console2.sol"; -... -console2.log(someValue); -``` - -If you need compatibility with Hardhat, you must use the standard `console.sol` instead. -Due to a bug in `console.sol`, logs that use `uint256` or `int256` types will not be properly decoded in Forge traces. - -```solidity -// import it indirectly via Test.sol -import "forge-std/Test.sol"; -// or directly import it -import "forge-std/console.sol"; -... -console.log(someValue); -``` diff --git a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/.gitignore b/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/.gitignore deleted file mode 100644 index 63f0b2c6..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/.dapple -/build -/out diff --git a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/LICENSE b/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/LICENSE deleted file mode 100644 index 94a9ed02..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/Makefile b/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/Makefile deleted file mode 100644 index 661dac48..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -all:; dapp build - -test: - -dapp --use solc:0.4.23 build - -dapp --use solc:0.4.26 build - -dapp --use solc:0.5.17 build - -dapp --use solc:0.6.12 build - -dapp --use solc:0.7.5 build - -demo: - DAPP_SRC=demo dapp --use solc:0.7.5 build - -hevm dapp-test --verbose 3 - -.PHONY: test demo diff --git a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/default.nix b/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/default.nix deleted file mode 100644 index cf65419a..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/default.nix +++ /dev/null @@ -1,4 +0,0 @@ -{ solidityPackage, dappsys }: solidityPackage { - name = "ds-test"; - src = ./src; -} diff --git a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/demo/demo.sol b/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/demo/demo.sol deleted file mode 100644 index d3a7d81f..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/demo/demo.sol +++ /dev/null @@ -1,223 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -pragma solidity >=0.4.23; - -import "../src/test.sol"; - -contract DemoTest is DSTest { - function test_this() public pure { - require(true); - } - function test_logs() public { - emit log("-- log(string)"); - emit log("a string"); - - emit log("-- log_named_uint(string, uint)"); - log_named_uint("uint", 512); - - emit log("-- log_named_int(string, int)"); - log_named_int("int", -512); - - emit log("-- log_named_address(string, address)"); - log_named_address("address", address(this)); - - emit log("-- log_named_bytes32(string, bytes32)"); - log_named_bytes32("bytes32", "a string"); - - emit log("-- log_named_bytes(string, bytes)"); - log_named_bytes("bytes", hex"cafefe"); - - emit log("-- log_named_string(string, string)"); - log_named_string("string", "a string"); - - emit log("-- log_named_decimal_uint(string, uint, uint)"); - log_named_decimal_uint("decimal uint", 1.0e18, 18); - - emit log("-- log_named_decimal_int(string, int, uint)"); - log_named_decimal_int("decimal int", -1.0e18, 18); - } - event log_old_named_uint(bytes32,uint); - function test_old_logs() public { - log_old_named_uint("key", 500); - log_named_bytes32("bkey", "val"); - } - function test_trace() public view { - this.echo("string 1", "string 2"); - } - function test_multiline() public { - emit log("a multiline\\n" "string"); - emit log("a multiline " "string"); - log_bytes("a string"); - log_bytes("a multiline\n" "string"); - log_bytes("a multiline\\n" "string"); - emit log(unicode"Ώ"); - logs(hex"0000"); - log_named_bytes("0x0000", hex"0000"); - logs(hex"ff"); - } - function echo(string memory s1, string memory s2) public pure - returns (string memory, string memory) - { - return (s1, s2); - } - - function prove_this(uint x) public { - log_named_uint("sym x", x); - assertGt(x + 1, 0); - } - - function test_logn() public { - assembly { - log0(0x01, 0x02) - log1(0x01, 0x02, 0x03) - log2(0x01, 0x02, 0x03, 0x04) - log3(0x01, 0x02, 0x03, 0x04, 0x05) - } - } - - event MyEvent(uint, uint indexed, uint, uint indexed); - function test_events() public { - emit MyEvent(1, 2, 3, 4); - } - - function test_asserts() public { - string memory err = "this test has failed!"; - emit log("## assertTrue(bool)\n"); - assertTrue(false); - emit log("\n"); - assertTrue(false, err); - - emit log("\n## assertEq(address,address)\n"); - assertEq(address(this), msg.sender); - emit log("\n"); - assertEq(address(this), msg.sender, err); - - emit log("\n## assertEq32(bytes32,bytes32)\n"); - assertEq32("bytes 1", "bytes 2"); - emit log("\n"); - assertEq32("bytes 1", "bytes 2", err); - - emit log("\n## assertEq(bytes32,bytes32)\n"); - assertEq32("bytes 1", "bytes 2"); - emit log("\n"); - assertEq32("bytes 1", "bytes 2", err); - - emit log("\n## assertEq(uint,uint)\n"); - assertEq(uint(0), 1); - emit log("\n"); - assertEq(uint(0), 1, err); - - emit log("\n## assertEq(int,int)\n"); - assertEq(-1, -2); - emit log("\n"); - assertEq(-1, -2, err); - - emit log("\n## assertEqDecimal(int,int,uint)\n"); - assertEqDecimal(-1.0e18, -1.1e18, 18); - emit log("\n"); - assertEqDecimal(-1.0e18, -1.1e18, 18, err); - - emit log("\n## assertEqDecimal(uint,uint,uint)\n"); - assertEqDecimal(uint(1.0e18), 1.1e18, 18); - emit log("\n"); - assertEqDecimal(uint(1.0e18), 1.1e18, 18, err); - - emit log("\n## assertGt(uint,uint)\n"); - assertGt(uint(0), 0); - emit log("\n"); - assertGt(uint(0), 0, err); - - emit log("\n## assertGt(int,int)\n"); - assertGt(-1, -1); - emit log("\n"); - assertGt(-1, -1, err); - - emit log("\n## assertGtDecimal(int,int,uint)\n"); - assertGtDecimal(-2.0e18, -1.1e18, 18); - emit log("\n"); - assertGtDecimal(-2.0e18, -1.1e18, 18, err); - - emit log("\n## assertGtDecimal(uint,uint,uint)\n"); - assertGtDecimal(uint(1.0e18), 1.1e18, 18); - emit log("\n"); - assertGtDecimal(uint(1.0e18), 1.1e18, 18, err); - - emit log("\n## assertGe(uint,uint)\n"); - assertGe(uint(0), 1); - emit log("\n"); - assertGe(uint(0), 1, err); - - emit log("\n## assertGe(int,int)\n"); - assertGe(-1, 0); - emit log("\n"); - assertGe(-1, 0, err); - - emit log("\n## assertGeDecimal(int,int,uint)\n"); - assertGeDecimal(-2.0e18, -1.1e18, 18); - emit log("\n"); - assertGeDecimal(-2.0e18, -1.1e18, 18, err); - - emit log("\n## assertGeDecimal(uint,uint,uint)\n"); - assertGeDecimal(uint(1.0e18), 1.1e18, 18); - emit log("\n"); - assertGeDecimal(uint(1.0e18), 1.1e18, 18, err); - - emit log("\n## assertLt(uint,uint)\n"); - assertLt(uint(0), 0); - emit log("\n"); - assertLt(uint(0), 0, err); - - emit log("\n## assertLt(int,int)\n"); - assertLt(-1, -1); - emit log("\n"); - assertLt(-1, -1, err); - - emit log("\n## assertLtDecimal(int,int,uint)\n"); - assertLtDecimal(-1.0e18, -1.1e18, 18); - emit log("\n"); - assertLtDecimal(-1.0e18, -1.1e18, 18, err); - - emit log("\n## assertLtDecimal(uint,uint,uint)\n"); - assertLtDecimal(uint(2.0e18), 1.1e18, 18); - emit log("\n"); - assertLtDecimal(uint(2.0e18), 1.1e18, 18, err); - - emit log("\n## assertLe(uint,uint)\n"); - assertLe(uint(1), 0); - emit log("\n"); - assertLe(uint(1), 0, err); - - emit log("\n## assertLe(int,int)\n"); - assertLe(0, -1); - emit log("\n"); - assertLe(0, -1, err); - - emit log("\n## assertLeDecimal(int,int,uint)\n"); - assertLeDecimal(-1.0e18, -1.1e18, 18); - emit log("\n"); - assertLeDecimal(-1.0e18, -1.1e18, 18, err); - - emit log("\n## assertLeDecimal(uint,uint,uint)\n"); - assertLeDecimal(uint(2.0e18), 1.1e18, 18); - emit log("\n"); - assertLeDecimal(uint(2.0e18), 1.1e18, 18, err); - - emit log("\n## assertEq(string,string)\n"); - string memory s1 = "string 1"; - string memory s2 = "string 2"; - assertEq(s1, s2); - emit log("\n"); - assertEq(s1, s2, err); - - emit log("\n## assertEq0(bytes,bytes)\n"); - assertEq0(hex"abcdef01", hex"abcdef02"); - log("\n"); - assertEq0(hex"abcdef01", hex"abcdef02", err); - } -} - -contract DemoTestWithSetUp { - function setUp() public { - } - function test_pass() public pure { - } -} diff --git a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/src/test.sol b/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/src/test.sol deleted file mode 100644 index 515a3bd0..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/lib/ds-test/src/test.sol +++ /dev/null @@ -1,469 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -pragma solidity >=0.5.0; - -contract DSTest { - event log (string); - event logs (bytes); - - event log_address (address); - event log_bytes32 (bytes32); - event log_int (int); - event log_uint (uint); - event log_bytes (bytes); - event log_string (string); - - event log_named_address (string key, address val); - event log_named_bytes32 (string key, bytes32 val); - event log_named_decimal_int (string key, int val, uint decimals); - event log_named_decimal_uint (string key, uint val, uint decimals); - event log_named_int (string key, int val); - event log_named_uint (string key, uint val); - event log_named_bytes (string key, bytes val); - event log_named_string (string key, string val); - - bool public IS_TEST = true; - bool private _failed; - - address constant HEVM_ADDRESS = - address(bytes20(uint160(uint256(keccak256('hevm cheat code'))))); - - modifier mayRevert() { _; } - modifier testopts(string memory) { _; } - - function failed() public returns (bool) { - if (_failed) { - return _failed; - } else { - bool globalFailed = false; - if (hasHEVMContext()) { - (, bytes memory retdata) = HEVM_ADDRESS.call( - abi.encodePacked( - bytes4(keccak256("load(address,bytes32)")), - abi.encode(HEVM_ADDRESS, bytes32("failed")) - ) - ); - globalFailed = abi.decode(retdata, (bool)); - } - return globalFailed; - } - } - - function fail() internal { - if (hasHEVMContext()) { - (bool status, ) = HEVM_ADDRESS.call( - abi.encodePacked( - bytes4(keccak256("store(address,bytes32,bytes32)")), - abi.encode(HEVM_ADDRESS, bytes32("failed"), bytes32(uint256(0x01))) - ) - ); - status; // Silence compiler warnings - } - _failed = true; - } - - function hasHEVMContext() internal view returns (bool) { - uint256 hevmCodeSize = 0; - assembly { - hevmCodeSize := extcodesize(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D) - } - return hevmCodeSize > 0; - } - - modifier logs_gas() { - uint startGas = gasleft(); - _; - uint endGas = gasleft(); - emit log_named_uint("gas", startGas - endGas); - } - - function assertTrue(bool condition) internal { - if (!condition) { - emit log("Error: Assertion Failed"); - fail(); - } - } - - function assertTrue(bool condition, string memory err) internal { - if (!condition) { - emit log_named_string("Error", err); - assertTrue(condition); - } - } - - function assertEq(address a, address b) internal { - if (a != b) { - emit log("Error: a == b not satisfied [address]"); - emit log_named_address(" Expected", b); - emit log_named_address(" Actual", a); - fail(); - } - } - function assertEq(address a, address b, string memory err) internal { - if (a != b) { - emit log_named_string ("Error", err); - assertEq(a, b); - } - } - - function assertEq(bytes32 a, bytes32 b) internal { - if (a != b) { - emit log("Error: a == b not satisfied [bytes32]"); - emit log_named_bytes32(" Expected", b); - emit log_named_bytes32(" Actual", a); - fail(); - } - } - function assertEq(bytes32 a, bytes32 b, string memory err) internal { - if (a != b) { - emit log_named_string ("Error", err); - assertEq(a, b); - } - } - function assertEq32(bytes32 a, bytes32 b) internal { - assertEq(a, b); - } - function assertEq32(bytes32 a, bytes32 b, string memory err) internal { - assertEq(a, b, err); - } - - function assertEq(int a, int b) internal { - if (a != b) { - emit log("Error: a == b not satisfied [int]"); - emit log_named_int(" Expected", b); - emit log_named_int(" Actual", a); - fail(); - } - } - function assertEq(int a, int b, string memory err) internal { - if (a != b) { - emit log_named_string("Error", err); - assertEq(a, b); - } - } - function assertEq(uint a, uint b) internal { - if (a != b) { - emit log("Error: a == b not satisfied [uint]"); - emit log_named_uint(" Expected", b); - emit log_named_uint(" Actual", a); - fail(); - } - } - function assertEq(uint a, uint b, string memory err) internal { - if (a != b) { - emit log_named_string("Error", err); - assertEq(a, b); - } - } - function assertEqDecimal(int a, int b, uint decimals) internal { - if (a != b) { - emit log("Error: a == b not satisfied [decimal int]"); - emit log_named_decimal_int(" Expected", b, decimals); - emit log_named_decimal_int(" Actual", a, decimals); - fail(); - } - } - function assertEqDecimal(int a, int b, uint decimals, string memory err) internal { - if (a != b) { - emit log_named_string("Error", err); - assertEqDecimal(a, b, decimals); - } - } - function assertEqDecimal(uint a, uint b, uint decimals) internal { - if (a != b) { - emit log("Error: a == b not satisfied [decimal uint]"); - emit log_named_decimal_uint(" Expected", b, decimals); - emit log_named_decimal_uint(" Actual", a, decimals); - fail(); - } - } - function assertEqDecimal(uint a, uint b, uint decimals, string memory err) internal { - if (a != b) { - emit log_named_string("Error", err); - assertEqDecimal(a, b, decimals); - } - } - - function assertGt(uint a, uint b) internal { - if (a <= b) { - emit log("Error: a > b not satisfied [uint]"); - emit log_named_uint(" Value a", a); - emit log_named_uint(" Value b", b); - fail(); - } - } - function assertGt(uint a, uint b, string memory err) internal { - if (a <= b) { - emit log_named_string("Error", err); - assertGt(a, b); - } - } - function assertGt(int a, int b) internal { - if (a <= b) { - emit log("Error: a > b not satisfied [int]"); - emit log_named_int(" Value a", a); - emit log_named_int(" Value b", b); - fail(); - } - } - function assertGt(int a, int b, string memory err) internal { - if (a <= b) { - emit log_named_string("Error", err); - assertGt(a, b); - } - } - function assertGtDecimal(int a, int b, uint decimals) internal { - if (a <= b) { - emit log("Error: a > b not satisfied [decimal int]"); - emit log_named_decimal_int(" Value a", a, decimals); - emit log_named_decimal_int(" Value b", b, decimals); - fail(); - } - } - function assertGtDecimal(int a, int b, uint decimals, string memory err) internal { - if (a <= b) { - emit log_named_string("Error", err); - assertGtDecimal(a, b, decimals); - } - } - function assertGtDecimal(uint a, uint b, uint decimals) internal { - if (a <= b) { - emit log("Error: a > b not satisfied [decimal uint]"); - emit log_named_decimal_uint(" Value a", a, decimals); - emit log_named_decimal_uint(" Value b", b, decimals); - fail(); - } - } - function assertGtDecimal(uint a, uint b, uint decimals, string memory err) internal { - if (a <= b) { - emit log_named_string("Error", err); - assertGtDecimal(a, b, decimals); - } - } - - function assertGe(uint a, uint b) internal { - if (a < b) { - emit log("Error: a >= b not satisfied [uint]"); - emit log_named_uint(" Value a", a); - emit log_named_uint(" Value b", b); - fail(); - } - } - function assertGe(uint a, uint b, string memory err) internal { - if (a < b) { - emit log_named_string("Error", err); - assertGe(a, b); - } - } - function assertGe(int a, int b) internal { - if (a < b) { - emit log("Error: a >= b not satisfied [int]"); - emit log_named_int(" Value a", a); - emit log_named_int(" Value b", b); - fail(); - } - } - function assertGe(int a, int b, string memory err) internal { - if (a < b) { - emit log_named_string("Error", err); - assertGe(a, b); - } - } - function assertGeDecimal(int a, int b, uint decimals) internal { - if (a < b) { - emit log("Error: a >= b not satisfied [decimal int]"); - emit log_named_decimal_int(" Value a", a, decimals); - emit log_named_decimal_int(" Value b", b, decimals); - fail(); - } - } - function assertGeDecimal(int a, int b, uint decimals, string memory err) internal { - if (a < b) { - emit log_named_string("Error", err); - assertGeDecimal(a, b, decimals); - } - } - function assertGeDecimal(uint a, uint b, uint decimals) internal { - if (a < b) { - emit log("Error: a >= b not satisfied [decimal uint]"); - emit log_named_decimal_uint(" Value a", a, decimals); - emit log_named_decimal_uint(" Value b", b, decimals); - fail(); - } - } - function assertGeDecimal(uint a, uint b, uint decimals, string memory err) internal { - if (a < b) { - emit log_named_string("Error", err); - assertGeDecimal(a, b, decimals); - } - } - - function assertLt(uint a, uint b) internal { - if (a >= b) { - emit log("Error: a < b not satisfied [uint]"); - emit log_named_uint(" Value a", a); - emit log_named_uint(" Value b", b); - fail(); - } - } - function assertLt(uint a, uint b, string memory err) internal { - if (a >= b) { - emit log_named_string("Error", err); - assertLt(a, b); - } - } - function assertLt(int a, int b) internal { - if (a >= b) { - emit log("Error: a < b not satisfied [int]"); - emit log_named_int(" Value a", a); - emit log_named_int(" Value b", b); - fail(); - } - } - function assertLt(int a, int b, string memory err) internal { - if (a >= b) { - emit log_named_string("Error", err); - assertLt(a, b); - } - } - function assertLtDecimal(int a, int b, uint decimals) internal { - if (a >= b) { - emit log("Error: a < b not satisfied [decimal int]"); - emit log_named_decimal_int(" Value a", a, decimals); - emit log_named_decimal_int(" Value b", b, decimals); - fail(); - } - } - function assertLtDecimal(int a, int b, uint decimals, string memory err) internal { - if (a >= b) { - emit log_named_string("Error", err); - assertLtDecimal(a, b, decimals); - } - } - function assertLtDecimal(uint a, uint b, uint decimals) internal { - if (a >= b) { - emit log("Error: a < b not satisfied [decimal uint]"); - emit log_named_decimal_uint(" Value a", a, decimals); - emit log_named_decimal_uint(" Value b", b, decimals); - fail(); - } - } - function assertLtDecimal(uint a, uint b, uint decimals, string memory err) internal { - if (a >= b) { - emit log_named_string("Error", err); - assertLtDecimal(a, b, decimals); - } - } - - function assertLe(uint a, uint b) internal { - if (a > b) { - emit log("Error: a <= b not satisfied [uint]"); - emit log_named_uint(" Value a", a); - emit log_named_uint(" Value b", b); - fail(); - } - } - function assertLe(uint a, uint b, string memory err) internal { - if (a > b) { - emit log_named_string("Error", err); - assertLe(a, b); - } - } - function assertLe(int a, int b) internal { - if (a > b) { - emit log("Error: a <= b not satisfied [int]"); - emit log_named_int(" Value a", a); - emit log_named_int(" Value b", b); - fail(); - } - } - function assertLe(int a, int b, string memory err) internal { - if (a > b) { - emit log_named_string("Error", err); - assertLe(a, b); - } - } - function assertLeDecimal(int a, int b, uint decimals) internal { - if (a > b) { - emit log("Error: a <= b not satisfied [decimal int]"); - emit log_named_decimal_int(" Value a", a, decimals); - emit log_named_decimal_int(" Value b", b, decimals); - fail(); - } - } - function assertLeDecimal(int a, int b, uint decimals, string memory err) internal { - if (a > b) { - emit log_named_string("Error", err); - assertLeDecimal(a, b, decimals); - } - } - function assertLeDecimal(uint a, uint b, uint decimals) internal { - if (a > b) { - emit log("Error: a <= b not satisfied [decimal uint]"); - emit log_named_decimal_uint(" Value a", a, decimals); - emit log_named_decimal_uint(" Value b", b, decimals); - fail(); - } - } - function assertLeDecimal(uint a, uint b, uint decimals, string memory err) internal { - if (a > b) { - emit log_named_string("Error", err); - assertGeDecimal(a, b, decimals); - } - } - - function assertEq(string memory a, string memory b) internal { - if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) { - emit log("Error: a == b not satisfied [string]"); - emit log_named_string(" Expected", b); - emit log_named_string(" Actual", a); - fail(); - } - } - function assertEq(string memory a, string memory b, string memory err) internal { - if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) { - emit log_named_string("Error", err); - assertEq(a, b); - } - } - - function checkEq0(bytes memory a, bytes memory b) internal pure returns (bool ok) { - ok = true; - if (a.length == b.length) { - for (uint i = 0; i < a.length; i++) { - if (a[i] != b[i]) { - ok = false; - } - } - } else { - ok = false; - } - } - function assertEq0(bytes memory a, bytes memory b) internal { - if (!checkEq0(a, b)) { - emit log("Error: a == b not satisfied [bytes]"); - emit log_named_bytes(" Expected", b); - emit log_named_bytes(" Actual", a); - fail(); - } - } - function assertEq0(bytes memory a, bytes memory b, string memory err) internal { - if (!checkEq0(a, b)) { - emit log_named_string("Error", err); - assertEq0(a, b); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/Test.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/Test.sol deleted file mode 100644 index f03f2e21..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/Test.sol +++ /dev/null @@ -1,682 +0,0 @@ -// SPDX-License-Identifier: Unlicense -pragma solidity >=0.6.0 <0.9.0; - -import "./Vm.sol"; -import "ds-test/test.sol"; -import "./console.sol"; -import "./console2.sol"; - -// Wrappers around Cheatcodes to avoid footguns -abstract contract Test is DSTest { - using stdStorage for StdStorage; - - uint256 private constant UINT256_MAX = 115792089237316195423570985008687907853269984665640564039457584007913129639935; - - event WARNING_Deprecated(string msg); - - Vm public constant vm = Vm(HEVM_ADDRESS); - StdStorage internal stdstore; - - /*////////////////////////////////////////////////////////////////////////// - STD-CHEATS - //////////////////////////////////////////////////////////////////////////*/ - - // Skip forward or rewind time by the specified number of seconds - function skip(uint256 time) public { - vm.warp(block.timestamp + time); - } - - function rewind(uint256 time) public { - vm.warp(block.timestamp - time); - } - - // Setup a prank from an address that has some ether - function hoax(address who) public { - vm.deal(who, 1 << 128); - vm.prank(who); - } - - function hoax(address who, uint256 give) public { - vm.deal(who, give); - vm.prank(who); - } - - function hoax(address who, address origin) public { - vm.deal(who, 1 << 128); - vm.prank(who, origin); - } - - function hoax(address who, address origin, uint256 give) public { - vm.deal(who, give); - vm.prank(who, origin); - } - - // Start perpetual prank from an address that has some ether - function startHoax(address who) public { - vm.deal(who, 1 << 128); - vm.startPrank(who); - } - - function startHoax(address who, uint256 give) public { - vm.deal(who, give); - vm.startPrank(who); - } - - // Start perpetual prank from an address that has some ether - // tx.origin is set to the origin parameter - function startHoax(address who, address origin) public { - vm.deal(who, 1 << 128); - vm.startPrank(who, origin); - } - - function startHoax(address who, address origin, uint256 give) public { - vm.deal(who, give); - vm.startPrank(who, origin); - } - - function changePrank(address who) internal { - vm.stopPrank(); - vm.startPrank(who); - } - - // DEPRECATED: Use `deal` instead - function tip(address token, address to, uint256 give) public { - emit WARNING_Deprecated("The `tip` stdcheat has been deprecated. Use `deal` instead."); - stdstore - .target(token) - .sig(0x70a08231) - .with_key(to) - .checked_write(give); - } - - // The same as Hevm's `deal` - // Use the alternative signature for ERC20 tokens - function deal(address to, uint256 give) public { - vm.deal(to, give); - } - - // Set the balance of an account for any ERC20 token - // Use the alternative signature to update `totalSupply` - function deal(address token, address to, uint256 give) public { - deal(token, to, give, false); - } - - function deal(address token, address to, uint256 give, bool adjust) public { - // get current balance - (, bytes memory balData) = token.call(abi.encodeWithSelector(0x70a08231, to)); - uint256 prevBal = abi.decode(balData, (uint256)); - - // update balance - stdstore - .target(token) - .sig(0x70a08231) - .with_key(to) - .checked_write(give); - - // update total supply - if(adjust){ - (, bytes memory totSupData) = token.call(abi.encodeWithSelector(0x18160ddd)); - uint256 totSup = abi.decode(totSupData, (uint256)); - if(give < prevBal) { - totSup -= (prevBal - give); - } else { - totSup += (give - prevBal); - } - stdstore - .target(token) - .sig(0x18160ddd) - .checked_write(totSup); - } - } - - function bound(uint256 x, uint256 min, uint256 max) public returns (uint256 result) { - require(min <= max, "Test bound(uint256,uint256,uint256): Max is less than min."); - - uint256 size = max - min; - - if (size == 0) - { - result = min; - } - else if (size == UINT256_MAX) - { - result = x; - } - else - { - ++size; // make `max` inclusive - uint256 mod = x % size; - result = min + mod; - } - - emit log_named_uint("Bound Result", result); - } - - // Deploy a contract by fetching the contract bytecode from - // the artifacts directory - // e.g. `deployCode(code, abi.encode(arg1,arg2,arg3))` - function deployCode(string memory what, bytes memory args) - public - returns (address addr) - { - bytes memory bytecode = abi.encodePacked(vm.getCode(what), args); - /// @solidity memory-safe-assembly - assembly { - addr := create(0, add(bytecode, 0x20), mload(bytecode)) - } - - require( - addr != address(0), - "Test deployCode(string,bytes): Deployment failed." - ); - } - - function deployCode(string memory what) - public - returns (address addr) - { - bytes memory bytecode = vm.getCode(what); - /// @solidity memory-safe-assembly - assembly { - addr := create(0, add(bytecode, 0x20), mload(bytecode)) - } - - require( - addr != address(0), - "Test deployCode(string): Deployment failed." - ); - } - - /*////////////////////////////////////////////////////////////////////////// - STD-ASSERTIONS - //////////////////////////////////////////////////////////////////////////*/ - - function fail(string memory err) internal virtual { - emit log_named_string("Error", err); - fail(); - } - - function assertFalse(bool data) internal virtual { - assertTrue(!data); - } - - function assertFalse(bool data, string memory err) internal virtual { - assertTrue(!data, err); - } - - function assertEq(bool a, bool b) internal { - if (a != b) { - emit log ("Error: a == b not satisfied [bool]"); - emit log_named_string (" Expected", b ? "true" : "false"); - emit log_named_string (" Actual", a ? "true" : "false"); - fail(); - } - } - - function assertEq(bool a, bool b, string memory err) internal { - if (a != b) { - emit log_named_string("Error", err); - assertEq(a, b); - } - } - - function assertEq(bytes memory a, bytes memory b) internal { - if (keccak256(a) != keccak256(b)) { - emit log ("Error: a == b not satisfied [bytes]"); - emit log_named_bytes(" Expected", b); - emit log_named_bytes(" Actual", a); - fail(); - } - } - - function assertEq(bytes memory a, bytes memory b, string memory err) internal { - if (keccak256(a) != keccak256(b)) { - emit log_named_string ("Error", err); - assertEq(a, b); - } - } - - function assertApproxEqAbs( - uint256 a, - uint256 b, - uint256 maxDelta - ) internal virtual { - uint256 delta = stdMath.delta(a, b); - - if (delta > maxDelta) { - emit log ("Error: a ~= b not satisfied [uint]"); - emit log_named_uint (" Expected", b); - emit log_named_uint (" Actual", a); - emit log_named_uint (" Max Delta", maxDelta); - emit log_named_uint (" Delta", delta); - fail(); - } - } - - function assertApproxEqAbs( - uint256 a, - uint256 b, - uint256 maxDelta, - string memory err - ) internal virtual { - uint256 delta = stdMath.delta(a, b); - - if (delta > maxDelta) { - emit log_named_string ("Error", err); - assertApproxEqAbs(a, b, maxDelta); - } - } - - function assertApproxEqAbs( - int256 a, - int256 b, - uint256 maxDelta - ) internal virtual { - uint256 delta = stdMath.delta(a, b); - - if (delta > maxDelta) { - emit log ("Error: a ~= b not satisfied [int]"); - emit log_named_int (" Expected", b); - emit log_named_int (" Actual", a); - emit log_named_uint (" Max Delta", maxDelta); - emit log_named_uint (" Delta", delta); - fail(); - } - } - - function assertApproxEqAbs( - int256 a, - int256 b, - uint256 maxDelta, - string memory err - ) internal virtual { - uint256 delta = stdMath.delta(a, b); - - if (delta > maxDelta) { - emit log_named_string ("Error", err); - assertApproxEqAbs(a, b, maxDelta); - } - } - - function assertApproxEqRel( - uint256 a, - uint256 b, - uint256 maxPercentDelta // An 18 decimal fixed point number, where 1e18 == 100% - ) internal virtual { - if (b == 0) return assertEq(a, b); // If the expected is 0, actual must be too. - - uint256 percentDelta = stdMath.percentDelta(a, b); - - if (percentDelta > maxPercentDelta) { - emit log ("Error: a ~= b not satisfied [uint]"); - emit log_named_uint (" Expected", b); - emit log_named_uint (" Actual", a); - emit log_named_decimal_uint (" Max % Delta", maxPercentDelta, 18); - emit log_named_decimal_uint (" % Delta", percentDelta, 18); - fail(); - } - } - - function assertApproxEqRel( - uint256 a, - uint256 b, - uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100% - string memory err - ) internal virtual { - if (b == 0) return assertEq(a, b); // If the expected is 0, actual must be too. - - uint256 percentDelta = stdMath.percentDelta(a, b); - - if (percentDelta > maxPercentDelta) { - emit log_named_string ("Error", err); - assertApproxEqRel(a, b, maxPercentDelta); - } - } - - function assertApproxEqRel( - int256 a, - int256 b, - uint256 maxPercentDelta - ) internal virtual { - if (b == 0) return assertEq(a, b); // If the expected is 0, actual must be too. - - uint256 percentDelta = stdMath.percentDelta(a, b); - - if (percentDelta > maxPercentDelta) { - emit log ("Error: a ~= b not satisfied [int]"); - emit log_named_int (" Expected", b); - emit log_named_int (" Actual", a); - emit log_named_decimal_uint(" Max % Delta", maxPercentDelta, 18); - emit log_named_decimal_uint(" % Delta", percentDelta, 18); - fail(); - } - } - - function assertApproxEqRel( - int256 a, - int256 b, - uint256 maxPercentDelta, - string memory err - ) internal virtual { - if (b == 0) return assertEq(a, b); // If the expected is 0, actual must be too. - - uint256 percentDelta = stdMath.percentDelta(a, b); - - if (percentDelta > maxPercentDelta) { - emit log_named_string ("Error", err); - assertApproxEqRel(a, b, maxPercentDelta); - } - } -} - -/*////////////////////////////////////////////////////////////////////////// - STD-ERRORS -//////////////////////////////////////////////////////////////////////////*/ - -library stdError { - bytes public constant assertionError = abi.encodeWithSignature("Panic(uint256)", 0x01); - bytes public constant arithmeticError = abi.encodeWithSignature("Panic(uint256)", 0x11); - bytes public constant divisionError = abi.encodeWithSignature("Panic(uint256)", 0x12); - bytes public constant enumConversionError = abi.encodeWithSignature("Panic(uint256)", 0x21); - bytes public constant encodeStorageError = abi.encodeWithSignature("Panic(uint256)", 0x22); - bytes public constant popError = abi.encodeWithSignature("Panic(uint256)", 0x31); - bytes public constant indexOOBError = abi.encodeWithSignature("Panic(uint256)", 0x32); - bytes public constant memOverflowError = abi.encodeWithSignature("Panic(uint256)", 0x41); - bytes public constant zeroVarError = abi.encodeWithSignature("Panic(uint256)", 0x51); - // DEPRECATED: Use Hevm's `expectRevert` without any arguments instead - bytes public constant lowLevelError = bytes(""); // `0x` -} - -/*////////////////////////////////////////////////////////////////////////// - STD-STORAGE -//////////////////////////////////////////////////////////////////////////*/ - -struct StdStorage { - mapping (address => mapping(bytes4 => mapping(bytes32 => uint256))) slots; - mapping (address => mapping(bytes4 => mapping(bytes32 => bool))) finds; - - bytes32[] _keys; - bytes4 _sig; - uint256 _depth; - address _target; - bytes32 _set; -} - -library stdStorage { - event SlotFound(address who, bytes4 fsig, bytes32 keysHash, uint slot); - event WARNING_UninitedSlot(address who, uint slot); - - uint256 private constant UINT256_MAX = 115792089237316195423570985008687907853269984665640564039457584007913129639935; - int256 private constant INT256_MAX = 57896044618658097711785492504343953926634992332820282019728792003956564819967; - - Vm private constant vm_std_store = Vm(address(uint160(uint256(keccak256('hevm cheat code'))))); - - function sigs( - string memory sigStr - ) - internal - pure - returns (bytes4) - { - return bytes4(keccak256(bytes(sigStr))); - } - - /// @notice find an arbitrary storage slot given a function sig, input data, address of the contract and a value to check against - // slot complexity: - // if flat, will be bytes32(uint256(uint)); - // if map, will be keccak256(abi.encode(key, uint(slot))); - // if deep map, will be keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot))))); - // if map struct, will be bytes32(uint256(keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))) + structFieldDepth); - function find( - StdStorage storage self - ) - internal - returns (uint256) - { - address who = self._target; - bytes4 fsig = self._sig; - uint256 field_depth = self._depth; - bytes32[] memory ins = self._keys; - - // calldata to test against - if (self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]) { - return self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]; - } - bytes memory cald = abi.encodePacked(fsig, flatten(ins)); - vm_std_store.record(); - bytes32 fdat; - { - (, bytes memory rdat) = who.staticcall(cald); - fdat = bytesToBytes32(rdat, 32*field_depth); - } - - (bytes32[] memory reads, ) = vm_std_store.accesses(address(who)); - if (reads.length == 1) { - bytes32 curr = vm_std_store.load(who, reads[0]); - if (curr == bytes32(0)) { - emit WARNING_UninitedSlot(who, uint256(reads[0])); - } - if (fdat != curr) { - require(false, "stdStorage find(StdStorage): Packed slot. This would cause dangerous overwriting and currently isnt supported"); - } - emit SlotFound(who, fsig, keccak256(abi.encodePacked(ins, field_depth)), uint256(reads[0])); - self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = uint256(reads[0]); - self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = true; - } else if (reads.length > 1) { - for (uint256 i = 0; i < reads.length; i++) { - bytes32 prev = vm_std_store.load(who, reads[i]); - if (prev == bytes32(0)) { - emit WARNING_UninitedSlot(who, uint256(reads[i])); - } - // store - vm_std_store.store(who, reads[i], bytes32(hex"1337")); - bool success; - bytes memory rdat; - { - (success, rdat) = who.staticcall(cald); - fdat = bytesToBytes32(rdat, 32*field_depth); - } - - if (success && fdat == bytes32(hex"1337")) { - // we found which of the slots is the actual one - emit SlotFound(who, fsig, keccak256(abi.encodePacked(ins, field_depth)), uint256(reads[i])); - self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = uint256(reads[i]); - self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = true; - vm_std_store.store(who, reads[i], prev); - break; - } - vm_std_store.store(who, reads[i], prev); - } - } else { - require(false, "stdStorage find(StdStorage): No storage use detected for target."); - } - - require(self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))], "stdStorage find(StdStorage): Slot(s) not found."); - - delete self._target; - delete self._sig; - delete self._keys; - delete self._depth; - - return self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]; - } - - function target(StdStorage storage self, address _target) internal returns (StdStorage storage) { - self._target = _target; - return self; - } - - function sig(StdStorage storage self, bytes4 _sig) internal returns (StdStorage storage) { - self._sig = _sig; - return self; - } - - function sig(StdStorage storage self, string memory _sig) internal returns (StdStorage storage) { - self._sig = sigs(_sig); - return self; - } - - function with_key(StdStorage storage self, address who) internal returns (StdStorage storage) { - self._keys.push(bytes32(uint256(uint160(who)))); - return self; - } - - function with_key(StdStorage storage self, uint256 amt) internal returns (StdStorage storage) { - self._keys.push(bytes32(amt)); - return self; - } - function with_key(StdStorage storage self, bytes32 key) internal returns (StdStorage storage) { - self._keys.push(key); - return self; - } - - function depth(StdStorage storage self, uint256 _depth) internal returns (StdStorage storage) { - self._depth = _depth; - return self; - } - - function checked_write(StdStorage storage self, address who) internal { - checked_write(self, bytes32(uint256(uint160(who)))); - } - - function checked_write(StdStorage storage self, uint256 amt) internal { - checked_write(self, bytes32(amt)); - } - - function checked_write(StdStorage storage self, bool write) internal { - bytes32 t; - /// @solidity memory-safe-assembly - assembly { - t := write - } - checked_write(self, t); - } - - function checked_write( - StdStorage storage self, - bytes32 set - ) internal { - address who = self._target; - bytes4 fsig = self._sig; - uint256 field_depth = self._depth; - bytes32[] memory ins = self._keys; - - bytes memory cald = abi.encodePacked(fsig, flatten(ins)); - if (!self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]) { - find(self); - } - bytes32 slot = bytes32(self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]); - - bytes32 fdat; - { - (, bytes memory rdat) = who.staticcall(cald); - fdat = bytesToBytes32(rdat, 32*field_depth); - } - bytes32 curr = vm_std_store.load(who, slot); - - if (fdat != curr) { - require(false, "stdStorage find(StdStorage): Packed slot. This would cause dangerous overwriting and currently isnt supported."); - } - vm_std_store.store(who, slot, set); - delete self._target; - delete self._sig; - delete self._keys; - delete self._depth; - } - - function read(StdStorage storage self) private returns (bytes memory) { - address t = self._target; - uint256 s = find(self); - return abi.encode(vm_std_store.load(t, bytes32(s))); - } - - function read_bytes32(StdStorage storage self) internal returns (bytes32) { - return abi.decode(read(self), (bytes32)); - } - - - function read_bool(StdStorage storage self) internal returns (bool) { - return abi.decode(read(self), (bool)); - } - - function read_address(StdStorage storage self) internal returns (address) { - return abi.decode(read(self), (address)); - } - - function read_uint(StdStorage storage self) internal returns (uint256) { - return abi.decode(read(self), (uint256)); - } - - function read_int(StdStorage storage self) internal returns (int256) { - return abi.decode(read(self), (int256)); - } - - function bytesToBytes32(bytes memory b, uint offset) public pure returns (bytes32) { - bytes32 out; - - uint256 max = b.length > 32 ? 32 : b.length; - for (uint i = 0; i < max; i++) { - out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); - } - return out; - } - - function flatten(bytes32[] memory b) private pure returns (bytes memory) - { - bytes memory result = new bytes(b.length * 32); - for (uint256 i = 0; i < b.length; i++) { - bytes32 k = b[i]; - /// @solidity memory-safe-assembly - assembly { - mstore(add(result, add(32, mul(32, i))), k) - } - } - - return result; - } -} - -/*////////////////////////////////////////////////////////////////////////// - STD-MATH -//////////////////////////////////////////////////////////////////////////*/ - -library stdMath { - int256 private constant INT256_MIN = -57896044618658097711785492504343953926634992332820282019728792003956564819968; - - function abs(int256 a) internal pure returns (uint256) { - // Required or it will fail when `a = type(int256).min` - if (a == INT256_MIN) - return 57896044618658097711785492504343953926634992332820282019728792003956564819968; - - return uint256(a >= 0 ? a : -a); - } - - function delta(uint256 a, uint256 b) internal pure returns (uint256) { - return a > b - ? a - b - : b - a; - } - - function delta(int256 a, int256 b) internal pure returns (uint256) { - // a and b are of the same sign - if (a >= 0 && b >= 0 || a < 0 && b < 0) { - return delta(abs(a), abs(b)); - } - - // a and b are of opposite signs - return abs(a) + abs(b); - } - - function percentDelta(uint256 a, uint256 b) internal pure returns (uint256) { - uint256 absDelta = delta(a, b); - - return absDelta * 1e18 / b; - } - - function percentDelta(int256 a, int256 b) internal pure returns (uint256) { - uint256 absDelta = delta(a, b); - uint256 absB = abs(b); - - return absDelta * 1e18 / absB; - } -} diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/Vm.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/Vm.sol deleted file mode 100644 index a0f03922..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/Vm.sol +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-License-Identifier: Unlicense -pragma solidity >=0.6.0; -pragma experimental ABIEncoderV2; - -interface Vm { - // Set block.timestamp (newTimestamp) - function warp(uint256) external; - // Set block.height (newHeight) - function roll(uint256) external; - // Set block.basefee (newBasefee) - function fee(uint256) external; - // Set block.chainid - function chainId(uint256) external; - // Loads a storage slot from an address (who, slot) - function load(address,bytes32) external returns (bytes32); - // Stores a value to an address' storage slot, (who, slot, value) - function store(address,bytes32,bytes32) external; - // Signs data, (privateKey, digest) => (v, r, s) - function sign(uint256,bytes32) external returns (uint8,bytes32,bytes32); - // Gets address for a given private key, (privateKey) => (address) - function addr(uint256) external returns (address); - // Gets the nonce of an account - function getNonce(address) external returns (uint64); - // Sets the nonce of an account; must be higher than the current nonce of the account - function setNonce(address, uint64) external; - // Performs a foreign function call via terminal, (stringInputs) => (result) - function ffi(string[] calldata) external returns (bytes memory); - // Sets the *next* call's msg.sender to be the input address - function prank(address) external; - // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called - function startPrank(address) external; - // Sets the *next* call's msg.sender to be the input address, and the tx.origin to be the second input - function prank(address,address) external; - // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called, and the tx.origin to be the second input - function startPrank(address,address) external; - // Resets subsequent calls' msg.sender to be `address(this)` - function stopPrank() external; - // Sets an address' balance, (who, newBalance) - function deal(address, uint256) external; - // Sets an address' code, (who, newCode) - function etch(address, bytes calldata) external; - // Expects an error on next call - function expectRevert(bytes calldata) external; - function expectRevert(bytes4) external; - function expectRevert() external; - // Record all storage reads and writes - function record() external; - // Gets all accessed reads and write slot from a recording session, for a given address - function accesses(address) external returns (bytes32[] memory reads, bytes32[] memory writes); - // Prepare an expected log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData). - // Call this function, then emit an event, then call a function. Internally after the call, we check if - // logs were emitted in the expected order with the expected topics and data (as specified by the booleans) - function expectEmit(bool,bool,bool,bool) external; - function expectEmit(bool,bool,bool,bool,address) external; - // Mocks a call to an address, returning specified data. - // Calldata can either be strict or a partial match, e.g. if you only - // pass a Solidity selector to the expected calldata, then the entire Solidity - // function will be mocked. - function mockCall(address,bytes calldata,bytes calldata) external; - // Mocks a call to an address with a specific msg.value, returning specified data. - // Calldata match takes precedence over msg.value in case of ambiguity. - function mockCall(address,uint256,bytes calldata,bytes calldata) external; - // Clears all mocked calls - function clearMockedCalls() external; - // Expect a call to an address with the specified calldata. - // Calldata can either be strict or a partial match - function expectCall(address,bytes calldata) external; - // Expect a call to an address with the specified msg.value and calldata - function expectCall(address,uint256,bytes calldata) external; - // Gets the code from an artifact file. Takes in the relative path to the json file - function getCode(string calldata) external returns (bytes memory); - // Labels an address in call traces - function label(address, string calldata) external; - // If the condition is false, discard this run's fuzz inputs and generate new ones - function assume(bool) external; - // Set block.coinbase (who) - function coinbase(address) external; -} diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/console.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/console.sol deleted file mode 100644 index ad57e536..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/console.sol +++ /dev/null @@ -1,1533 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.4.22 <0.9.0; - -library console { - address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); - - function _sendLogPayload(bytes memory payload) private view { - uint256 payloadLength = payload.length; - address consoleAddress = CONSOLE_ADDRESS; - /// @solidity memory-safe-assembly - assembly { - let payloadStart := add(payload, 32) - let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) - } - } - - function log() internal view { - _sendLogPayload(abi.encodeWithSignature("log()")); - } - - function logInt(int p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); - } - - function logUint(uint p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); - } - - function logString(string memory p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); - } - - function logBool(bool p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); - } - - function logAddress(address p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); - } - - function logBytes(bytes memory p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); - } - - function logBytes1(bytes1 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); - } - - function logBytes2(bytes2 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); - } - - function logBytes3(bytes3 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); - } - - function logBytes4(bytes4 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); - } - - function logBytes5(bytes5 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); - } - - function logBytes6(bytes6 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); - } - - function logBytes7(bytes7 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); - } - - function logBytes8(bytes8 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); - } - - function logBytes9(bytes9 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); - } - - function logBytes10(bytes10 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); - } - - function logBytes11(bytes11 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); - } - - function logBytes12(bytes12 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); - } - - function logBytes13(bytes13 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); - } - - function logBytes14(bytes14 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); - } - - function logBytes15(bytes15 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); - } - - function logBytes16(bytes16 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); - } - - function logBytes17(bytes17 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); - } - - function logBytes18(bytes18 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); - } - - function logBytes19(bytes19 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); - } - - function logBytes20(bytes20 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); - } - - function logBytes21(bytes21 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); - } - - function logBytes22(bytes22 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); - } - - function logBytes23(bytes23 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); - } - - function logBytes24(bytes24 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); - } - - function logBytes25(bytes25 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); - } - - function logBytes26(bytes26 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); - } - - function logBytes27(bytes27 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); - } - - function logBytes28(bytes28 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); - } - - function logBytes29(bytes29 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); - } - - function logBytes30(bytes30 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); - } - - function logBytes31(bytes31 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); - } - - function logBytes32(bytes32 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); - } - - function log(uint p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); - } - - function log(string memory p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); - } - - function log(bool p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); - } - - function log(address p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); - } - - function log(uint p0, uint p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); - } - - function log(uint p0, string memory p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); - } - - function log(uint p0, bool p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); - } - - function log(uint p0, address p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); - } - - function log(string memory p0, uint p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); - } - - function log(string memory p0, string memory p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); - } - - function log(string memory p0, bool p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); - } - - function log(string memory p0, address p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); - } - - function log(bool p0, uint p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); - } - - function log(bool p0, string memory p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); - } - - function log(bool p0, bool p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); - } - - function log(bool p0, address p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); - } - - function log(address p0, uint p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); - } - - function log(address p0, string memory p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); - } - - function log(address p0, bool p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); - } - - function log(address p0, address p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); - } - - function log(uint p0, uint p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); - } - - function log(uint p0, uint p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); - } - - function log(uint p0, uint p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); - } - - function log(uint p0, uint p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); - } - - function log(uint p0, string memory p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); - } - - function log(uint p0, string memory p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); - } - - function log(uint p0, string memory p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); - } - - function log(uint p0, string memory p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); - } - - function log(uint p0, bool p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); - } - - function log(uint p0, bool p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); - } - - function log(uint p0, bool p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); - } - - function log(uint p0, bool p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); - } - - function log(uint p0, address p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); - } - - function log(uint p0, address p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); - } - - function log(uint p0, address p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); - } - - function log(uint p0, address p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); - } - - function log(string memory p0, uint p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); - } - - function log(string memory p0, uint p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); - } - - function log(string memory p0, uint p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); - } - - function log(string memory p0, uint p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); - } - - function log(string memory p0, string memory p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); - } - - function log(string memory p0, string memory p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); - } - - function log(string memory p0, string memory p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); - } - - function log(string memory p0, string memory p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); - } - - function log(string memory p0, bool p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); - } - - function log(string memory p0, bool p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); - } - - function log(string memory p0, bool p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); - } - - function log(string memory p0, bool p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); - } - - function log(string memory p0, address p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); - } - - function log(string memory p0, address p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); - } - - function log(string memory p0, address p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); - } - - function log(string memory p0, address p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); - } - - function log(bool p0, uint p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); - } - - function log(bool p0, uint p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); - } - - function log(bool p0, uint p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); - } - - function log(bool p0, uint p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); - } - - function log(bool p0, string memory p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); - } - - function log(bool p0, string memory p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); - } - - function log(bool p0, string memory p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); - } - - function log(bool p0, string memory p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); - } - - function log(bool p0, bool p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); - } - - function log(bool p0, bool p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); - } - - function log(bool p0, bool p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); - } - - function log(bool p0, bool p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); - } - - function log(bool p0, address p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); - } - - function log(bool p0, address p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); - } - - function log(bool p0, address p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); - } - - function log(bool p0, address p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); - } - - function log(address p0, uint p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); - } - - function log(address p0, uint p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); - } - - function log(address p0, uint p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); - } - - function log(address p0, uint p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); - } - - function log(address p0, string memory p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); - } - - function log(address p0, string memory p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); - } - - function log(address p0, string memory p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); - } - - function log(address p0, string memory p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); - } - - function log(address p0, bool p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); - } - - function log(address p0, bool p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); - } - - function log(address p0, bool p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); - } - - function log(address p0, bool p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); - } - - function log(address p0, address p1, uint p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); - } - - function log(address p0, address p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); - } - - function log(address p0, address p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); - } - - function log(address p0, address p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); - } - - function log(uint p0, uint p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, uint p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, string memory p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, bool p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); - } - - function log(uint p0, address p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, uint p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); - } - - function log(address p0, uint p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, uint p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, uint p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, uint p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, uint p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, string memory p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, bool p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, address p2, uint p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); - } - -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/console2.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/console2.sol deleted file mode 100644 index 2edfda5b..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/console2.sol +++ /dev/null @@ -1,1538 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.4.22 <0.9.0; - -// The orignal console.sol uses `int` and `uint` for computing function selectors, but it should -// use `int256` and `uint256`. This modified version fixes that. This version is recommended -// over `console.sol` if you don't need compatibility with Hardhat as the logs will show up in -// forge stack traces. If you do need compatibility with Hardhat, you must use `console.sol`. -// Reference: https://github.com/NomicFoundation/hardhat/issues/2178 - -library console2 { - address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); - - function _sendLogPayload(bytes memory payload) private view { - uint256 payloadLength = payload.length; - address consoleAddress = CONSOLE_ADDRESS; - assembly { - let payloadStart := add(payload, 32) - let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) - } - } - - function log() internal view { - _sendLogPayload(abi.encodeWithSignature("log()")); - } - - function logInt(int256 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(int256)", p0)); - } - - function logUint(uint256 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0)); - } - - function logString(string memory p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); - } - - function logBool(bool p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); - } - - function logAddress(address p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); - } - - function logBytes(bytes memory p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); - } - - function logBytes1(bytes1 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); - } - - function logBytes2(bytes2 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); - } - - function logBytes3(bytes3 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); - } - - function logBytes4(bytes4 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); - } - - function logBytes5(bytes5 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); - } - - function logBytes6(bytes6 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); - } - - function logBytes7(bytes7 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); - } - - function logBytes8(bytes8 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); - } - - function logBytes9(bytes9 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); - } - - function logBytes10(bytes10 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); - } - - function logBytes11(bytes11 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); - } - - function logBytes12(bytes12 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); - } - - function logBytes13(bytes13 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); - } - - function logBytes14(bytes14 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); - } - - function logBytes15(bytes15 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); - } - - function logBytes16(bytes16 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); - } - - function logBytes17(bytes17 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); - } - - function logBytes18(bytes18 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); - } - - function logBytes19(bytes19 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); - } - - function logBytes20(bytes20 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); - } - - function logBytes21(bytes21 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); - } - - function logBytes22(bytes22 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); - } - - function logBytes23(bytes23 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); - } - - function logBytes24(bytes24 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); - } - - function logBytes25(bytes25 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); - } - - function logBytes26(bytes26 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); - } - - function logBytes27(bytes27 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); - } - - function logBytes28(bytes28 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); - } - - function logBytes29(bytes29 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); - } - - function logBytes30(bytes30 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); - } - - function logBytes31(bytes31 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); - } - - function logBytes32(bytes32 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); - } - - function log(uint256 p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0)); - } - - function log(string memory p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); - } - - function log(bool p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); - } - - function log(address p0) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); - } - - function log(uint256 p0, uint256 p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1)); - } - - function log(uint256 p0, string memory p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1)); - } - - function log(uint256 p0, bool p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1)); - } - - function log(uint256 p0, address p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1)); - } - - function log(string memory p0, uint256 p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1)); - } - - function log(string memory p0, string memory p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); - } - - function log(string memory p0, bool p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); - } - - function log(string memory p0, address p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); - } - - function log(bool p0, uint256 p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1)); - } - - function log(bool p0, string memory p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); - } - - function log(bool p0, bool p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); - } - - function log(bool p0, address p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); - } - - function log(address p0, uint256 p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1)); - } - - function log(address p0, string memory p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); - } - - function log(address p0, bool p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); - } - - function log(address p0, address p1) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); - } - - function log(uint256 p0, uint256 p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2)); - } - - function log(uint256 p0, uint256 p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2)); - } - - function log(uint256 p0, uint256 p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2)); - } - - function log(uint256 p0, uint256 p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2)); - } - - function log(uint256 p0, string memory p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2)); - } - - function log(uint256 p0, string memory p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2)); - } - - function log(uint256 p0, string memory p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2)); - } - - function log(uint256 p0, string memory p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2)); - } - - function log(uint256 p0, bool p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2)); - } - - function log(uint256 p0, bool p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2)); - } - - function log(uint256 p0, bool p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2)); - } - - function log(uint256 p0, bool p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2)); - } - - function log(uint256 p0, address p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2)); - } - - function log(uint256 p0, address p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2)); - } - - function log(uint256 p0, address p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2)); - } - - function log(uint256 p0, address p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2)); - } - - function log(string memory p0, uint256 p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2)); - } - - function log(string memory p0, uint256 p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2)); - } - - function log(string memory p0, uint256 p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2)); - } - - function log(string memory p0, uint256 p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2)); - } - - function log(string memory p0, string memory p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2)); - } - - function log(string memory p0, string memory p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); - } - - function log(string memory p0, string memory p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); - } - - function log(string memory p0, string memory p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); - } - - function log(string memory p0, bool p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2)); - } - - function log(string memory p0, bool p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); - } - - function log(string memory p0, bool p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); - } - - function log(string memory p0, bool p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); - } - - function log(string memory p0, address p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2)); - } - - function log(string memory p0, address p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); - } - - function log(string memory p0, address p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); - } - - function log(string memory p0, address p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); - } - - function log(bool p0, uint256 p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2)); - } - - function log(bool p0, uint256 p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2)); - } - - function log(bool p0, uint256 p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2)); - } - - function log(bool p0, uint256 p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2)); - } - - function log(bool p0, string memory p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2)); - } - - function log(bool p0, string memory p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); - } - - function log(bool p0, string memory p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); - } - - function log(bool p0, string memory p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); - } - - function log(bool p0, bool p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2)); - } - - function log(bool p0, bool p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); - } - - function log(bool p0, bool p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); - } - - function log(bool p0, bool p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); - } - - function log(bool p0, address p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2)); - } - - function log(bool p0, address p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); - } - - function log(bool p0, address p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); - } - - function log(bool p0, address p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); - } - - function log(address p0, uint256 p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2)); - } - - function log(address p0, uint256 p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2)); - } - - function log(address p0, uint256 p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2)); - } - - function log(address p0, uint256 p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2)); - } - - function log(address p0, string memory p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2)); - } - - function log(address p0, string memory p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); - } - - function log(address p0, string memory p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); - } - - function log(address p0, string memory p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); - } - - function log(address p0, bool p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2)); - } - - function log(address p0, bool p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); - } - - function log(address p0, bool p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); - } - - function log(address p0, bool p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); - } - - function log(address p0, address p1, uint256 p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2)); - } - - function log(address p0, address p1, string memory p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); - } - - function log(address p0, address p1, bool p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); - } - - function log(address p0, address p1, address p2) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); - } - - function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, uint256 p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, string memory p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, bool p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3)); - } - - function log(uint256 p0, address p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, uint256 p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, string memory p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, bool p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); - } - - function log(string memory p0, address p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, uint256 p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, string memory p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, bool p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); - } - - function log(bool p0, address p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3)); - } - - function log(address p0, uint256 p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); - } - - function log(address p0, string memory p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); - } - - function log(address p0, bool p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, uint256 p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, uint256 p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, uint256 p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, uint256 p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, string memory p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, string memory p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, string memory p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, string memory p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, bool p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, bool p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, bool p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, bool p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, address p2, uint256 p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, address p2, string memory p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, address p2, bool p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); - } - - function log(address p0, address p1, address p2, address p3) internal view { - _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); - } - -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdAssertions.t.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdAssertions.t.sol deleted file mode 100644 index b1816135..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdAssertions.t.sol +++ /dev/null @@ -1,379 +0,0 @@ -// SPDX-License-Identifier: Unlicense -pragma solidity >=0.7.0 <0.9.0; - -import "../Test.sol"; - -contract StdAssertionsTest is Test -{ - string constant CUSTOM_ERROR = "guh!"; - - bool constant EXPECT_PASS = false; - bool constant EXPECT_FAIL = true; - - TestTest t = new TestTest(); - - /*////////////////////////////////////////////////////////////////////////// - FAIL(STRING) - //////////////////////////////////////////////////////////////////////////*/ - - function testShouldFail() external { - vm.expectEmit(false, false, false, true); - emit log_named_string("Error", CUSTOM_ERROR); - t._fail(CUSTOM_ERROR); - } - - /*////////////////////////////////////////////////////////////////////////// - ASSERT_FALSE - //////////////////////////////////////////////////////////////////////////*/ - - function testAssertFalse_Pass() external { - t._assertFalse(false, EXPECT_PASS); - } - - function testAssertFalse_Fail() external { - vm.expectEmit(false, false, false, true); - emit log("Error: Assertion Failed"); - t._assertFalse(true, EXPECT_FAIL); - } - - function testAssertFalse_Err_Pass() external { - t._assertFalse(false, CUSTOM_ERROR, EXPECT_PASS); - } - - function testAssertFalse_Err_Fail() external { - vm.expectEmit(true, false, false, true); - emit log_named_string("Error", CUSTOM_ERROR); - t._assertFalse(true, CUSTOM_ERROR, EXPECT_FAIL); - } - - /*////////////////////////////////////////////////////////////////////////// - ASSERT_EQ(BOOL) - //////////////////////////////////////////////////////////////////////////*/ - - function testAssertEq_Bool_Pass(bool a, bool b) external { - vm.assume(a == b); - - t._assertEq(a, b, EXPECT_PASS); - } - - function testAssertEq_Bool_Fail(bool a, bool b) external { - vm.assume(a != b); - - vm.expectEmit(false, false, false, true); - emit log("Error: a == b not satisfied [bool]"); - t._assertEq(a, b, EXPECT_FAIL); - } - - function testAssertEq_BoolErr_Pass(bool a, bool b) external { - vm.assume(a == b); - - t._assertEq(a, b, CUSTOM_ERROR, EXPECT_PASS); - } - - function testAssertEq_BoolErr_Fail(bool a, bool b) external { - vm.assume(a != b); - - vm.expectEmit(true, false, false, true); - emit log_named_string("Error", CUSTOM_ERROR); - t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL); - } - - /*////////////////////////////////////////////////////////////////////////// - ASSERT_EQ(BYTES) - //////////////////////////////////////////////////////////////////////////*/ - - function testAssertEq_Bytes_Pass(bytes calldata a, bytes calldata b) external { - vm.assume(keccak256(a) == keccak256(b)); - - t._assertEq(a, b, EXPECT_PASS); - } - - function testAssertEq_Bytes_Fail(bytes calldata a, bytes calldata b) external { - vm.assume(keccak256(a) != keccak256(b)); - - vm.expectEmit(false, false, false, true); - emit log("Error: a == b not satisfied [bytes]"); - t._assertEq(a, b, EXPECT_FAIL); - } - - function testAssertEq_BytesErr_Pass(bytes calldata a, bytes calldata b) external { - vm.assume(keccak256(a) == keccak256(b)); - - t._assertEq(a, b, CUSTOM_ERROR, EXPECT_PASS); - } - - function testAssertEq_BytesErr_Fail(bytes calldata a, bytes calldata b) external { - vm.assume(keccak256(a) != keccak256(b)); - - vm.expectEmit(true, false, false, true); - emit log_named_string("Error", CUSTOM_ERROR); - t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL); - } - - /*////////////////////////////////////////////////////////////////////////// - APPROX_EQ_ABS(UINT) - //////////////////////////////////////////////////////////////////////////*/ - - function testAssertApproxEqAbs_Uint_Pass(uint256 a, uint256 b, uint256 maxDelta) external { - vm.assume(stdMath.delta(a, b) <= maxDelta); - - t._assertApproxEqAbs(a, b, maxDelta, EXPECT_PASS); - } - - function testAssertApproxEqAbs_Uint_Fail(uint256 a, uint256 b, uint256 maxDelta) external { - vm.assume(stdMath.delta(a, b) > maxDelta); - - vm.expectEmit(false, false, false, true); - emit log("Error: a ~= b not satisfied [uint]"); - t._assertApproxEqAbs(a, b, maxDelta, EXPECT_FAIL); - } - - function testAssertApproxEqAbs_UintErr_Pass(uint256 a, uint256 b, uint256 maxDelta) external { - vm.assume(stdMath.delta(a, b) <= maxDelta); - - t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_PASS); - } - - function testAssertApproxEqAbs_UintErr_Fail(uint256 a, uint256 b, uint256 maxDelta) external { - vm.assume(stdMath.delta(a, b) > maxDelta); - - vm.expectEmit(true, false, false, true); - emit log_named_string("Error", CUSTOM_ERROR); - t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_FAIL); - } - - /*////////////////////////////////////////////////////////////////////////// - APPROX_EQ_ABS(INT) - //////////////////////////////////////////////////////////////////////////*/ - - function testAssertApproxEqAbs_Int_Pass(int256 a, int256 b, uint256 maxDelta) external { - vm.assume(stdMath.delta(a, b) <= maxDelta); - - t._assertApproxEqAbs(a, b, maxDelta, EXPECT_PASS); - } - - function testAssertApproxEqAbs_Int_Fail(int256 a, int256 b, uint256 maxDelta) external { - vm.assume(stdMath.delta(a, b) > maxDelta); - - vm.expectEmit(false, false, false, true); - emit log("Error: a ~= b not satisfied [int]"); - t._assertApproxEqAbs(a, b, maxDelta, EXPECT_FAIL); - } - - function testAssertApproxEqAbs_IntErr_Pass(int256 a, int256 b, uint256 maxDelta) external { - vm.assume(stdMath.delta(a, b) <= maxDelta); - - t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_PASS); - } - - function testAssertApproxEqAbs_IntErr_Fail(int256 a, int256 b, uint256 maxDelta) external { - vm.assume(stdMath.delta(a, b) > maxDelta); - - vm.expectEmit(true, false, false, true); - emit log_named_string("Error", CUSTOM_ERROR); - t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_FAIL); - } - - /*////////////////////////////////////////////////////////////////////////// - APPROX_EQ_REL(UINT) - //////////////////////////////////////////////////////////////////////////*/ - - function testAssertApproxEqRel_Uint_Pass(uint256 a, uint256 b, uint256 maxPercentDelta) external { - vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0); - vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta); - - t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_PASS); - } - - function testAssertApproxEqRel_Uint_Fail(uint256 a, uint256 b, uint256 maxPercentDelta) external { - vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0); - vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta); - - vm.expectEmit(false, false, false, true); - emit log("Error: a ~= b not satisfied [uint]"); - t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_FAIL); - } - - function testAssertApproxEqRel_UintErr_Pass(uint256 a, uint256 b, uint256 maxPercentDelta) external { - vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0); - vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta); - - t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_PASS); - } - - function testAssertApproxEqRel_UintErr_Fail(uint256 a, uint256 b, uint256 maxPercentDelta) external { - vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0); - vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta); - - vm.expectEmit(true, false, false, true); - emit log_named_string("Error", CUSTOM_ERROR); - t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_FAIL); - } - - /*////////////////////////////////////////////////////////////////////////// - APPROX_EQ_REL(INT) - //////////////////////////////////////////////////////////////////////////*/ - - function testAssertApproxEqRel_Int_Pass(int128 a, int128 b, uint128 maxPercentDelta) external { - vm.assume(b != 0); - vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta); - - t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_PASS); - } - - function testAssertApproxEqRel_Int_Fail(int128 a, int128 b, uint128 maxPercentDelta) external { - vm.assume(b != 0); - vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta); - - vm.expectEmit(false, false, false, true); - emit log("Error: a ~= b not satisfied [int]"); - t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_FAIL); - } - - function testAssertApproxEqRel_IntErr_Pass(int128 a, int128 b, uint128 maxPercentDelta) external { - vm.assume(b != 0); - vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta); - - t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_PASS); - } - - function testAssertApproxEqRel_IntErr_Fail(int128 a, int128 b, uint128 maxPercentDelta) external { - vm.assume(b != 0); - vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta); - - vm.expectEmit(true, false, false, true); - emit log_named_string("Error", CUSTOM_ERROR); - t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_FAIL); - } -} - - -contract TestTest is Test -{ - modifier expectFailure(bool expectFail) { - bool preState = vm.load(HEVM_ADDRESS, bytes32("failed")) != bytes32(0x00); - _; - bool postState = vm.load(HEVM_ADDRESS, bytes32("failed")) != bytes32(0x00); - - if (preState == true) { - return; - } - - if (expectFail) { - require(postState == true, "expected failure not triggered"); - - // unwind the expected failure - vm.store(HEVM_ADDRESS, bytes32("failed"), bytes32(uint256(0x00))); - } else { - require(postState == false, "unexpected failure was triggered"); - } - } - - function _fail(string memory err) external expectFailure(true) { - fail(err); - } - - function _assertFalse(bool data, bool expectFail) external expectFailure(expectFail) { - assertFalse(data); - } - - function _assertFalse(bool data, string memory err, bool expectFail) external expectFailure(expectFail) { - assertFalse(data, err); - } - - function _assertEq(bool a, bool b, bool expectFail) external expectFailure(expectFail) { - assertEq(a, b); - } - - function _assertEq(bool a, bool b, string memory err, bool expectFail) external expectFailure(expectFail) { - assertEq(a, b, err); - } - - function _assertEq(bytes memory a, bytes memory b, bool expectFail) external expectFailure(expectFail) { - assertEq(a, b); - } - - function _assertEq(bytes memory a, - bytes memory b, - string memory err, - bool expectFail - ) external expectFailure(expectFail) { - assertEq(a, b, err); - } - - function _assertApproxEqAbs( - uint256 a, - uint256 b, - uint256 maxDelta, - bool expectFail - ) external expectFailure(expectFail) { - assertApproxEqAbs(a, b, maxDelta); - } - - function _assertApproxEqAbs( - uint256 a, - uint256 b, - uint256 maxDelta, - string memory err, - bool expectFail - ) external expectFailure(expectFail) { - assertApproxEqAbs(a, b, maxDelta, err); - } - - function _assertApproxEqAbs( - int256 a, - int256 b, - uint256 maxDelta, - bool expectFail - ) external expectFailure(expectFail) { - assertApproxEqAbs(a, b, maxDelta); - } - - function _assertApproxEqAbs( - int256 a, - int256 b, - uint256 maxDelta, - string memory err, - bool expectFail - ) external expectFailure(expectFail) { - assertApproxEqAbs(a, b, maxDelta, err); - } - - function _assertApproxEqRel( - uint256 a, - uint256 b, - uint256 maxPercentDelta, - bool expectFail - ) external expectFailure(expectFail) { - assertApproxEqRel(a, b, maxPercentDelta); - } - - function _assertApproxEqRel( - uint256 a, - uint256 b, - uint256 maxPercentDelta, - string memory err, - bool expectFail - ) external expectFailure(expectFail) { - assertApproxEqRel(a, b, maxPercentDelta, err); - } - - function _assertApproxEqRel( - int256 a, - int256 b, - uint256 maxPercentDelta, - bool expectFail - ) external expectFailure(expectFail) { - assertApproxEqRel(a, b, maxPercentDelta); - } - - function _assertApproxEqRel( - int256 a, - int256 b, - uint256 maxPercentDelta, - string memory err, - bool expectFail - ) external expectFailure(expectFail) { - assertApproxEqRel(a, b, maxPercentDelta, err); - } -} diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdCheats.t.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdCheats.t.sol deleted file mode 100644 index 9a48ab57..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdCheats.t.sol +++ /dev/null @@ -1,193 +0,0 @@ -// SPDX-License-Identifier: Unlicense -pragma solidity >=0.7.0 <0.9.0; - -import "../Test.sol"; - -contract StdCheatsTest is Test { - Bar test; - - function setUp() public { - test = new Bar(); - } - - function testSkip() public { - vm.warp(100); - skip(25); - assertEq(block.timestamp, 125); - } - - function testRewind() public { - vm.warp(100); - rewind(25); - assertEq(block.timestamp, 75); - } - - function testHoax() public { - hoax(address(1337)); - test.bar{value: 100}(address(1337)); - } - - function testHoaxOrigin() public { - hoax(address(1337), address(1337)); - test.origin{value: 100}(address(1337)); - } - - function testHoaxDifferentAddresses() public { - hoax(address(1337), address(7331)); - test.origin{value: 100}(address(1337), address(7331)); - } - - function testStartHoax() public { - startHoax(address(1337)); - test.bar{value: 100}(address(1337)); - test.bar{value: 100}(address(1337)); - vm.stopPrank(); - test.bar(address(this)); - } - - function testStartHoaxOrigin() public { - startHoax(address(1337), address(1337)); - test.origin{value: 100}(address(1337)); - test.origin{value: 100}(address(1337)); - vm.stopPrank(); - test.bar(address(this)); - } - - function testChangePrank() public { - vm.startPrank(address(1337)); - test.bar(address(1337)); - changePrank(address(0xdead)); - test.bar(address(0xdead)); - changePrank(address(1337)); - test.bar(address(1337)); - vm.stopPrank(); - } - - function testDeal() public { - deal(address(this), 1 ether); - assertEq(address(this).balance, 1 ether); - } - - function testDealToken() public { - Bar barToken = new Bar(); - address bar = address(barToken); - deal(bar, address(this), 10000e18); - assertEq(barToken.balanceOf(address(this)), 10000e18); - } - - function testDealTokenAdjustTS() public { - Bar barToken = new Bar(); - address bar = address(barToken); - deal(bar, address(this), 10000e18, true); - assertEq(barToken.balanceOf(address(this)), 10000e18); - assertEq(barToken.totalSupply(), 20000e18); - deal(bar, address(this), 0, true); - assertEq(barToken.balanceOf(address(this)), 0); - assertEq(barToken.totalSupply(), 10000e18); - } - - function testBound() public { - assertEq(bound(5, 0, 4), 0); - assertEq(bound(0, 69, 69), 69); - assertEq(bound(0, 68, 69), 68); - assertEq(bound(10, 150, 190), 160); - assertEq(bound(300, 2800, 3200), 3100); - assertEq(bound(9999, 1337, 6666), 6006); - } - - function testCannotBoundMaxLessThanMin() public { - vm.expectRevert(bytes("Test bound(uint256,uint256,uint256): Max is less than min.")); - bound(5, 100, 10); - } - - function testBound( - uint256 num, - uint256 min, - uint256 max - ) public { - if (min > max) (min, max) = (max, min); - - uint256 bounded = bound(num, min, max); - - assertGe(bounded, min); - assertLe(bounded, max); - } - - function testBoundUint256Max() public { - assertEq(bound(0, type(uint256).max - 1, type(uint256).max), type(uint256).max - 1); - assertEq(bound(1, type(uint256).max - 1, type(uint256).max), type(uint256).max); - } - - function testCannotBoundMaxLessThanMin( - uint256 num, - uint256 min, - uint256 max - ) public { - vm.assume(min > max); - vm.expectRevert(bytes("Test bound(uint256,uint256,uint256): Max is less than min.")); - bound(num, min, max); - } - - function testDeployCode() public { - address deployed = deployCode("StdCheats.t.sol:StdCheatsTest", bytes("")); - assertEq(string(getCode(deployed)), string(getCode(address(this)))); - } - - function testDeployCodeNoArgs() public { - address deployed = deployCode("StdCheats.t.sol:StdCheatsTest"); - assertEq(string(getCode(deployed)), string(getCode(address(this)))); - } - - function testDeployCodeFail() public { - vm.expectRevert(bytes("Test deployCode(string): Deployment failed.")); - this.deployCode("StdCheats.t.sol:RevertingContract"); - } - - function getCode(address who) internal view returns (bytes memory o_code) { - /// @solidity memory-safe-assembly - assembly { - // retrieve the size of the code, this needs assembly - let size := extcodesize(who) - // allocate output byte array - this could also be done without assembly - // by using o_code = new bytes(size) - o_code := mload(0x40) - // new "memory end" including padding - mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) - // store length in memory - mstore(o_code, size) - // actually retrieve the code, this needs assembly - extcodecopy(who, add(o_code, 0x20), 0, size) - } - } -} - -contract Bar { - constructor() { - /// `DEAL` STDCHEAT - totalSupply = 10000e18; - balanceOf[address(this)] = totalSupply; - } - - /// `HOAX` STDCHEATS - function bar(address expectedSender) public payable { - require(msg.sender == expectedSender, "!prank"); - } - function origin(address expectedSender) public payable { - require(msg.sender == expectedSender, "!prank"); - require(tx.origin == expectedSender, "!prank"); - } - function origin(address expectedSender, address expectedOrigin) public payable { - require(msg.sender == expectedSender, "!prank"); - require(tx.origin == expectedOrigin, "!prank"); - } - - /// `DEAL` STDCHEAT - mapping (address => uint256) public balanceOf; - uint256 public totalSupply; -} - -contract RevertingContract { - constructor() { - revert(); - } -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdError.t.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdError.t.sol deleted file mode 100644 index 9382d3fd..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdError.t.sol +++ /dev/null @@ -1,124 +0,0 @@ -// SPDX-License-Identifier: Unlicense -pragma solidity >=0.8.10 <0.9.0; - -import "../Test.sol"; - -contract StdErrorsTest is Test { - ErrorsTest test; - - function setUp() public { - test = new ErrorsTest(); - } - - function testExpectAssertion() public { - vm.expectRevert(stdError.assertionError); - test.assertionError(); - } - - function testExpectArithmetic() public { - vm.expectRevert(stdError.arithmeticError); - test.arithmeticError(10); - } - - function testExpectDiv() public { - vm.expectRevert(stdError.divisionError); - test.divError(0); - } - - function testExpectMod() public { - vm.expectRevert(stdError.divisionError); - test.modError(0); - } - - function testExpectEnum() public { - vm.expectRevert(stdError.enumConversionError); - test.enumConversion(1); - } - - function testExpectEncodeStg() public { - vm.expectRevert(stdError.encodeStorageError); - test.encodeStgError(); - } - - function testExpectPop() public { - vm.expectRevert(stdError.popError); - test.pop(); - } - - function testExpectOOB() public { - vm.expectRevert(stdError.indexOOBError); - test.indexOOBError(1); - } - - function testExpectMem() public { - vm.expectRevert(stdError.memOverflowError); - test.mem(); - } - - function testExpectIntern() public { - vm.expectRevert(stdError.zeroVarError); - test.intern(); - } - - function testExpectLowLvl() public { - vm.expectRevert(stdError.lowLevelError); - test.someArr(0); - } -} - -contract ErrorsTest { - enum T { - T1 - } - - uint256[] public someArr; - bytes someBytes; - - function assertionError() public pure { - assert(false); - } - - function arithmeticError(uint256 a) public pure { - a -= 100; - } - - function divError(uint256 a) public pure { - 100 / a; - } - - function modError(uint256 a) public pure { - 100 % a; - } - - function enumConversion(uint256 a) public pure { - T(a); - } - - function encodeStgError() public { - /// @solidity memory-safe-assembly - assembly { - sstore(someBytes.slot, 1) - } - keccak256(someBytes); - } - - function pop() public { - someArr.pop(); - } - - function indexOOBError(uint256 a) public pure { - uint256[] memory t = new uint256[](0); - t[a]; - } - - function mem() public pure { - uint256 l = 2**256 / 32; - new uint256[](l); - } - - function intern() public returns (uint256) { - function(uint256) internal returns (uint256) x; - x(2); - return 7; - } -} diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdMath.t.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdMath.t.sol deleted file mode 100644 index 8317118a..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdMath.t.sol +++ /dev/null @@ -1,200 +0,0 @@ -// SPDX-License-Identifier: Unlicense -pragma solidity >=0.8.0 <0.9.0; - -import "../Test.sol"; - -contract StdMathTest is Test -{ - function testGetAbs() external { - assertEq(stdMath.abs(-50), 50); - assertEq(stdMath.abs(50), 50); - assertEq(stdMath.abs(-1337), 1337); - assertEq(stdMath.abs(0), 0); - - assertEq(stdMath.abs(type(int256).min), (type(uint256).max >> 1) + 1); - assertEq(stdMath.abs(type(int256).max), (type(uint256).max >> 1)); - } - - function testGetAbs_Fuzz(int256 a) external { - uint256 manualAbs = getAbs(a); - - uint256 abs = stdMath.abs(a); - - assertEq(abs, manualAbs); - } - - function testGetDelta_Uint() external { - assertEq(stdMath.delta(uint256(0), uint256(0)), 0); - assertEq(stdMath.delta(uint256(0), uint256(1337)), 1337); - assertEq(stdMath.delta(uint256(0), type(uint64).max), type(uint64).max); - assertEq(stdMath.delta(uint256(0), type(uint128).max), type(uint128).max); - assertEq(stdMath.delta(uint256(0), type(uint256).max), type(uint256).max); - - assertEq(stdMath.delta(0, uint256(0)), 0); - assertEq(stdMath.delta(1337, uint256(0)), 1337); - assertEq(stdMath.delta(type(uint64).max, uint256(0)), type(uint64).max); - assertEq(stdMath.delta(type(uint128).max, uint256(0)), type(uint128).max); - assertEq(stdMath.delta(type(uint256).max, uint256(0)), type(uint256).max); - - assertEq(stdMath.delta(1337, uint256(1337)), 0); - assertEq(stdMath.delta(type(uint256).max, type(uint256).max), 0); - assertEq(stdMath.delta(5000, uint256(1250)), 3750); - } - - function testGetDelta_Uint_Fuzz(uint256 a, uint256 b) external { - uint256 manualDelta; - if (a > b) { - manualDelta = a - b; - } else { - manualDelta = b - a; - } - - uint256 delta = stdMath.delta(a, b); - - assertEq(delta, manualDelta); - } - - function testGetDelta_Int() external { - assertEq(stdMath.delta(int256(0), int256(0)), 0); - assertEq(stdMath.delta(int256(0), int256(1337)), 1337); - assertEq(stdMath.delta(int256(0), type(int64).max), type(uint64).max >> 1); - assertEq(stdMath.delta(int256(0), type(int128).max), type(uint128).max >> 1); - assertEq(stdMath.delta(int256(0), type(int256).max), type(uint256).max >> 1); - - assertEq(stdMath.delta(0, int256(0)), 0); - assertEq(stdMath.delta(1337, int256(0)), 1337); - assertEq(stdMath.delta(type(int64).max, int256(0)), type(uint64).max >> 1); - assertEq(stdMath.delta(type(int128).max, int256(0)), type(uint128).max >> 1); - assertEq(stdMath.delta(type(int256).max, int256(0)), type(uint256).max >> 1); - - assertEq(stdMath.delta(-0, int256(0)), 0); - assertEq(stdMath.delta(-1337, int256(0)), 1337); - assertEq(stdMath.delta(type(int64).min, int256(0)), (type(uint64).max >> 1) + 1); - assertEq(stdMath.delta(type(int128).min, int256(0)), (type(uint128).max >> 1) + 1); - assertEq(stdMath.delta(type(int256).min, int256(0)), (type(uint256).max >> 1) + 1); - - assertEq(stdMath.delta(int256(0), -0), 0); - assertEq(stdMath.delta(int256(0), -1337), 1337); - assertEq(stdMath.delta(int256(0), type(int64).min), (type(uint64).max >> 1) + 1); - assertEq(stdMath.delta(int256(0), type(int128).min), (type(uint128).max >> 1) + 1); - assertEq(stdMath.delta(int256(0), type(int256).min), (type(uint256).max >> 1) + 1); - - assertEq(stdMath.delta(1337, int256(1337)), 0); - assertEq(stdMath.delta(type(int256).max, type(int256).max), 0); - assertEq(stdMath.delta(type(int256).min, type(int256).min), 0); - assertEq(stdMath.delta(type(int256).min, type(int256).max), type(uint256).max); - assertEq(stdMath.delta(5000, int256(1250)), 3750); - } - - function testGetDelta_Int_Fuzz(int256 a, int256 b) external { - uint256 absA = getAbs(a); - uint256 absB = getAbs(b); - uint256 absDelta = absA > absB - ? absA - absB - : absB - absA; - - uint256 manualDelta; - if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) { - manualDelta = absDelta; - } - // (a < 0 && b >= 0) || (a >= 0 && b < 0) - else { - manualDelta = absA + absB; - } - - uint256 delta = stdMath.delta(a, b); - - assertEq(delta, manualDelta); - } - - function testGetPercentDelta_Uint() external { - assertEq(stdMath.percentDelta(uint256(0), uint256(1337)), 1e18); - assertEq(stdMath.percentDelta(uint256(0), type(uint64).max), 1e18); - assertEq(stdMath.percentDelta(uint256(0), type(uint128).max), 1e18); - assertEq(stdMath.percentDelta(uint256(0), type(uint192).max), 1e18); - - assertEq(stdMath.percentDelta(1337, uint256(1337)), 0); - assertEq(stdMath.percentDelta(type(uint192).max, type(uint192).max), 0); - assertEq(stdMath.percentDelta(0, uint256(2500)), 1e18); - assertEq(stdMath.percentDelta(2500, uint256(2500)), 0); - assertEq(stdMath.percentDelta(5000, uint256(2500)), 1e18); - assertEq(stdMath.percentDelta(7500, uint256(2500)), 2e18); - - vm.expectRevert(stdError.divisionError); - stdMath.percentDelta(uint256(1), 0); - } - - function testGetPercentDelta_Uint_Fuzz(uint192 a, uint192 b) external { - vm.assume(b != 0); - uint256 manualDelta; - if (a > b) { - manualDelta = a - b; - } else { - manualDelta = b - a; - } - - uint256 manualPercentDelta = manualDelta * 1e18 / b; - uint256 percentDelta = stdMath.percentDelta(a, b); - - assertEq(percentDelta, manualPercentDelta); - } - - function testGetPercentDelta_Int() external { - assertEq(stdMath.percentDelta(int256(0), int256(1337)), 1e18); - assertEq(stdMath.percentDelta(int256(0), -1337), 1e18); - assertEq(stdMath.percentDelta(int256(0), type(int64).min), 1e18); - assertEq(stdMath.percentDelta(int256(0), type(int128).min), 1e18); - assertEq(stdMath.percentDelta(int256(0), type(int192).min), 1e18); - assertEq(stdMath.percentDelta(int256(0), type(int64).max), 1e18); - assertEq(stdMath.percentDelta(int256(0), type(int128).max), 1e18); - assertEq(stdMath.percentDelta(int256(0), type(int192).max), 1e18); - - assertEq(stdMath.percentDelta(1337, int256(1337)), 0); - assertEq(stdMath.percentDelta(type(int192).max, type(int192).max), 0); - assertEq(stdMath.percentDelta(type(int192).min, type(int192).min), 0); - - assertEq(stdMath.percentDelta(type(int192).min, type(int192).max), 2e18); // rounds the 1 wei diff down - assertEq(stdMath.percentDelta(type(int192).max, type(int192).min), 2e18 - 1); // rounds the 1 wei diff down - assertEq(stdMath.percentDelta(0, int256(2500)), 1e18); - assertEq(stdMath.percentDelta(2500, int256(2500)), 0); - assertEq(stdMath.percentDelta(5000, int256(2500)), 1e18); - assertEq(stdMath.percentDelta(7500, int256(2500)), 2e18); - - vm.expectRevert(stdError.divisionError); - stdMath.percentDelta(int256(1), 0); - } - - function testGetPercentDelta_Int_Fuzz(int192 a, int192 b) external { - vm.assume(b != 0); - uint256 absA = getAbs(a); - uint256 absB = getAbs(b); - uint256 absDelta = absA > absB - ? absA - absB - : absB - absA; - - uint256 manualDelta; - if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) { - manualDelta = absDelta; - } - // (a < 0 && b >= 0) || (a >= 0 && b < 0) - else { - manualDelta = absA + absB; - } - - uint256 manualPercentDelta = manualDelta * 1e18 / absB; - uint256 percentDelta = stdMath.percentDelta(a, b); - - assertEq(percentDelta, manualPercentDelta); - } - - /*////////////////////////////////////////////////////////////////////////// - HELPERS - //////////////////////////////////////////////////////////////////////////*/ - - function getAbs(int256 a) private pure returns (uint256) { - if (a < 0) - return a == type(int256).min ? uint256(type(int256).max) + 1 : uint256(-a); - - return uint256(a); - } -} diff --git a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdStorage.t.sol b/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdStorage.t.sol deleted file mode 100644 index 347297f2..00000000 --- a/CVLByExample/aave-token-v3/lib/forge-std/src/test/StdStorage.t.sol +++ /dev/null @@ -1,306 +0,0 @@ -// SPDX-License-Identifier: Unlicense -pragma solidity >=0.7.0 <0.9.0; - -import "../Test.sol"; - -contract StdStorageTest is Test { - using stdStorage for StdStorage; - - StorageTest test; - - function setUp() public { - test = new StorageTest(); - } - - function testStorageHidden() public { - assertEq(uint256(keccak256("my.random.var")), stdstore.target(address(test)).sig("hidden()").find()); - } - - function testStorageObvious() public { - assertEq(uint256(0), stdstore.target(address(test)).sig("exists()").find()); - } - - function testStorageCheckedWriteHidden() public { - stdstore.target(address(test)).sig(test.hidden.selector).checked_write(100); - assertEq(uint256(test.hidden()), 100); - } - - function testStorageCheckedWriteObvious() public { - stdstore.target(address(test)).sig(test.exists.selector).checked_write(100); - assertEq(test.exists(), 100); - } - - function testStorageMapStructA() public { - uint256 slot = stdstore - .target(address(test)) - .sig(test.map_struct.selector) - .with_key(address(this)) - .depth(0) - .find(); - assertEq(uint256(keccak256(abi.encode(address(this), 4))), slot); - } - - function testStorageMapStructB() public { - uint256 slot = stdstore - .target(address(test)) - .sig(test.map_struct.selector) - .with_key(address(this)) - .depth(1) - .find(); - assertEq(uint256(keccak256(abi.encode(address(this), 4))) + 1, slot); - } - - function testStorageDeepMap() public { - uint256 slot = stdstore - .target(address(test)) - .sig(test.deep_map.selector) - .with_key(address(this)) - .with_key(address(this)) - .find(); - assertEq(uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint(5)))))), slot); - } - - function testStorageCheckedWriteDeepMap() public { - stdstore - .target(address(test)) - .sig(test.deep_map.selector) - .with_key(address(this)) - .with_key(address(this)) - .checked_write(100); - assertEq(100, test.deep_map(address(this), address(this))); - } - - function testStorageDeepMapStructA() public { - uint256 slot = stdstore - .target(address(test)) - .sig(test.deep_map_struct.selector) - .with_key(address(this)) - .with_key(address(this)) - .depth(0) - .find(); - assertEq(bytes32(uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint(6)))))) + 0), bytes32(slot)); - } - - function testStorageDeepMapStructB() public { - uint256 slot = stdstore - .target(address(test)) - .sig(test.deep_map_struct.selector) - .with_key(address(this)) - .with_key(address(this)) - .depth(1) - .find(); - assertEq(bytes32(uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint(6)))))) + 1), bytes32(slot)); - } - - function testStorageCheckedWriteDeepMapStructA() public { - stdstore - .target(address(test)) - .sig(test.deep_map_struct.selector) - .with_key(address(this)) - .with_key(address(this)) - .depth(0) - .checked_write(100); - (uint256 a, uint256 b) = test.deep_map_struct(address(this), address(this)); - assertEq(100, a); - assertEq(0, b); - } - - function testStorageCheckedWriteDeepMapStructB() public { - stdstore - .target(address(test)) - .sig(test.deep_map_struct.selector) - .with_key(address(this)) - .with_key(address(this)) - .depth(1) - .checked_write(100); - (uint256 a, uint256 b) = test.deep_map_struct(address(this), address(this)); - assertEq(0, a); - assertEq(100, b); - } - - function testStorageCheckedWriteMapStructA() public { - stdstore - .target(address(test)) - .sig(test.map_struct.selector) - .with_key(address(this)) - .depth(0) - .checked_write(100); - (uint256 a, uint256 b) = test.map_struct(address(this)); - assertEq(a, 100); - assertEq(b, 0); - } - - function testStorageCheckedWriteMapStructB() public { - stdstore - .target(address(test)) - .sig(test.map_struct.selector) - .with_key(address(this)) - .depth(1) - .checked_write(100); - (uint256 a, uint256 b) = test.map_struct(address(this)); - assertEq(a, 0); - assertEq(b, 100); - } - - function testStorageStructA() public { - uint256 slot = stdstore.target(address(test)).sig(test.basic.selector).depth(0).find(); - assertEq(uint256(7), slot); - } - - function testStorageStructB() public { - uint256 slot = stdstore.target(address(test)).sig(test.basic.selector).depth(1).find(); - assertEq(uint256(7) + 1, slot); - } - - function testStorageCheckedWriteStructA() public { - stdstore.target(address(test)).sig(test.basic.selector).depth(0).checked_write(100); - (uint256 a, uint256 b) = test.basic(); - assertEq(a, 100); - assertEq(b, 1337); - } - - function testStorageCheckedWriteStructB() public { - stdstore.target(address(test)).sig(test.basic.selector).depth(1).checked_write(100); - (uint256 a, uint256 b) = test.basic(); - assertEq(a, 1337); - assertEq(b, 100); - } - - function testStorageMapAddrFound() public { - uint256 slot = stdstore.target(address(test)).sig(test.map_addr.selector).with_key(address(this)).find(); - assertEq(uint256(keccak256(abi.encode(address(this), uint(1)))), slot); - } - - function testStorageMapUintFound() public { - uint256 slot = stdstore.target(address(test)).sig(test.map_uint.selector).with_key(100).find(); - assertEq(uint256(keccak256(abi.encode(100, uint(2)))), slot); - } - - function testStorageCheckedWriteMapUint() public { - stdstore.target(address(test)).sig(test.map_uint.selector).with_key(100).checked_write(100); - assertEq(100, test.map_uint(100)); - } - - function testStorageCheckedWriteMapAddr() public { - stdstore.target(address(test)).sig(test.map_addr.selector).with_key(address(this)).checked_write(100); - assertEq(100, test.map_addr(address(this))); - } - - function testStorageCheckedWriteMapBool() public { - stdstore.target(address(test)).sig(test.map_bool.selector).with_key(address(this)).checked_write(true); - assertTrue(test.map_bool(address(this))); - } - - function testFailStorageCheckedWriteMapPacked() public { - // expect PackedSlot error but not external call so cant expectRevert - stdstore.target(address(test)).sig(test.read_struct_lower.selector).with_key(address(uint160(1337))).checked_write(100); - } - - function testStorageCheckedWriteMapPackedSuccess() public { - uint256 full = test.map_packed(address(1337)); - // keep upper 128, set lower 128 to 1337 - full = (full & (uint256((1 << 128) - 1) << 128)) | 1337; - stdstore.target(address(test)).sig(test.map_packed.selector).with_key(address(uint160(1337))).checked_write(full); - assertEq(1337, test.read_struct_lower(address(1337))); - } - - function testFailStorageConst() public { - // vm.expectRevert(abi.encodeWithSignature("NotStorage(bytes4)", bytes4(keccak256("const()")))); - stdstore.target(address(test)).sig("const()").find(); - } - - function testFailStorageNativePack() public { - stdstore.target(address(test)).sig(test.tA.selector).find(); - stdstore.target(address(test)).sig(test.tB.selector).find(); - - // these both would fail - stdstore.target(address(test)).sig(test.tC.selector).find(); - stdstore.target(address(test)).sig(test.tD.selector).find(); - } - - function testStorageReadBytes32() public { - bytes32 val = stdstore.target(address(test)).sig(test.tE.selector).read_bytes32(); - assertEq(val, hex"1337"); - } - - function testStorageReadBool() public { - bool val = stdstore.target(address(test)).sig(test.tB.selector).read_bool(); - assertEq(val, false); - } - - function testStorageReadAddress() public { - address val = stdstore.target(address(test)).sig(test.tF.selector).read_address(); - assertEq(val, address(1337)); - } - - function testStorageReadUint() public { - uint256 val = stdstore.target(address(test)).sig(test.exists.selector).read_uint(); - assertEq(val, 1); - } - - function testStorageReadInt() public { - int256 val = stdstore.target(address(test)).sig(test.tG.selector).read_int(); - assertEq(val, type(int256).min); - } -} - -contract StorageTest { - uint256 public exists = 1; - mapping(address => uint256) public map_addr; - mapping(uint256 => uint256) public map_uint; - mapping(address => uint256) public map_packed; - mapping(address => UnpackedStruct) public map_struct; - mapping(address => mapping(address => uint256)) public deep_map; - mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct; - UnpackedStruct public basic; - - uint248 public tA; - bool public tB; - - - bool public tC = false; - uint248 public tD = 1; - - - struct UnpackedStruct { - uint256 a; - uint256 b; - } - - mapping(address => bool) public map_bool; - - bytes32 public tE = hex"1337"; - address public tF = address(1337); - int256 public tG = type(int256).min; - - constructor() { - basic = UnpackedStruct({ - a: 1337, - b: 1337 - }); - - uint256 two = (1<<128) | 1; - map_packed[msg.sender] = two; - map_packed[address(bytes20(uint160(1337)))] = 1<<128; - } - - function read_struct_upper(address who) public view returns (uint256) { - return map_packed[who] >> 128; - } - - function read_struct_lower(address who) public view returns (uint256) { - return map_packed[who] & ((1 << 128) - 1); - } - - function hidden() public view returns (bytes32 t) { - bytes32 slot = keccak256("my.random.var"); - /// @solidity memory-safe-assembly - assembly { - t := sload(slot) - } - } - - function const() public pure returns (bytes32 t) { - t = bytes32(hex"1337"); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.codecov.yml b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.codecov.yml deleted file mode 100644 index 54616a49..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.codecov.yml +++ /dev/null @@ -1,11 +0,0 @@ -comment: off -github_checks: - annotations: false -coverage: - status: - patch: - default: - target: 95% - project: - default: - threshold: 1% diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.editorconfig b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.editorconfig deleted file mode 100644 index 9e0ee91b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.editorconfig +++ /dev/null @@ -1,21 +0,0 @@ -# EditorConfig is awesome: https://EditorConfig.org - -# top-most EditorConfig file -root = true - -[*] -charset = utf-8 -end_of_line = lf -indent_style = space -insert_final_newline = true -trim_trailing_whitespace = false -max_line_length = 120 - -[*.sol] -indent_size = 4 - -[*.js] -indent_size = 2 - -[*.adoc] -max_line_length = 0 diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.eslintrc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.eslintrc deleted file mode 100644 index 6be0feff..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.eslintrc +++ /dev/null @@ -1,64 +0,0 @@ -{ - "extends" : [ - "standard", - "plugin:promise/recommended", - ], - "plugins": [ - "mocha-no-only", - "promise", - ], - "env": { - "browser" : true, - "node" : true, - "mocha" : true, - "jest" : true, - }, - "globals" : { - "artifacts": false, - "contract": false, - "assert": false, - "web3": false, - "usePlugin": false, - "extendEnvironment": false, - }, - "rules": { - - // Strict mode - "strict": ["error", "global"], - - // Code style - "array-bracket-spacing": ["off"], - "camelcase": ["error", {"properties": "always"}], - "comma-dangle": ["error", "always-multiline"], - "comma-spacing": ["error", {"before": false, "after": true}], - "dot-notation": ["error", {"allowKeywords": true, "allowPattern": ""}], - "eol-last": ["error", "always"], - "eqeqeq": ["error", "smart"], - "generator-star-spacing": ["error", "before"], - "indent": ["error", 2], - "linebreak-style": ["error", "unix"], - "max-len": ["error", 120, 2], - "no-debugger": "off", - "no-dupe-args": "error", - "no-dupe-keys": "error", - "no-mixed-spaces-and-tabs": ["error", "smart-tabs"], - "no-redeclare": ["error", {"builtinGlobals": true}], - "no-trailing-spaces": ["error", { "skipBlankLines": false }], - "no-undef": "error", - "no-use-before-define": "off", - "no-var": "error", - "object-curly-spacing": ["error", "always"], - "prefer-const": "error", - "quotes": ["error", "single"], - "semi": ["error", "always"], - "space-before-function-paren": ["error", "always"], - - "mocha-no-only/mocha-no-only": ["error"], - - "promise/always-return": "off", - "promise/avoid-new": "off", - }, - "parserOptions": { - "ecmaVersion": 2018 - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.gitattributes b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.gitattributes deleted file mode 100644 index 52031de5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.sol linguist-language=Solidity diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/bug_report.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 2797a088..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -name: Bug report -about: Report a bug in OpenZeppelin Contracts - ---- - - - - - -**💻 Environment** - - - -**📝 Details** - - - -**🔢 Code to reproduce bug** - - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/config.yml b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 80ffe00c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,4 +0,0 @@ -contact_links: - - name: Support request - url: https://forum.openzeppelin.com/c/support/contracts/18 - about: Ask the community in the Community Forum diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/feature_request.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index ff596b0c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for OpenZeppelin Contracts - ---- - -**🧐 Motivation** - - -**📝 Details** - - - - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/PULL_REQUEST_TEMPLATE.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 469c645b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,20 +0,0 @@ - - - - - -Fixes #???? - - - - - -#### PR Checklist - - - - - -- [ ] Tests -- [ ] Documentation -- [ ] Changelog entry diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/docs.yml b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/docs.yml deleted file mode 100644 index 6f5ca62d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/docs.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Build Docs - -on: - push: - branches: [release-v*] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v2 - with: - node-version: 12.x - - uses: actions/cache@v2 - id: cache - with: - path: '**/node_modules' - key: npm-v2-${{ hashFiles('**/package-lock.json') }} - restore-keys: npm-v2- - - run: npm ci - if: steps.cache.outputs.cache-hit != 'true' - - run: bash scripts/git-user-config.sh - - run: node scripts/update-docs-branch.js - - run: git push --all origin diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/test.yml b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/test.yml deleted file mode 100644 index 8d13372b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/test.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: Test - -on: - push: - branches: - - master - - release-v* - pull_request: {} - workflow_dispatch: {} - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v2 - with: - node-version: 12.x - - uses: actions/cache@v2 - id: cache - with: - path: '**/node_modules' - key: npm-v2-${{ hashFiles('**/package-lock.json') }} - restore-keys: npm-v2- - - run: npm ci - if: steps.cache.outputs.cache-hit != 'true' - - run: npm run lint - - run: npm run test - env: - FORCE_COLOR: 1 - ENABLE_GAS_REPORT: true - - run: npm run test:inheritance - - name: Print gas report - run: cat gas-report.txt - - coverage: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 2 - - uses: actions/setup-node@v2 - with: - node-version: 12.x - - uses: actions/cache@v2 - id: cache - with: - path: '**/node_modules' - key: npm-v2-${{ hashFiles('**/package-lock.json') }} - restore-keys: npm-v2- - - run: npm ci - if: steps.cache.outputs.cache-hit != 'true' - - run: npm run coverage - env: - NODE_OPTIONS: --max_old_space_size=4096 - - uses: codecov/codecov-action@v2 diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/upgradeable.yml b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/upgradeable.yml deleted file mode 100644 index a94f78c9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.github/workflows/upgradeable.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: Upgradeable Trigger - -on: - push: - branches: - - master - - release-v* - -jobs: - trigger: - runs-on: ubuntu-latest - steps: - - id: app - uses: getsentry/action-github-app-token@v1 - with: - app_id: ${{ secrets.UPGRADEABLE_APP_ID }} - private_key: ${{ secrets.UPGRADEABLE_APP_PK }} - - run: | - curl -X POST \ - https://api.github.com/repos/OpenZeppelin/openzeppelin-contracts-upgradeable/dispatches \ - -H 'Accept: application/vnd.github.v3+json' \ - -H 'Authorization: token ${{ steps.app.outputs.token }}' \ - -d '{ "event_type": "Update", "client_payload": { "ref": "${{ github.ref }}" } }' diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.gitignore b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.gitignore deleted file mode 100644 index c60c5d94..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.gitignore +++ /dev/null @@ -1,64 +0,0 @@ -*.swp -*.swo - -# Logs -logs -*.log - -# Runtime data -pids -*.pid -*.seed -allFiredEvents -scTopics - -# Coverage directory used by tools like istanbul -coverage -coverage.json -coverageEnv - -# node-waf configuration -.lock-wscript - -# Dependency directory -node_modules - -# Debug log from npm -npm-debug.log - -# local env variables -.env - -# truffle build directory -build/ - -# macOS -.DS_Store - -# truffle -.node-xmlhttprequest-* - -# IntelliJ IDE -.idea - -# docs artifacts -docs/modules/api - -# only used to package @openzeppelin/contracts -contracts/build/ -contracts/README.md - -# temporary artifact from solidity-coverage -allFiredEvents -.coverage_artifacts -.coverage_cache -.coverage_contracts - -# hardhat -cache -artifacts - -# Certora -.certora* -.last_confs -certora_* diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.mocharc.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.mocharc.js deleted file mode 100644 index 920662db..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.mocharc.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - require: 'hardhat/register', - timeout: 4000, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.prettierrc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.prettierrc deleted file mode 100644 index 5c11cc22..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.prettierrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "overrides": [ - { - "files": "*.sol", - "options": { - "printWidth": 120, - "explicitTypes": "always" - } - } - ] -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.solcover.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.solcover.js deleted file mode 100644 index 6cf991ef..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.solcover.js +++ /dev/null @@ -1,15 +0,0 @@ -module.exports = { - norpc: true, - testCommand: 'npm test', - compileCommand: 'npm run compile', - skipFiles: [ - 'mocks', - ], - providerOptions: { - default_balance_ether: '10000000000000000000000000', - }, - mocha: { - fgrep: '[skip-on-coverage]', - invert: true, - }, -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.solhint.json b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.solhint.json deleted file mode 100644 index 77292884..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/.solhint.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "rules": { - "no-unused-vars": "error", - "const-name-snakecase": "error", - "contract-name-camelcase": "error", - "event-name-camelcase": "error", - "func-name-mixedcase": "error", - "func-param-name-mixedcase": "error", - "modifier-name-mixedcase": "error", - "private-vars-leading-underscore": "error", - "var-name-mixedcase": "error", - "imports-on-top": "error" - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CHANGELOG.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CHANGELOG.md deleted file mode 100644 index 0de91f6b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CHANGELOG.md +++ /dev/null @@ -1,452 +0,0 @@ -# Changelog - -## 4.5.0 (2022-02-09) - - * `ERC2981`: add implementation of the royalty standard, and the respective extensions for `ERC721` and `ERC1155`. ([#3012](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3012)) - * `GovernorTimelockControl`: improve the `state()` function to have it reflect cases where a proposal has been canceled directly on the timelock. ([#2977](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2977)) - * Preset contracts are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com). ([#2986](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2986)) - * `Governor`: add a relay function to help recover assets sent to a governor that is not its own executor (e.g. when using a timelock). ([#2926](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2926)) - * `GovernorPreventLateQuorum`: add new module to ensure a minimum voting duration is available after the quorum is reached. ([#2973](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2973)) - * `ERC721`: improved revert reason when transferring from wrong owner. ([#2975](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2975)) - * `Votes`: Added a base contract for vote tracking with delegation. ([#2944](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2944)) - * `ERC721Votes`: Added an extension of ERC721 enabled with vote tracking and delegation. ([#2944](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2944)) - * `ERC2771Context`: use immutable storage to store the forwarder address, no longer an issue since Solidity >=0.8.8 allows reading immutable variables in the constructor. ([#2917](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2917)) - * `Base64`: add a library to parse bytes into base64 strings using `encode(bytes memory)` function, and provide examples to show how to use to build URL-safe `tokenURIs`. ([#2884](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2884)) - * `ERC20`: reduce allowance before triggering transfer. ([#3056](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3056)) - * `ERC20`: do not update allowance on `transferFrom` when allowance is `type(uint256).max`. ([#3085](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3085)) - * `ERC20`: add a `_spendAllowance` internal function. ([#3170](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3170)) - * `ERC20Burnable`: do not update allowance on `burnFrom` when allowance is `type(uint256).max`. ([#3170](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3170)) - * `ERC777`: do not update allowance on `transferFrom` when allowance is `type(uint256).max`. ([#3085](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3085)) - * `ERC777`: add a `_spendAllowance` internal function. ([#3170](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3170)) - * `SignedMath`: a new signed version of the Math library with `max`, `min`, and `average`. ([#2686](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2686)) - * `SignedMath`: add a `abs(int256)` method that returns the unsigned absolute value of a signed value. ([#2984](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2984)) - * `ERC1967Upgrade`: Refactor the secure upgrade to use `ERC1822` instead of the previous rollback mechanism. This reduces code complexity and attack surface with similar security guarantees. ([#3021](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3021)) - * `UUPSUpgradeable`: Add `ERC1822` compliance to support the updated secure upgrade mechanism. ([#3021](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3021)) - * Some more functions have been made virtual to customize them via overrides. In many cases this will not imply that other functions in the contract will automatically adapt to the overridden definitions. People who wish to override should consult the source code to understand the impact and if they need to override any additional functions to achieve the desired behavior. - -### Breaking changes - -* `ERC1967Upgrade`: The function `_upgradeToAndCallSecure` was renamed to `_upgradeToAndCallUUPS`, along with the change in security mechanism described above. -* `Address`: The Solidity pragma is increased from `^0.8.0` to `^0.8.1`. This is required by the `account.code.length` syntax that replaces inline assembly. This may require users to bump their compiler version from `0.8.0` to `0.8.1` or later. Note that other parts of the code already include stricter requirements. - -## 4.4.2 (2022-01-11) - -### Bugfixes - * `GovernorCompatibilityBravo`: Fix error in the encoding of calldata for proposals submitted through the compatibility interface with explicit signatures. ([#3100](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3100)) - -## 4.4.1 (2021-12-14) - - * `Initializable`: change the existing `initializer` modifier and add a new `onlyInitializing` modifier to prevent reentrancy risk. ([#3006](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3006)) - -### Breaking change - -It is no longer possible to call an `initializer`-protected function from within another `initializer` function outside the context of a constructor. Projects using OpenZeppelin upgradeable proxies should continue to work as is, since in the common case the initializer is invoked in the constructor directly. If this is not the case for you, the suggested change is to use the new `onlyInitializing` modifier in the following way: - -```diff - contract A { -- function initialize() public initializer { ... } -+ function initialize() internal onlyInitializing { ... } - } - contract B is A { - function initialize() public initializer { - A.initialize(); - } - } -``` - -## 4.4.0 (2021-11-25) - - * `Ownable`: add an internal `_transferOwnership(address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568)) - * `AccessControl`: add internal `_grantRole(bytes32,address)` and `_revokeRole(bytes32,address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568)) - * `AccessControl`: mark `_setupRole(bytes32,address)` as deprecated in favor of `_grantRole(bytes32,address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568)) - * `AccessControlEnumerable`: hook into `_grantRole(bytes32,address)` and `_revokeRole(bytes32,address)`. ([#2946](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2946)) - * `EIP712`: cache `address(this)` to immutable storage to avoid potential issues if a vanilla contract is used in a delegatecall context. ([#2852](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2852)) - * Add internal `_setApprovalForAll` to `ERC721` and `ERC1155`. ([#2834](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2834)) - * `Governor`: shift vote start and end by one block to better match Compound's GovernorBravo and prevent voting at the Governor level if the voting snapshot is not ready. ([#2892](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2892)) - * `GovernorCompatibilityBravo`: consider quorum an inclusive rather than exclusive minimum to match Compound's GovernorBravo. ([#2974](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2974)) - * `GovernorSettings`: a new governor module that manages voting settings updatable through governance actions. ([#2904](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2904)) - * `PaymentSplitter`: now supports ERC20 assets in addition to Ether. ([#2858](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2858)) - * `ECDSA`: add a variant of `toEthSignedMessageHash` for arbitrary length message hashing. ([#2865](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2865)) - * `MerkleProof`: add a `processProof` function that returns the rebuilt root hash given a leaf and a proof. ([#2841](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2841)) - * `VestingWallet`: new contract that handles the vesting of Ether and ERC20 tokens following a customizable vesting schedule. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2748)) - * `Governor`: enable receiving Ether when a Timelock contract is not used. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2849)) - * `GovernorTimelockCompound`: fix ability to use Ether stored in the Timelock contract. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2849)) - -## 4.3.3 - - * `ERC1155Supply`: Handle `totalSupply` changes by hooking into `_beforeTokenTransfer` to ensure consistency of balances and supply during `IERC1155Receiver.onERC1155Received` calls. - -## 4.3.2 (2021-09-14) - - * `UUPSUpgradeable`: Add modifiers to prevent `upgradeTo` and `upgradeToAndCall` being executed on any contract that is not the active ERC1967 proxy. This prevents these functions being called on implementation contracts or minimal ERC1167 clones, in particular. - -## 4.3.1 (2021-08-26) - - * `TimelockController`: Add additional isOperationReady check. - -## 4.3.0 (2021-08-17) - - * `ERC2771Context`: use private variable from storage to store the forwarder address. Fixes issues where `_msgSender()` was not callable from constructors. ([#2754](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2754)) - * `EnumerableSet`: add `values()` functions that returns an array containing all values in a single call. ([#2768](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2768)) - * `Governor`: added a modular system of `Governor` contracts based on `GovernorAlpha` and `GovernorBravo`. ([#2672](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2672)) - * Add an `interfaces` folder containing solidity interfaces to final ERCs. ([#2517](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2517)) - * `ECDSA`: add `tryRecover` functions that will not throw if the signature is invalid, and will return an error flag instead. ([#2661](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2661)) - * `SignatureChecker`: Reduce gas usage of the `isValidSignatureNow` function for the "signature by EOA" case. ([#2661](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2661)) - -## 4.2.0 (2021-06-30) - - * `ERC20Votes`: add a new extension of the `ERC20` token with support for voting snapshots and delegation. ([#2632](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2632)) - * `ERC20VotesComp`: Variant of `ERC20Votes` that is compatible with Compound's `Comp` token interface but restricts supply to `uint96`. ([#2706](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2706)) - * `ERC20Wrapper`: add a new extension of the `ERC20` token which wraps an underlying token. Deposit and withdraw guarantee that the total supply is backed by a corresponding amount of underlying token. ([#2633](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2633)) - * Enumerables: Improve gas cost of removal in `EnumerableSet` and `EnumerableMap`. - * Enumerables: Improve gas cost of lookup in `EnumerableSet` and `EnumerableMap`. - * `Counter`: add a reset method. ([#2678](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2678)) - * Tokens: Wrap definitely safe subtractions in `unchecked` blocks. - * `Math`: Add a `ceilDiv` method for performing ceiling division. - * `ERC1155Supply`: add a new `ERC1155` extension that keeps track of the totalSupply of each tokenId. ([#2593](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2593)) - * `BitMaps`: add a new `BitMaps` library that provides a storage efficient datastructure for `uint256` to `bool` mapping with contiguous keys. ([#2710](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2710)) - -### Breaking Changes - - * `ERC20FlashMint` is no longer a Draft ERC. ([#2673](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2673))) - -**How to update:** Change your import paths by removing the `draft-` prefix from `@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20FlashMint.sol`. - -> See [Releases and Stability: Drafts](https://docs.openzeppelin.com/contracts/4.x/releases-stability#drafts). - -## 4.1.0 (2021-04-29) - - * `IERC20Metadata`: add a new extended interface that includes the optional `name()`, `symbol()` and `decimals()` functions. ([#2561](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2561)) - * `ERC777`: make reception acquirement optional in `_mint`. ([#2552](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2552)) - * `ERC20Permit`: add a `_useNonce` to enable further usage of ERC712 signatures. ([#2565](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2565)) - * `ERC20FlashMint`: add an implementation of the ERC3156 extension for flash-minting ERC20 tokens. ([#2543](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2543)) - * `SignatureChecker`: add a signature verification library that supports both EOA and ERC1271 compliant contracts as signers. ([#2532](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2532)) - * `Multicall`: add abstract contract with `multicall(bytes[] calldata data)` function to bundle multiple calls together ([#2608](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2608)) - * `ECDSA`: add support for ERC2098 short-signatures. ([#2582](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2582)) - * `AccessControl`: add a `onlyRole` modifier to restrict specific function to callers bearing a specific role. ([#2609](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2609)) - * `StorageSlot`: add a library for reading and writing primitive types to specific storage slots. ([#2542](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2542)) - * UUPS Proxies: add `UUPSUpgradeable` to implement the UUPS proxy pattern together with `EIP1967Proxy`. ([#2542](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2542)) - -### Breaking changes - -This release includes two small breaking changes in `TimelockController`. - -1. The `onlyRole` modifier in this contract was designed to let anyone through if the role was granted to `address(0)`, - allowing the possibility to to make a role "open", which can be used for `EXECUTOR_ROLE`. This modifier is now - replaced by `AccessControl.onlyRole`, which does not have this ability. The previous behavior was moved to the - modifier `TimelockController.onlyRoleOrOpenRole`. -2. It was possible to make `PROPOSER_ROLE` an open role (as described in the previous item) if it was granted to - `address(0)`. This would affect the `schedule`, `scheduleBatch`, and `cancel` operations in `TimelockController`. - This ability was removed as it does not make sense to open up the `PROPOSER_ROLE` in the same way that it does for - `EXECUTOR_ROLE`. - -## 4.0.0 (2021-03-23) - - * Now targeting the 0.8.x line of Solidity compilers. For 0.6.x (resp 0.7.x) support, use version 3.4.0 (resp 3.4.0-solc-0.7) of OpenZeppelin. - * `Context`: making `_msgData` return `bytes calldata` instead of `bytes memory` ([#2492](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2492)) - * `ERC20`: removed the `_setDecimals` function and the storage slot associated to decimals. ([#2502](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2502)) - * `Strings`: addition of a `toHexString` function. ([#2504](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2504)) - * `EnumerableMap`: change implementation to optimize for `key → value` lookups instead of enumeration. ([#2518](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2518)) - * `GSN`: deprecate GSNv1 support in favor of upcoming support for GSNv2. ([#2521](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2521)) - * `ERC165`: remove uses of storage in the base ERC165 implementation. ERC165 based contracts now use storage-less virtual functions. Old behavior remains available in the `ERC165Storage` extension. ([#2505](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2505)) - * `Initializable`: make initializer check stricter during construction. ([#2531](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2531)) - * `ERC721`: remove enumerability of tokens from the base implementation. This feature is now provided separately through the `ERC721Enumerable` extension. ([#2511](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2511)) - * `AccessControl`: removed enumerability by default for a more lightweight contract. It is now opt-in through `AccessControlEnumerable`. ([#2512](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2512)) - * Meta Transactions: add `ERC2771Context` and a `MinimalForwarder` for meta-transactions. ([#2508](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2508)) - * Overall reorganization of the contract folder to improve clarity and discoverability. ([#2503](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2503)) - * `ERC20Capped`: optimize gas usage by enforcing the check directly in `_mint`. ([#2524](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2524)) - * Rename `UpgradeableProxy` to `ERC1967Proxy`. ([#2547](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2547)) - * `ERC777`: optimize the gas costs of the constructor. ([#2551](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2551)) - * `ERC721URIStorage`: add a new extension that implements the `_setTokenURI` behavior as it was available in 3.4.0. ([#2555](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2555)) - * `AccessControl`: added ERC165 interface detection. ([#2562](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2562)) - * `ERC1155`: make `uri` public so overloading function can call it using super. ([#2576](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2576)) - -### Bug fixes for beta releases - - * `AccessControlEnumerable`: Fixed `renounceRole` not updating enumerable set of addresses for a role. ([#2572](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2572)) - -### How to upgrade from 3.x - -Since this version has moved a few contracts to different directories, users upgrading from a previous version will need to adjust their import statements. To make this easier, the package includes a script that will migrate import statements automatically. After upgrading to the latest version of the package, run: - -``` -npx openzeppelin-contracts-migrate-imports -``` - -Make sure you're using git or another version control system to be able to recover from any potential error in our script. - -### How to upgrade from 4.0-beta.x - -Some further changes have been done between the different beta iterations. Transitions made during this period are configured in the `migrate-imports` script. Consequently, you can upgrade from any previous 4.0-beta.x version using the same script as described in the *How to upgrade from 3.x* section. - -## 3.4.2 - - * `TimelockController`: Add additional isOperationReady check. - -## 3.4.1 (2021-03-03) - - * `ERC721`: made `_approve` an internal function (was private). - -## 3.4.0 (2021-02-02) - - * `BeaconProxy`: added new kind of proxy that allows simultaneous atomic upgrades. ([#2411](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2411)) - * `EIP712`: added helpers to verify EIP712 typed data signatures on chain. ([#2418](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2418)) - * `ERC20Permit`: added an implementation of the ERC20 permit extension for gasless token approvals. ([#2237](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237)) - * Presets: added token presets with preminted fixed supply `ERC20PresetFixedSupply` and `ERC777PresetFixedSupply`. ([#2399](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2399)) - * `Address`: added `functionDelegateCall`, similar to the existing `functionCall`. ([#2333](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2333)) - * `Clones`: added a library for deploying EIP 1167 minimal proxies. ([#2449](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2449)) - * `Context`: moved from `contracts/GSN` to `contracts/utils`. ([#2453](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2453)) - * `PaymentSplitter`: replace usage of `.transfer()` with `Address.sendValue` for improved compatibility with smart wallets. ([#2455](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2455)) - * `UpgradeableProxy`: bubble revert reasons from initialization calls. ([#2454](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2454)) - * `SafeMath`: fix a memory allocation issue by adding new `SafeMath.tryOp(uint,uint)→(bool,uint)` functions. `SafeMath.op(uint,uint,string)→uint` are now deprecated. ([#2462](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2462)) - * `EnumerableMap`: fix a memory allocation issue by adding new `EnumerableMap.tryGet(uint)→(bool,address)` functions. `EnumerableMap.get(uint)→string` is now deprecated. ([#2462](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2462)) - * `ERC165Checker`: added batch `getSupportedInterfaces`. ([#2469](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2469)) - * `RefundEscrow`: `beneficiaryWithdraw` will forward all available gas to the beneficiary. ([#2480](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2480)) - * Many view and pure functions have been made virtual to customize them via overrides. In many cases this will not imply that other functions in the contract will automatically adapt to the overridden definitions. People who wish to override should consult the source code to understand the impact and if they need to override any additional functions to achieve the desired behavior. - -### Security Fixes - - * `ERC777`: fix potential reentrancy issues for custom extensions to `ERC777`. ([#2483](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2483)) - -If you're using our implementation of ERC777 from version 3.3.0 or earlier, and you define a custom `_beforeTokenTransfer` function that writes to a storage variable, you may be vulnerable to a reentrancy attack. If you're affected and would like assistance please write to security@openzeppelin.com. [Read more in the pull request.](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2483) - -## 3.3.0 (2020-11-26) - - * Now supports both Solidity 0.6 and 0.7. Compiling with solc 0.7 will result in warnings. Install the `solc-0.7` tag to compile without warnings. - * `Address`: added `functionStaticCall`, similar to the existing `functionCall`. ([#2333](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2333)) - * `TimelockController`: added a contract to augment access control schemes with a delay. ([#2354](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2354)) - * `EnumerableSet`: added `Bytes32Set`, for sets of `bytes32`. ([#2395](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2395)) - -## 3.2.2-solc-0.7 (2020-10-28) - * Resolve warnings introduced by Solidity 0.7.4. ([#2396](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2396)) - -## 3.2.1-solc-0.7 (2020-09-15) - * `ERC777`: Remove a warning about function state visibility in Solidity 0.7. ([#2327](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2327)) - -## 3.2.0 (2020-09-10) - -### New features - * Proxies: added the proxy contracts from OpenZeppelin SDK. ([#2335](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2335)) - -#### Proxy changes with respect to OpenZeppelin SDK - -Aside from upgrading them from Solidity 0.5 to 0.6, we've changed a few minor things from the proxy contracts as they were found in OpenZeppelin SDK. - -- `UpgradeabilityProxy` was renamed to `UpgradeableProxy`. -- `AdminUpgradeabilityProxy` was renamed to `TransparentUpgradeableProxy`. -- `Proxy._willFallback` was renamed to `Proxy._beforeFallback`. -- `UpgradeabilityProxy._setImplementation` and `AdminUpgradeabilityProxy._setAdmin` were made private. - -### Improvements - * `Address.isContract`: switched from `extcodehash` to `extcodesize` for less gas usage. ([#2311](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2311)) - -### Breaking changes - * `ERC20Snapshot`: switched to using `_beforeTokenTransfer` hook instead of overriding ERC20 operations. ([#2312](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2312)) - -This small change in the way we implemented `ERC20Snapshot` may affect users who are combining this contract with -other ERC20 flavors, since it no longer overrides `_transfer`, `_mint`, and `_burn`. This can result in having to remove Solidity `override(...)` specifiers in derived contracts for these functions, and to instead have to add it for `_beforeTokenTransfer`. See [Using Hooks](https://docs.openzeppelin.com/contracts/3.x/extending-contracts#using-hooks) in the documentation. - -## 3.1.0 (2020-06-23) - -### New features - * `SafeCast`: added functions to downcast signed integers (e.g. `toInt32`), improving usability of `SignedSafeMath`. ([#2243](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2243)) - * `functionCall`: new helpers that replicate Solidity's function call semantics, reducing the need to rely on `call`. ([#2264](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2264)) - * `ERC1155`: added support for a base implementation, non-standard extensions and a preset contract. ([#2014](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2014), [#2230](https://github.com/OpenZeppelin/openzeppelin-contracts/issues/2230)) - -### Improvements - * `ReentrancyGuard`: reduced overhead of using the `nonReentrant` modifier. ([#2171](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2171)) - * `AccessControl`: added a `RoleAdminChanged` event to `_setAdminRole`. ([#2214](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2214)) - * Made all `public` functions in the token preset contracts `virtual`. ([#2257](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2257)) - -### Deprecations - * `SafeERC20`: deprecated `safeApprove`. ([#2268](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2268)) - -## 3.0.2 (2020-06-08) - -### Improvements - * Added SPX license identifier to all contracts. ([#2235](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2235)) - -## 3.0.1 (2020-04-27) - -### Bugfixes - * `ERC777`: fixed the `_approve` internal function not validating some of their arguments for non-zero addresses. ([#2213](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2213)) - -## 3.0.0 (2020-04-20) - -### New features - * `AccessControl`: new contract for managing permissions in a system, replacement for `Ownable` and `Roles`. ([#2112](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2112)) - * `SafeCast`: new functions to convert to and from signed and unsigned values: `toUint256` and `toInt256`. ([#2123](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2123)) - * `EnumerableMap`: a new data structure for key-value pairs (like `mapping`) that can be iterated over. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160)) - -### Breaking changes - * `ERC721`: `burn(owner, tokenId)` was removed, use `burn(tokenId)` instead. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125)) - * `ERC721`: `_checkOnERC721Received` was removed. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125)) - * `ERC721`: `_transferFrom` and `_safeTransferFrom` were renamed to `_transfer` and `_safeTransfer`. ([#2162](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2162)) - * `Ownable`: removed `_transferOwnership`. ([#2162](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2162)) - * `PullPayment`, `Escrow`: `withdrawWithGas` was removed. The old `withdraw` function now forwards all gas. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125)) - * `Roles` was removed, use `AccessControl` as a replacement. ([#2112](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2112)) - * `ECDSA`: when receiving an invalid signature, `recover` now reverts instead of returning the zero address. ([#2114](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2114)) - * `Create2`: added an `amount` argument to `deploy` for contracts with `payable` constructors. ([#2117](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2117)) - * `Pausable`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122)) - * `Strings`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122)) - * `Counters`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122)) - * `SignedSafeMath`: moved to the `math` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122)) - * `ERC20Snapshot`: moved to the `token/ERC20` directory. `snapshot` was changed into an `internal` function. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122)) - * `Ownable`: moved to the `access` directory. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120)) - * `Ownable`: removed `isOwner`. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120)) - * `Secondary`: removed from the library, use `Ownable` instead. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120)) - * `Escrow`, `ConditionalEscrow`, `RefundEscrow`: these now use `Ownable` instead of `Secondary`, their external API changed accordingly. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120)) - * `ERC20`: removed `_burnFrom`. ([#2119](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2119)) - * `Address`: removed `toPayable`, use `payable(address)` instead. ([#2133](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2133)) - * `ERC777`: `_send`, `_mint` and `_burn` now use the caller as the operator. ([#2134](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2134)) - * `ERC777`: removed `_callsTokensToSend` and `_callTokensReceived`. ([#2134](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2134)) - * `EnumerableSet`: renamed `get` to `at`. ([#2151](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2151)) - * `ERC165Checker`: functions no longer have a leading underscore. ([#2150](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2150)) - * `ERC721Metadata`, `ERC721Enumerable`: these contracts were removed, and their functionality merged into `ERC721`. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160)) - * `ERC721`: added a constructor for `name` and `symbol`. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160)) - * `ERC20Detailed`: this contract was removed and its functionality merged into `ERC20`. ([#2161](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2161)) - * `ERC20`: added a constructor for `name` and `symbol`. `decimals` now defaults to 18. ([#2161](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2161)) - * `Strings`: renamed `fromUint256` to `toString` ([#2188](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2188)) - -## 2.5.1 (2020-04-24) - -### Bugfixes - * `ERC777`: fixed the `_send` and `_approve` internal functions not validating some of their arguments for non-zero addresses. ([#2212](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2212)) - -## 2.5.0 (2020-02-04) - -### New features - * `SafeCast.toUintXX`: new library for integer downcasting, which allows for safe operation on smaller types (e.g. `uint32`) when combined with `SafeMath`. ([#1926](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1926)) - * `ERC721Metadata`: added `baseURI`, which can be used for dramatic gas savings when all token URIs share a prefix (e.g. `http://api.myapp.com/tokens/`). ([#1970](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1970)) - * `EnumerableSet`: new library for storing enumerable sets of values. Only `AddressSet` is supported in this release. ([#2061](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/2061)) - * `Create2`: simple library to make usage of the `CREATE2` opcode easier. ([#1744](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1744)) - -### Improvements - * `ERC777`: `_burn` is now internal, providing more flexibility and making it easier to create tokens that deflate. ([#1908](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1908)) - * `ReentrancyGuard`: greatly improved gas efficiency by using the net gas metering mechanism introduced in the Istanbul hardfork. ([#1992](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1992), [#1996](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1996)) - * `ERC777`: improve extensibility by making `_send` and related functions `internal`. ([#2027](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2027)) - * `ERC721`: improved revert reason when transferring tokens to a non-recipient contract. ([#2018](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2018)) - -### Breaking changes - * `ERC165Checker` now requires a minimum Solidity compiler version of 0.5.10. ([#1829](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1829)) - -## 2.4.0 (2019-10-29) - -### New features - * `Address.toPayable`: added a helper to convert between address types without having to resort to low-level casting. ([#1773](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1773)) - * Facilities to make metatransaction-enabled contracts through the Gas Station Network. ([#1844](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1844)) - * `Address.sendValue`: added a replacement to Solidity's `transfer`, removing the fixed gas stipend. ([#1962](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1962)) - * Added replacement for functions that don't forward all gas (which have been deprecated): ([#1976](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1976)) - * `PullPayment.withdrawPaymentsWithGas(address payable payee)` - * `Escrow.withdrawWithGas(address payable payee)` - * `SafeMath`: added support for custom error messages to `sub`, `div` and `mod` functions. ([#1828](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1828)) - -### Improvements - * `Address.isContract`: switched from `extcodesize` to `extcodehash` for less gas usage. ([#1802](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1802)) - * `ERC20` and `ERC777` updated to throw custom errors on subtraction overflows. ([#1828](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1828)) - -### Deprecations - * Deprecated functions that don't forward all gas: ([#1976](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1976)) - * `PullPayment.withdrawPayments(address payable payee)` - * `Escrow.withdraw(address payable payee)` - -### Breaking changes - * `Address` now requires a minimum Solidity compiler version of 0.5.5. ([#1802](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1802)) - * `SignatureBouncer` has been removed from drafts, both to avoid confusions with the GSN and `GSNRecipientSignature` (previously called `GSNBouncerSignature`) and because the API was not very clear. ([#1879](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1879)) - -### How to upgrade from 2.4.0-beta - -The final 2.4.0 release includes a refactor of the GSN contracts that will be a breaking change for 2.4.0-beta users. - - * The default empty implementations of `_preRelayedCall` and `_postRelayedCall` were removed and must now be explicitly implemented always in custom recipients. If your custom recipient didn't include an implementation, you can provide an empty one. - * `GSNRecipient`, `GSNBouncerBase`, and `GSNContext` were all merged into `GSNRecipient`. - * `GSNBouncerSignature` and `GSNBouncerERC20Fee` were renamed to `GSNRecipientSignature` and `GSNRecipientERC20Fee`. - * It is no longer necessary to inherit from `GSNRecipient` when using `GSNRecipientSignature` and `GSNRecipientERC20Fee`. - -For example, a contract using `GSNBouncerSignature` would have to be changed in the following way. - -```diff --contract MyDapp is GSNRecipient, GSNBouncerSignature { -+contract MyDapp is GSNRecipientSignature { -``` - -Refer to the table below to adjust your inheritance list. - -| 2.4.0-beta | 2.4.0 | -| ---------------------------------- | ---------------------------- | -| `GSNRecipient, GSNBouncerSignature`| `GSNRecipientSignature` | -| `GSNRecipient, GSNBouncerERC20Fee` | `GSNRecipientERC20Fee` | -| `GSNBouncerBase` | `GSNRecipient` | - -## 2.3.0 (2019-05-27) - -### New features - * `ERC1820`: added support for interacting with the [ERC1820](https://eips.ethereum.org/EIPS/eip-1820) registry contract (`IERC1820Registry`), as well as base contracts that can be registered as implementers there. ([#1677](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1677)) - * `ERC777`: support for the [ERC777 token](https://eips.ethereum.org/EIPS/eip-777), which has multiple improvements over `ERC20` (but is backwards compatible with it) such as built-in burning, a more straightforward permission system, and optional sender and receiver hooks on transfer (mandatory for contracts!). ([#1684](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1684)) - * All contracts now have revert reason strings, which give insight into error conditions, and help debug failing transactions. ([#1704](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1704)) - -### Improvements - * Reverted the Solidity version bump done in v2.2.0, setting the minimum compiler version to v0.5.0, to prevent unexpected build breakage. Users are encouraged however to stay on top of new compiler releases, which usually include bugfixes. ([#1729](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1729)) - -### Bugfixes - * `PostDeliveryCrowdsale`: some validations where skipped when paired with other crowdsale flavors, such as `AllowanceCrowdsale`, or `MintableCrowdsale` and `ERC20Capped`, which could cause buyers to not be able to claim their purchased tokens. ([#1721](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1721)) - * `ERC20._transfer`: the `from` argument was allowed to be the zero address, so it was possible to internally trigger a transfer of 0 tokens from the zero address. This address is not a valid destinatary of transfers, nor can it give or receive allowance, so this behavior was inconsistent. It now reverts. ([#1752](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1752)) - -## 2.2.0 (2019-03-14) - -### New features - * `ERC20Snapshot`: create snapshots on demand of the token balances and total supply, to later retrieve and e.g. calculate dividends at a past time. ([#1617](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1617)) - * `SafeERC20`: `ERC20` contracts with no return value (i.e. that revert on failure) are now supported. ([#1655](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1655)) - * `ERC20`: added internal `_approve(address owner, address spender, uint256 value)`, allowing derived contracts to set the allowance of arbitrary accounts. ([#1609](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1609)) - * `ERC20Metadata`: added internal `_setTokenURI(string memory tokenURI)`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618)) - * `TimedCrowdsale`: added internal `_extendTime(uint256 newClosingTime)` as well as `TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime)` event allowing to extend the crowdsale, as long as it hasn't already closed. - -### Improvements - * Upgraded the minimum compiler version to v0.5.2: this removes many Solidity warnings that were false positives. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606)) - * `ECDSA`: `recover` no longer accepts malleable signatures (those using upper-range values for `s`, or 0/1 for `v`). ([#1622](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1622)) - * ``ERC721``'s transfers are now more gas efficient due to removal of unnecessary `SafeMath` calls. ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610)) - * Fixed variable shadowing issues. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606)) - -### Bugfixes - * (minor) `SafeERC20`: `safeApprove` wasn't properly checking for a zero allowance when attempting to set a non-zero allowance. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647)) - -### Breaking changes in drafts - * `TokenMetadata` has been renamed to `ERC20Metadata`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618)) - * The library `Counter` has been renamed to `Counters` and its API has been improved. See an example in `ERC721`, lines [17](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L17) and [204](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L204). ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610)) - -## 2.1.3 (2019-02-26) - * Backported `SafeERC20.safeApprove` bugfix. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647)) - -## 2.1.2 (2019-01-17) - * Removed most of the test suite from the npm package, except `PublicRole.behavior.js`, which may be useful to users testing their own `Roles`. - -## 2.1.1 (2019-01-04) - * Version bump to avoid conflict in the npm registry. - -## 2.1.0 (2019-01-04) - -### New features - * Now targeting the 0.5.x line of Solidity compilers. For 0.4.24 support, use version 2.0 of OpenZeppelin. - * `WhitelistCrowdsale`: a crowdsale where only whitelisted accounts (`WhitelistedRole`) can purchase tokens. Adding or removing accounts from the whitelist is done by whitelist admins (`WhitelistAdminRole`). Similar to the pre-2.0 `WhitelistedCrowdsale`. ([#1525](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1525), [#1589](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1589)) - * `RefundablePostDeliveryCrowdsale`: replacement for `RefundableCrowdsale` (deprecated, see below) where tokens are only granted once the crowdsale ends (if it meets its goal). ([#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543)) - * `PausableCrowdsale`: allows for pausers (`PauserRole`) to pause token purchases. Other crowdsale operations (e.g. withdrawals and refunds, if applicable) are not affected. ([#832](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/832)) - * `ERC20`: `transferFrom` and `_burnFrom ` now emit `Approval` events, to represent the token's state comprehensively through events. ([#1524](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1524)) - * `ERC721`: added `_burn(uint256 tokenId)`, replacing the similar deprecated function (see below). ([#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550)) - * `ERC721`: added `_tokensOfOwner(address owner)`, allowing to internally retrieve the array of an account's owned tokens. ([#1522](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1522)) - * Crowdsales: all constructors are now `public`, meaning it is not necessary to extend these contracts in order to deploy them. The exception is `FinalizableCrowdsale`, since it is meaningless unless extended. ([#1564](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1564)) - * `SignedSafeMath`: added overflow-safe operations for signed integers (`int256`). ([#1559](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1559), [#1588](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1588)) - -### Improvements - * The compiler version required by `Array` was behind the rest of the libray so it was updated to `v0.4.24`. ([#1553](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1553)) - * Now conforming to a 4-space indentation code style. ([1508](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1508)) - * `ERC20`: more gas efficient due to removed redundant `require`s. ([#1409](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1409)) - * `ERC721`: fixed a bug that prevented internal data structures from being properly cleaned, missing potential gas refunds. ([#1539](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1539) and [#1549](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1549)) - * `ERC721`: general gas savings on `transferFrom`, `_mint` and `_burn`, due to redudant `require`s and `SSTORE`s. ([#1549](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1549)) - -### Bugfixes - -### Breaking changes - -### Deprecations - * `ERC721._burn(address owner, uint256 tokenId)`: due to the `owner` parameter being unnecessary. ([#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550)) - * `RefundableCrowdsale`: due to trading abuse potential on crowdsales that miss their goal. ([#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543)) diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CODE_OF_CONDUCT.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CODE_OF_CONDUCT.md deleted file mode 100644 index 86c0474c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,73 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at maintainers@openzeppelin.org. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CONTRIBUTING.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CONTRIBUTING.md deleted file mode 100644 index 1c55795d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/CONTRIBUTING.md +++ /dev/null @@ -1,64 +0,0 @@ -Contributing to OpenZeppelin Contracts -======= - -We really appreciate and value contributions to OpenZeppelin Contracts. Please take 5' to review the items listed below to make sure that your contributions are merged as soon as possible. - -## Contribution guidelines - -Smart contracts manage value and are highly vulnerable to errors and attacks. We have very strict [guidelines], please make sure to review them! - -## Creating Pull Requests (PRs) - -As a contributor, you are expected to fork this repository, work on your own fork and then submit pull requests. The pull requests will be reviewed and eventually merged into the main repo. See ["Fork-a-Repo"](https://help.github.com/articles/fork-a-repo/) for how this works. - -## A typical workflow - -1) Make sure your fork is up to date with the main repository: - -``` -cd openzeppelin-contracts -git remote add upstream https://github.com/OpenZeppelin/openzeppelin-contracts.git -git fetch upstream -git pull --rebase upstream master -``` -NOTE: The directory `openzeppelin-contracts` represents your fork's local copy. - -2) Branch out from `master` into `fix/some-bug-#123`: -(Postfixing #123 will associate your PR with the issue #123 and make everyone's life easier =D) -``` -git checkout -b fix/some-bug-#123 -``` - -3) Make your changes, add your files, commit, and push to your fork. - -``` -git add SomeFile.js -git commit "Fix some bug #123" -git push origin fix/some-bug-#123 -``` - -4) Run tests, linter, etc. This can be done by running local continuous integration and make sure it passes. - -```bash -npm test -npm run lint -``` - -5) Go to [github.com/OpenZeppelin/openzeppelin-contracts](https://github.com/OpenZeppelin/openzeppelin-contracts) in your web browser and issue a new pull request. - -*IMPORTANT* Read the PR template very carefully and make sure to follow all the instructions. These instructions -refer to some very important conditions that your PR must meet in order to be accepted, such as making sure that all tests pass, JS linting tests pass, Solidity linting tests pass, etc. - -6) Maintainers will review your code and possibly ask for changes before your code is pulled in to the main repository. We'll check that all tests pass, review the coding style, and check for general code correctness. If everything is OK, we'll merge your pull request and your code will be part of OpenZeppelin Contracts. - -*IMPORTANT* Please pay attention to the maintainer's feedback, since its a necessary step to keep up with the standards OpenZeppelin Contracts attains to. - -## All set! - -If you have any questions, feel free to post them to github.com/OpenZeppelin/openzeppelin-contracts/issues. - -Finally, if you're looking to collaborate and want to find easy tasks to start, look at the issues we marked as ["Good first issue"](https://github.com/OpenZeppelin/openzeppelin-contracts/labels/good%20first%20issue). - -Thanks for your time and code! - -[guidelines]: GUIDELINES.md diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/DOCUMENTATION.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/DOCUMENTATION.md deleted file mode 100644 index ca39e51d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/DOCUMENTATION.md +++ /dev/null @@ -1,16 +0,0 @@ -Documentation is hosted at https://docs.openzeppelin.com/contracts. - -All of the content for the site is in this repository. The guides are in the -[docs](/docs) directory, and the API Reference is extracted from comments in -the source code. If you want to help improve the content, this is the -repository you should be contributing to. - -[`solidity-docgen`](https://github.com/OpenZeppelin/solidity-docgen) is the -program that extracts the API Reference from source code. - -The [`docs.openzeppelin.com`](https://github.com/OpenZeppelin/docs.openzeppelin.com) -repository hosts the configuration for the entire site, which includes -documentation for all of the OpenZeppelin projects. - -To run the docs locally you should run `npm run docs:watch` on this -repository. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/GUIDELINES.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/GUIDELINES.md deleted file mode 100644 index 97067500..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/GUIDELINES.md +++ /dev/null @@ -1,105 +0,0 @@ -Design Guidelines -======= - -These are some global design goals in OpenZeppelin Contracts. - -#### D0 - Security in Depth -We strive to provide secure, tested, audited code. To achieve this, we need to match intention with function. Thus, documentation, code clarity, community review and security discussions are fundamental. - -#### D1 - Simple and Modular -Simpler code means easier audits, and better understanding of what each component does. We look for small files, small contracts, and small functions. If you can separate a contract into two independent functionalities you should probably do it. - -#### D2 - Naming Matters - -We take our time with picking names. Code is going to be written once, and read hundreds of times. Renaming for clarity is encouraged. - -#### D3 - Tests - -Write tests for all your code. We encourage Test Driven Development so we know when our code is right. Even though not all code in the repository is tested at the moment, we aim to test every line of code in the future. - -#### D4 - Check preconditions and post-conditions - -A very important way to prevent vulnerabilities is to catch a contract’s inconsistent state as early as possible. This is why we want functions to check pre- and post-conditions for executing its logic. When writing code, ask yourself what you are expecting to be true before and after the function runs, and express it in code. - -#### D5 - Code Consistency - -Consistency on the way classes are used is paramount to an easier understanding of the library. The codebase should be as unified as possible. Read existing code and get inspired before you write your own. Follow the style guidelines. Don’t hesitate to ask for help on how to best write a specific piece of code. - -#### D6 - Regular Audits -Following good programming practices is a way to reduce the risk of vulnerabilities, but professional code audits are still needed. We will perform regular code audits on major releases, and hire security professionals to provide independent review. - -# Style Guidelines - -The design guidelines have quite a high abstraction level. These style guidelines are more concrete and easier to apply, and also more opinionated. We value clean code and consistency, and those are prerequisites for us to include new code in the repository. Before proposing a change, please read these guidelines and take some time to familiarize yourself with the style of the existing codebase. - -## Solidity code - -In order to be consistent with all the other Solidity projects, we follow the -[official recommendations documented in the Solidity style guide](http://solidity.readthedocs.io/en/latest/style-guide.html). - -Any exception or additions specific to our project are documented below. - -* Try to avoid acronyms and abbreviations. - -* All state variables should be private. - -* Private state variables should have an underscore prefix. - - ``` - contract TestContract { - uint256 private _privateVar; - uint256 internal _internalVar; - } - ``` - -* Parameters must not be prefixed with an underscore. - - ``` - function test(uint256 testParameter1, uint256 testParameter2) { - ... - } - ``` - -* Internal and private functions should have an underscore prefix. - - ``` - function _testInternal() internal { - ... - } - ``` - - ``` - function _testPrivate() private { - ... - } - ``` - -* Events should be emitted immediately after the state change that they - represent, and consequently they should be named in past tense. - - ``` - function _burn(address who, uint256 value) internal { - super._burn(who, value); - emit TokensBurned(who, value); - } - ``` - - Some standards (e.g. ERC20) use present tense, and in those cases the - standard specification prevails. - -* Interface names should have a capital I prefix. - - ``` - interface IERC777 { - ``` - - -## Tests - -* Tests Must be Written Elegantly - - Tests are a good way to show how to use the library, and maintaining them is extremely necessary. Don't write long tests, write helper functions to make them be as short and concise as possible (they should take just a few lines each), and use good variable names. - -* Tests Must not be Random - - Inputs for tests should not be generated randomly. Accounts used to create test contracts are an exception, those can be random. Also, the type and structure of outputs should be checked. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/LICENSE b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/LICENSE deleted file mode 100644 index ade2b707..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016-2020 zOS Global Limited - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/README.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/README.md deleted file mode 100644 index d8537d27..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# OpenZeppelin - -[![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-blue)](https://docs.openzeppelin.com/contracts) -[![NPM Package](https://img.shields.io/npm/v/@openzeppelin/contracts.svg)](https://www.npmjs.org/package/@openzeppelin/contracts) -[![Coverage Status](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts/graph/badge.svg)](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts) - -**A library for secure smart contract development.** Build on a solid foundation of community-vetted code. - - * Implementations of standards like [ERC20](https://docs.openzeppelin.com/contracts/erc20) and [ERC721](https://docs.openzeppelin.com/contracts/erc721). - * Flexible [role-based permissioning](https://docs.openzeppelin.com/contracts/access-control) scheme. - * Reusable [Solidity components](https://docs.openzeppelin.com/contracts/utilities) to build custom contracts and complex decentralized systems. - -:mage: **Not sure how to get started?** Check out [Contracts Wizard](https://wizard.openzeppelin.com/) — an interactive smart contract generator. - -## Overview - -### Installation - -```console -$ npm install @openzeppelin/contracts -``` - -OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/contracts/releases-stability#api-stability), which means your contracts won't break unexpectedly when upgrading to a newer minor version. - -### Usage - -Once installed, you can use the contracts in the library by importing them: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; - -contract MyCollectible is ERC721 { - constructor() ERC721("MyCollectible", "MCO") { - } -} -``` - -_If you're new to smart contract development, head to [Developing Smart Contracts](https://docs.openzeppelin.com/learn/developing-smart-contracts) to learn about creating a new project and compiling your contracts._ - -To keep your system secure, you should **always** use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don't need to worry about it needlessly increasing gas costs. - -## Learn More - -The guides in the [docs site](https://docs.openzeppelin.com/contracts) will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides: - -* [Access Control](https://docs.openzeppelin.com/contracts/access-control): decide who can perform each of the actions on your system. -* [Tokens](https://docs.openzeppelin.com/contracts/tokens): create tradeable assets or collectives, and distribute them via [Crowdsales](https://docs.openzeppelin.com/contracts/crowdsales). -* [Gas Station Network](https://docs.openzeppelin.com/contracts/gsn): let your users interact with your contracts without having to pay for gas themselves. -* [Utilities](https://docs.openzeppelin.com/contracts/utilities): generic useful tools, including non-overflowing math, signature verification, and trustless paying systems. - -The [full API](https://docs.openzeppelin.com/contracts/api/token/ERC20) is also thoroughly documented, and serves as a great reference when developing your smart contract application. You can also ask for help or follow Contracts's development in the [community forum](https://forum.openzeppelin.com). - -Finally, you may want to take a look at the [guides on our blog](https://blog.openzeppelin.com/guides), which cover several common use cases and good practices.. The following articles provide great background reading, though please note, some of the referenced tools have changed as the tooling in the ecosystem continues to rapidly evolve. - -* [The Hitchhiker’s Guide to Smart Contracts in Ethereum](https://blog.openzeppelin.com/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) will help you get an overview of the various tools available for smart contract development, and help you set up your environment. -* [A Gentle Introduction to Ethereum Programming, Part 1](https://blog.openzeppelin.com/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) provides very useful information on an introductory level, including many basic concepts from the Ethereum platform. -* For a more in-depth dive, you may read the guide [Designing the Architecture for Your Ethereum Application](https://blog.openzeppelin.com/designing-the-architecture-for-your-ethereum-application-9cec086f8317), which discusses how to better structure your application and its relationship to the real world. - -## Security - -This project is maintained by [OpenZeppelin](https://openzeppelin.com), and developed following our high standards for code quality and security. OpenZeppelin Contracts is meant to provide tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problems you might experience. - -The core development principles and strategies that OpenZeppelin Contracts is based on include: security in depth, simple and modular code, clarity-driven naming conventions, comprehensive unit testing, pre-and-post-condition sanity checks, code consistency, and regular audits. - -The latest audit was done on October 2018 on version 2.0.0. - -We have a [**bug bounty program** on Immunefi](https://www.immunefi.com/bounty/openzeppelin). Please report any security issues you find through the Immunefi dashboard, or reach out to security@openzeppelin.com. - -Critical bug fixes will be backported to past major releases. - -## Contribute - -OpenZeppelin Contracts exists thanks to its contributors. There are many ways you can participate and help build high quality software. Check out the [contribution guide](CONTRIBUTING.md)! - -## License - -OpenZeppelin Contracts is released under the [MIT License](LICENSE). diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/RELEASING.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/RELEASING.md deleted file mode 100644 index f356ab2e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/RELEASING.md +++ /dev/null @@ -1,36 +0,0 @@ -# Releasing - -> Visit the documentation for [details about release schedule]. - -Start on an up-to-date `master` branch. - -Create the release branch with `npm run release start minor`. - -Publish a release candidate with `npm run release rc`. - -Publish the final release with `npm run release final`. - -Follow the general [OpenZeppelin Contracts release checklist]. - -[details about release schedule]: https://docs.openzeppelin.com/contracts/releases-stability -[OpenZeppelin Contracts release checklist]: https://github.com/OpenZeppelin/code-style/blob/master/RELEASE_CHECKLIST.md - - -## Merging the release branch - -After the final release, the release branch should be merged back into `master`. This merge must not be squashed because it would lose the tagged release commit. Since the GitHub repo is set up to only allow squashed merges, the merge should be done locally and pushed. - -Make sure to have the latest changes from `upstream` in your local release branch. - -``` -git checkout release-vX.Y.Z -git pull upstream -``` - -``` -git checkout master -git merge --no-ff release-vX.Y.Z -git push upstream master -``` - -The release branch can then be deleted on GitHub. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/SECURITY.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/SECURITY.md deleted file mode 100644 index 98701be6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/SECURITY.md +++ /dev/null @@ -1,20 +0,0 @@ -# Security Policy - -## Bug Bounty - -We have a [**bug bounty program** on Immunefi](https://www.immunefi.com/bounty/openzeppelin). Please report any security issues you find through the Immunefi dashboard, or reach out to security@openzeppelin.com. - -Critical bug fixes will be backported to past major releases. - -## Supported Versions - -The recommendation is to use the latest version available. - -| Version | Supported | -| ------- | ------------------------------------ | -| 4.x | :white_check_mark::white_check_mark: | -| 3.4 | :white_check_mark: | -| 2.5 | :white_check_mark: | -| < 2.0 | :x: | - -Note that the Solidity language itself only guarantees security updates for the latest release. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/audit/2017-03.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/audit/2017-03.md deleted file mode 100644 index 53eb702a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/audit/2017-03.md +++ /dev/null @@ -1,292 +0,0 @@ -# OpenZeppelin Audit - -NOTE ON 2021-07-19: This report makes reference to Zeppelin, OpenZeppelin, OpenZeppelin [C]ontracts, the OpenZeppelin team, and OpenZeppelin library. Many of these things have since been renamed and know that this audit applies to what is currently called the OpenZeppelin Contracts which are maintained by the OpenZeppelin Conracts Community. - -March, 2017 -Authored by Dennis Peterson and Peter Vessenes - -# Introduction - -Zeppelin requested that New Alchemy perform an audit of the contracts in their OpenZeppelin library. The OpenZeppelin contracts are a set of contracts intended to be a safe building block for a variety of uses by parties that may not be as sophisticated as the OpenZeppelin team. It is a design goal that the contracts be deployable safely and "as-is". - -The contracts are hosted at: - -https://github.com/OpenZeppelin/zeppelin-solidity - -All the contracts in the "contracts" folder are in scope. - -The git commit hash we evaluated is: -9c5975a706b076b7000e8179f8101e0c61024c87 - -# Disclaimer - -The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bugfree status. The audit documentation is for discussion purposes only. - -# Executive Summary - -Overall the OpenZeppelin codebase is of reasonably high quality -- it is clean, modular and follows best practices throughout. - -It is still in flux as a codebase, and needs better documentation per file as to expected behavior and future plans. It probably needs more comprehensive and aggressive tests written by people less nice than the current OpenZeppelin team. - -We identified two critical errors and one moderate issue, and would not recommend this commit hash for public use until these bugs are remedied. - -The repository includes a set of Truffle unit tests, a requirement and best practice for smart contracts like these; we recommend these be bulked up. - -# Discussion - -## Big Picture: Is This A Worthwhile Project? - -As soon as a developer touches OpenZeppelin contracts, they will modify something, leaving them in an un-audited state. We do not recommend developers deploy any unaudited code to the Blockchain if it will handle money, information or other things of value. - -> "In accordance with Unix philosophy, Perl gives you enough rope to hang yourself" -> --Larry Wall - -We think this is an incredibly worthwhile project -- aided by the high code quality. Creating a framework that can be easily extended helps increase the average code quality on the Blockchain by charting a course for developers and encouraging containment of modifications to certain sections. - -> "Rust: The language that makes you take the safety off before shooting yourself in the foot" -> -- (@mbrubeck) - -We think much more could be done here, and recommend the OpenZeppelin team keep at this and keep focusing on the design goal of removing rope and adding safety. - -## Solidity Version Updates Recommended - -Most of the code uses Solidity 0.4.11, but some files under `Ownership` are marked 0.4.0. These should be updated. - -Solidity 0.4.10 will add several features which could be useful in these contracts: - -- `assert(condition)`, which throws if the condition is false - -- `revert()`, which rolls back without consuming all remaining gas. - -- `address.transfer(value)`, which is like `send` but automatically propagates exceptions, and supports `.gas()`. See https://github.com/ethereum/solidity/issues/610 for more on this. - -## Error Handling: Throw vs Return False -Solidity standards allow two ways to handle an error -- either calling `throw` or returning `false`. Both have benefits. In particular, a `throw` guarantees a complete wipe of the call stack (up to the preceding external call), whereas `false` allows a function to continue. - -In general we prefer `throw` in our code audits, because it is simpler -- it's less for an engineer to keep track of. Returning `false` and using logic to check results can quickly become a poorly-tracked state machine, and this sort of complexity can cause errors. - -In the OpenZeppelin contracts, both styles are used in different parts of the codebase. `SimpleToken` transfers throw upon failure, while the full ERC20 token returns `false`. Some modifiers `throw`, others just wrap the function body in a conditional, effectively allowing the function to return false if the condition is not met. - -We don't love this, and would usually recommend you stick with one style or the other throughout the codebase. - -In at least one case, these different techniques are combined cleverly (see the Multisig comments, line 65). As a set of contracts intended for general use, we recommend you either strive for more consistency or document explicit design criteria that govern which techniques are used where. - -Note that it may be impossible to use either one in all situations. For example, SafeMath functions pretty much have to throw upon failure, but ERC20 specifies returning booleans. Therefore we make no particular recommendations, but simply point out inconsistencies to consider. - -# Critical Issues - -## Stuck Ether in Crowdsale contract -CrowdsaleToken.sol has no provision for withdrawing the raised ether. We *strongly* recommend a standard `withdraw` function be added. There is no scenario in which someone should deploy this contract as is, whether for testing or live. - -## Recursive Call in MultisigWallet -Line 45 of `MultisigWallet.sol` checks if the amount being sent by `execute` is under a daily limit. - -This function can only be called by the "Owner". As a first angle of attack, it's worth asking what will happen if the multisig wallet owners reset the daily limit by approving a call to `resetSpentToday`. - -If a chain of calls can be constructed in which the owner confirms the `resetSpentToday` function and then withdraws through `execute` in a recursive call, the contract can be drained. In fact, this could be done without a recursive call, just through repeated `execute` calls alternating with the `confirm` calls. - -We are still working through the confirmation protocol in `Shareable.sol`, but we are not convinced that this is impossible, in fact it looks possible. The flexibility any shared owner has in being able to revoke confirmation later is another worrisome angle of approach even if some simple patches are included. - -This bug has a number of causes that need to be addressed: - -1. `resetSpentToday` and `confirm` together do not limit the days on which the function can be called or (it appears) the number of times it can be called. -1. Once a call has been confirmed and `execute`d it appears that it can be re-executed. This is not good. -3. `confirmandCheck` doesn't seem to have logic about whether or not the function in question has been called. -4. Even if it did, `revoke` would need updates and logic to deal with revocation requests after a function call had been completed. - -We do not recommend using the MultisigWallet until these issues are fixed. - -# Moderate to Minor Issues - -## PullPayment -PullPayment.sol needs some work. It has no explicit provision for cancelling a payment. This would be desirable in a number of scenarios; consider a payee losing their wallet, or giving a griefing address, or just an address that requires more than the default gas offered by `send`. - -`asyncSend` has no overflow checking. This is a bad plan. We recommend overflow and underflow checking at the layer closest to the data manipulation. - -`asyncSend` allows more balance to be queued up for sending than the contract holds. This is probably a bad idea, or at the very least should be called something different. If the intent is to allow this, it should have provisions for dealing with race conditions between competing `withdrawPayments` calls. - -It would be nice to see how many payments are pending. This would imply a bit of a rewrite; we recommend this contract get some design time, and that developers don't rely on it in its current state. - -## Shareable Contract - -We do not believe the `Shareable.sol` contract is ready for primetime. It is missing functions, and as written may be vulnerable to a reordering attack -- an attack in which a miner or other party "racing" with a smart contract participant inserts their own information into a list or mapping. - -The confirmation and revocation code needs to be looked over with a very careful eye imagining extraordinarily bad behavior by shared owners before this contract can be called safe. - -No sanity checks on the initial constructor's `required` argument are worrisome as well. - -# Line by Line Comments - -## Lifecycle - -### Killable - -Very simple, allows owner to call selfdestruct, sending funds to owner. No issues. However, note that `selfdestruct` should typically not be used; it is common that a developer may want to access data in a former contract, and they may not understand that `selfdestruct` limits access to the contract. We recommend better documentation about this dynamic, and an alternate function name for `kill` like `completelyDestroy` while `kill` would perhaps merely send funds to the owner. - -Also note that a killable function allows the owner to take funds regardless of other logic. This may be desirable or undesirable depending on the circumstances. Perhaps `Killable` should have a different name as well. - -### Migrations - -I presume that the goal of this contract is to allow and annotate a migration to a new smart contract address. We are not clear here how this would be accomplished by the code; we'd like to review with the OpenZeppelin team. - -### Pausable - -We like these pauses! Note that these allow significant griefing potential by owners, and that this might not be obvious to participants in smart contracts using the OpenZeppelin framework. We would recommend that additional sample logic be added to for instance the TokenContract showing safer use of the pause and resume functions. In particular, we would recommend a timelock after which anyone could unpause the contract. - -The modifers use the pattern `if(bool){_;}`. This is fine for functions that return false upon failure, but could be problematic for functions expected to throw upon failure. See our comments above on standardizing on `throw` or `return(false)`. - -## Ownership - -### Ownable - -Line 19: Modifier throws if doesn't meet condition, in contrast to some other inheritable modifiers (e.g. in Pausable) that use `if(bool){_;}`. - -### Claimable - -Inherits from Ownable but the existing owner sets a pendingOwner who has to claim ownership. - -Line 17: Another modifier that throws. - -### DelayedClaimable - -Is there any reason to descend from Ownable directly, instead of just Claimable, which descends from Ownable? If not, descending from both just adds confusion. - -### Contactable - -Allows owner to set a public string of contract information. No issues. - -### Shareable - -This needs some work. Doesn't check if `_required <= len(_owners)` for instance, that would be a bummer. What if _required were like `MAX - 1`? - -I have a general concern about the difference between `owners`, `_owners`, and `owner` in `Ownable.sol`. I recommend "Owners" be renamed. In general we do not recomment single character differences in variable names, although a preceding underscore is not uncommon in Solidity code. - -Line 34: "this contract only has six types of events"...actually only two. - -Line 61: Why is `ownerIndex` keyed by addresses hashed to `uint`s? Why not use the addresses directly, so `ownerIndex` is less obscure, and so there's stronger typing? - -Line 62: Do not love `++i) ... owners[2+ i]`. Makes me do math, which is not what I want to do. I want to not have to do math. - -There should probably be a function for adding a new operation, so the developer doesn't have to work directly with the internal data. (This would make the multisig contract even shorter.) - -There's a `revoke` function but not a `propose` function that we can see. - -Beware reordering. If `propose` allows the user to choose a bytes string for their proposal, bad things(TM) will happen as currently written. - - -### Multisig - -Just an interface. Note it allows changing an owner address, but not changing the number of owners. This is somewhat limiting but also simplifies implementation. - -## Payment - -### PullPayment - -Safe from reentrance attack since ether send is at the end, plus it uses `.send()` rather than `.call.value()`. - -There's an argument to be made that `.call.value()` is a better option *if* you're sure that it will be done after all state updates, since `.send` will fail if the recipient has an expensive fallback function. However, in the context of a function meant to be embedded in other contracts, it's probably better to use `.send`. One possible compromise is to add a function which allows only the owner to send ether via `.call.value`. - -If you don't use `call.value` you should implement a `cancel` function in case some value is pending here. - -Line 14: -Doesn't use safeAdd. Although it appears that payout amounts can only be increased, in fact the payer could lower the payout as much as desired via overflow. Also, the payer could add a large non-overflowing amount, causing the payment to exceed the contract balance and therefore fail when withdraw is attempted. - -Recommendation: track the sum of non-withdrawn asyncSends, and don't allow a new one which exceeds the leftover balance. If it's ever desirable to make payments revocable, it should be done explicitly. - -## Tokens - -### ERC20 - -Standard ERC20 interface only. - -There's a security hole in the standard, reported at Edcon: `approve` does not protect against race conditions and simply replaces the current value. An approved spender could wait for the owner to call `approve` again, then attempt to spend the old limit before the new limit is applied. If successful, this attacker could successfully spend the sum of both limits. - -This could be fixed by either (1) including the old limit as a parameter, so the update will fail if some gets spent, or (2) using the value parameter as a delta instead of replacement value. - -This is not fixable while adhering to the current full ERC20 standard, though it would be possible to add a "secureApprove" function. The impact isn't extreme since at least you can only be attacked by addresses you approved. Also, users could mitigate this by always setting spending limits to zero and checking for spends, before setting the new limit. - -Edcon slides: -https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view - -### ERC20Basic - -Simpler interface skipping the Approve function. Note this departs from ERC20 in another way: transfer throws instead of returning false. - -### BasicToken - -Uses `SafeSub` and `SafeMath`, so transfer `throw`s instead of returning false. This complies with ERC20Basic but not the actual ERC20 standard. - -### StandardToken - -Implementation of full ERC20 token. - -Transfer() and transferFrom() use SafeMath functions, which will cause them to throw instead of returning false. Not a security issue but departs from standard. - -### SimpleToken - -Sample instantiation of StandardToken. Note that in this sample, decimals is 18 and supply only 10,000, so the supply is a small fraction of a single nominal token. - -### CrowdsaleToken - -StandardToken which mints tokens at a fixed price when sent ether. - -There's no provision for owner withdrawing the ether. As a sample for crowdsales it should be Ownable and allow the owner to withdraw ether, rather than stranding the ether in the contract. - -Note: an alternative pattern is a mint() function which is only callable from a separate crowdsale contract, so any sort of rules can be added without modifying the token itself. - -### VestedToken - -Lines 23, 27: -Functions `transfer()` and `transferFrom()` have a modifier canTransfer which throws if not enough tokens are available. However, transfer() returns a boolean success. Inconsistent treatment of failure conditions may cause problems for other contracts using the token. (Note that transferableTokens() relies on safeSub(), so will also throw if there's insufficient balance.) - -Line 64: -Delete not actually necessary since the value is overwritten in the next line anyway. - -## Root level - -### Bounty - -Avoids potential race condition by having each researcher deploy a separate contract for attack; if a research manages to break his associated contract, other researchers can't immediately claim the reward, they have to reproduce the attack in their own contracts. - -A developer could subvert this intent by implementing `deployContract()` to always return the same address. However, this would break the `researchers` mapping, updating the researcher address associated with the contract. This could be prevented by blocking rewrites in `researchers`. - -### DayLimit - -The modifier `limitedDaily` calls `underLimit`, which both checks that the spend is below the daily limit, and adds the input value to the daily spend. This is fine if all functions throw upon failure. However, not all OpenZeppelin functions do this; there are functions that returns false, and modifiers that wrap the function body in `if (bool) {_;}`. In these cases, `_value` will be added to `spentToday`, but ether may not actually be sent because other preconditions were not met. (However in the OpenZeppelin multisig this is not a problem.) - -Lines 4, 11: -Comment claims that `DayLimit` is multiowned, and Shareable is imported, but DayLimit does not actually inherit from Shareable. The intent may be for child contracts to inherit from Shareable (as Multisig does); in this case the import should be removed and the comment altered. - -Line 46: -Manual overflow check instead of using safeAdd. Since this is called from a function that throws upon failure anyway, there's no real downside to using safeAdd. - -### LimitBalance - -No issues. - -### MultisigWallet - -Lines 28, 76, 80: -`kill`, `setDailyLimit`, and `resetSpentToday` only happen with multisig approval, and hashes for these actions are logged by Shareable. However, they should probably post their own events for easy reading. - -Line 45: -This call to underLimit will reduce the daily limit, and then either throw or return 0. So in this case there's no danger that the limit will be reduced without the operation going through. - -Line 65: -Shareable's onlyManyOwners will take the user's confirmation, and execute the function body if and only if enough users have confirmed. Whole thing throws if the send fails, which will roll back the confirmation. Confirm returns false if not enough have confirmed yet, true if the whole thing succeeds, and throws only in the exceptional circumstance that the designated transaction unexpectedly fails. Elegant design. - -Line 68: -Throw here is good but note this function can fail either by returning false or by throwing. - -Line 92: -A bit odd to split `clearPending()` between this contract and Shareable. However this does allow contracts inheriting from Shareable to use custom structs for pending transactions. - - -### SafeMath - -Another interesting comment from the same Edcon presentation was that the overflow behavior of Solidity is undocumented, so in theory, source code that relies on it could break with a future revision. - -However, compiled code should be fine, and in the unlikely event that the compiler is revised in this way, there should be plenty of warning. (But this is an argument for keeping overflow checks isolated in SafeMath.) - -Aside from that small caveat, these are fine. - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/audit/2018-10.pdf b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/audit/2018-10.pdf deleted file mode 100644 index d5bf1274..00000000 Binary files a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/audit/2018-10.pdf and /dev/null differ diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/Makefile b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/Makefile deleted file mode 100644 index bbbddbca..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -default: help - -PATCH = applyHarness.patch -CONTRACTS_DIR = ../contracts -MUNGED_DIR = munged - -help: - @echo "usage:" - @echo " make clean: remove all generated files (those ignored by git)" - @echo " make $(MUNGED_DIR): create $(MUNGED_DIR) directory by applying the patch file to $(CONTRACTS_DIR)" - @echo " make record: record a new patch file capturing the differences between $(CONTRACTS_DIR) and $(MUNGED_DIR)" - -munged: $(wildcard $(CONTRACTS_DIR)/*.sol) $(PATCH) - rm -rf $@ - cp -r $(CONTRACTS_DIR) $@ - patch -p0 -d $@ < $(PATCH) - -record: - diff -ruN $(CONTRACTS_DIR) $(MUNGED_DIR) | sed 's+../contracts/++g' | sed 's+munged/++g' > $(PATCH) - -clean: - git clean -fdX - touch $(PATCH) - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/README.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/README.md deleted file mode 100644 index 55f84d42..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# Running the certora verification tool - -These instructions detail the process for running CVT on the OpenZeppelin (Wizard/Governor) contracts. - -Documentation for CVT and the specification language are available -[here](https://certora.atlassian.net/wiki/spaces/CPD/overview) - -## Running the verification - -The scripts in the `certora/scripts` directory are used to submit verification -jobs to the Certora verification service. After the job is complete, the results will be available on -[the Certora portal](https://vaas-stg.certora.com/). - -These scripts should be run from the root directory; for example by running - -``` -sh certora/scripts/verifyAll.sh -``` - -The most important of these is `verifyAll.sh`, which checks -all of the harnessed contracts (`certora/harness/Wizard*.sol`) against all of -the specifications (`certora/spec/*.spec`). - -The other scripts run a subset of the specifications or the contracts. You can -verify different contracts or specifications by changing the `--verify` option, -and you can run a single rule or method with the `--rule` or `--method` option. - -For example, to verify the `WizardFirstPriority` contract against the -`GovernorCountingSimple` specification, you could change the `--verify` line of -the `WizardControlFirstPriortity.sh` script to: - -``` ---verify WizardFirstPriority:certora/specs/GovernorCountingSimple.spec \ -``` - -## Adapting to changes in the contracts - -Some of our rules require the code to be simplified in various ways. Our -primary tool for performing these simplifications is to run verification on a -contract that extends the original contracts and overrides some of the methods. -These "harness" contracts can be found in the `certora/harness` directory. - -This pattern does require some modifications to the original code: some methods -need to be made virtual or public, for example. These changes are handled by -applying a patch to the code before verification. - -When one of the `verify` scripts is executed, it first applies the patch file -`certora/applyHarness.patch` to the `contracts` directory, placing the output -in the `certora/munged` directory. We then verify the contracts in the -`certora/munged` directory. - -If the original contracts change, it is possible to create a conflict with the -patch. In this case, the verify scripts will report an error message and output -rejected changes in the `munged` directory. After merging the changes, run -`make record` in the `certora` directory; this will regenerate the patch file, -which can then be checked into git. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/applyHarness.patch b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/applyHarness.patch deleted file mode 100644 index 42b10fab..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/applyHarness.patch +++ /dev/null @@ -1,101 +0,0 @@ -diff -ruN .gitignore .gitignore ---- .gitignore 1969-12-31 19:00:00.000000000 -0500 -+++ .gitignore 2021-12-09 14:46:33.923637220 -0500 -@@ -0,0 +1,2 @@ -+* -+!.gitignore -diff -ruN governance/compatibility/GovernorCompatibilityBravo.sol governance/compatibility/GovernorCompatibilityBravo.sol ---- governance/compatibility/GovernorCompatibilityBravo.sol 2021-12-03 15:24:56.523654357 -0500 -+++ governance/compatibility/GovernorCompatibilityBravo.sol 2021-12-09 14:46:33.923637220 -0500 -@@ -245,7 +245,7 @@ - /** - * @dev See {Governor-_quorumReached}. In this module, only forVotes count toward the quorum. - */ -- function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { -+ function _quorumReached(uint256 proposalId) public view virtual override returns (bool) { // HARNESS: changed to public from internal - ProposalDetails storage details = _proposalDetails[proposalId]; - return quorum(proposalSnapshot(proposalId)) <= details.forVotes; - } -@@ -253,7 +253,7 @@ - /** - * @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes. - */ -- function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) { -+ function _voteSucceeded(uint256 proposalId) public view virtual override returns (bool) { // HARNESS: changed to public from internal - ProposalDetails storage details = _proposalDetails[proposalId]; - return details.forVotes > details.againstVotes; - } -diff -ruN governance/extensions/GovernorCountingSimple.sol governance/extensions/GovernorCountingSimple.sol ---- governance/extensions/GovernorCountingSimple.sol 2021-12-03 15:24:56.523654357 -0500 -+++ governance/extensions/GovernorCountingSimple.sol 2021-12-09 14:46:33.923637220 -0500 -@@ -64,7 +64,7 @@ - /** - * @dev See {Governor-_quorumReached}. - */ -- function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { -+ function _quorumReached(uint256 proposalId) public view virtual override returns (bool) { - ProposalVote storage proposalvote = _proposalVotes[proposalId]; - - return quorum(proposalSnapshot(proposalId)) <= proposalvote.forVotes + proposalvote.abstainVotes; -@@ -73,7 +73,7 @@ - /** - * @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be strictly over the againstVotes. - */ -- function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) { -+ function _voteSucceeded(uint256 proposalId) public view virtual override returns (bool) { - ProposalVote storage proposalvote = _proposalVotes[proposalId]; - - return proposalvote.forVotes > proposalvote.againstVotes; -diff -ruN governance/extensions/GovernorTimelockControl.sol governance/extensions/GovernorTimelockControl.sol ---- governance/extensions/GovernorTimelockControl.sol 2021-12-03 15:24:56.523654357 -0500 -+++ governance/extensions/GovernorTimelockControl.sol 2021-12-09 14:46:33.923637220 -0500 -@@ -111,7 +111,7 @@ - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual override { -- _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash); -+ _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash); - } - - /** -diff -ruN governance/Governor.sol governance/Governor.sol ---- governance/Governor.sol 2021-12-03 15:24:56.523654357 -0500 -+++ governance/Governor.sol 2021-12-09 14:46:56.411503587 -0500 -@@ -38,8 +38,8 @@ - - string private _name; - -- mapping(uint256 => ProposalCore) private _proposals; -- -+ mapping(uint256 => ProposalCore) public _proposals; -+ - /** - * @dev Restrict access to governor executing address. Some module might override the _executor function to make - * sure this modifier is consistant with the execution model. -@@ -167,12 +167,12 @@ - /** - * @dev Amount of votes already cast passes the threshold limit. - */ -- function _quorumReached(uint256 proposalId) internal view virtual returns (bool); -+ function _quorumReached(uint256 proposalId) public view virtual returns (bool); // HARNESS: changed to public from internal - - /** - * @dev Is the proposal successful or not. - */ -- function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool); -+ function _voteSucceeded(uint256 proposalId) public view virtual returns (bool); // HARNESS: changed to public from internal - - /** - * @dev Register a vote with a given support and voting weight. -diff -ruN token/ERC20/extensions/ERC20Votes.sol token/ERC20/extensions/ERC20Votes.sol ---- token/ERC20/extensions/ERC20Votes.sol 2021-12-03 15:24:56.527654330 -0500 -+++ token/ERC20/extensions/ERC20Votes.sol 2021-12-09 14:46:33.927637196 -0500 -@@ -84,7 +84,7 @@ - * - * - `blockNumber` must have been already mined - */ -- function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { -+ function getPastVotes(address account, uint256 blockNumber) public view virtual returns (uint256) { - require(blockNumber < block.number, "ERC20Votes: block not yet mined"); - return _checkpointsLookup(_checkpoints[account], blockNumber); - } diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/ERC20VotesHarness.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/ERC20VotesHarness.sol deleted file mode 100644 index 5067ecfb..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/ERC20VotesHarness.sol +++ /dev/null @@ -1,28 +0,0 @@ -import "../munged/token/ERC20/extensions/ERC20Votes.sol"; - -contract ERC20VotesHarness is ERC20Votes { - constructor(string memory name, string memory symbol) ERC20Permit(name) ERC20(name, symbol) {} - - mapping(address => mapping(uint256 => uint256)) public _getPastVotes; - - function _afterTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual override { - super._afterTokenTransfer(from, to, amount); - _getPastVotes[from][block.number] -= amount; - _getPastVotes[to][block.number] += amount; - } - - /** - * @dev Change delegation for `delegator` to `delegatee`. - * - * Emits events {DelegateChanged} and {DelegateVotesChanged}. - */ - function _delegate(address delegator, address delegatee) internal virtual override{ - super._delegate(delegator, delegatee); - _getPastVotes[delegator][block.number] -= balanceOf(delegator); - _getPastVotes[delegatee][block.number] += balanceOf(delegator); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/WizardControlFirstPriority.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/WizardControlFirstPriority.sol deleted file mode 100644 index 5ae7fe06..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/WizardControlFirstPriority.sol +++ /dev/null @@ -1,150 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.2; - -import "../munged/governance/Governor.sol"; -import "../munged/governance/extensions/GovernorCountingSimple.sol"; -import "../munged/governance/extensions/GovernorVotes.sol"; -import "../munged/governance/extensions/GovernorVotesQuorumFraction.sol"; -import "../munged/governance/extensions/GovernorTimelockControl.sol"; -import "../munged/governance/extensions/GovernorProposalThreshold.sol"; - -/* -Wizard options: -ProposalThreshhold = 10 -ERC20Votes -TimelockController -*/ - -contract WizardControlFirstPriority is Governor, GovernorProposalThreshold, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl { - constructor(ERC20Votes _token, TimelockController _timelock, string memory name, uint256 quorumFraction) - Governor(name) - GovernorVotes(_token) - GovernorVotesQuorumFraction(quorumFraction) - GovernorTimelockControl(_timelock) - {} - - //HARNESS - - function isExecuted(uint256 proposalId) public view returns (bool) { - return _proposals[proposalId].executed; - } - - function isCanceled(uint256 proposalId) public view returns (bool) { - return _proposals[proposalId].canceled; - } - - uint256 _votingDelay; - - uint256 _votingPeriod; - - uint256 _proposalThreshold; - - mapping(uint256 => uint256) public ghost_sum_vote_power_by_id; - - function _castVote( - uint256 proposalId, - address account, - uint8 support, - string memory reason - ) internal override virtual returns (uint256) { - - uint256 deltaWeight = super._castVote(proposalId, account, support, reason); //HARNESS - ghost_sum_vote_power_by_id[proposalId] += deltaWeight; - - return deltaWeight; - } - - function snapshot(uint256 proposalId) public view returns (uint64) { - return _proposals[proposalId].voteStart._deadline; - } - - - function getExecutor() public view returns (address){ - return _executor(); - } - - // original code, harnessed - - function votingDelay() public view override returns (uint256) { // HARNESS: pure -> view - return _votingDelay; // HARNESS: parametric - } - - function votingPeriod() public view override returns (uint256) { // HARNESS: pure -> view - return _votingPeriod; // HARNESS: parametric - } - - function proposalThreshold() public view override returns (uint256) { // HARNESS: pure -> view - return _proposalThreshold; // HARNESS: parametric - } - - // original code, not harnessed - // The following functions are overrides required by Solidity. - - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function getVotes(address account, uint256 blockNumber) - public - view - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function state(uint256 proposalId) - public - view - override(Governor, GovernorTimelockControl) - returns (ProposalState) - { - return super.state(proposalId); - } - - function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description) - public - override(Governor, GovernorProposalThreshold, IGovernor) - returns (uint256) - { - return super.propose(targets, values, calldatas, description); - } - - function _execute(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) - internal - override(Governor, GovernorTimelockControl) - { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) - internal - override(Governor, GovernorTimelockControl) - returns (uint256) - { - return super._cancel(targets, values, calldatas, descriptionHash); - } - - function _executor() - internal - view - override(Governor, GovernorTimelockControl) - returns (address) - { - return super._executor(); - } - - function supportsInterface(bytes4 interfaceId) - public - view - override(Governor, GovernorTimelockControl) - returns (bool) - { - return super.supportsInterface(interfaceId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/WizardFirstTry.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/WizardFirstTry.sol deleted file mode 100644 index 83fece04..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/harnesses/WizardFirstTry.sol +++ /dev/null @@ -1,141 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.2; - -import "../munged/governance/Governor.sol"; -import "../munged/governance/extensions/GovernorCountingSimple.sol"; -import "../munged/governance/extensions/GovernorVotes.sol"; -import "../munged/governance/extensions/GovernorVotesQuorumFraction.sol"; -import "../munged/governance/extensions/GovernorTimelockCompound.sol"; - -/* -Wizard options: -ERC20Votes -TimelockCompound -*/ - -contract WizardFirstTry is Governor, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockCompound { - constructor(ERC20Votes _token, ICompoundTimelock _timelock, string memory name, uint256 quorumFraction) - Governor(name) - GovernorVotes(_token) - GovernorVotesQuorumFraction(quorumFraction) - GovernorTimelockCompound(_timelock) - {} - - //HARNESS - - function isExecuted(uint256 proposalId) public view returns (bool) { - return _proposals[proposalId].executed; - } - - function isCanceled(uint256 proposalId) public view returns (bool) { - return _proposals[proposalId].canceled; - } - - function snapshot(uint256 proposalId) public view returns (uint64) { - return _proposals[proposalId].voteStart._deadline; - } - - function getExecutor() public view returns (address){ - return _executor(); - } - - uint256 _votingDelay; - - uint256 _votingPeriod; - - mapping(uint256 => uint256) public ghost_sum_vote_power_by_id; - - function _castVote( - uint256 proposalId, - address account, - uint8 support, - string memory reason - ) internal override virtual returns (uint256) { - - uint256 deltaWeight = super._castVote(proposalId, account, support, reason); //HARNESS - ghost_sum_vote_power_by_id[proposalId] += deltaWeight; - - return deltaWeight; - } - - // original code, harnessed - - function votingDelay() public view override virtual returns (uint256) { // HARNESS: pure -> view - return _votingDelay; // HARNESS: parametric - } - - function votingPeriod() public view override virtual returns (uint256) { // HARNESS: pure -> view - return _votingPeriod; // HARNESS: parametric - } - - // original code, not harnessed - // The following functions are overrides required by Solidity. - - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function getVotes(address account, uint256 blockNumber) - public - view - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function state(uint256 proposalId) - public - view - override(Governor, GovernorTimelockCompound) - returns (ProposalState) - { - return super.state(proposalId); - } - - function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description) - public - override(Governor, IGovernor) - returns (uint256) - { - return super.propose(targets, values, calldatas, description); - } - - function _execute(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) - internal - override(Governor, GovernorTimelockCompound) - { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) - internal - override(Governor, GovernorTimelockCompound) - returns (uint256) - { - return super._cancel(targets, values, calldatas, descriptionHash); - } - - function _executor() - internal - view - override(Governor, GovernorTimelockCompound) - returns (address) - { - return super._executor(); - } - - function supportsInterface(bytes4 interfaceId) - public - view - override(Governor, GovernorTimelockCompound) - returns (bool) - { - return super.supportsInterface(interfaceId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/munged/.gitignore b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/munged/.gitignore deleted file mode 100644 index d6b7ef32..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/munged/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/Governor.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/Governor.sh deleted file mode 100755 index 53ade506..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/Governor.sh +++ /dev/null @@ -1,10 +0,0 @@ -make -C certora munged - -certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/GovernorHarness.sol \ - --verify GovernorHarness:certora/specs/GovernorBase.spec \ - --solc solc8.0 \ - --staging shelly/forSasha \ - --optimistic_loop \ - --settings -copyLoopUnroll=4 \ - --rule voteStartBeforeVoteEnd \ - --msg "$1" diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/GovernorCountingSimple-counting.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/GovernorCountingSimple-counting.sh deleted file mode 100644 index 9ed8fe34..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/GovernorCountingSimple-counting.sh +++ /dev/null @@ -1,10 +0,0 @@ -make -C certora munged - -certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/GovernorBasicHarness.sol \ - --verify GovernorBasicHarness:certora/specs/GovernorCountingSimple.spec \ - --solc solc8.2 \ - --staging shelly/forSasha \ - --optimistic_loop \ - --settings -copyLoopUnroll=4 \ - --rule hasVotedCorrelation \ - --msg "$1" diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/WizardControlFirstPriority.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/WizardControlFirstPriority.sh deleted file mode 100644 index b815986e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/WizardControlFirstPriority.sh +++ /dev/null @@ -1,12 +0,0 @@ -make -C certora munged - -certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/WizardControlFirstPriority.sol \ - --link WizardControlFirstPriority:token=ERC20VotesHarness \ - --verify WizardControlFirstPriority:certora/specs/GovernorBase.spec \ - --solc solc8.2 \ - --disableLocalTypeChecking \ - --staging shelly/forSasha \ - --optimistic_loop \ - --settings -copyLoopUnroll=4 \ - --rule canVoteDuringVotingPeriod \ - --msg "$1" diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/WizardFirstTry.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/WizardFirstTry.sh deleted file mode 100644 index fd5a32ab..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/WizardFirstTry.sh +++ /dev/null @@ -1,10 +0,0 @@ -make -C certora munged - -certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/WizardFirstTry.sol \ - --verify WizardFirstTry:certora/specs/GovernorBase.spec \ - --solc solc8.2 \ - --staging shelly/forSasha \ - --optimistic_loop \ - --disableLocalTypeChecking \ - --settings -copyLoopUnroll=4 \ - --msg "$1" diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/sanity.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/sanity.sh deleted file mode 100644 index b6cdb4ec..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/sanity.sh +++ /dev/null @@ -1,14 +0,0 @@ -make -C certora munged - -for f in certora/harnesses/Wizard*.sol -do - echo "Processing $f" - file=$(basename $f) - echo ${file%.*} - certoraRun certora/harnesses/$file \ - --verify ${file%.*}:certora/specs/sanity.spec "$@" \ - --solc solc8.2 --staging shelly/forSasha \ - --optimistic_loop \ - --msg "checking sanity on ${file%.*}" - --settings -copyLoopUnroll=4 -done diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/verifyAll.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/verifyAll.sh deleted file mode 100644 index 90d76912..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/scripts/verifyAll.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/bash - -make -C certora munged - -for contract in certora/harnesses/Wizard*.sol; -do - for spec in certora/specs/*.spec; - do - contractFile=$(basename $contract) - specFile=$(basename $spec) - if [[ "${specFile%.*}" != "RulesInProgress" ]]; - then - echo "Processing ${contractFile%.*} with $specFile" - if [[ "${contractFile%.*}" = *"WizardControl"* ]]; - then - certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/$contractFile \ - --link ${contractFile%.*}:token=ERC20VotesHarness \ - --verify ${contractFile%.*}:certora/specs/$specFile "$@" \ - --solc solc8.2 \ - --staging shelly/forSasha \ - --disableLocalTypeChecking \ - --optimistic_loop \ - --settings -copyLoopUnroll=4 \ - --send_only \ - --msg "checking $specFile on ${contractFile%.*}" - else - certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/$contractFile \ - --verify ${contractFile%.*}:certora/specs/$specFile "$@" \ - --solc solc8.2 \ - --staging shelly/forSasha \ - --disableLocalTypeChecking \ - --optimistic_loop \ - --settings -copyLoopUnroll=4 \ - --send_only \ - --msg "checking $specFile on ${contractFile%.*}" - fi - fi - done -done diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/GovernorBase.spec b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/GovernorBase.spec deleted file mode 100644 index d6f6d814..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/GovernorBase.spec +++ /dev/null @@ -1,334 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -///////////////////// Governor.sol base definitions ////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -using ERC20VotesHarness as erc20votes; - -methods { - function proposalSnapshot(uint256) external returns uint256 envfree; // matches proposalVoteStart - function proposalDeadline(uint256) external returns uint256 envfree; // matches proposalVoteEnd - function hashProposal(address[],uint256[],bytes[],bytes32) external returns uint256 envfree; - function isExecuted(uint256) external returns bool envfree; - function isCanceled(uint256) external returns bool envfree; - function execute(address[], uint256[], bytes[], bytes32) external returns uint256; - function hasVoted(uint256, address) external returns bool; - function castVote(uint256, uint8) external returns uint256; - function updateQuorumNumerator(uint256) external; - function queue(address[], uint256[], bytes[], bytes32) external returns uint256; - - // internal functions made public in harness: - function _quorumReached(uint256) external returns bool; - function _voteSucceeded(uint256) external returns bool envfree; - - // function summarization - function proposalThreshold() external returns uint256 envfree; - - function _.getVotes(address, uint256) external returns uint256 => DISPATCHER(true); - - function _.getPastTotalSupply(uint256 t) returns uint256 => PER_CALLEE_CONSTANT; - function _.getPastVotes(address a, uint256 t) returns uint256 => PER_CALLEE_CONSTANT; - - //scheduleBatch(address[],uint256[],bytes[],bytes32,bytes32,uint256) => DISPATCHER(true) - //executeBatch(address[], uint256[], bytes[], bytes32, bytes32) => DISPATCHER(true) -} - -////////////////////////////////////////////////////////////////////////////// -//////////////////////////////// Definitions ///////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - - -// proposal was created - relation proved in noStartBeforeCreation -definition proposalCreated(uint256 pId) returns bool = proposalSnapshot(pId) > 0; - - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////// Helper Functions /////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -function helperFunctionsWithRevert(uint256 proposalId, method f, env e) { - address[] targets; uint256[] values; bytes[] calldatas; string reason; bytes32 descriptionHash; - uint8 support; uint8 v; bytes32 r; bytes32 s; - if (f.selector == sig:propose(address[], uint256[], bytes[], string).selector) { - uint256 result = propose@withrevert(e, targets, values, calldatas, reason); - require(result == proposalId); - } else if (f.selector == sig:execute(address[], uint256[], bytes[], bytes32).selector) { - uint256 result = execute@withrevert(e, targets, values, calldatas, descriptionHash); - require(result == proposalId); - } else if (f.selector == sig:castVote(uint256, uint8).selector) { - castVote@withrevert(e, proposalId, support); - } else if (f.selector == sig:castVoteWithReason(uint256, uint8, string).selector) { - castVoteWithReason@withrevert(e, proposalId, support, reason); - } else if (f.selector == sig:castVoteBySig(uint256, uint8,uint8, bytes32, bytes32).selector) { - castVoteBySig@withrevert(e, proposalId, support, v, r, s); - } else if (f.selector == sig:queue(address[], uint256[], bytes[], bytes32).selector) { - queue@withrevert(e, targets, values, calldatas, descriptionHash); - } else { - calldataarg args; - f@withrevert(e, args); - } -} - -/* - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////////////////////////// State Diagram ////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // // - // castVote(s)() // - // ------------- propose() ---------------------- time pass --------------- time passes ----------- // - // | No Proposal | --------> | Before Start (Delay) | --------> | Voting Period | ----------------------> | execute() | // - // ------------- ---------------------- --------------- -> Executed/Canceled ----------- // - // ------------------------------------------------------------|---------------|-------------------------|--------------> // - // t start end timelock // - // // - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -*/ - - -/////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////// Global Valid States ///////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////// - - -/* - * Start and end date are either initialized (non zero) or uninitialized (zero) simultaneously - * This invariant assumes that the block number cannot be 0 at any stage of the contract cycle - * This is very safe assumption as usually the 0 block is genesis block which is uploaded with data - * by the developers and will not be valid to raise proposals (at the current way that block chain is functioning) - */ - // To use env with general preserved block disable type checking [--disableLocalTypeChecking] -invariant startAndEndDatesNonZero(uint256 pId) - proposalSnapshot(pId) != 0 <=> proposalDeadline(pId) != 0 - { preserved with (env e){ - require e.block.number > 0; - }} - - -/* - * If a proposal is canceled it must have a start and an end date - */ - // To use env with general preserved block disable type checking [--disableLocalTypeChecking] -invariant canceledImplyStartAndEndDateNonZero(uint pId) - isCanceled(pId) => proposalSnapshot(pId) != 0 - {preserved with (env e){ - require e.block.number > 0; - }} - - -/* - * If a proposal is executed it must have a start and an end date - */ - // To use env with general preserved block disable type checking [--disableLocalTypeChecking] -invariant executedImplyStartAndEndDateNonZero(uint pId) - isExecuted(pId) => proposalSnapshot(pId) != 0 - { preserved with (env e){ - requireInvariant startAndEndDatesNonZero(pId); - require e.block.number > 0; - }} - - -/* - * A proposal starting block number must be less or equal than the proposal end date - */ -invariant voteStartBeforeVoteEnd(uint256 pId) - // from < to <= because snapshot and deadline can be the same block number if delays are set to 0 - // This is possible before the integration of GovernorSettings.sol to the system. - // After integration of GovernorSettings.sol the invariant expression should be changed from <= to < - (proposalSnapshot(pId) > 0 => proposalSnapshot(pId) <= proposalDeadline(pId)) - // (proposalSnapshot(pId) > 0 => proposalSnapshot(pId) <= proposalDeadline(pId)) - { preserved { - requireInvariant startAndEndDatesNonZero(pId); - }} - - -/* - * A proposal cannot be both executed and canceled simultaneously. - */ -invariant noBothExecutedAndCanceled(uint256 pId) - !isExecuted(pId) || !isCanceled(pId) - - -/* - * A proposal could be executed only if quorum was reached and vote succeeded - */ -rule executionOnlyIfQuoromReachedAndVoteSucceeded(uint256 pId, env e, method f){ - bool isExecutedBefore = isExecuted(pId); - bool quorumReachedBefore = _quorumReached(e, pId); - bool voteSucceededBefore = _voteSucceeded(pId); - - calldataarg args; - f(e, args); - - bool isExecutedAfter = isExecuted(pId); - assert (!isExecutedBefore && isExecutedAfter) => (quorumReachedBefore && voteSucceededBefore), "quorum was changed"; -} - -/////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////// In-State Rules ///////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////// - -//========================================== -//------------- Voting Period -------------- -//========================================== - -/* - * A user cannot vote twice - */ - // Checked for castVote only. all 3 castVote functions call _castVote, so the completness of the verification is counted on - // the fact that the 3 functions themselves makes no chages, but rather call an internal function to execute. - // That means that we do not check those 3 functions directly, however for castVote & castVoteWithReason it is quite trivial - // to understand why this is ok. For castVoteBySig we basically assume that the signature referendum is correct without checking it. - // We could check each function seperately and pass the rule, but that would have uglyfied the code with no concrete - // benefit, as it is evident that nothing is happening in the first 2 functions (calling a view function), and we do not desire to check the signature verification. -rule doubleVoting(uint256 pId, uint8 sup, method f) { - env e; - address user = e.msg.sender; - bool votedCheck = hasVoted(e, pId, user); - - castVote@withrevert(e, pId, sup); - - assert votedCheck => lastReverted, "double voting accured"; -} - - -/////////////////////////////////////////////////////////////////////////////////////// -//////////////////////////// State Transitions Rules ////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////// - -//=========================================== -//-------- Propose() --> End of Time -------- -//=========================================== - - -/* - * Once a proposal is created, voteStart and voteEnd are immutable - */ -rule immutableFieldsAfterProposalCreation(uint256 pId, method f) { - uint256 _voteStart = proposalSnapshot(pId); - uint256 _voteEnd = proposalDeadline(pId); - - require proposalCreated(pId); // startDate > 0 - - env e; calldataarg arg; - f(e, arg); - - uint256 voteStart_ = proposalSnapshot(pId); - uint256 voteEnd_ = proposalDeadline(pId); - assert _voteStart == voteStart_, "Start date was changed"; - assert _voteEnd == voteEnd_, "End date was changed"; -} - - -/* - * Voting cannot start at a block number prior to proposal’s creation block number - */ -rule noStartBeforeCreation(uint256 pId) { - uint256 previousStart = proposalSnapshot(pId); - // This line makes sure that we see only cases where start date is changed from 0, i.e. creation of proposal - // We proved in immutableFieldsAfterProposalCreation that once dates set for proposal, it cannot be changed - require !proposalCreated(pId); // previousStart == 0; - - env e; calldataarg args; - propose(e, args); - - uint256 newStart = proposalSnapshot(pId); - // if created, start is after current block number (creation block) - assert(newStart != previousStart => newStart >= e.block.number); -} - - -//============================================ -//--- End of Voting Period --> End of Time --- -//============================================ - - -/* - * A proposal can neither be executed nor canceled before it ends - */ - // By induction it cannot be executed nor canceled before it starts, due to voteStartBeforeVoteEnd -rule noExecuteOrCancelBeforeDeadline(uint256 pId, method f){ - require !isExecuted(pId) && !isCanceled(pId); - - env e; calldataarg args; - f(e, args); - - assert e.block.number < proposalDeadline(pId) => (!isExecuted(pId) && !isCanceled(pId)), "executed/cancelled before deadline"; -} - -//////////////////////////////////////////////////////////////////////////////// -////////////////////// Integrity Of Functions (Unit Tests) ///////////////////// -//////////////////////////////////////////////////////////////////////////////// - - -//////////////////////////////////////////////////////////////////////////////// -////////////////////////////// High Level Rules //////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - - -//////////////////////////////////////////////////////////////////////////////// -///////////////////////////// Not Categorized Yet ////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - - -/* - * All proposal specific (non-view) functions should revert if proposal is executed - */ - // In this rule we show that if a function is executed, i.e. execute() was called on the proposal ID, - // non of the proposal specific functions can make changes again. In executedOnlyAfterExecuteFunc - // we connected the executed attribute to the execute() function, showing that only execute() can - // change it, and that it will always change it. -rule allFunctionsRevertIfExecuted(method f) filtered { f -> - !f.isView && !f.isFallback - && f.selector != sig:updateTimelock(address).selector - && f.selector != sig:updateQuorumNumerator(uint256).selector - && f.selector != sig:queue(address[],uint256[],bytes[],bytes32).selector - && f.selector != sig:relay(address,uint256,bytes).selector - && f.selector != 0xb9a61961 // __acceptAdmin() -} { - env e; calldataarg args; - uint256 pId; - require(isExecuted(pId)); - requireInvariant noBothExecutedAndCanceled(pId); - requireInvariant executedImplyStartAndEndDateNonZero(pId); - - helperFunctionsWithRevert(pId, f, e); - - assert(lastReverted, "Function was not reverted"); -} - -/* - * All proposal specific (non-view) functions should revert if proposal is canceled - */ -rule allFunctionsRevertIfCanceled(method f) filtered { - f -> !f.isView && !f.isFallback - && f.selector != sig:updateTimelock(address).selector - && f.selector != sig:updateQuorumNumerator(uint256).selector - && f.selector != sig:queue(address[],uint256[],bytes[],bytes32).selector - && f.selector != sig:relay(address,uint256,bytes).selector - && f.selector != 0xb9a61961 // __acceptAdmin() -} { - env e; calldataarg args; - uint256 pId; - require(isCanceled(pId)); - requireInvariant noBothExecutedAndCanceled(pId); - requireInvariant canceledImplyStartAndEndDateNonZero(pId); - - helperFunctionsWithRevert(pId, f, e); - - assert(lastReverted, "Function was not reverted"); -} - -/* - * Proposal can be switched to executed only via execute() function - */ -rule executedOnlyAfterExecuteFunc(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash, method f) { - env e; calldataarg args; - uint256 pId; - bool executedBefore = isExecuted(pId); - require(!executedBefore); - - helperFunctionsWithRevert(pId, f, e); - - bool executedAfter = isExecuted(pId); - assert(executedAfter != executedBefore => f.selector == sig:execute(address[], uint256[], bytes[], bytes32).selector, "isExecuted only changes in the execute method"); -} - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/GovernorCountingSimple.spec b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/GovernorCountingSimple.spec deleted file mode 100644 index f8f08fed..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/GovernorCountingSimple.spec +++ /dev/null @@ -1,221 +0,0 @@ -import "GovernorBase.spec"; - -using ERC20VotesHarness as erc20votes; - -methods { - function ghost_sum_vote_power_by_id(uint256) external returns uint256 envfree; - - function quorum(uint256) external returns uint256; - function proposalVotes(uint256) external returns (uint256, uint256, uint256) envfree; - - function quorumNumerator() external returns uint256; - function _executor() external returns address; - - function erc20votes._getPastVotes(address, uint256) external returns uint256; - - function getExecutor() external returns address; - - function timelock() external returns address; -} - - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////////// GHOSTS ///////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - - -//////////// ghosts to keep track of votes counting //////////// - -/* - * the sum of voting power of those who voted - */ -ghost sum_all_votes_power() returns uint256 { - init_state axiom sum_all_votes_power() == 0; -} - -hook Sstore ghost_sum_vote_power_by_id [KEY uint256 pId] uint256 current_power(uint256 old_power) STORAGE { - havoc sum_all_votes_power assuming sum_all_votes_power@new() == sum_all_votes_power@old() - old_power + current_power; -} - -/* - * sum of all votes casted per proposal - */ -ghost tracked_weight(uint256) returns uint256 { - init_state axiom forall uint256 p. tracked_weight(p) == 0; -} - -/* - * sum of all votes casted - */ -ghost sum_tracked_weight() returns uint256 { - init_state axiom sum_tracked_weight() == 0; -} - -/* - * getter for _proposalVotes.againstVotes - */ -ghost votesAgainst() returns uint256 { - init_state axiom votesAgainst() == 0; -} - -/* - * getter for _proposalVotes.forVotes - */ -ghost votesFor() returns uint256 { - init_state axiom votesFor() == 0; -} - -/* - * getter for _proposalVotes.abstainVotes - */ -ghost votesAbstain() returns uint256 { - init_state axiom votesAbstain() == 0; -} - -hook Sstore _proposalVotes [KEY uint256 pId].againstVotes uint256 votes(uint256 old_votes) STORAGE { - havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) && - (p != pId => tracked_weight@new(p) == tracked_weight@old(p)); - havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes; - havoc votesAgainst assuming votesAgainst@new() == votesAgainst@old() - old_votes + votes; -} - -hook Sstore _proposalVotes [KEY uint256 pId].forVotes uint256 votes(uint256 old_votes) STORAGE { - havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) && - (p != pId => tracked_weight@new(p) == tracked_weight@old(p)); - havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes; - havoc votesFor assuming votesFor@new() == votesFor@old() - old_votes + votes; -} - -hook Sstore _proposalVotes [KEY uint256 pId].abstainVotes uint256 votes(uint256 old_votes) STORAGE { - havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) && - (p != pId => tracked_weight@new(p) == tracked_weight@old(p)); - havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes; - havoc votesAbstain assuming votesAbstain@new() == votesAbstain@old() - old_votes + votes; -} - - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////// INVARIANTS //////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - - -/* - * sum of all votes casted is equal to the sum of voting power of those who voted, per each proposal - */ -invariant SumOfVotesCastEqualSumOfPowerOfVotedPerProposal(uint256 pId) - tracked_weight(pId) == ghost_sum_vote_power_by_id(pId) - - -/* - * sum of all votes casted is equal to the sum of voting power of those who voted - */ -invariant SumOfVotesCastEqualSumOfPowerOfVoted() - sum_tracked_weight() == sum_all_votes_power() - - -/* -* sum of all votes casted is greater or equal to the sum of voting power of those who voted at a specific proposal -*/ -invariant OneIsNotMoreThanAll(uint256 pId) - sum_all_votes_power() >= tracked_weight(pId) - - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////////// RULES ////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - - -/* - * Only sender's voting status can be changed by execution of any cast vote function - */ -// Checked for castVote only. all 3 castVote functions call _castVote, so the completness of the verification is counted on - // the fact that the 3 functions themselves makes no chages, but rather call an internal function to execute. - // That means that we do not check those 3 functions directly, however for castVote & castVoteWithReason it is quite trivial - // to understand why this is ok. For castVoteBySig we basically assume that the signature referendum is correct without checking it. - // We could check each function seperately and pass the rule, but that would have uglyfied the code with no concrete - // benefit, as it is evident that nothing is happening in the first 2 functions (calling a view function), and we do not desire to check the signature verification. -rule noVoteForSomeoneElse(uint256 pId, uint8 sup, method f) { - env e; calldataarg args; - - address voter = e.msg.sender; - address user; - - bool hasVotedBefore_User = hasVoted(e, pId, user); - - castVote@withrevert(e, pId, sup); - require(!lastReverted); - - bool hasVotedAfter_User = hasVoted(e, pId, user); - - assert user != voter => hasVotedBefore_User == hasVotedAfter_User; -} - - -/* -* Total voting tally is monotonically non-decreasing in every operation -*/ -rule votingWeightMonotonicity(method f){ - uint256 votingWeightBefore = sum_tracked_weight(); - - env e; - calldataarg args; - f(e, args); - - uint256 votingWeightAfter = sum_tracked_weight(); - - assert votingWeightBefore <= votingWeightAfter, "Voting weight was decreased somehow"; -} - - -/* -* A change in hasVoted must be correlated with an non-decreasing of the vote supports (nondecrease because user can vote with weight 0) -*/ -rule hasVotedCorrelation(uint256 pId, method f, env e, uint256 bn) { - address acc = e.msg.sender; - - uint256 againstBefore = votesAgainst(); - uint256 forBefore = votesFor(); - uint256 abstainBefore = votesAbstain(); - - bool hasVotedBefore = hasVoted(e, pId, acc); - - helperFunctionsWithRevert(pId, f, e); - require(!lastReverted); - - uint256 againstAfter = votesAgainst(); - uint256 forAfter = votesFor(); - uint256 abstainAfter = votesAbstain(); - - bool hasVotedAfter = hasVoted(e, pId, acc); - - assert (!hasVotedBefore && hasVotedAfter) => againstBefore <= againstAfter || forBefore <= forAfter || abstainBefore <= abstainAfter, "no correlation"; -} - - -/* -* Only privileged users can execute privileged operations, e.g. change _quorumNumerator or _timelock -*/ -rule privilegedOnlyNumerator(method f, uint256 newQuorumNumerator){ - env e; - calldataarg arg; - uint256 quorumNumBefore = quorumNumerator(e); - - f(e, arg); - - uint256 quorumNumAfter = quorumNumerator(e); - address executorCheck = getExecutor(e); - - assert quorumNumBefore != quorumNumAfter => e.msg.sender == executorCheck, "non priveleged user changed quorum numerator"; -} - -rule privilegedOnlyTimelock(method f, uint256 newQuorumNumerator){ - env e; - calldataarg arg; - uint256 timelockBefore = timelock(e); - - f(e, arg); - - uint256 timelockAfter = timelock(e); - - assert timelockBefore != timelockAfter => e.msg.sender == timelockBefore, "non priveleged user changed timelock"; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/RulesInProgress.spec b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/RulesInProgress.spec deleted file mode 100644 index b3295d76..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/RulesInProgress.spec +++ /dev/null @@ -1,139 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -////////////// THIS SPEC IS A RESERVE FOR NOT IN PROGRESS ////////////// -////////////////////////////////////////////////////////////////////////////// - -import "GovernorBase.spec"; - -using ERC20VotesHarness as erc20votes; - -methods { - function ghost_sum_vote_power_by_id(uint256) external returns uint256 envfree; - - function quorum(uint256) external returns uint256; - function proposalVotes(uint256) external returns (uint256, uint256, uint256) envfree; - - function quorumNumerator() external returns uint256; - function _executor() external returns address; - - function erc20votes._getPastVotes(address, uint256) external returns uint256; - - function getExecutor() external returns address; - - function timelock() external returns address; -} - - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////////// GHOSTS ///////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - - -//////////// ghosts to keep track of votes counting //////////// - -/* - * the sum of voting power of those who voted - */ -ghost sum_all_votes_power() returns uint256 { - init_state axiom sum_all_votes_power() == 0; -} - -hook Sstore ghost_sum_vote_power_by_id [KEY uint256 pId] uint256 current_power(uint256 old_power) STORAGE { - havoc sum_all_votes_power assuming sum_all_votes_power@new() == sum_all_votes_power@old() - old_power + current_power; -} - -/* - * sum of all votes casted per proposal - */ -ghost tracked_weight(uint256) returns uint256 { - init_state axiom forall uint256 p. tracked_weight(p) == 0; -} - -/* - * sum of all votes casted - */ -ghost sum_tracked_weight() returns uint256 { - init_state axiom sum_tracked_weight() == 0; -} - -/* - * getter for _proposalVotes.againstVotes - */ -ghost votesAgainst() returns uint256 { - init_state axiom votesAgainst() == 0; -} - -/* - * getter for _proposalVotes.forVotes - */ -ghost votesFor() returns uint256 { - init_state axiom votesFor() == 0; -} - -/* - * getter for _proposalVotes.abstainVotes - */ -ghost votesAbstain() returns uint256 { - init_state axiom votesAbstain() == 0; -} - -hook Sstore _proposalVotes [KEY uint256 pId].againstVotes uint256 votes(uint256 old_votes) STORAGE { - havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) && - (p != pId => tracked_weight@new(p) == tracked_weight@old(p)); - havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes; - havoc votesAgainst assuming votesAgainst@new() == votesAgainst@old() - old_votes + votes; -} - -hook Sstore _proposalVotes [KEY uint256 pId].forVotes uint256 votes(uint256 old_votes) STORAGE { - havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) && - (p != pId => tracked_weight@new(p) == tracked_weight@old(p)); - havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes; - havoc votesFor assuming votesFor@new() == votesFor@old() - old_votes + votes; -} - -hook Sstore _proposalVotes [KEY uint256 pId].abstainVotes uint256 votes(uint256 old_votes) STORAGE { - havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) && - (p != pId => tracked_weight@new(p) == tracked_weight@old(p)); - havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes; - havoc votesAbstain assuming votesAbstain@new() == votesAbstain@old() - old_votes + votes; -} - - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////// INVARIANTS //////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - - - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////////// RULES ////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - - -//NOT FINISHED -/* -* the sum of voting power of those who voted is less or equal to the maximum possible votes, per each proposal -*/ -rule possibleTotalVotes(uint256 pId, uint8 sup, env e, method f) { - - // add requireinvariant for all i, j. i = i - 1 && i < j => checkpointlookup[i] < checkpointlookup[j]; - require tracked_weight(pId) <= erc20votes.getPastTotalSupply(e, proposalSnapshot(pId)); - - uint256 againstB; - uint256 forB; - uint256 absatinB; - againstB, forB, absatinB = proposalVotes(pId); - - calldataarg args; - //f(e, args); - - castVote(e, pId, sup); - - uint256 against; - uint256 for; - uint256 absatin; - against, for, absatin = proposalVotes(pId); - - uint256 ps = proposalSnapshot(pId); - - assert tracked_weight(pId) <= erc20votes.getPastTotalSupply(e, proposalSnapshot(pId)), "bla bla bla"; -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/sanity.spec b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/sanity.spec deleted file mode 100644 index 5c5226c2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/certora/specs/sanity.spec +++ /dev/null @@ -1,14 +0,0 @@ -/* -This rule looks for a non-reverting execution path to each method, including those overridden in the harness. -A method has such an execution path if it violates this rule. -How it works: - - If there is a non-reverting execution path, we reach the false assertion, and the sanity fails. - - If all execution paths are reverting, we never call the assertion, and the method will pass this rule vacuously. -*/ - -rule sanity(method f) { - env e; - calldataarg arg; - f(e, arg); - assert false; -} \ No newline at end of file diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/AccessControl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/AccessControl.sol deleted file mode 100644 index 4df6b441..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/AccessControl.sol +++ /dev/null @@ -1,223 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) - -pragma solidity ^0.8.0; - -import "./IAccessControl.sol"; -import "../utils/Context.sol"; -import "../utils/Strings.sol"; -import "../utils/introspection/ERC165.sol"; - -/** - * @dev Contract module that allows children to implement role-based access - * control mechanisms. This is a lightweight version that doesn't allow enumerating role - * members except through off-chain means by accessing the contract event logs. Some - * applications may benefit from on-chain enumerability, for those cases see - * {AccessControlEnumerable}. - * - * Roles are referred to by their `bytes32` identifier. These should be exposed - * in the external API and be unique. The best way to achieve this is by - * using `public constant` hash digests: - * - * ``` - * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); - * ``` - * - * Roles can be used to represent a set of permissions. To restrict access to a - * function call, use {hasRole}: - * - * ``` - * function foo() public { - * require(hasRole(MY_ROLE, msg.sender)); - * ... - * } - * ``` - * - * Roles can be granted and revoked dynamically via the {grantRole} and - * {revokeRole} functions. Each role has an associated admin role, and only - * accounts that have a role's admin role can call {grantRole} and {revokeRole}. - * - * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means - * that only accounts with this role will be able to grant or revoke other - * roles. More complex role relationships can be created by using - * {_setRoleAdmin}. - * - * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to - * grant and revoke this role. Extra precautions should be taken to secure - * accounts that have been granted it. - */ -abstract contract AccessControl is Context, IAccessControl, ERC165 { - struct RoleData { - mapping(address => bool) members; - bytes32 adminRole; - } - - mapping(bytes32 => RoleData) private _roles; - - bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; - - /** - * @dev Modifier that checks that an account has a specific role. Reverts - * with a standardized message including the required role. - * - * The format of the revert reason is given by the following regular expression: - * - * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ - * - * _Available since v4.1._ - */ - modifier onlyRole(bytes32 role) { - _checkRole(role, _msgSender()); - _; - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev Returns `true` if `account` has been granted `role`. - */ - function hasRole(bytes32 role, address account) public view virtual override returns (bool) { - return _roles[role].members[account]; - } - - /** - * @dev Revert with a standard message if `account` is missing `role`. - * - * The format of the revert reason is given by the following regular expression: - * - * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ - */ - function _checkRole(bytes32 role, address account) internal view virtual { - if (!hasRole(role, account)) { - revert( - string( - abi.encodePacked( - "AccessControl: account ", - Strings.toHexString(uint160(account), 20), - " is missing role ", - Strings.toHexString(uint256(role), 32) - ) - ) - ); - } - } - - /** - * @dev Returns the admin role that controls `role`. See {grantRole} and - * {revokeRole}. - * - * To change a role's admin, use {_setRoleAdmin}. - */ - function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { - return _roles[role].adminRole; - } - - /** - * @dev Grants `role` to `account`. - * - * If `account` had not been already granted `role`, emits a {RoleGranted} - * event. - * - * Requirements: - * - * - the caller must have ``role``'s admin role. - */ - function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { - _grantRole(role, account); - } - - /** - * @dev Revokes `role` from `account`. - * - * If `account` had been granted `role`, emits a {RoleRevoked} event. - * - * Requirements: - * - * - the caller must have ``role``'s admin role. - */ - function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { - _revokeRole(role, account); - } - - /** - * @dev Revokes `role` from the calling account. - * - * Roles are often managed via {grantRole} and {revokeRole}: this function's - * purpose is to provide a mechanism for accounts to lose their privileges - * if they are compromised (such as when a trusted device is misplaced). - * - * If the calling account had been revoked `role`, emits a {RoleRevoked} - * event. - * - * Requirements: - * - * - the caller must be `account`. - */ - function renounceRole(bytes32 role, address account) public virtual override { - require(account == _msgSender(), "AccessControl: can only renounce roles for self"); - - _revokeRole(role, account); - } - - /** - * @dev Grants `role` to `account`. - * - * If `account` had not been already granted `role`, emits a {RoleGranted} - * event. Note that unlike {grantRole}, this function doesn't perform any - * checks on the calling account. - * - * [WARNING] - * ==== - * This function should only be called from the constructor when setting - * up the initial roles for the system. - * - * Using this function in any other way is effectively circumventing the admin - * system imposed by {AccessControl}. - * ==== - * - * NOTE: This function is deprecated in favor of {_grantRole}. - */ - function _setupRole(bytes32 role, address account) internal virtual { - _grantRole(role, account); - } - - /** - * @dev Sets `adminRole` as ``role``'s admin role. - * - * Emits a {RoleAdminChanged} event. - */ - function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { - bytes32 previousAdminRole = getRoleAdmin(role); - _roles[role].adminRole = adminRole; - emit RoleAdminChanged(role, previousAdminRole, adminRole); - } - - /** - * @dev Grants `role` to `account`. - * - * Internal function without access restriction. - */ - function _grantRole(bytes32 role, address account) internal virtual { - if (!hasRole(role, account)) { - _roles[role].members[account] = true; - emit RoleGranted(role, account, _msgSender()); - } - } - - /** - * @dev Revokes `role` from `account`. - * - * Internal function without access restriction. - */ - function _revokeRole(bytes32 role, address account) internal virtual { - if (hasRole(role, account)) { - _roles[role].members[account] = false; - emit RoleRevoked(role, account, _msgSender()); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/AccessControlEnumerable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/AccessControlEnumerable.sol deleted file mode 100644 index 354e1bed..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/AccessControlEnumerable.sol +++ /dev/null @@ -1,64 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) - -pragma solidity ^0.8.0; - -import "./IAccessControlEnumerable.sol"; -import "./AccessControl.sol"; -import "../utils/structs/EnumerableSet.sol"; - -/** - * @dev Extension of {AccessControl} that allows enumerating the members of each role. - */ -abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { - using EnumerableSet for EnumerableSet.AddressSet; - - mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev Returns one of the accounts that have `role`. `index` must be a - * value between 0 and {getRoleMemberCount}, non-inclusive. - * - * Role bearers are not sorted in any particular way, and their ordering may - * change at any point. - * - * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure - * you perform all queries on the same block. See the following - * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] - * for more information. - */ - function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { - return _roleMembers[role].at(index); - } - - /** - * @dev Returns the number of accounts that have `role`. Can be used - * together with {getRoleMember} to enumerate all bearers of a role. - */ - function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { - return _roleMembers[role].length(); - } - - /** - * @dev Overload {_grantRole} to track enumerable memberships - */ - function _grantRole(bytes32 role, address account) internal virtual override { - super._grantRole(role, account); - _roleMembers[role].add(account); - } - - /** - * @dev Overload {_revokeRole} to track enumerable memberships - */ - function _revokeRole(bytes32 role, address account) internal virtual override { - super._revokeRole(role, account); - _roleMembers[role].remove(account); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol deleted file mode 100644 index f773ecc6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) - -pragma solidity ^0.8.0; - -/** - * @dev External interface of AccessControl declared to support ERC165 detection. - */ -interface IAccessControl { - /** - * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` - * - * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite - * {RoleAdminChanged} not being emitted signaling this. - * - * _Available since v3.1._ - */ - event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); - - /** - * @dev Emitted when `account` is granted `role`. - * - * `sender` is the account that originated the contract call, an admin role - * bearer except when using {AccessControl-_setupRole}. - */ - event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); - - /** - * @dev Emitted when `account` is revoked `role`. - * - * `sender` is the account that originated the contract call: - * - if using `revokeRole`, it is the admin role bearer - * - if using `renounceRole`, it is the role bearer (i.e. `account`) - */ - event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); - - /** - * @dev Returns `true` if `account` has been granted `role`. - */ - function hasRole(bytes32 role, address account) external view returns (bool); - - /** - * @dev Returns the admin role that controls `role`. See {grantRole} and - * {revokeRole}. - * - * To change a role's admin, use {AccessControl-_setRoleAdmin}. - */ - function getRoleAdmin(bytes32 role) external view returns (bytes32); - - /** - * @dev Grants `role` to `account`. - * - * If `account` had not been already granted `role`, emits a {RoleGranted} - * event. - * - * Requirements: - * - * - the caller must have ``role``'s admin role. - */ - function grantRole(bytes32 role, address account) external; - - /** - * @dev Revokes `role` from `account`. - * - * If `account` had been granted `role`, emits a {RoleRevoked} event. - * - * Requirements: - * - * - the caller must have ``role``'s admin role. - */ - function revokeRole(bytes32 role, address account) external; - - /** - * @dev Revokes `role` from the calling account. - * - * Roles are often managed via {grantRole} and {revokeRole}: this function's - * purpose is to provide a mechanism for accounts to lose their privileges - * if they are compromised (such as when a trusted device is misplaced). - * - * If the calling account had been granted `role`, emits a {RoleRevoked} - * event. - * - * Requirements: - * - * - the caller must be `account`. - */ - function renounceRole(bytes32 role, address account) external; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/IAccessControlEnumerable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/IAccessControlEnumerable.sol deleted file mode 100644 index 61aaf57a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/IAccessControlEnumerable.sol +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) - -pragma solidity ^0.8.0; - -import "./IAccessControl.sol"; - -/** - * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. - */ -interface IAccessControlEnumerable is IAccessControl { - /** - * @dev Returns one of the accounts that have `role`. `index` must be a - * value between 0 and {getRoleMemberCount}, non-inclusive. - * - * Role bearers are not sorted in any particular way, and their ordering may - * change at any point. - * - * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure - * you perform all queries on the same block. See the following - * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] - * for more information. - */ - function getRoleMember(bytes32 role, uint256 index) external view returns (address); - - /** - * @dev Returns the number of accounts that have `role`. Can be used - * together with {getRoleMember} to enumerate all bearers of a role. - */ - function getRoleMemberCount(bytes32 role) external view returns (uint256); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/Ownable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/Ownable.sol deleted file mode 100644 index 0b2ca8e3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/Ownable.sol +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) - -pragma solidity ^0.8.0; - -import "../utils/Context.sol"; - -/** - * @dev Contract module which provides a basic access control mechanism, where - * there is an account (an owner) that can be granted exclusive access to - * specific functions. - * - * By default, the owner account will be the one that deploys the contract. This - * can later be changed with {transferOwnership}. - * - * This module is used through inheritance. It will make available the modifier - * `onlyOwner`, which can be applied to your functions to restrict their use to - * the owner. - */ -abstract contract Ownable is Context { - address private _owner; - - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - /** - * @dev Initializes the contract setting the deployer as the initial owner. - */ - constructor() { - _transferOwnership(_msgSender()); - } - - /** - * @dev Returns the address of the current owner. - */ - function owner() public view virtual returns (address) { - return _owner; - } - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(owner() == _msgSender(), "Ownable: caller is not the owner"); - _; - } - - /** - * @dev Leaves the contract without owner. It will not be possible to call - * `onlyOwner` functions anymore. Can only be called by the current owner. - * - * NOTE: Renouncing ownership will leave the contract without an owner, - * thereby removing any functionality that is only available to the owner. - */ - function renounceOwnership() public virtual onlyOwner { - _transferOwnership(address(0)); - } - - /** - * @dev Transfers ownership of the contract to a new account (`newOwner`). - * Can only be called by the current owner. - */ - function transferOwnership(address newOwner) public virtual onlyOwner { - require(newOwner != address(0), "Ownable: new owner is the zero address"); - _transferOwnership(newOwner); - } - - /** - * @dev Transfers ownership of the contract to a new account (`newOwner`). - * Internal function without access restriction. - */ - function _transferOwnership(address newOwner) internal virtual { - address oldOwner = _owner; - _owner = newOwner; - emit OwnershipTransferred(oldOwner, newOwner); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/README.adoc deleted file mode 100644 index 2e84c09a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/access/README.adoc +++ /dev/null @@ -1,21 +0,0 @@ -= Access Control - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/access - -This directory provides ways to restrict who can access the functions of a contract or when they can do it. - -- {AccessControl} provides a general role based access control mechanism. Multiple hierarchical roles can be created and assigned each to multiple accounts. -- {Ownable} is a simpler mechanism with a single owner "role" that can be assigned to a single account. This simpler mechanism can be useful for quick tests but projects with production concerns are likely to outgrow it. - -== Authorization - -{{Ownable}} - -{{IAccessControl}} - -{{AccessControl}} - -{{IAccessControlEnumerable}} - -{{AccessControlEnumerable}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/PaymentSplitter.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/PaymentSplitter.sol deleted file mode 100644 index 94d2ab82..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/PaymentSplitter.sol +++ /dev/null @@ -1,189 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC20/utils/SafeERC20.sol"; -import "../utils/Address.sol"; -import "../utils/Context.sol"; - -/** - * @title PaymentSplitter - * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware - * that the Ether will be split in this way, since it is handled transparently by the contract. - * - * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each - * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim - * an amount proportional to the percentage of total shares they were assigned. - * - * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the - * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} - * function. - * - * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and - * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you - * to run tests before sending real value to this contract. - */ -contract PaymentSplitter is Context { - event PayeeAdded(address account, uint256 shares); - event PaymentReleased(address to, uint256 amount); - event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); - event PaymentReceived(address from, uint256 amount); - - uint256 private _totalShares; - uint256 private _totalReleased; - - mapping(address => uint256) private _shares; - mapping(address => uint256) private _released; - address[] private _payees; - - mapping(IERC20 => uint256) private _erc20TotalReleased; - mapping(IERC20 => mapping(address => uint256)) private _erc20Released; - - /** - * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at - * the matching position in the `shares` array. - * - * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no - * duplicates in `payees`. - */ - constructor(address[] memory payees, uint256[] memory shares_) payable { - require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); - require(payees.length > 0, "PaymentSplitter: no payees"); - - for (uint256 i = 0; i < payees.length; i++) { - _addPayee(payees[i], shares_[i]); - } - } - - /** - * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully - * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the - * reliability of the events, and not the actual splitting of Ether. - * - * To learn more about this see the Solidity documentation for - * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback - * functions]. - */ - receive() external payable virtual { - emit PaymentReceived(_msgSender(), msg.value); - } - - /** - * @dev Getter for the total shares held by payees. - */ - function totalShares() public view returns (uint256) { - return _totalShares; - } - - /** - * @dev Getter for the total amount of Ether already released. - */ - function totalReleased() public view returns (uint256) { - return _totalReleased; - } - - /** - * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 - * contract. - */ - function totalReleased(IERC20 token) public view returns (uint256) { - return _erc20TotalReleased[token]; - } - - /** - * @dev Getter for the amount of shares held by an account. - */ - function shares(address account) public view returns (uint256) { - return _shares[account]; - } - - /** - * @dev Getter for the amount of Ether already released to a payee. - */ - function released(address account) public view returns (uint256) { - return _released[account]; - } - - /** - * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an - * IERC20 contract. - */ - function released(IERC20 token, address account) public view returns (uint256) { - return _erc20Released[token][account]; - } - - /** - * @dev Getter for the address of the payee number `index`. - */ - function payee(uint256 index) public view returns (address) { - return _payees[index]; - } - - /** - * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the - * total shares and their previous withdrawals. - */ - function release(address payable account) public virtual { - require(_shares[account] > 0, "PaymentSplitter: account has no shares"); - - uint256 totalReceived = address(this).balance + totalReleased(); - uint256 payment = _pendingPayment(account, totalReceived, released(account)); - - require(payment != 0, "PaymentSplitter: account is not due payment"); - - _released[account] += payment; - _totalReleased += payment; - - Address.sendValue(account, payment); - emit PaymentReleased(account, payment); - } - - /** - * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their - * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 - * contract. - */ - function release(IERC20 token, address account) public virtual { - require(_shares[account] > 0, "PaymentSplitter: account has no shares"); - - uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); - uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); - - require(payment != 0, "PaymentSplitter: account is not due payment"); - - _erc20Released[token][account] += payment; - _erc20TotalReleased[token] += payment; - - SafeERC20.safeTransfer(token, account, payment); - emit ERC20PaymentReleased(token, account, payment); - } - - /** - * @dev internal logic for computing the pending payment of an `account` given the token historical balances and - * already released amounts. - */ - function _pendingPayment( - address account, - uint256 totalReceived, - uint256 alreadyReleased - ) private view returns (uint256) { - return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; - } - - /** - * @dev Add a new payee to the contract. - * @param account The address of the payee to add. - * @param shares_ The number of shares owned by the payee. - */ - function _addPayee(address account, uint256 shares_) private { - require(account != address(0), "PaymentSplitter: account is the zero address"); - require(shares_ > 0, "PaymentSplitter: shares are 0"); - require(_shares[account] == 0, "PaymentSplitter: account already has shares"); - - _payees.push(account); - _shares[account] = shares_; - _totalShares = _totalShares + shares_; - emit PayeeAdded(account, shares_); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/README.adoc deleted file mode 100644 index b64af312..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/README.adoc +++ /dev/null @@ -1,20 +0,0 @@ -= Finance - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/finance - -This directory includes primitives for financial systems: - -- {PaymentSplitter} allows to split Ether and ERC20 payments among a group of accounts. The sender does not need to be - aware that the assets will be split in this way, since it is handled transparently by the contract. The split can be - in equal parts or in any other arbitrary proportion. - -- {VestingWallet} handles the vesting of Ether and ERC20 tokens for a given beneficiary. Custody of multiple tokens can - be given to this contract, which will release the token to the beneficiary following a given, customizable, vesting - schedule. - -== Contracts - -{{PaymentSplitter}} - -{{VestingWallet}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/VestingWallet.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/VestingWallet.sol deleted file mode 100644 index 5ffbfcb6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/finance/VestingWallet.sol +++ /dev/null @@ -1,135 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (finance/VestingWallet.sol) -pragma solidity ^0.8.0; - -import "../token/ERC20/utils/SafeERC20.sol"; -import "../utils/Address.sol"; -import "../utils/Context.sol"; -import "../utils/math/Math.sol"; - -/** - * @title VestingWallet - * @dev This contract handles the vesting of Eth and ERC20 tokens for a given beneficiary. Custody of multiple tokens - * can be given to this contract, which will release the token to the beneficiary following a given vesting schedule. - * The vesting schedule is customizable through the {vestedAmount} function. - * - * Any token transferred to this contract will follow the vesting schedule as if they were locked from the beginning. - * Consequently, if the vesting has already started, any amount of tokens sent to this contract will (at least partly) - * be immediately releasable. - */ -contract VestingWallet is Context { - event EtherReleased(uint256 amount); - event ERC20Released(address indexed token, uint256 amount); - - uint256 private _released; - mapping(address => uint256) private _erc20Released; - address private immutable _beneficiary; - uint64 private immutable _start; - uint64 private immutable _duration; - - /** - * @dev Set the beneficiary, start timestamp and vesting duration of the vesting wallet. - */ - constructor( - address beneficiaryAddress, - uint64 startTimestamp, - uint64 durationSeconds - ) { - require(beneficiaryAddress != address(0), "VestingWallet: beneficiary is zero address"); - _beneficiary = beneficiaryAddress; - _start = startTimestamp; - _duration = durationSeconds; - } - - /** - * @dev The contract should be able to receive Eth. - */ - receive() external payable virtual {} - - /** - * @dev Getter for the beneficiary address. - */ - function beneficiary() public view virtual returns (address) { - return _beneficiary; - } - - /** - * @dev Getter for the start timestamp. - */ - function start() public view virtual returns (uint256) { - return _start; - } - - /** - * @dev Getter for the vesting duration. - */ - function duration() public view virtual returns (uint256) { - return _duration; - } - - /** - * @dev Amount of eth already released - */ - function released() public view virtual returns (uint256) { - return _released; - } - - /** - * @dev Amount of token already released - */ - function released(address token) public view virtual returns (uint256) { - return _erc20Released[token]; - } - - /** - * @dev Release the native token (ether) that have already vested. - * - * Emits a {TokensReleased} event. - */ - function release() public virtual { - uint256 releasable = vestedAmount(uint64(block.timestamp)) - released(); - _released += releasable; - emit EtherReleased(releasable); - Address.sendValue(payable(beneficiary()), releasable); - } - - /** - * @dev Release the tokens that have already vested. - * - * Emits a {TokensReleased} event. - */ - function release(address token) public virtual { - uint256 releasable = vestedAmount(token, uint64(block.timestamp)) - released(token); - _erc20Released[token] += releasable; - emit ERC20Released(token, releasable); - SafeERC20.safeTransfer(IERC20(token), beneficiary(), releasable); - } - - /** - * @dev Calculates the amount of ether that has already vested. Default implementation is a linear vesting curve. - */ - function vestedAmount(uint64 timestamp) public view virtual returns (uint256) { - return _vestingSchedule(address(this).balance + released(), timestamp); - } - - /** - * @dev Calculates the amount of tokens that has already vested. Default implementation is a linear vesting curve. - */ - function vestedAmount(address token, uint64 timestamp) public view virtual returns (uint256) { - return _vestingSchedule(IERC20(token).balanceOf(address(this)) + released(token), timestamp); - } - - /** - * @dev Virtual implementation of the vesting formula. This returns the amout vested, as a function of time, for - * an asset given its total historical allocation. - */ - function _vestingSchedule(uint256 totalAllocation, uint64 timestamp) internal view virtual returns (uint256) { - if (timestamp < start()) { - return 0; - } else if (timestamp > start() + duration()) { - return totalAllocation; - } else { - return (totalAllocation * (timestamp - start())) / duration(); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/Governor.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/Governor.sol deleted file mode 100644 index 837a9b61..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/Governor.sol +++ /dev/null @@ -1,385 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/Governor.sol) - -pragma solidity ^0.8.0; - -import "../utils/cryptography/ECDSA.sol"; -import "../utils/cryptography/draft-EIP712.sol"; -import "../utils/introspection/ERC165.sol"; -import "../utils/math/SafeCast.sol"; -import "../utils/Address.sol"; -import "../utils/Context.sol"; -import "../utils/Timers.sol"; -import "./IGovernor.sol"; - -/** - * @dev Core of the governance system, designed to be extended though various modules. - * - * This contract is abstract and requires several function to be implemented in various modules: - * - * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote} - * - A voting module must implement {getVotes} - * - Additionanly, the {votingPeriod} must also be implemented - * - * _Available since v4.3._ - */ -abstract contract Governor is Context, ERC165, EIP712, IGovernor { - using SafeCast for uint256; - using Timers for Timers.BlockNumber; - - bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); - - struct ProposalCore { - Timers.BlockNumber voteStart; - Timers.BlockNumber voteEnd; - bool executed; - bool canceled; - } - - string private _name; - - mapping(uint256 => ProposalCore) private _proposals; - - /** - * @dev Restrict access of functions to the governance executor, which may be the Governor itself or a timelock - * contract, as specified by {_executor}. This generally means that function with this modifier must be voted on and - * executed through the governance protocol. - */ - modifier onlyGovernance() { - require(_msgSender() == _executor(), "Governor: onlyGovernance"); - _; - } - - /** - * @dev Sets the value for {name} and {version} - */ - constructor(string memory name_) EIP712(name_, version()) { - _name = name_; - } - - /** - * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract) - */ - receive() external payable virtual { - require(_executor() == address(this)); - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { - return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev See {IGovernor-name}. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev See {IGovernor-version}. - */ - function version() public view virtual override returns (string memory) { - return "1"; - } - - /** - * @dev See {IGovernor-hashProposal}. - * - * The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array - * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id - * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in - * advance, before the proposal is submitted. - * - * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the - * same proposal (with same operation and same description) will have the same id if submitted on multiple governors - * accross multiple networks. This also means that in order to execute the same operation twice (on the same - * governor) the proposer will have to change the description in order to avoid proposal id conflicts. - */ - function hashProposal( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public pure virtual override returns (uint256) { - return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash))); - } - - /** - * @dev See {IGovernor-state}. - */ - function state(uint256 proposalId) public view virtual override returns (ProposalState) { - ProposalCore storage proposal = _proposals[proposalId]; - - if (proposal.executed) { - return ProposalState.Executed; - } - - if (proposal.canceled) { - return ProposalState.Canceled; - } - - uint256 snapshot = proposalSnapshot(proposalId); - - if (snapshot == 0) { - revert("Governor: unknown proposal id"); - } - - if (snapshot >= block.number) { - return ProposalState.Pending; - } - - uint256 deadline = proposalDeadline(proposalId); - - if (deadline >= block.number) { - return ProposalState.Active; - } - - if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) { - return ProposalState.Succeeded; - } else { - return ProposalState.Defeated; - } - } - - /** - * @dev See {IGovernor-proposalSnapshot}. - */ - function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) { - return _proposals[proposalId].voteStart.getDeadline(); - } - - /** - * @dev See {IGovernor-proposalDeadline}. - */ - function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) { - return _proposals[proposalId].voteEnd.getDeadline(); - } - - /** - * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_. - */ - function proposalThreshold() public view virtual returns (uint256) { - return 0; - } - - /** - * @dev Amount of votes already cast passes the threshold limit. - */ - function _quorumReached(uint256 proposalId) internal view virtual returns (bool); - - /** - * @dev Is the proposal successful or not. - */ - function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool); - - /** - * @dev Register a vote with a given support and voting weight. - * - * Note: Support is generic and can represent various things depending on the voting system used. - */ - function _countVote( - uint256 proposalId, - address account, - uint8 support, - uint256 weight - ) internal virtual; - - /** - * @dev See {IGovernor-propose}. - */ - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public virtual override returns (uint256) { - require( - getVotes(msg.sender, block.number - 1) >= proposalThreshold(), - "GovernorCompatibilityBravo: proposer votes below proposal threshold" - ); - - uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description))); - - require(targets.length == values.length, "Governor: invalid proposal length"); - require(targets.length == calldatas.length, "Governor: invalid proposal length"); - require(targets.length > 0, "Governor: empty proposal"); - - ProposalCore storage proposal = _proposals[proposalId]; - require(proposal.voteStart.isUnset(), "Governor: proposal already exists"); - - uint64 snapshot = block.number.toUint64() + votingDelay().toUint64(); - uint64 deadline = snapshot + votingPeriod().toUint64(); - - proposal.voteStart.setDeadline(snapshot); - proposal.voteEnd.setDeadline(deadline); - - emit ProposalCreated( - proposalId, - _msgSender(), - targets, - values, - new string[](targets.length), - calldatas, - snapshot, - deadline, - description - ); - - return proposalId; - } - - /** - * @dev See {IGovernor-execute}. - */ - function execute( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public payable virtual override returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - - ProposalState status = state(proposalId); - require( - status == ProposalState.Succeeded || status == ProposalState.Queued, - "Governor: proposal not successful" - ); - _proposals[proposalId].executed = true; - - emit ProposalExecuted(proposalId); - - _execute(proposalId, targets, values, calldatas, descriptionHash); - - return proposalId; - } - - /** - * @dev Internal execution mechanism. Can be overriden to implement different execution mechanism - */ - function _execute( - uint256, /* proposalId */ - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 /*descriptionHash*/ - ) internal virtual { - string memory errorMessage = "Governor: call reverted without message"; - for (uint256 i = 0; i < targets.length; ++i) { - (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]); - Address.verifyCallResult(success, returndata, errorMessage); - } - } - - /** - * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as - * canceled to allow distinguishing it from executed proposals. - * - * Emits a {IGovernor-ProposalCanceled} event. - */ - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - ProposalState status = state(proposalId); - - require( - status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed, - "Governor: proposal not active" - ); - _proposals[proposalId].canceled = true; - - emit ProposalCanceled(proposalId); - - return proposalId; - } - - /** - * @dev See {IGovernor-castVote}. - */ - function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) { - address voter = _msgSender(); - return _castVote(proposalId, voter, support, ""); - } - - /** - * @dev See {IGovernor-castVoteWithReason}. - */ - function castVoteWithReason( - uint256 proposalId, - uint8 support, - string calldata reason - ) public virtual override returns (uint256) { - address voter = _msgSender(); - return _castVote(proposalId, voter, support, reason); - } - - /** - * @dev See {IGovernor-castVoteBySig}. - */ - function castVoteBySig( - uint256 proposalId, - uint8 support, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual override returns (uint256) { - address voter = ECDSA.recover( - _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))), - v, - r, - s - ); - return _castVote(proposalId, voter, support, ""); - } - - /** - * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve - * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. - * - * Emits a {IGovernor-VoteCast} event. - */ - function _castVote( - uint256 proposalId, - address account, - uint8 support, - string memory reason - ) internal virtual returns (uint256) { - ProposalCore storage proposal = _proposals[proposalId]; - require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active"); - - uint256 weight = getVotes(account, proposal.voteStart.getDeadline()); - _countVote(proposalId, account, support, weight); - - emit VoteCast(account, proposalId, support, weight, reason); - - return weight; - } - - /** - * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor - * is some contract other than the governor itself, like when using a timelock, this function can be invoked - * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake. - * Note that if the executor is simply the governor itself, use of `relay` is redundant. - */ - function relay( - address target, - uint256 value, - bytes calldata data - ) external virtual onlyGovernance { - Address.functionCallWithValue(target, data, value); - } - - /** - * @dev Address through which the governor executes action. Will be overloaded by module that execute actions - * through another contract such as a timelock. - */ - function _executor() internal view virtual returns (address) { - return address(this); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/IGovernor.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/IGovernor.sol deleted file mode 100644 index 3c65f40d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/IGovernor.sol +++ /dev/null @@ -1,218 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/IGovernor.sol) - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC165.sol"; - -/** - * @dev Interface of the {Governor} core. - * - * _Available since v4.3._ - */ -abstract contract IGovernor is IERC165 { - enum ProposalState { - Pending, - Active, - Canceled, - Defeated, - Succeeded, - Queued, - Expired, - Executed - } - - /** - * @dev Emitted when a proposal is created. - */ - event ProposalCreated( - uint256 proposalId, - address proposer, - address[] targets, - uint256[] values, - string[] signatures, - bytes[] calldatas, - uint256 startBlock, - uint256 endBlock, - string description - ); - - /** - * @dev Emitted when a proposal is canceled. - */ - event ProposalCanceled(uint256 proposalId); - - /** - * @dev Emitted when a proposal is executed. - */ - event ProposalExecuted(uint256 proposalId); - - /** - * @dev Emitted when a vote is cast. - * - * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. - */ - event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); - - /** - * @notice module:core - * @dev Name of the governor instance (used in building the ERC712 domain separator). - */ - function name() public view virtual returns (string memory); - - /** - * @notice module:core - * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" - */ - function version() public view virtual returns (string memory); - - /** - * @notice module:voting - * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to - * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of - * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. - * - * There are 2 standard keys: `support` and `quorum`. - * - * - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`. - * - `quorum=bravo` means that only For votes are counted towards quorum. - * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. - * - * NOTE: The string can be decoded by the standard - * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] - * JavaScript class. - */ - // solhint-disable-next-line func-name-mixedcase - function COUNTING_MODE() public pure virtual returns (string memory); - - /** - * @notice module:core - * @dev Hashing function used to (re)build the proposal id from the proposal details.. - */ - function hashProposal( - address[] calldata targets, - uint256[] calldata values, - bytes[] calldata calldatas, - bytes32 descriptionHash - ) public pure virtual returns (uint256); - - /** - * @notice module:core - * @dev Current state of a proposal, following Compound's convention - */ - function state(uint256 proposalId) public view virtual returns (ProposalState); - - /** - * @notice module:core - * @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's - * ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the - * beginning of the following block. - */ - function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); - - /** - * @notice module:core - * @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote - * during this block. - */ - function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); - - /** - * @notice module:user-config - * @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to - * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. - */ - function votingDelay() public view virtual returns (uint256); - - /** - * @notice module:user-config - * @dev Delay, in number of blocks, between the vote start and vote ends. - * - * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting - * duration compared to the voting delay. - */ - function votingPeriod() public view virtual returns (uint256); - - /** - * @notice module:user-config - * @dev Minimum number of cast voted required for a proposal to be successful. - * - * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the - * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). - */ - function quorum(uint256 blockNumber) public view virtual returns (uint256); - - /** - * @notice module:reputation - * @dev Voting power of an `account` at a specific `blockNumber`. - * - * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or - * multiple), {ERC20Votes} tokens. - */ - function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); - - /** - * @notice module:voting - * @dev Returns weither `account` has cast a vote on `proposalId`. - */ - function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); - - /** - * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends - * {IGovernor-votingPeriod} blocks after the voting starts. - * - * Emits a {ProposalCreated} event. - */ - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public virtual returns (uint256 proposalId); - - /** - * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the - * deadline to be reached. - * - * Emits a {ProposalExecuted} event. - * - * Note: some module can modify the requirements for execution, for example by adding an additional timelock. - */ - function execute( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public payable virtual returns (uint256 proposalId); - - /** - * @dev Cast a vote - * - * Emits a {VoteCast} event. - */ - function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); - - /** - * @dev Cast a vote with a reason - * - * Emits a {VoteCast} event. - */ - function castVoteWithReason( - uint256 proposalId, - uint8 support, - string calldata reason - ) public virtual returns (uint256 balance); - - /** - * @dev Cast a vote using the user cryptographic signature. - * - * Emits a {VoteCast} event. - */ - function castVoteBySig( - uint256 proposalId, - uint8 support, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual returns (uint256 balance); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/README.adoc deleted file mode 100644 index 58daf56e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/README.adoc +++ /dev/null @@ -1,176 +0,0 @@ -= Governance - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/governance - -This directory includes primitives for on-chain governance. - -== Governor - -This modular system of Governor contracts allows the deployment on-chain voting protocols similar to https://compound.finance/docs/governance[Compound's Governor Alpha & Bravo] and beyond, through the ability to easily customize multiple aspects of the protocol. - -[TIP] -==== -For a guided experience, set up your Governor contract using https://wizard.openzeppelin.com/#governor[Contracts Wizard]. - -For a written walkthrough, check out our guide on xref:ROOT:governance.adoc[How to set up on-chain governance]. -==== - -* {Governor}: The core contract that contains all the logic and primitives. It is abstract and requires choosing one of each of the modules below, or custom ones. - -Votes modules determine the source of voting power, and sometimes quorum number. - -* {GovernorVotes}: Extracts voting weight from an {ERC20Votes} token. - -* {GovernorVotesComp}: Extracts voting weight from a COMP-like or {ERC20VotesComp} token. - -* {GovernorVotesQuorumFraction}: Combines with `GovernorVotes` to set the quorum as a fraction of the total token supply. - -Counting modules determine valid voting options. - -* {GovernorCountingSimple}: Simple voting mechanism with 3 voting options: Against, For and Abstain. - -Timelock extensions add a delay for governance decisions to be executed. The workflow is extended to require a `queue` step before execution. With these modules, proposals are executed by the external timelock contract, thus it is the timelock that has to hold the assets that are being governed. - -* {GovernorTimelockControl}: Connects with an instance of {TimelockController}. Allows multiple proposers and executors, in addition to the Governor itself. - -* {GovernorTimelockCompound}: Connects with an instance of Compound's https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[`Timelock`] contract. - -Other extensions can customize the behavior or interface in multiple ways. - -* {GovernorCompatibilityBravo}: Extends the interface to be fully `GovernorBravo`-compatible. Note that events are compatible regardless of whether this extension is included or not. - -* {GovernorSettings}: Manages some of the settings (voting delay, voting period duration, and proposal threshold) in a way that can be updated through a governance proposal, without requiering an upgrade. - -* {GovernorPreventLateQuorum}: Ensures there is a minimum voting period after quorum is reached as a security protection against large voters. - -In addition to modules and extensions, the core contract requires a few virtual functions to be implemented to your particular specifications: - -* <>: Delay (in number of blocks) since the proposal is submitted until voting power is fixed and voting starts. This can be used to enforce a delay after a proposal is published for users to buy tokens, or delegate their votes. -* <>: Delay (in number of blocks) since the proposal starts until voting ends. -* <>: Quorum required for a proposal to be successful. This function includes a `blockNumber` argument so the quorum can adapt through time, for example, to follow a token's `totalSupply`. - -NOTE: Functions of the `Governor` contract do not include access control. If you want to restrict access, you should add these checks by overloading the particular functions. Among these, {Governor-_cancel} is internal by default, and you will have to expose it (with the right access control mechanism) yourself if this function is needed. - -=== Core - -{{IGovernor}} - -{{Governor}} - -=== Modules - -{{GovernorCountingSimple}} - -{{GovernorVotes}} - -{{GovernorVotesQuorumFraction}} - -{{GovernorVotesComp}} - -=== Extensions - -{{GovernorTimelockControl}} - -{{GovernorTimelockCompound}} - -{{GovernorSettings}} - -{{GovernorPreventLateQuorum}} - -{{GovernorCompatibilityBravo}} - -=== Deprecated - -{{GovernorProposalThreshold}} - -== Utils - -{{Votes}} - -== Timelock - -In a governance system, the {TimelockController} contract is in charge of introducing a delay between a proposal and its execution. It can be used with or without a {Governor}. - -{{TimelockController}} - -[[timelock-terminology]] -==== Terminology - -* *Operation:* A transaction (or a set of transactions) that is the subject of the timelock. It has to be scheduled by a proposer and executed by an executor. The timelock enforces a minimum delay between the proposition and the execution (see xref:access-control.adoc#operation_lifecycle[operation lifecycle]). If the operation contains multiple transactions (batch mode), they are executed atomically. Operations are identified by the hash of their content. -* *Operation status:* -** *Unset:* An operation that is not part of the timelock mechanism. -** *Pending:* An operation that has been scheduled, before the timer expires. -** *Ready:* An operation that has been scheduled, after the timer expires. -** *Done:* An operation that has been executed. -* *Predecessor*: An (optional) dependency between operations. An operation can depend on another operation (its predecessor), forcing the execution order of these two operations. -* *Role*: -** *Admin:* An address (smart contract or EOA) that is in charge of granting the roles of Proposer and Executor. -** *Proposer:* An address (smart contract or EOA) that is in charge of scheduling (and cancelling) operations. -** *Executor:* An address (smart contract or EOA) that is in charge of executing operations once the timelock has expired. This role can be given to the zero address to allow anyone to execute operations. - -[[timelock-operation]] -==== Operation structure - -Operation executed by the xref:api:governance.adoc#TimelockController[`TimelockController`] can contain one or multiple subsequent calls. Depending on whether you need to multiple calls to be executed atomically, you can either use simple or batched operations. - -Both operations contain: - -* *Target*, the address of the smart contract that the timelock should operate on. -* *Value*, in wei, that should be sent with the transaction. Most of the time this will be 0. Ether can be deposited before-end or passed along when executing the transaction. -* *Data*, containing the encoded function selector and parameters of the call. This can be produced using a number of tools. For example, a maintenance operation granting role `ROLE` to `ACCOUNT` can be encode using web3js as follows: - -```javascript -const data = timelock.contract.methods.grantRole(ROLE, ACCOUNT).encodeABI() -``` - -* *Predecessor*, that specifies a dependency between operations. This dependency is optional. Use `bytes32(0)` if the operation does not have any dependency. -* *Salt*, used to disambiguate two otherwise identical operations. This can be any random value. - -In the case of batched operations, `target`, `value` and `data` are specified as arrays, which must be of the same length. - -[[timelock-operation-lifecycle]] -==== Operation lifecycle - -Timelocked operations are identified by a unique id (their hash) and follow a specific lifecycle: - -`Unset` -> `Pending` -> `Pending` + `Ready` -> `Done` - -* By calling xref:api:governance.adoc#TimelockController-schedule-address-uint256-bytes-bytes32-bytes32-uint256-[`schedule`] (or xref:api:governance.adoc#TimelockController-scheduleBatch-address---uint256---bytes---bytes32-bytes32-uint256-[`scheduleBatch`]), a proposer moves the operation from the `Unset` to the `Pending` state. This starts a timer that must be longer than the minimum delay. The timer expires at a timestamp accessible through the xref:api:governance.adoc#TimelockController-getTimestamp-bytes32-[`getTimestamp`] method. -* Once the timer expires, the operation automatically gets the `Ready` state. At this point, it can be executed. -* By calling xref:api:governance.adoc#TimelockController-TimelockController-execute-address-uint256-bytes-bytes32-bytes32-[`execute`] (or xref:api:governance.adoc#TimelockController-executeBatch-address---uint256---bytes---bytes32-bytes32-[`executeBatch`]), an executor triggers the operation's underlying transactions and moves it to the `Done` state. If the operation has a predecessor, it has to be in the `Done` state for this transition to succeed. -* xref:api:governance.adoc#TimelockController-TimelockController-cancel-bytes32-[`cancel`] allows proposers to cancel any `Pending` operation. This resets the operation to the `Unset` state. It is thus possible for a proposer to re-schedule an operation that has been cancelled. In this case, the timer restarts when the operation is re-scheduled. - -Operations status can be queried using the functions: - -* xref:api:governance.adoc#TimelockController-isOperationPending-bytes32-[`isOperationPending(bytes32)`] -* xref:api:governance.adoc#TimelockController-isOperationReady-bytes32-[`isOperationReady(bytes32)`] -* xref:api:governance.adoc#TimelockController-isOperationDone-bytes32-[`isOperationDone(bytes32)`] - -[[timelock-roles]] -==== Roles - -[[timelock-admin]] -===== Admin - -The admins are in charge of managing proposers and executors. For the timelock to be self-governed, this role should only be given to the timelock itself. Upon deployment, both the timelock and the deployer have this role. After further configuration and testing, the deployer can renounce this role such that all further maintenance operations have to go through the timelock process. - -This role is identified by the *TIMELOCK_ADMIN_ROLE* value: `0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5` - -[[timelock-proposer]] -===== Proposer - -The proposers are in charge of scheduling (and cancelling) operations. This is a critical role, that should be given to governing entities. This could be an EOA, a multisig, or a DAO. - -WARNING: *Proposer fight:* Having multiple proposers, while providing redundancy in case one becomes unavailable, can be dangerous. As proposer have their say on all operations, they could cancel operations they disagree with, including operations to remove them for the proposers. - -This role is identified by the *PROPOSER_ROLE* value: `0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1` - -[[timelock-executor]] -===== Executor - -The executors are in charge of executing the operations scheduled by the proposers once the timelock expires. Logic dictates that multisig or DAO that are proposers should also be executors in order to guarantee operations that have been scheduled will eventually be executed. However, having additional executors can reduce the cost (the executing transaction does not require validation by the multisig or DAO that proposed it), while ensuring whoever is in charge of execution cannot trigger actions that have not been scheduled by the proposers. Alternatively, it is possible to allow _any_ address to execute a proposal once the timelock has expired by granting the executor role to the zero address. - -This role is identified by the *EXECUTOR_ROLE* value: `0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63` - -WARNING: A live contract without at least one proposer and one executor is locked. Make sure these roles are filled by reliable entities before the deployer renounces its administrative rights in favour of the timelock contract itself. See the {AccessControl} documentation to learn more about role management. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/TimelockController.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/TimelockController.sol deleted file mode 100644 index 6e2f7a55..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/TimelockController.sol +++ /dev/null @@ -1,353 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (governance/TimelockController.sol) - -pragma solidity ^0.8.0; - -import "../access/AccessControl.sol"; - -/** - * @dev Contract module which acts as a timelocked controller. When set as the - * owner of an `Ownable` smart contract, it enforces a timelock on all - * `onlyOwner` maintenance operations. This gives time for users of the - * controlled contract to exit before a potentially dangerous maintenance - * operation is applied. - * - * By default, this contract is self administered, meaning administration tasks - * have to go through the timelock process. The proposer (resp executor) role - * is in charge of proposing (resp executing) operations. A common use case is - * to position this {TimelockController} as the owner of a smart contract, with - * a multisig or a DAO as the sole proposer. - * - * _Available since v3.3._ - */ -contract TimelockController is AccessControl { - bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); - bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); - bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); - uint256 internal constant _DONE_TIMESTAMP = uint256(1); - - mapping(bytes32 => uint256) private _timestamps; - uint256 private _minDelay; - - /** - * @dev Emitted when a call is scheduled as part of operation `id`. - */ - event CallScheduled( - bytes32 indexed id, - uint256 indexed index, - address target, - uint256 value, - bytes data, - bytes32 predecessor, - uint256 delay - ); - - /** - * @dev Emitted when a call is performed as part of operation `id`. - */ - event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); - - /** - * @dev Emitted when operation `id` is cancelled. - */ - event Cancelled(bytes32 indexed id); - - /** - * @dev Emitted when the minimum delay for future operations is modified. - */ - event MinDelayChange(uint256 oldDuration, uint256 newDuration); - - /** - * @dev Initializes the contract with a given `minDelay`. - */ - constructor( - uint256 minDelay, - address[] memory proposers, - address[] memory executors - ) { - _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); - _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); - _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); - - // deployer + self administration - _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); - _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); - - // register proposers - for (uint256 i = 0; i < proposers.length; ++i) { - _setupRole(PROPOSER_ROLE, proposers[i]); - } - - // register executors - for (uint256 i = 0; i < executors.length; ++i) { - _setupRole(EXECUTOR_ROLE, executors[i]); - } - - _minDelay = minDelay; - emit MinDelayChange(0, minDelay); - } - - /** - * @dev Modifier to make a function callable only by a certain role. In - * addition to checking the sender's role, `address(0)` 's role is also - * considered. Granting a role to `address(0)` is equivalent to enabling - * this role for everyone. - */ - modifier onlyRoleOrOpenRole(bytes32 role) { - if (!hasRole(role, address(0))) { - _checkRole(role, _msgSender()); - } - _; - } - - /** - * @dev Contract might receive/hold ETH as part of the maintenance process. - */ - receive() external payable {} - - /** - * @dev Returns whether an id correspond to a registered operation. This - * includes both Pending, Ready and Done operations. - */ - function isOperation(bytes32 id) public view virtual returns (bool pending) { - return getTimestamp(id) > 0; - } - - /** - * @dev Returns whether an operation is pending or not. - */ - function isOperationPending(bytes32 id) public view virtual returns (bool pending) { - return getTimestamp(id) > _DONE_TIMESTAMP; - } - - /** - * @dev Returns whether an operation is ready or not. - */ - function isOperationReady(bytes32 id) public view virtual returns (bool ready) { - uint256 timestamp = getTimestamp(id); - return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; - } - - /** - * @dev Returns whether an operation is done or not. - */ - function isOperationDone(bytes32 id) public view virtual returns (bool done) { - return getTimestamp(id) == _DONE_TIMESTAMP; - } - - /** - * @dev Returns the timestamp at with an operation becomes ready (0 for - * unset operations, 1 for done operations). - */ - function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { - return _timestamps[id]; - } - - /** - * @dev Returns the minimum delay for an operation to become valid. - * - * This value can be changed by executing an operation that calls `updateDelay`. - */ - function getMinDelay() public view virtual returns (uint256 duration) { - return _minDelay; - } - - /** - * @dev Returns the identifier of an operation containing a single - * transaction. - */ - function hashOperation( - address target, - uint256 value, - bytes calldata data, - bytes32 predecessor, - bytes32 salt - ) public pure virtual returns (bytes32 hash) { - return keccak256(abi.encode(target, value, data, predecessor, salt)); - } - - /** - * @dev Returns the identifier of an operation containing a batch of - * transactions. - */ - function hashOperationBatch( - address[] calldata targets, - uint256[] calldata values, - bytes[] calldata datas, - bytes32 predecessor, - bytes32 salt - ) public pure virtual returns (bytes32 hash) { - return keccak256(abi.encode(targets, values, datas, predecessor, salt)); - } - - /** - * @dev Schedule an operation containing a single transaction. - * - * Emits a {CallScheduled} event. - * - * Requirements: - * - * - the caller must have the 'proposer' role. - */ - function schedule( - address target, - uint256 value, - bytes calldata data, - bytes32 predecessor, - bytes32 salt, - uint256 delay - ) public virtual onlyRole(PROPOSER_ROLE) { - bytes32 id = hashOperation(target, value, data, predecessor, salt); - _schedule(id, delay); - emit CallScheduled(id, 0, target, value, data, predecessor, delay); - } - - /** - * @dev Schedule an operation containing a batch of transactions. - * - * Emits one {CallScheduled} event per transaction in the batch. - * - * Requirements: - * - * - the caller must have the 'proposer' role. - */ - function scheduleBatch( - address[] calldata targets, - uint256[] calldata values, - bytes[] calldata datas, - bytes32 predecessor, - bytes32 salt, - uint256 delay - ) public virtual onlyRole(PROPOSER_ROLE) { - require(targets.length == values.length, "TimelockController: length mismatch"); - require(targets.length == datas.length, "TimelockController: length mismatch"); - - bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); - _schedule(id, delay); - for (uint256 i = 0; i < targets.length; ++i) { - emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay); - } - } - - /** - * @dev Schedule an operation that is to becomes valid after a given delay. - */ - function _schedule(bytes32 id, uint256 delay) private { - require(!isOperation(id), "TimelockController: operation already scheduled"); - require(delay >= getMinDelay(), "TimelockController: insufficient delay"); - _timestamps[id] = block.timestamp + delay; - } - - /** - * @dev Cancel an operation. - * - * Requirements: - * - * - the caller must have the 'proposer' role. - */ - function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) { - require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); - delete _timestamps[id]; - - emit Cancelled(id); - } - - /** - * @dev Execute an (ready) operation containing a single transaction. - * - * Emits a {CallExecuted} event. - * - * Requirements: - * - * - the caller must have the 'executor' role. - */ - function execute( - address target, - uint256 value, - bytes calldata data, - bytes32 predecessor, - bytes32 salt - ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { - bytes32 id = hashOperation(target, value, data, predecessor, salt); - _beforeCall(id, predecessor); - _call(id, 0, target, value, data); - _afterCall(id); - } - - /** - * @dev Execute an (ready) operation containing a batch of transactions. - * - * Emits one {CallExecuted} event per transaction in the batch. - * - * Requirements: - * - * - the caller must have the 'executor' role. - */ - function executeBatch( - address[] calldata targets, - uint256[] calldata values, - bytes[] calldata datas, - bytes32 predecessor, - bytes32 salt - ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { - require(targets.length == values.length, "TimelockController: length mismatch"); - require(targets.length == datas.length, "TimelockController: length mismatch"); - - bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); - _beforeCall(id, predecessor); - for (uint256 i = 0; i < targets.length; ++i) { - _call(id, i, targets[i], values[i], datas[i]); - } - _afterCall(id); - } - - /** - * @dev Checks before execution of an operation's calls. - */ - function _beforeCall(bytes32 id, bytes32 predecessor) private view { - require(isOperationReady(id), "TimelockController: operation is not ready"); - require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); - } - - /** - * @dev Checks after execution of an operation's calls. - */ - function _afterCall(bytes32 id) private { - require(isOperationReady(id), "TimelockController: operation is not ready"); - _timestamps[id] = _DONE_TIMESTAMP; - } - - /** - * @dev Execute an operation's call. - * - * Emits a {CallExecuted} event. - */ - function _call( - bytes32 id, - uint256 index, - address target, - uint256 value, - bytes calldata data - ) private { - (bool success, ) = target.call{value: value}(data); - require(success, "TimelockController: underlying transaction reverted"); - - emit CallExecuted(id, index, target, value, data); - } - - /** - * @dev Changes the minimum timelock duration for future operations. - * - * Emits a {MinDelayChange} event. - * - * Requirements: - * - * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing - * an operation where the timelock is the target and the data is the ABI-encoded call to this function. - */ - function updateDelay(uint256 newDelay) external virtual { - require(msg.sender == address(this), "TimelockController: caller must be timelock"); - emit MinDelayChange(_minDelay, newDelay); - _minDelay = newDelay; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/compatibility/GovernorCompatibilityBravo.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/compatibility/GovernorCompatibilityBravo.sol deleted file mode 100644 index cbb2200b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/compatibility/GovernorCompatibilityBravo.sol +++ /dev/null @@ -1,288 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/compatibility/GovernorCompatibilityBravo.sol) - -pragma solidity ^0.8.0; - -import "../../utils/Counters.sol"; -import "../../utils/math/SafeCast.sol"; -import "../extensions/IGovernorTimelock.sol"; -import "../Governor.sol"; -import "./IGovernorCompatibilityBravo.sol"; - -/** - * @dev Compatibility layer that implements GovernorBravo compatibility on to of {Governor}. - * - * This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added - * through inheritance. It does not include token bindings, not does it include any variable upgrade patterns. - * - * NOTE: When using this module, you may need to enable the Solidity optimizer to avoid hitting the contract size limit. - * - * _Available since v4.3._ - */ -abstract contract GovernorCompatibilityBravo is IGovernorTimelock, IGovernorCompatibilityBravo, Governor { - using Counters for Counters.Counter; - using Timers for Timers.BlockNumber; - - enum VoteType { - Against, - For, - Abstain - } - - struct ProposalDetails { - address proposer; - address[] targets; - uint256[] values; - string[] signatures; - bytes[] calldatas; - uint256 forVotes; - uint256 againstVotes; - uint256 abstainVotes; - mapping(address => Receipt) receipts; - bytes32 descriptionHash; - } - - mapping(uint256 => ProposalDetails) private _proposalDetails; - - // solhint-disable-next-line func-name-mixedcase - function COUNTING_MODE() public pure virtual override returns (string memory) { - return "support=bravo&quorum=bravo"; - } - - // ============================================== Proposal lifecycle ============================================== - /** - * @dev See {IGovernor-propose}. - */ - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public virtual override(IGovernor, Governor) returns (uint256) { - _storeProposal(_msgSender(), targets, values, new string[](calldatas.length), calldatas, description); - return super.propose(targets, values, calldatas, description); - } - - /** - * @dev See {IGovernorCompatibilityBravo-propose}. - */ - function propose( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas, - string memory description - ) public virtual override returns (uint256) { - _storeProposal(_msgSender(), targets, values, signatures, calldatas, description); - return propose(targets, values, _encodeCalldata(signatures, calldatas), description); - } - - /** - * @dev See {IGovernorCompatibilityBravo-queue}. - */ - function queue(uint256 proposalId) public virtual override { - ProposalDetails storage details = _proposalDetails[proposalId]; - queue( - details.targets, - details.values, - _encodeCalldata(details.signatures, details.calldatas), - details.descriptionHash - ); - } - - /** - * @dev See {IGovernorCompatibilityBravo-execute}. - */ - function execute(uint256 proposalId) public payable virtual override { - ProposalDetails storage details = _proposalDetails[proposalId]; - execute( - details.targets, - details.values, - _encodeCalldata(details.signatures, details.calldatas), - details.descriptionHash - ); - } - - function cancel(uint256 proposalId) public virtual override { - ProposalDetails storage details = _proposalDetails[proposalId]; - - require( - _msgSender() == details.proposer || getVotes(details.proposer, block.number - 1) < proposalThreshold(), - "GovernorBravo: proposer above threshold" - ); - - _cancel( - details.targets, - details.values, - _encodeCalldata(details.signatures, details.calldatas), - details.descriptionHash - ); - } - - /** - * @dev Encodes calldatas with optional function signature. - */ - function _encodeCalldata(string[] memory signatures, bytes[] memory calldatas) - private - pure - returns (bytes[] memory) - { - bytes[] memory fullcalldatas = new bytes[](calldatas.length); - - for (uint256 i = 0; i < signatures.length; ++i) { - fullcalldatas[i] = bytes(signatures[i]).length == 0 - ? calldatas[i] - : abi.encodePacked(bytes4(keccak256(bytes(signatures[i]))), calldatas[i]); - } - - return fullcalldatas; - } - - /** - * @dev Store proposal metadata for later lookup - */ - function _storeProposal( - address proposer, - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas, - string memory description - ) private { - bytes32 descriptionHash = keccak256(bytes(description)); - uint256 proposalId = hashProposal(targets, values, _encodeCalldata(signatures, calldatas), descriptionHash); - - ProposalDetails storage details = _proposalDetails[proposalId]; - if (details.descriptionHash == bytes32(0)) { - details.proposer = proposer; - details.targets = targets; - details.values = values; - details.signatures = signatures; - details.calldatas = calldatas; - details.descriptionHash = descriptionHash; - } - } - - // ==================================================== Views ===================================================== - /** - * @dev See {IGovernorCompatibilityBravo-proposals}. - */ - function proposals(uint256 proposalId) - public - view - virtual - override - returns ( - uint256 id, - address proposer, - uint256 eta, - uint256 startBlock, - uint256 endBlock, - uint256 forVotes, - uint256 againstVotes, - uint256 abstainVotes, - bool canceled, - bool executed - ) - { - id = proposalId; - eta = proposalEta(proposalId); - startBlock = proposalSnapshot(proposalId); - endBlock = proposalDeadline(proposalId); - - ProposalDetails storage details = _proposalDetails[proposalId]; - proposer = details.proposer; - forVotes = details.forVotes; - againstVotes = details.againstVotes; - abstainVotes = details.abstainVotes; - - ProposalState status = state(proposalId); - canceled = status == ProposalState.Canceled; - executed = status == ProposalState.Executed; - } - - /** - * @dev See {IGovernorCompatibilityBravo-getActions}. - */ - function getActions(uint256 proposalId) - public - view - virtual - override - returns ( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas - ) - { - ProposalDetails storage details = _proposalDetails[proposalId]; - return (details.targets, details.values, details.signatures, details.calldatas); - } - - /** - * @dev See {IGovernorCompatibilityBravo-getReceipt}. - */ - function getReceipt(uint256 proposalId, address voter) public view virtual override returns (Receipt memory) { - return _proposalDetails[proposalId].receipts[voter]; - } - - /** - * @dev See {IGovernorCompatibilityBravo-quorumVotes}. - */ - function quorumVotes() public view virtual override returns (uint256) { - return quorum(block.number - 1); - } - - // ==================================================== Voting ==================================================== - /** - * @dev See {IGovernor-hasVoted}. - */ - function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) { - return _proposalDetails[proposalId].receipts[account].hasVoted; - } - - /** - * @dev See {Governor-_quorumReached}. In this module, only forVotes count toward the quorum. - */ - function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { - ProposalDetails storage details = _proposalDetails[proposalId]; - return quorum(proposalSnapshot(proposalId)) <= details.forVotes; - } - - /** - * @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes. - */ - function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) { - ProposalDetails storage details = _proposalDetails[proposalId]; - return details.forVotes > details.againstVotes; - } - - /** - * @dev See {Governor-_countVote}. In this module, the support follows Governor Bravo. - */ - function _countVote( - uint256 proposalId, - address account, - uint8 support, - uint256 weight - ) internal virtual override { - ProposalDetails storage details = _proposalDetails[proposalId]; - Receipt storage receipt = details.receipts[account]; - - require(!receipt.hasVoted, "GovernorCompatibilityBravo: vote already cast"); - receipt.hasVoted = true; - receipt.support = support; - receipt.votes = SafeCast.toUint96(weight); - - if (support == uint8(VoteType.Against)) { - details.againstVotes += weight; - } else if (support == uint8(VoteType.For)) { - details.forVotes += weight; - } else if (support == uint8(VoteType.Abstain)) { - details.abstainVotes += weight; - } else { - revert("GovernorCompatibilityBravo: invalid vote type"); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/compatibility/IGovernorCompatibilityBravo.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/compatibility/IGovernorCompatibilityBravo.sol deleted file mode 100644 index 83e4e1ae..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/compatibility/IGovernorCompatibilityBravo.sol +++ /dev/null @@ -1,114 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (governance/compatibility/IGovernorCompatibilityBravo.sol) - -pragma solidity ^0.8.0; - -import "../IGovernor.sol"; - -/** - * @dev Interface extension that adds missing functions to the {Governor} core to provide `GovernorBravo` compatibility. - * - * _Available since v4.3._ - */ -abstract contract IGovernorCompatibilityBravo is IGovernor { - /** - * @dev Proposal structure from Compound Governor Bravo. Not actually used by the compatibility layer, as - * {{proposal}} returns a very different structure. - */ - struct Proposal { - uint256 id; - address proposer; - uint256 eta; - address[] targets; - uint256[] values; - string[] signatures; - bytes[] calldatas; - uint256 startBlock; - uint256 endBlock; - uint256 forVotes; - uint256 againstVotes; - uint256 abstainVotes; - bool canceled; - bool executed; - mapping(address => Receipt) receipts; - } - - /** - * @dev Receipt structure from Compound Governor Bravo - */ - struct Receipt { - bool hasVoted; - uint8 support; - uint96 votes; - } - - /** - * @dev Part of the Governor Bravo's interface. - */ - function quorumVotes() public view virtual returns (uint256); - - /** - * @dev Part of the Governor Bravo's interface: _"The official record of all proposals ever proposed"_. - */ - function proposals(uint256) - public - view - virtual - returns ( - uint256 id, - address proposer, - uint256 eta, - uint256 startBlock, - uint256 endBlock, - uint256 forVotes, - uint256 againstVotes, - uint256 abstainVotes, - bool canceled, - bool executed - ); - - /** - * @dev Part of the Governor Bravo's interface: _"Function used to propose a new proposal"_. - */ - function propose( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas, - string memory description - ) public virtual returns (uint256); - - /** - * @dev Part of the Governor Bravo's interface: _"Queues a proposal of state succeeded"_. - */ - function queue(uint256 proposalId) public virtual; - - /** - * @dev Part of the Governor Bravo's interface: _"Executes a queued proposal if eta has passed"_. - */ - function execute(uint256 proposalId) public payable virtual; - - /** - * @dev Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold. - */ - function cancel(uint256 proposalId) public virtual; - - /** - * @dev Part of the Governor Bravo's interface: _"Gets actions of a proposal"_. - */ - function getActions(uint256 proposalId) - public - view - virtual - returns ( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas - ); - - /** - * @dev Part of the Governor Bravo's interface: _"Gets the receipt for a voter on a given proposal"_. - */ - function getReceipt(uint256 proposalId, address voter) public view virtual returns (Receipt memory); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorCountingSimple.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorCountingSimple.sol deleted file mode 100644 index 38054d91..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorCountingSimple.sol +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorCountingSimple.sol) - -pragma solidity ^0.8.0; - -import "../Governor.sol"; - -/** - * @dev Extension of {Governor} for simple, 3 options, vote counting. - * - * _Available since v4.3._ - */ -abstract contract GovernorCountingSimple is Governor { - /** - * @dev Supported vote types. Matches Governor Bravo ordering. - */ - enum VoteType { - Against, - For, - Abstain - } - - struct ProposalVote { - uint256 againstVotes; - uint256 forVotes; - uint256 abstainVotes; - mapping(address => bool) hasVoted; - } - - mapping(uint256 => ProposalVote) private _proposalVotes; - - /** - * @dev See {IGovernor-COUNTING_MODE}. - */ - // solhint-disable-next-line func-name-mixedcase - function COUNTING_MODE() public pure virtual override returns (string memory) { - return "support=bravo&quorum=for,abstain"; - } - - /** - * @dev See {IGovernor-hasVoted}. - */ - function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) { - return _proposalVotes[proposalId].hasVoted[account]; - } - - /** - * @dev Accessor to the internal vote counts. - */ - function proposalVotes(uint256 proposalId) - public - view - virtual - returns ( - uint256 againstVotes, - uint256 forVotes, - uint256 abstainVotes - ) - { - ProposalVote storage proposalvote = _proposalVotes[proposalId]; - return (proposalvote.againstVotes, proposalvote.forVotes, proposalvote.abstainVotes); - } - - /** - * @dev See {Governor-_quorumReached}. - */ - function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { - ProposalVote storage proposalvote = _proposalVotes[proposalId]; - - return quorum(proposalSnapshot(proposalId)) <= proposalvote.forVotes + proposalvote.abstainVotes; - } - - /** - * @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be strictly over the againstVotes. - */ - function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) { - ProposalVote storage proposalvote = _proposalVotes[proposalId]; - - return proposalvote.forVotes > proposalvote.againstVotes; - } - - /** - * @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo). - */ - function _countVote( - uint256 proposalId, - address account, - uint8 support, - uint256 weight - ) internal virtual override { - ProposalVote storage proposalvote = _proposalVotes[proposalId]; - - require(!proposalvote.hasVoted[account], "GovernorVotingSimple: vote already cast"); - proposalvote.hasVoted[account] = true; - - if (support == uint8(VoteType.Against)) { - proposalvote.againstVotes += weight; - } else if (support == uint8(VoteType.For)) { - proposalvote.forVotes += weight; - } else if (support == uint8(VoteType.Abstain)) { - proposalvote.abstainVotes += weight; - } else { - revert("GovernorVotingSimple: invalid value for enum VoteType"); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorPreventLateQuorum.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorPreventLateQuorum.sol deleted file mode 100644 index 6d96dc33..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorPreventLateQuorum.sol +++ /dev/null @@ -1,107 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/extensions/GovernorPreventLateQuorum.sol) - -pragma solidity ^0.8.0; - -import "../Governor.sol"; -import "../../utils/math/Math.sol"; - -/** - * @dev A module that ensures there is a minimum voting period after quorum is reached. This prevents a large voter from - * swaying a vote and triggering quorum at the last minute, by ensuring there is always time for other voters to react - * and try to oppose the decision. - * - * If a vote causes quorum to be reached, the proposal's voting period may be extended so that it does not end before at - * least a given number of blocks have passed (the "vote extension" parameter). This parameter can be set by the - * governance executor (e.g. through a governance proposal). - * - * _Available since v4.5._ - */ -abstract contract GovernorPreventLateQuorum is Governor { - using SafeCast for uint256; - using Timers for Timers.BlockNumber; - - uint64 private _voteExtension; - mapping(uint256 => Timers.BlockNumber) private _extendedDeadlines; - - /// @dev Emitted when a proposal deadline is pushed back due to reaching quorum late in its voting period. - event ProposalExtended(uint256 indexed proposalId, uint64 extendedDeadline); - - /// @dev Emitted when the {lateQuorumVoteExtension} parameter is changed. - event LateQuorumVoteExtensionSet(uint64 oldVoteExtension, uint64 newVoteExtension); - - /** - * @dev Initializes the vote extension parameter: the number of blocks that are required to pass since a proposal - * reaches quorum until its voting period ends. If necessary the voting period will be extended beyond the one set - * at proposal creation. - */ - constructor(uint64 initialVoteExtension) { - _setLateQuorumVoteExtension(initialVoteExtension); - } - - /** - * @dev Returns the proposal deadline, which may have been extended beyond that set at proposal creation, if the - * proposal reached quorum late in the voting period. See {Governor-proposalDeadline}. - */ - function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) { - return Math.max(super.proposalDeadline(proposalId), _extendedDeadlines[proposalId].getDeadline()); - } - - /** - * @dev Casts a vote and detects if it caused quorum to be reached, potentially extending the voting period. See - * {Governor-_castVote}. - * - * May emit a {ProposalExtended} event. - */ - function _castVote( - uint256 proposalId, - address account, - uint8 support, - string memory reason - ) internal virtual override returns (uint256) { - uint256 result = super._castVote(proposalId, account, support, reason); - - Timers.BlockNumber storage extendedDeadline = _extendedDeadlines[proposalId]; - - if (extendedDeadline.isUnset() && _quorumReached(proposalId)) { - uint64 extendedDeadlineValue = block.number.toUint64() + lateQuorumVoteExtension(); - - if (extendedDeadlineValue > proposalDeadline(proposalId)) { - emit ProposalExtended(proposalId, extendedDeadlineValue); - } - - extendedDeadline.setDeadline(extendedDeadlineValue); - } - - return result; - } - - /** - * @dev Returns the current value of the vote extension parameter: the number of blocks that are required to pass - * from the time a proposal reaches quorum until its voting period ends. - */ - function lateQuorumVoteExtension() public view virtual returns (uint64) { - return _voteExtension; - } - - /** - * @dev Changes the {lateQuorumVoteExtension}. This operation can only be performed by the governance executor, - * generally through a governance proposal. - * - * Emits a {LateQuorumVoteExtensionSet} event. - */ - function setLateQuorumVoteExtension(uint64 newVoteExtension) public virtual onlyGovernance { - _setLateQuorumVoteExtension(newVoteExtension); - } - - /** - * @dev Changes the {lateQuorumVoteExtension}. This is an internal function that can be exposed in a public function - * like {setLateQuorumVoteExtension} if another access control mechanism is needed. - * - * Emits a {LateQuorumVoteExtensionSet} event. - */ - function _setLateQuorumVoteExtension(uint64 newVoteExtension) internal virtual { - emit LateQuorumVoteExtensionSet(_voteExtension, newVoteExtension); - _voteExtension = newVoteExtension; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorProposalThreshold.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorProposalThreshold.sol deleted file mode 100644 index 3feebace..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorProposalThreshold.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorProposalThreshold.sol) - -pragma solidity ^0.8.0; - -import "../Governor.sol"; - -/** - * @dev Extension of {Governor} for proposal restriction to token holders with a minimum balance. - * - * _Available since v4.3._ - * _Deprecated since v4.4._ - */ -abstract contract GovernorProposalThreshold is Governor { - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public virtual override returns (uint256) { - return super.propose(targets, values, calldatas, description); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorSettings.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorSettings.sol deleted file mode 100644 index a3187c6e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorSettings.sol +++ /dev/null @@ -1,114 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorSettings.sol) - -pragma solidity ^0.8.0; - -import "../Governor.sol"; - -/** - * @dev Extension of {Governor} for settings updatable through governance. - * - * _Available since v4.4._ - */ -abstract contract GovernorSettings is Governor { - uint256 private _votingDelay; - uint256 private _votingPeriod; - uint256 private _proposalThreshold; - - event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay); - event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod); - event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold); - - /** - * @dev Initialize the governance parameters. - */ - constructor( - uint256 initialVotingDelay, - uint256 initialVotingPeriod, - uint256 initialProposalThreshold - ) { - _setVotingDelay(initialVotingDelay); - _setVotingPeriod(initialVotingPeriod); - _setProposalThreshold(initialProposalThreshold); - } - - /** - * @dev See {IGovernor-votingDelay}. - */ - function votingDelay() public view virtual override returns (uint256) { - return _votingDelay; - } - - /** - * @dev See {IGovernor-votingPeriod}. - */ - function votingPeriod() public view virtual override returns (uint256) { - return _votingPeriod; - } - - /** - * @dev See {Governor-proposalThreshold}. - */ - function proposalThreshold() public view virtual override returns (uint256) { - return _proposalThreshold; - } - - /** - * @dev Update the voting delay. This operation can only be performed through a governance proposal. - * - * Emits a {VotingDelaySet} event. - */ - function setVotingDelay(uint256 newVotingDelay) public virtual onlyGovernance { - _setVotingDelay(newVotingDelay); - } - - /** - * @dev Update the voting period. This operation can only be performed through a governance proposal. - * - * Emits a {VotingPeriodSet} event. - */ - function setVotingPeriod(uint256 newVotingPeriod) public virtual onlyGovernance { - _setVotingPeriod(newVotingPeriod); - } - - /** - * @dev Update the proposal threshold. This operation can only be performed through a governance proposal. - * - * Emits a {ProposalThresholdSet} event. - */ - function setProposalThreshold(uint256 newProposalThreshold) public virtual onlyGovernance { - _setProposalThreshold(newProposalThreshold); - } - - /** - * @dev Internal setter for the voting delay. - * - * Emits a {VotingDelaySet} event. - */ - function _setVotingDelay(uint256 newVotingDelay) internal virtual { - emit VotingDelaySet(_votingDelay, newVotingDelay); - _votingDelay = newVotingDelay; - } - - /** - * @dev Internal setter for the voting period. - * - * Emits a {VotingPeriodSet} event. - */ - function _setVotingPeriod(uint256 newVotingPeriod) internal virtual { - // voting period must be at least one block long - require(newVotingPeriod > 0, "GovernorSettings: voting period too low"); - emit VotingPeriodSet(_votingPeriod, newVotingPeriod); - _votingPeriod = newVotingPeriod; - } - - /** - * @dev Internal setter for the proposal threshold. - * - * Emits a {ProposalThresholdSet} event. - */ - function _setProposalThreshold(uint256 newProposalThreshold) internal virtual { - emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold); - _proposalThreshold = newProposalThreshold; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorTimelockCompound.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorTimelockCompound.sol deleted file mode 100644 index 99aea98b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorTimelockCompound.sol +++ /dev/null @@ -1,246 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/extensions/GovernorTimelockCompound.sol) - -pragma solidity ^0.8.0; - -import "./IGovernorTimelock.sol"; -import "../Governor.sol"; -import "../../utils/math/SafeCast.sol"; - -/** - * https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[Compound's timelock] interface - */ -interface ICompoundTimelock { - receive() external payable; - - // solhint-disable-next-line func-name-mixedcase - function GRACE_PERIOD() external view returns (uint256); - - // solhint-disable-next-line func-name-mixedcase - function MINIMUM_DELAY() external view returns (uint256); - - // solhint-disable-next-line func-name-mixedcase - function MAXIMUM_DELAY() external view returns (uint256); - - function admin() external view returns (address); - - function pendingAdmin() external view returns (address); - - function delay() external view returns (uint256); - - function queuedTransactions(bytes32) external view returns (bool); - - function setDelay(uint256) external; - - function acceptAdmin() external; - - function setPendingAdmin(address) external; - - function queueTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) external returns (bytes32); - - function cancelTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) external; - - function executeTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) external payable returns (bytes memory); -} - -/** - * @dev Extension of {Governor} that binds the execution process to a Compound Timelock. This adds a delay, enforced by - * the external timelock to all successful proposal (in addition to the voting duration). The {Governor} needs to be - * the admin of the timelock for any operation to be performed. A public, unrestricted, - * {GovernorTimelockCompound-__acceptAdmin} is available to accept ownership of the timelock. - * - * Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, - * the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be - * inaccessible. - * - * _Available since v4.3._ - */ -abstract contract GovernorTimelockCompound is IGovernorTimelock, Governor { - using SafeCast for uint256; - using Timers for Timers.Timestamp; - - struct ProposalTimelock { - Timers.Timestamp timer; - } - - ICompoundTimelock private _timelock; - - mapping(uint256 => ProposalTimelock) private _proposalTimelocks; - - /** - * @dev Emitted when the timelock controller used for proposal execution is modified. - */ - event TimelockChange(address oldTimelock, address newTimelock); - - /** - * @dev Set the timelock. - */ - constructor(ICompoundTimelock timelockAddress) { - _updateTimelock(timelockAddress); - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) { - return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev Overriden version of the {Governor-state} function with added support for the `Queued` and `Expired` status. - */ - function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) { - ProposalState status = super.state(proposalId); - - if (status != ProposalState.Succeeded) { - return status; - } - - uint256 eta = proposalEta(proposalId); - if (eta == 0) { - return status; - } else if (block.timestamp >= eta + _timelock.GRACE_PERIOD()) { - return ProposalState.Expired; - } else { - return ProposalState.Queued; - } - } - - /** - * @dev Public accessor to check the address of the timelock - */ - function timelock() public view virtual override returns (address) { - return address(_timelock); - } - - /** - * @dev Public accessor to check the eta of a queued proposal - */ - function proposalEta(uint256 proposalId) public view virtual override returns (uint256) { - return _proposalTimelocks[proposalId].timer.getDeadline(); - } - - /** - * @dev Function to queue a proposal to the timelock. - */ - function queue( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public virtual override returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - - require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful"); - - uint256 eta = block.timestamp + _timelock.delay(); - _proposalTimelocks[proposalId].timer.setDeadline(eta.toUint64()); - for (uint256 i = 0; i < targets.length; ++i) { - require( - !_timelock.queuedTransactions(keccak256(abi.encode(targets[i], values[i], "", calldatas[i], eta))), - "GovernorTimelockCompound: identical proposal action already queued" - ); - _timelock.queueTransaction(targets[i], values[i], "", calldatas[i], eta); - } - - emit ProposalQueued(proposalId, eta); - - return proposalId; - } - - /** - * @dev Overriden execute function that run the already queued proposal through the timelock. - */ - function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 /*descriptionHash*/ - ) internal virtual override { - uint256 eta = proposalEta(proposalId); - require(eta > 0, "GovernorTimelockCompound: proposal not yet queued"); - Address.sendValue(payable(_timelock), msg.value); - for (uint256 i = 0; i < targets.length; ++i) { - _timelock.executeTransaction(targets[i], values[i], "", calldatas[i], eta); - } - } - - /** - * @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already - * been queued. - */ - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual override returns (uint256) { - uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash); - - uint256 eta = proposalEta(proposalId); - if (eta > 0) { - for (uint256 i = 0; i < targets.length; ++i) { - _timelock.cancelTransaction(targets[i], values[i], "", calldatas[i], eta); - } - _proposalTimelocks[proposalId].timer.reset(); - } - - return proposalId; - } - - /** - * @dev Address through which the governor executes action. In this case, the timelock. - */ - function _executor() internal view virtual override returns (address) { - return address(_timelock); - } - - /** - * @dev Accept admin right over the timelock. - */ - // solhint-disable-next-line private-vars-leading-underscore - function __acceptAdmin() public { - _timelock.acceptAdmin(); - } - - /** - * @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates - * must be proposed, scheduled, and executed through governance proposals. - * - * For security reasons, the timelock must be handed over to another admin before setting up a new one. The two - * operations (hand over the timelock) and do the update can be batched in a single proposal. - * - * Note that if the timelock admin has been handed over in a previous operation, we refuse updates made through the - * timelock if admin of the timelock has already been accepted and the operation is executed outside the scope of - * governance. - - * CAUTION: It is not recommended to change the timelock while there are other queued governance proposals. - */ - function updateTimelock(ICompoundTimelock newTimelock) external virtual onlyGovernance { - _updateTimelock(newTimelock); - } - - function _updateTimelock(ICompoundTimelock newTimelock) private { - emit TimelockChange(address(_timelock), address(newTimelock)); - _timelock = newTimelock; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorTimelockControl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorTimelockControl.sol deleted file mode 100644 index 3678b240..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorTimelockControl.sol +++ /dev/null @@ -1,163 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/extensions/GovernorTimelockControl.sol) - -pragma solidity ^0.8.0; - -import "./IGovernorTimelock.sol"; -import "../Governor.sol"; -import "../TimelockController.sol"; - -/** - * @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a - * delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The - * {Governor} needs the proposer (and ideally the executor) roles for the {Governor} to work properly. - * - * Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, - * the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be - * inaccessible. - * - * WARNING: Setting up the TimelockController to have additional proposers besides the governor is very risky, as it - * grants them powers that they must be trusted or known not to use: 1) {onlyGovernance} functions like {relay} are - * available to them through the timelock, and 2) approved governance proposals can be blocked by them, effectively - * executing a Denial of Service attack. This risk will be mitigated in a future release. - * - * _Available since v4.3._ - */ -abstract contract GovernorTimelockControl is IGovernorTimelock, Governor { - TimelockController private _timelock; - mapping(uint256 => bytes32) private _timelockIds; - - /** - * @dev Emitted when the timelock controller used for proposal execution is modified. - */ - event TimelockChange(address oldTimelock, address newTimelock); - - /** - * @dev Set the timelock. - */ - constructor(TimelockController timelockAddress) { - _updateTimelock(timelockAddress); - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) { - return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev Overriden version of the {Governor-state} function with added support for the `Queued` status. - */ - function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) { - ProposalState status = super.state(proposalId); - - if (status != ProposalState.Succeeded) { - return status; - } - - // core tracks execution, so we just have to check if successful proposal have been queued. - bytes32 queueid = _timelockIds[proposalId]; - if (queueid == bytes32(0)) { - return status; - } else if (_timelock.isOperationDone(queueid)) { - return ProposalState.Executed; - } else if (_timelock.isOperationPending(queueid)) { - return ProposalState.Queued; - } else { - return ProposalState.Canceled; - } - } - - /** - * @dev Public accessor to check the address of the timelock - */ - function timelock() public view virtual override returns (address) { - return address(_timelock); - } - - /** - * @dev Public accessor to check the eta of a queued proposal - */ - function proposalEta(uint256 proposalId) public view virtual override returns (uint256) { - uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]); - return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value - } - - /** - * @dev Function to queue a proposal to the timelock. - */ - function queue( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public virtual override returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - - require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful"); - - uint256 delay = _timelock.getMinDelay(); - _timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash); - _timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay); - - emit ProposalQueued(proposalId, block.timestamp + delay); - - return proposalId; - } - - /** - * @dev Overriden execute function that run the already queued proposal through the timelock. - */ - function _execute( - uint256, /* proposalId */ - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual override { - _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash); - } - - /** - * @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already - * been queued. - */ - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual override returns (uint256) { - uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash); - - if (_timelockIds[proposalId] != 0) { - _timelock.cancel(_timelockIds[proposalId]); - delete _timelockIds[proposalId]; - } - - return proposalId; - } - - /** - * @dev Address through which the governor executes action. In this case, the timelock. - */ - function _executor() internal view virtual override returns (address) { - return address(_timelock); - } - - /** - * @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates - * must be proposed, scheduled, and executed through governance proposals. - * - * CAUTION: It is not recommended to change the timelock while there are other queued governance proposals. - */ - function updateTimelock(TimelockController newTimelock) external virtual onlyGovernance { - _updateTimelock(newTimelock); - } - - function _updateTimelock(TimelockController newTimelock) private { - emit TimelockChange(address(_timelock), address(newTimelock)); - _timelock = newTimelock; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotes.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotes.sol deleted file mode 100644 index 75f56356..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotes.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/extensions/GovernorVotes.sol) - -pragma solidity ^0.8.0; - -import "../Governor.sol"; -import "../utils/IVotes.sol"; - -/** - * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token, or since v4.5 an {ERC721Votes} token. - * - * _Available since v4.3._ - */ -abstract contract GovernorVotes is Governor { - IVotes public immutable token; - - constructor(IVotes tokenAddress) { - token = tokenAddress; - } - - /** - * Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}). - */ - function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { - return token.getPastVotes(account, blockNumber); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotesComp.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotesComp.sol deleted file mode 100644 index 9eb87a35..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotesComp.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorVotesComp.sol) - -pragma solidity ^0.8.0; - -import "../Governor.sol"; -import "../../token/ERC20/extensions/ERC20VotesComp.sol"; - -/** - * @dev Extension of {Governor} for voting weight extraction from a Comp token. - * - * _Available since v4.3._ - */ -abstract contract GovernorVotesComp is Governor { - ERC20VotesComp public immutable token; - - constructor(ERC20VotesComp token_) { - token = token_; - } - - /** - * Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}). - */ - function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { - return token.getPriorVotes(account, blockNumber); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotesQuorumFraction.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotesQuorumFraction.sol deleted file mode 100644 index 40f912cb..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/GovernorVotesQuorumFraction.sol +++ /dev/null @@ -1,85 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/extensions/GovernorVotesQuorumFraction.sol) - -pragma solidity ^0.8.0; - -import "./GovernorVotes.sol"; - -/** - * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a - * fraction of the total supply. - * - * _Available since v4.3._ - */ -abstract contract GovernorVotesQuorumFraction is GovernorVotes { - uint256 private _quorumNumerator; - - event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator); - - /** - * @dev Initialize quorum as a fraction of the token's total supply. - * - * The fraction is specified as `numerator / denominator`. By default the denominator is 100, so quorum is - * specified as a percent: a numerator of 10 corresponds to quorum being 10% of total supply. The denominator can be - * customized by overriding {quorumDenominator}. - */ - constructor(uint256 quorumNumeratorValue) { - _updateQuorumNumerator(quorumNumeratorValue); - } - - /** - * @dev Returns the current quorum numerator. See {quorumDenominator}. - */ - function quorumNumerator() public view virtual returns (uint256) { - return _quorumNumerator; - } - - /** - * @dev Returns the quorum denominator. Defaults to 100, but may be overridden. - */ - function quorumDenominator() public view virtual returns (uint256) { - return 100; - } - - /** - * @dev Returns the quorum for a block number, in terms of number of votes: `supply * numerator / denominator`. - */ - function quorum(uint256 blockNumber) public view virtual override returns (uint256) { - return (token.getPastTotalSupply(blockNumber) * quorumNumerator()) / quorumDenominator(); - } - - /** - * @dev Changes the quorum numerator. - * - * Emits a {QuorumNumeratorUpdated} event. - * - * Requirements: - * - * - Must be called through a governance proposal. - * - New numerator must be smaller or equal to the denominator. - */ - function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance { - _updateQuorumNumerator(newQuorumNumerator); - } - - /** - * @dev Changes the quorum numerator. - * - * Emits a {QuorumNumeratorUpdated} event. - * - * Requirements: - * - * - New numerator must be smaller or equal to the denominator. - */ - function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { - require( - newQuorumNumerator <= quorumDenominator(), - "GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator" - ); - - uint256 oldQuorumNumerator = _quorumNumerator; - _quorumNumerator = newQuorumNumerator; - - emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/IGovernorTimelock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/IGovernorTimelock.sol deleted file mode 100644 index 40402f61..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/extensions/IGovernorTimelock.sol +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (governance/extensions/IGovernorTimelock.sol) - -pragma solidity ^0.8.0; - -import "../IGovernor.sol"; - -/** - * @dev Extension of the {IGovernor} for timelock supporting modules. - * - * _Available since v4.3._ - */ -abstract contract IGovernorTimelock is IGovernor { - event ProposalQueued(uint256 proposalId, uint256 eta); - - function timelock() public view virtual returns (address); - - function proposalEta(uint256 proposalId) public view virtual returns (uint256); - - function queue( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public virtual returns (uint256 proposalId); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/utils/IVotes.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/utils/IVotes.sol deleted file mode 100644 index 6317d775..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/utils/IVotes.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol) -pragma solidity ^0.8.0; - -/** - * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. - * - * _Available since v4.5._ - */ -interface IVotes { - /** - * @dev Emitted when an account changes their delegate. - */ - event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); - - /** - * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes. - */ - event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); - - /** - * @dev Returns the current amount of votes that `account` has. - */ - function getVotes(address account) external view returns (uint256); - - /** - * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). - */ - function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); - - /** - * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`). - * - * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. - * Votes that have not been delegated are still part of total supply, even though they would not participate in a - * vote. - */ - function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); - - /** - * @dev Returns the delegate that `account` has chosen. - */ - function delegates(address account) external view returns (address); - - /** - * @dev Delegates votes from the sender to `delegatee`. - */ - function delegate(address delegatee) external; - - /** - * @dev Delegates votes from signer to `delegatee`. - */ - function delegateBySig( - address delegatee, - uint256 nonce, - uint256 expiry, - uint8 v, - bytes32 r, - bytes32 s - ) external; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/utils/Votes.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/utils/Votes.sol deleted file mode 100644 index cc5101b9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/governance/utils/Votes.sol +++ /dev/null @@ -1,211 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/Votes.sol) -pragma solidity ^0.8.0; - -import "../../utils/Context.sol"; -import "../../utils/Counters.sol"; -import "../../utils/Checkpoints.sol"; -import "../../utils/cryptography/draft-EIP712.sol"; -import "./IVotes.sol"; - -/** - * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be - * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of - * "representative" that will pool delegated voting units from different accounts and can then use it to vote in - * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to - * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative. - * - * This contract is often combined with a token contract such that voting units correspond to token units. For an - * example, see {ERC721Votes}. - * - * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed - * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the - * cost of this history tracking optional. - * - * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return - * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the - * previous example, it would be included in {ERC721-_beforeTokenTransfer}). - * - * _Available since v4.5._ - */ -abstract contract Votes is IVotes, Context, EIP712 { - using Checkpoints for Checkpoints.History; - using Counters for Counters.Counter; - - bytes32 private constant _DELEGATION_TYPEHASH = - keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); - - mapping(address => address) private _delegation; - mapping(address => Checkpoints.History) private _delegateCheckpoints; - Checkpoints.History private _totalCheckpoints; - - mapping(address => Counters.Counter) private _nonces; - - /** - * @dev Returns the current amount of votes that `account` has. - */ - function getVotes(address account) public view virtual override returns (uint256) { - return _delegateCheckpoints[account].latest(); - } - - /** - * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). - * - * Requirements: - * - * - `blockNumber` must have been already mined - */ - function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { - return _delegateCheckpoints[account].getAtBlock(blockNumber); - } - - /** - * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`). - * - * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. - * Votes that have not been delegated are still part of total supply, even though they would not participate in a - * vote. - * - * Requirements: - * - * - `blockNumber` must have been already mined - */ - function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) { - require(blockNumber < block.number, "Votes: block not yet mined"); - return _totalCheckpoints.getAtBlock(blockNumber); - } - - /** - * @dev Returns the current total supply of votes. - */ - function _getTotalSupply() internal view virtual returns (uint256) { - return _totalCheckpoints.latest(); - } - - /** - * @dev Returns the delegate that `account` has chosen. - */ - function delegates(address account) public view virtual override returns (address) { - return _delegation[account]; - } - - /** - * @dev Delegates votes from the sender to `delegatee`. - */ - function delegate(address delegatee) public virtual override { - address account = _msgSender(); - _delegate(account, delegatee); - } - - /** - * @dev Delegates votes from signer to `delegatee`. - */ - function delegateBySig( - address delegatee, - uint256 nonce, - uint256 expiry, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual override { - require(block.timestamp <= expiry, "Votes: signature expired"); - address signer = ECDSA.recover( - _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), - v, - r, - s - ); - require(nonce == _useNonce(signer), "Votes: invalid nonce"); - _delegate(signer, delegatee); - } - - /** - * @dev Delegate all of `account`'s voting units to `delegatee`. - * - * Emits events {DelegateChanged} and {DelegateVotesChanged}. - */ - function _delegate(address account, address delegatee) internal virtual { - address oldDelegate = delegates(account); - _delegation[account] = delegatee; - - emit DelegateChanged(account, oldDelegate, delegatee); - _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account)); - } - - /** - * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to` - * should be zero. Total supply of voting units will be adjusted with mints and burns. - */ - function _transferVotingUnits( - address from, - address to, - uint256 amount - ) internal virtual { - if (from == address(0)) { - _totalCheckpoints.push(_add, amount); - } - if (to == address(0)) { - _totalCheckpoints.push(_subtract, amount); - } - _moveDelegateVotes(delegates(from), delegates(to), amount); - } - - /** - * @dev Moves delegated votes from one delegate to another. - */ - function _moveDelegateVotes( - address from, - address to, - uint256 amount - ) private { - if (from != to && amount > 0) { - if (from != address(0)) { - (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount); - emit DelegateVotesChanged(from, oldValue, newValue); - } - if (to != address(0)) { - (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount); - emit DelegateVotesChanged(to, oldValue, newValue); - } - } - } - - function _add(uint256 a, uint256 b) private pure returns (uint256) { - return a + b; - } - - function _subtract(uint256 a, uint256 b) private pure returns (uint256) { - return a - b; - } - - /** - * @dev Consumes a nonce. - * - * Returns the current value and increments nonce. - */ - function _useNonce(address owner) internal virtual returns (uint256 current) { - Counters.Counter storage nonce = _nonces[owner]; - current = nonce.current(); - nonce.increment(); - } - - /** - * @dev Returns an address nonce. - */ - function nonces(address owner) public view virtual returns (uint256) { - return _nonces[owner].current(); - } - - /** - * @dev Returns the contract's {EIP712} domain separator. - */ - // solhint-disable-next-line func-name-mixedcase - function DOMAIN_SEPARATOR() external view returns (bytes32) { - return _domainSeparatorV4(); - } - - /** - * @dev Must return the voting units held by an account. - */ - function _getVotingUnits(address) internal virtual returns (uint256); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155.sol deleted file mode 100644 index f8911321..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC1155/IERC1155.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155MetadataURI.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155MetadataURI.sol deleted file mode 100644 index 2aa885fe..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155MetadataURI.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155MetadataURI.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC1155/extensions/IERC1155MetadataURI.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155Receiver.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155Receiver.sol deleted file mode 100644 index a6d4ead1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1155Receiver.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155Receiver.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC1155/IERC1155Receiver.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol deleted file mode 100644 index 5ec44c72..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC1271 standard signature validation method for - * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. - * - * _Available since v4.1._ - */ -interface IERC1271 { - /** - * @dev Should return whether the signature provided is valid for the provided data - * @param hash Hash of the data to be signed - * @param signature Signature byte array associated with _data - */ - function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol deleted file mode 100644 index 5fad104c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol +++ /dev/null @@ -1,95 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; -import "./IERC165.sol"; - -interface IERC1363 is IERC165, IERC20 { - /* - * Note: the ERC-165 identifier for this interface is 0x4bbee2df. - * 0x4bbee2df === - * bytes4(keccak256('transferAndCall(address,uint256)')) ^ - * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ - * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ - * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) - */ - - /* - * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. - * 0xfb9ec8ce === - * bytes4(keccak256('approveAndCall(address,uint256)')) ^ - * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) - */ - - /** - * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @return true unless throwing - */ - function transferAndCall(address to, uint256 value) external returns (bool); - - /** - * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @param data bytes Additional data with no specified format, sent in call to `to` - * @return true unless throwing - */ - function transferAndCall( - address to, - uint256 value, - bytes memory data - ) external returns (bool); - - /** - * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver - * @param from address The address which you want to send tokens from - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @return true unless throwing - */ - function transferFromAndCall( - address from, - address to, - uint256 value - ) external returns (bool); - - /** - * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver - * @param from address The address which you want to send tokens from - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @param data bytes Additional data with no specified format, sent in call to `to` - * @return true unless throwing - */ - function transferFromAndCall( - address from, - address to, - uint256 value, - bytes memory data - ) external returns (bool); - - /** - * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender - * and then call `onApprovalReceived` on spender. - * @param spender address The address which will spend the funds - * @param value uint256 The amount of tokens to be spent - */ - function approveAndCall(address spender, uint256 value) external returns (bool); - - /** - * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender - * and then call `onApprovalReceived` on spender. - * @param spender address The address which will spend the funds - * @param value uint256 The amount of tokens to be spent - * @param data bytes Additional data with no specified format, sent in call to `spender` - */ - function approveAndCall( - address spender, - uint256 value, - bytes memory data - ) external returns (bool); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363Receiver.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363Receiver.sol deleted file mode 100644 index bc5eaddb..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363Receiver.sol +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Receiver.sol) - -pragma solidity ^0.8.0; - -interface IERC1363Receiver { - /* - * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. - * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) - */ - - /** - * @notice Handle the receipt of ERC1363 tokens - * @dev Any ERC1363 smart contract calls this function on the recipient - * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the token contract address is always the message sender. - * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function - * @param from address The address which are token transferred from - * @param value uint256 The amount of tokens transferred - * @param data bytes Additional data with no specified format - * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` - * unless throwing - */ - function onTransferReceived( - address operator, - address from, - uint256 value, - bytes memory data - ) external returns (bytes4); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363Spender.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363Spender.sol deleted file mode 100644 index 48f6fd56..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1363Spender.sol +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Spender.sol) - -pragma solidity ^0.8.0; - -interface IERC1363Spender { - /* - * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. - * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) - */ - - /** - * @notice Handle the approval of ERC1363 tokens - * @dev Any ERC1363 smart contract calls this function on the recipient - * after an `approve`. This function MAY throw to revert and reject the - * approval. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the token contract address is always the message sender. - * @param owner address The address which called `approveAndCall` function - * @param value uint256 The amount of tokens to be spent - * @param data bytes Additional data with no specified format - * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` - * unless throwing - */ - function onApprovalReceived( - address owner, - uint256 value, - bytes memory data - ) external returns (bytes4); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol deleted file mode 100644 index b97c4daa..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) - -pragma solidity ^0.8.0; - -import "../utils/introspection/IERC165.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1820Implementer.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1820Implementer.sol deleted file mode 100644 index a83a7a30..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1820Implementer.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1820Implementer.sol) - -pragma solidity ^0.8.0; - -import "../utils/introspection/IERC1820Implementer.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1820Registry.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1820Registry.sol deleted file mode 100644 index 1b1ba9fc..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC1820Registry.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1820Registry.sol) - -pragma solidity ^0.8.0; - -import "../utils/introspection/IERC1820Registry.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol deleted file mode 100644 index a819316d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC20/IERC20.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol deleted file mode 100644 index aa5c6391..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/IERC20Metadata.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol deleted file mode 100644 index cbd9e241..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) - -pragma solidity ^0.8.0; - -import "./IERC165.sol"; - -/** - * @dev Interface for the NFT Royalty Standard. - * - * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal - * support for royalty payments across all NFT marketplaces and ecosystem participants. - * - * _Available since v4.5._ - */ -interface IERC2981 is IERC165 { - /** - * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of - * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. - */ - function royaltyInfo(uint256 tokenId, uint256 salePrice) - external - view - returns (address receiver, uint256 royaltyAmount); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156.sol deleted file mode 100644 index 12381906..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156.sol +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156.sol) - -pragma solidity ^0.8.0; - -import "./IERC3156FlashBorrower.sol"; -import "./IERC3156FlashLender.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156FlashBorrower.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156FlashBorrower.sol deleted file mode 100644 index 68d0dacf..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156FlashBorrower.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashBorrower.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC3156 FlashBorrower, as defined in - * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. - * - * _Available since v4.1._ - */ -interface IERC3156FlashBorrower { - /** - * @dev Receive a flash loan. - * @param initiator The initiator of the loan. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @param fee The additional amount of tokens to repay. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" - */ - function onFlashLoan( - address initiator, - address token, - uint256 amount, - uint256 fee, - bytes calldata data - ) external returns (bytes32); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156FlashLender.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156FlashLender.sol deleted file mode 100644 index 31012830..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC3156FlashLender.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashLender.sol) - -pragma solidity ^0.8.0; - -import "./IERC3156FlashBorrower.sol"; - -/** - * @dev Interface of the ERC3156 FlashLender, as defined in - * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. - * - * _Available since v4.1._ - */ -interface IERC3156FlashLender { - /** - * @dev The amount of currency available to be lended. - * @param token The loan currency. - * @return The amount of `token` that can be borrowed. - */ - function maxFlashLoan(address token) external view returns (uint256); - - /** - * @dev The fee to be charged for a given loan. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function flashFee(address token, uint256 amount) external view returns (uint256); - - /** - * @dev Initiate a flash loan. - * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - */ - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) external returns (bool); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721.sol deleted file mode 100644 index 822b311c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC721/IERC721.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Enumerable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Enumerable.sol deleted file mode 100644 index e39a5a01..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Enumerable.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Enumerable.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/IERC721Enumerable.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Metadata.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Metadata.sol deleted file mode 100644 index afe2707c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Metadata.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Metadata.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/IERC721Metadata.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Receiver.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Receiver.sol deleted file mode 100644 index c9c153a2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC721Receiver.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Receiver.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC721/IERC721Receiver.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777.sol deleted file mode 100644 index b97ba7b8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC777.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC777/IERC777.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777Recipient.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777Recipient.sol deleted file mode 100644 index 0ce2704a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777Recipient.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC777Recipient.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC777/IERC777Recipient.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777Sender.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777Sender.sol deleted file mode 100644 index f1f17a22..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/IERC777Sender.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC777Sender.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC777/IERC777Sender.sol"; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/README.adoc deleted file mode 100644 index b6b96ffe..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/README.adoc +++ /dev/null @@ -1,50 +0,0 @@ -= Interfaces - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/interfaces - -== List of standardized interfaces -These interfaces are available as `.sol` files, and also as compiler `.json` ABI files (through the npm package). These -are useful to interact with third party contracts that implement them. - -- {IERC20} -- {IERC20Metadata} -- {IERC165} -- {IERC721} -- {IERC721Receiver} -- {IERC721Enumerable} -- {IERC721Metadata} -- {IERC777} -- {IERC777Recipient} -- {IERC777Sender} -- {IERC1155} -- {IERC1155Receiver} -- {IERC1155MetadataURI} -- {IERC1271} -- {IERC1363} -- {IERC1820Implementer} -- {IERC1820Registry} -- {IERC2612} -- {IERC2981} -- {IERC3156FlashLender} -- {IERC3156FlashBorrower} - -== Detailed ABI - -{{IERC1271}} - -{{IERC1363}} - -{{IERC1363Receiver}} - -{{IERC1820Implementer}} - -{{IERC1820Registry}} - -{{IERC2612}} - -{{IERC2981}} - -{{IERC3156FlashLender}} - -{{IERC3156FlashBorrower}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol deleted file mode 100644 index 3b73d744..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) - -pragma solidity ^0.8.0; - -/** - * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified - * proxy whose upgrades are fully controlled by the current implementation. - */ -interface IERC1822Proxiable { - /** - * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation - * address. - * - * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks - * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this - * function revert if invoked through a proxy. - */ - function proxiableUUID() external view returns (bytes32); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC2612.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC2612.sol deleted file mode 100644 index 1b3ae55f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC2612.sol +++ /dev/null @@ -1,8 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/draft-IERC2612.sol) - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/draft-IERC20Permit.sol"; - -interface IERC2612 is IERC20Permit {} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/ERC2771Context.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/ERC2771Context.sol deleted file mode 100644 index b5d16e56..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/ERC2771Context.sol +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (metatx/ERC2771Context.sol) - -pragma solidity ^0.8.9; - -import "../utils/Context.sol"; - -/** - * @dev Context variant with ERC2771 support. - */ -abstract contract ERC2771Context is Context { - /// @custom:oz-upgrades-unsafe-allow state-variable-immutable - address private immutable _trustedForwarder; - - /// @custom:oz-upgrades-unsafe-allow constructor - constructor(address trustedForwarder) { - _trustedForwarder = trustedForwarder; - } - - function isTrustedForwarder(address forwarder) public view virtual returns (bool) { - return forwarder == _trustedForwarder; - } - - function _msgSender() internal view virtual override returns (address sender) { - if (isTrustedForwarder(msg.sender)) { - // The assembly code is more direct than the Solidity version using `abi.decode`. - assembly { - sender := shr(96, calldataload(sub(calldatasize(), 20))) - } - } else { - return super._msgSender(); - } - } - - function _msgData() internal view virtual override returns (bytes calldata) { - if (isTrustedForwarder(msg.sender)) { - return msg.data[:msg.data.length - 20]; - } else { - return super._msgData(); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/MinimalForwarder.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/MinimalForwarder.sol deleted file mode 100644 index a7a1899f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/MinimalForwarder.sol +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (metatx/MinimalForwarder.sol) - -pragma solidity ^0.8.0; - -import "../utils/cryptography/ECDSA.sol"; -import "../utils/cryptography/draft-EIP712.sol"; - -/** - * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}. - */ -contract MinimalForwarder is EIP712 { - using ECDSA for bytes32; - - struct ForwardRequest { - address from; - address to; - uint256 value; - uint256 gas; - uint256 nonce; - bytes data; - } - - bytes32 private constant _TYPEHASH = - keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)"); - - mapping(address => uint256) private _nonces; - - constructor() EIP712("MinimalForwarder", "0.0.1") {} - - function getNonce(address from) public view returns (uint256) { - return _nonces[from]; - } - - function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) { - address signer = _hashTypedDataV4( - keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data))) - ).recover(signature); - return _nonces[req.from] == req.nonce && signer == req.from; - } - - function execute(ForwardRequest calldata req, bytes calldata signature) - public - payable - returns (bool, bytes memory) - { - require(verify(req, signature), "MinimalForwarder: signature does not match request"); - _nonces[req.from] = req.nonce + 1; - - (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}( - abi.encodePacked(req.data, req.from) - ); - - // Validate that the relayer has sent enough gas for the call. - // See https://ronan.eth.link/blog/ethereum-gas-dangers/ - if (gasleft() <= req.gas / 63) { - // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since - // neither revert or assert consume all gas since Solidity 0.8.0 - // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require - assembly { - invalid() - } - } - - return (success, returndata); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/README.adoc deleted file mode 100644 index eccdeaf9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/metatx/README.adoc +++ /dev/null @@ -1,12 +0,0 @@ -= Meta Transactions - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/metatx - -== Core - -{{ERC2771Context}} - -== Utils - -{{MinimalForwarder}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AccessControlEnumerableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AccessControlEnumerableMock.sol deleted file mode 100644 index 7b15e360..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AccessControlEnumerableMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../access/AccessControlEnumerable.sol"; - -contract AccessControlEnumerableMock is AccessControlEnumerable { - constructor() { - _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); - } - - function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public { - _setRoleAdmin(roleId, adminRoleId); - } - - function senderProtected(bytes32 roleId) public onlyRole(roleId) {} -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AccessControlMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AccessControlMock.sol deleted file mode 100644 index 86f51477..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AccessControlMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../access/AccessControl.sol"; - -contract AccessControlMock is AccessControl { - constructor() { - _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); - } - - function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public { - _setRoleAdmin(roleId, adminRoleId); - } - - function senderProtected(bytes32 roleId) public onlyRole(roleId) {} -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AddressImpl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AddressImpl.sol deleted file mode 100644 index 702093c7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/AddressImpl.sol +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Address.sol"; - -contract AddressImpl { - string public sharedAnswer; - - event CallReturnValue(string data); - - function isContract(address account) external view returns (bool) { - return Address.isContract(account); - } - - function sendValue(address payable receiver, uint256 amount) external { - Address.sendValue(receiver, amount); - } - - function functionCall(address target, bytes calldata data) external { - bytes memory returnData = Address.functionCall(target, data); - emit CallReturnValue(abi.decode(returnData, (string))); - } - - function functionCallWithValue( - address target, - bytes calldata data, - uint256 value - ) external payable { - bytes memory returnData = Address.functionCallWithValue(target, data, value); - emit CallReturnValue(abi.decode(returnData, (string))); - } - - function functionStaticCall(address target, bytes calldata data) external { - bytes memory returnData = Address.functionStaticCall(target, data); - emit CallReturnValue(abi.decode(returnData, (string))); - } - - function functionDelegateCall(address target, bytes calldata data) external { - bytes memory returnData = Address.functionDelegateCall(target, data); - emit CallReturnValue(abi.decode(returnData, (string))); - } - - // sendValue's tests require the contract to hold Ether - receive() external payable {} -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ArraysImpl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ArraysImpl.sol deleted file mode 100644 index f720524b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ArraysImpl.sol +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Arrays.sol"; - -contract ArraysImpl { - using Arrays for uint256[]; - - uint256[] private _array; - - constructor(uint256[] memory array) { - _array = array; - } - - function findUpperBound(uint256 element) external view returns (uint256) { - return _array.findUpperBound(element); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/BadBeacon.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/BadBeacon.sol deleted file mode 100644 index bedcfed8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/BadBeacon.sol +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -contract BadBeaconNoImpl {} - -contract BadBeaconNotContract { - function implementation() external pure returns (address) { - return address(0x1); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/Base64Mock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/Base64Mock.sol deleted file mode 100644 index b255487b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/Base64Mock.sol +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Base64.sol"; - -contract Base64Mock { - function encode(bytes memory value) external pure returns (string memory) { - return Base64.encode(value); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/BitmapMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/BitmapMock.sol deleted file mode 100644 index ccf8486f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/BitmapMock.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/structs/BitMaps.sol"; - -contract BitMapMock { - using BitMaps for BitMaps.BitMap; - - BitMaps.BitMap private _bitmap; - - function get(uint256 index) public view returns (bool) { - return _bitmap.get(index); - } - - function setTo(uint256 index, bool value) public { - _bitmap.setTo(index, value); - } - - function set(uint256 index) public { - _bitmap.set(index); - } - - function unset(uint256 index) public { - _bitmap.unset(index); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CallReceiverMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CallReceiverMock.sol deleted file mode 100644 index 926db68b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CallReceiverMock.sol +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -contract CallReceiverMock { - string public sharedAnswer; - - event MockFunctionCalled(); - event MockFunctionCalledWithArgs(uint256 a, uint256 b); - - uint256[] private _array; - - function mockFunction() public payable returns (string memory) { - emit MockFunctionCalled(); - - return "0x1234"; - } - - function mockFunctionWithArgs(uint256 a, uint256 b) public payable returns (string memory) { - emit MockFunctionCalledWithArgs(a, b); - - return "0x1234"; - } - - function mockFunctionNonPayable() public returns (string memory) { - emit MockFunctionCalled(); - - return "0x1234"; - } - - function mockStaticFunction() public pure returns (string memory) { - return "0x1234"; - } - - function mockFunctionRevertsNoReason() public payable { - revert(); - } - - function mockFunctionRevertsReason() public payable { - revert("CallReceiverMock: reverting"); - } - - function mockFunctionThrows() public payable { - assert(false); - } - - function mockFunctionOutOfGas() public payable { - for (uint256 i = 0; ; ++i) { - _array.push(i); - } - } - - function mockFunctionWritesStorage() public returns (string memory) { - sharedAnswer = "42"; - return "0x1234"; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CheckpointsImpl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CheckpointsImpl.sol deleted file mode 100644 index 5b9ec0ac..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CheckpointsImpl.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Checkpoints.sol"; - -contract CheckpointsImpl { - using Checkpoints for Checkpoints.History; - - Checkpoints.History private _totalCheckpoints; - - function latest() public view returns (uint256) { - return _totalCheckpoints.latest(); - } - - function getAtBlock(uint256 blockNumber) public view returns (uint256) { - return _totalCheckpoints.getAtBlock(blockNumber); - } - - function push(uint256 value) public returns (uint256, uint256) { - return _totalCheckpoints.push(value); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ClashingImplementation.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ClashingImplementation.sol deleted file mode 100644 index 80aca0c2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ClashingImplementation.sol +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -/** - * @dev Implementation contract with an admin() function made to clash with - * @dev TransparentUpgradeableProxy's to test correct functioning of the - * @dev Transparent Proxy feature. - */ -contract ClashingImplementation { - function admin() external pure returns (address) { - return 0x0000000000000000000000000000000011111142; - } - - function delegatedFunction() external pure returns (bool) { - return true; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ClonesMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ClonesMock.sol deleted file mode 100644 index 3719b0a7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ClonesMock.sol +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../proxy/Clones.sol"; -import "../utils/Address.sol"; - -contract ClonesMock { - using Address for address; - using Clones for address; - - event NewInstance(address instance); - - function clone(address implementation, bytes calldata initdata) public payable { - _initAndEmit(implementation.clone(), initdata); - } - - function cloneDeterministic( - address implementation, - bytes32 salt, - bytes calldata initdata - ) public payable { - _initAndEmit(implementation.cloneDeterministic(salt), initdata); - } - - function predictDeterministicAddress(address implementation, bytes32 salt) public view returns (address predicted) { - return implementation.predictDeterministicAddress(salt); - } - - function _initAndEmit(address instance, bytes memory initdata) private { - if (initdata.length > 0) { - instance.functionCallWithValue(initdata, msg.value); - } - emit NewInstance(instance); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ConditionalEscrowMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ConditionalEscrowMock.sol deleted file mode 100644 index ececf052..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ConditionalEscrowMock.sol +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/escrow/ConditionalEscrow.sol"; - -// mock class using ConditionalEscrow -contract ConditionalEscrowMock is ConditionalEscrow { - mapping(address => bool) private _allowed; - - function setAllowed(address payee, bool allowed) public { - _allowed[payee] = allowed; - } - - function withdrawalAllowed(address payee) public view override returns (bool) { - return _allowed[payee]; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ContextMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ContextMock.sol deleted file mode 100644 index f17af38a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ContextMock.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Context.sol"; - -contract ContextMock is Context { - event Sender(address sender); - - function msgSender() public { - emit Sender(_msgSender()); - } - - event Data(bytes data, uint256 integerValue, string stringValue); - - function msgData(uint256 integerValue, string memory stringValue) public { - emit Data(_msgData(), integerValue, stringValue); - } -} - -contract ContextMockCaller { - function callSender(ContextMock context) public { - context.msgSender(); - } - - function callData( - ContextMock context, - uint256 integerValue, - string memory stringValue - ) public { - context.msgData(integerValue, stringValue); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CountersImpl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CountersImpl.sol deleted file mode 100644 index 651b50ba..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/CountersImpl.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Counters.sol"; - -contract CountersImpl { - using Counters for Counters.Counter; - - Counters.Counter private _counter; - - function current() public view returns (uint256) { - return _counter.current(); - } - - function increment() public { - _counter.increment(); - } - - function decrement() public { - _counter.decrement(); - } - - function reset() public { - _counter.reset(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/Create2Impl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/Create2Impl.sol deleted file mode 100644 index 070ad367..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/Create2Impl.sol +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Create2.sol"; -import "../utils/introspection/ERC1820Implementer.sol"; - -contract Create2Impl { - function deploy( - uint256 value, - bytes32 salt, - bytes memory code - ) public { - Create2.deploy(value, salt, code); - } - - function deployERC1820Implementer(uint256 value, bytes32 salt) public { - Create2.deploy(value, salt, type(ERC1820Implementer).creationCode); - } - - function computeAddress(bytes32 salt, bytes32 codeHash) public view returns (address) { - return Create2.computeAddress(salt, codeHash); - } - - function computeAddressWithDeployer( - bytes32 salt, - bytes32 codeHash, - address deployer - ) public pure returns (address) { - return Create2.computeAddress(salt, codeHash, deployer); - } - - receive() external payable {} -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/DummyImplementation.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/DummyImplementation.sol deleted file mode 100644 index d8651340..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/DummyImplementation.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -abstract contract Impl { - function version() public pure virtual returns (string memory); -} - -contract DummyImplementation { - uint256 public value; - string public text; - uint256[] public values; - - function initializeNonPayable() public { - value = 10; - } - - function initializePayable() public payable { - value = 100; - } - - function initializeNonPayableWithValue(uint256 _value) public { - value = _value; - } - - function initializePayableWithValue(uint256 _value) public payable { - value = _value; - } - - function initialize( - uint256 _value, - string memory _text, - uint256[] memory _values - ) public { - value = _value; - text = _text; - values = _values; - } - - function get() public pure returns (bool) { - return true; - } - - function version() public pure virtual returns (string memory) { - return "V1"; - } - - function reverts() public pure { - require(false, "DummyImplementation reverted"); - } -} - -contract DummyImplementationV2 is DummyImplementation { - function migrate(uint256 newVal) public payable { - value = newVal; - } - - function version() public pure override returns (string memory) { - return "V2"; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ECDSAMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ECDSAMock.sol deleted file mode 100644 index 97bd4666..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ECDSAMock.sol +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/cryptography/ECDSA.sol"; - -contract ECDSAMock { - using ECDSA for bytes32; - using ECDSA for bytes; - - function recover(bytes32 hash, bytes memory signature) public pure returns (address) { - return hash.recover(signature); - } - - // solhint-disable-next-line func-name-mixedcase - function recover_v_r_s( - bytes32 hash, - uint8 v, - bytes32 r, - bytes32 s - ) public pure returns (address) { - return hash.recover(v, r, s); - } - - // solhint-disable-next-line func-name-mixedcase - function recover_r_vs( - bytes32 hash, - bytes32 r, - bytes32 vs - ) public pure returns (address) { - return hash.recover(r, vs); - } - - function toEthSignedMessageHash(bytes32 hash) public pure returns (bytes32) { - return hash.toEthSignedMessageHash(); - } - - function toEthSignedMessageHash(bytes memory s) public pure returns (bytes32) { - return s.toEthSignedMessageHash(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EIP712External.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EIP712External.sol deleted file mode 100644 index 6f244690..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EIP712External.sol +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/cryptography/draft-EIP712.sol"; -import "../utils/cryptography/ECDSA.sol"; - -contract EIP712External is EIP712 { - constructor(string memory name, string memory version) EIP712(name, version) {} - - function domainSeparator() external view returns (bytes32) { - return _domainSeparatorV4(); - } - - function verify( - bytes memory signature, - address signer, - address mailTo, - string memory mailContents - ) external view { - bytes32 digest = _hashTypedDataV4( - keccak256(abi.encode(keccak256("Mail(address to,string contents)"), mailTo, keccak256(bytes(mailContents)))) - ); - address recoveredSigner = ECDSA.recover(digest, signature); - require(recoveredSigner == signer); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155BurnableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155BurnableMock.sol deleted file mode 100644 index 62138f28..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155BurnableMock.sol +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC1155/extensions/ERC1155Burnable.sol"; - -contract ERC1155BurnableMock is ERC1155Burnable { - constructor(string memory uri) ERC1155(uri) {} - - function mint( - address to, - uint256 id, - uint256 value, - bytes memory data - ) public { - _mint(to, id, value, data); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155Mock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155Mock.sol deleted file mode 100644 index 0518ac26..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155Mock.sol +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC1155/ERC1155.sol"; - -/** - * @title ERC1155Mock - * This mock just publicizes internal functions for testing purposes - */ -contract ERC1155Mock is ERC1155 { - constructor(string memory uri) ERC1155(uri) {} - - function setURI(string memory newuri) public { - _setURI(newuri); - } - - function mint( - address to, - uint256 id, - uint256 value, - bytes memory data - ) public { - _mint(to, id, value, data); - } - - function mintBatch( - address to, - uint256[] memory ids, - uint256[] memory values, - bytes memory data - ) public { - _mintBatch(to, ids, values, data); - } - - function burn( - address owner, - uint256 id, - uint256 value - ) public { - _burn(owner, id, value); - } - - function burnBatch( - address owner, - uint256[] memory ids, - uint256[] memory values - ) public { - _burnBatch(owner, ids, values); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155PausableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155PausableMock.sol deleted file mode 100644 index b1a4a8e1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155PausableMock.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./ERC1155Mock.sol"; -import "../token/ERC1155/extensions/ERC1155Pausable.sol"; - -contract ERC1155PausableMock is ERC1155Mock, ERC1155Pausable { - constructor(string memory uri) ERC1155Mock(uri) {} - - function pause() external { - _pause(); - } - - function unpause() external { - _unpause(); - } - - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual override(ERC1155, ERC1155Pausable) { - super._beforeTokenTransfer(operator, from, to, ids, amounts, data); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155ReceiverMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155ReceiverMock.sol deleted file mode 100644 index 6443a56c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155ReceiverMock.sol +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC1155/IERC1155Receiver.sol"; -import "../utils/introspection/ERC165.sol"; - -contract ERC1155ReceiverMock is ERC165, IERC1155Receiver { - bytes4 private _recRetval; - bool private _recReverts; - bytes4 private _batRetval; - bool private _batReverts; - - event Received(address operator, address from, uint256 id, uint256 value, bytes data, uint256 gas); - event BatchReceived(address operator, address from, uint256[] ids, uint256[] values, bytes data, uint256 gas); - - constructor( - bytes4 recRetval, - bool recReverts, - bytes4 batRetval, - bool batReverts - ) { - _recRetval = recRetval; - _recReverts = recReverts; - _batRetval = batRetval; - _batReverts = batReverts; - } - - function onERC1155Received( - address operator, - address from, - uint256 id, - uint256 value, - bytes calldata data - ) external override returns (bytes4) { - require(!_recReverts, "ERC1155ReceiverMock: reverting on receive"); - emit Received(operator, from, id, value, data, gasleft()); - return _recRetval; - } - - function onERC1155BatchReceived( - address operator, - address from, - uint256[] calldata ids, - uint256[] calldata values, - bytes calldata data - ) external override returns (bytes4) { - require(!_batReverts, "ERC1155ReceiverMock: reverting on batch receive"); - emit BatchReceived(operator, from, ids, values, data, gasleft()); - return _batRetval; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155SupplyMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155SupplyMock.sol deleted file mode 100644 index 44b20800..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1155SupplyMock.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./ERC1155Mock.sol"; -import "../token/ERC1155/extensions/ERC1155Supply.sol"; - -contract ERC1155SupplyMock is ERC1155Mock, ERC1155Supply { - constructor(string memory uri) ERC1155Mock(uri) {} - - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual override(ERC1155, ERC1155Supply) { - super._beforeTokenTransfer(operator, from, to, ids, amounts, data); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1271WalletMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1271WalletMock.sol deleted file mode 100644 index c92acdba..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1271WalletMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../access/Ownable.sol"; -import "../interfaces/IERC1271.sol"; -import "../utils/cryptography/ECDSA.sol"; - -contract ERC1271WalletMock is Ownable, IERC1271 { - constructor(address originalOwner) { - transferOwnership(originalOwner); - } - - function isValidSignature(bytes32 hash, bytes memory signature) public view override returns (bytes4 magicValue) { - return ECDSA.recover(hash, signature) == owner() ? this.isValidSignature.selector : bytes4(0); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165InterfacesSupported.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165InterfacesSupported.sol deleted file mode 100644 index 7a5e5bc6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165InterfacesSupported.sol +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../../utils/introspection/IERC165.sol"; - -/** - * https://eips.ethereum.org/EIPS/eip-214#specification - * From the specification: - * > Any attempts to make state-changing operations inside an execution instance with STATIC set to true will instead - * throw an exception. - * > These operations include [...], LOG0, LOG1, LOG2, [...] - * - * therefore, because this contract is staticcall'd we need to not emit events (which is how solidity-coverage works) - * solidity-coverage ignores the /mocks folder, so we duplicate its implementation here to avoid instrumenting it - */ -contract SupportsInterfaceWithLookupMock is IERC165 { - /* - * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 - */ - bytes4 public constant INTERFACE_ID_ERC165 = 0x01ffc9a7; - - /** - * @dev A mapping of interface id to whether or not it's supported. - */ - mapping(bytes4 => bool) private _supportedInterfaces; - - /** - * @dev A contract implementing SupportsInterfaceWithLookup - * implement ERC165 itself. - */ - constructor() { - _registerInterface(INTERFACE_ID_ERC165); - } - - /** - * @dev Implement supportsInterface(bytes4) using a lookup table. - */ - function supportsInterface(bytes4 interfaceId) public view override returns (bool) { - return _supportedInterfaces[interfaceId]; - } - - /** - * @dev Private method for registering an interface. - */ - function _registerInterface(bytes4 interfaceId) internal { - require(interfaceId != 0xffffffff, "ERC165InterfacesSupported: invalid interface id"); - _supportedInterfaces[interfaceId] = true; - } -} - -contract ERC165InterfacesSupported is SupportsInterfaceWithLookupMock { - constructor(bytes4[] memory interfaceIds) { - for (uint256 i = 0; i < interfaceIds.length; i++) { - _registerInterface(interfaceIds[i]); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165MissingData.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165MissingData.sol deleted file mode 100644 index 59cd51ae..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165MissingData.sol +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -contract ERC165MissingData { - function supportsInterface(bytes4 interfaceId) public view {} // missing return -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165NotSupported.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165NotSupported.sol deleted file mode 100644 index 486c7f0a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165NotSupported.sol +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -contract ERC165NotSupported {} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165CheckerMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165CheckerMock.sol deleted file mode 100644 index bda5cfc7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165CheckerMock.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC165Checker.sol"; - -contract ERC165CheckerMock { - using ERC165Checker for address; - - function supportsERC165(address account) public view returns (bool) { - return account.supportsERC165(); - } - - function supportsInterface(address account, bytes4 interfaceId) public view returns (bool) { - return account.supportsInterface(interfaceId); - } - - function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) public view returns (bool) { - return account.supportsAllInterfaces(interfaceIds); - } - - function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) public view returns (bool[] memory) { - return account.getSupportedInterfaces(interfaceIds); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165Mock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165Mock.sol deleted file mode 100644 index c123d0ab..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165Mock.sol +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC165.sol"; - -contract ERC165Mock is ERC165 {} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165StorageMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165StorageMock.sol deleted file mode 100644 index 4b0bae90..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC165StorageMock.sol +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC165Storage.sol"; - -contract ERC165StorageMock is ERC165Storage { - function registerInterface(bytes4 interfaceId) public { - _registerInterface(interfaceId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1820ImplementerMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1820ImplementerMock.sol deleted file mode 100644 index a6012d7f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC1820ImplementerMock.sol +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC1820Implementer.sol"; - -contract ERC1820ImplementerMock is ERC1820Implementer { - function registerInterfaceForAddress(bytes32 interfaceHash, address account) public { - _registerInterfaceForAddress(interfaceHash, account); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20BurnableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20BurnableMock.sol deleted file mode 100644 index 0ed6c0c9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20BurnableMock.sol +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Burnable.sol"; - -contract ERC20BurnableMock is ERC20Burnable { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20CappedMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20CappedMock.sol deleted file mode 100644 index edb36f20..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20CappedMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Capped.sol"; - -contract ERC20CappedMock is ERC20Capped { - constructor( - string memory name, - string memory symbol, - uint256 cap - ) ERC20(name, symbol) ERC20Capped(cap) {} - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20DecimalsMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20DecimalsMock.sol deleted file mode 100644 index 924c3af3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20DecimalsMock.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/ERC20.sol"; - -contract ERC20DecimalsMock is ERC20 { - uint8 private immutable _decimals; - - constructor( - string memory name_, - string memory symbol_, - uint8 decimals_ - ) ERC20(name_, symbol_) { - _decimals = decimals_; - } - - function decimals() public view virtual override returns (uint8) { - return _decimals; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20FlashMintMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20FlashMintMock.sol deleted file mode 100644 index 0bb7871f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20FlashMintMock.sol +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20FlashMint.sol"; - -contract ERC20FlashMintMock is ERC20FlashMint { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20Mock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20Mock.sol deleted file mode 100644 index fd7f991b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20Mock.sol +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/ERC20.sol"; - -// mock class using ERC20 -contract ERC20Mock is ERC20 { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) payable ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - function burn(address account, uint256 amount) public { - _burn(account, amount); - } - - function transferInternal( - address from, - address to, - uint256 value - ) public { - _transfer(from, to, value); - } - - function approveInternal( - address owner, - address spender, - uint256 value - ) public { - _approve(owner, spender, value); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20PausableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20PausableMock.sol deleted file mode 100644 index 19160ba6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20PausableMock.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Pausable.sol"; - -// mock class using ERC20Pausable -contract ERC20PausableMock is ERC20Pausable { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } - - function pause() external { - _pause(); - } - - function unpause() external { - _unpause(); - } - - function mint(address to, uint256 amount) public { - _mint(to, amount); - } - - function burn(address from, uint256 amount) public { - _burn(from, amount); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20PermitMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20PermitMock.sol deleted file mode 100644 index 20302bfa..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20PermitMock.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/draft-ERC20Permit.sol"; - -contract ERC20PermitMock is ERC20Permit { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) payable ERC20(name, symbol) ERC20Permit(name) { - _mint(initialAccount, initialBalance); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20SnapshotMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20SnapshotMock.sol deleted file mode 100644 index cb304832..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20SnapshotMock.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Snapshot.sol"; - -contract ERC20SnapshotMock is ERC20Snapshot { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } - - function snapshot() public { - _snapshot(); - } - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - function burn(address account, uint256 amount) public { - _burn(account, amount); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20VotesCompMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20VotesCompMock.sol deleted file mode 100644 index 171071fd..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20VotesCompMock.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20VotesComp.sol"; - -contract ERC20VotesCompMock is ERC20VotesComp { - constructor(string memory name, string memory symbol) ERC20(name, symbol) ERC20Permit(name) {} - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - function burn(address account, uint256 amount) public { - _burn(account, amount); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20VotesMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20VotesMock.sol deleted file mode 100644 index 0975e8b9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20VotesMock.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Votes.sol"; - -contract ERC20VotesMock is ERC20Votes { - constructor(string memory name, string memory symbol) ERC20(name, symbol) ERC20Permit(name) {} - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - function burn(address account, uint256 amount) public { - _burn(account, amount); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20WrapperMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20WrapperMock.sol deleted file mode 100644 index cf34a7a5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC20WrapperMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Wrapper.sol"; - -contract ERC20WrapperMock is ERC20Wrapper { - constructor( - IERC20 _underlyingToken, - string memory name, - string memory symbol - ) ERC20(name, symbol) ERC20Wrapper(_underlyingToken) {} - - function recover(address account) public returns (uint256) { - return _recover(account); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC2771ContextMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC2771ContextMock.sol deleted file mode 100644 index ee111d1a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC2771ContextMock.sol +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.9; - -import "./ContextMock.sol"; -import "../metatx/ERC2771Context.sol"; - -// By inheriting from ERC2771Context, Context's internal functions are overridden automatically -contract ERC2771ContextMock is ContextMock, ERC2771Context { - /// @custom:oz-upgrades-unsafe-allow constructor - constructor(address trustedForwarder) ERC2771Context(trustedForwarder) { - emit Sender(_msgSender()); // _msgSender() should be accessible during construction - } - - function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) { - return ERC2771Context._msgSender(); - } - - function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) { - return ERC2771Context._msgData(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC3156FlashBorrowerMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC3156FlashBorrowerMock.sol deleted file mode 100644 index 288a278f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC3156FlashBorrowerMock.sol +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/IERC20.sol"; -import "../interfaces/IERC3156.sol"; -import "../utils/Address.sol"; - -/** - * @dev WARNING: this IERC3156FlashBorrower mock implementation is for testing purposes ONLY. - * Writing a secure flash lock borrower is not an easy task, and should be done with the utmost care. - * This is not an example of how it should be done, and no pattern present in this mock should be considered secure. - * Following best practices, always have your contract properly audited before using them to manipulate important funds on - * live networks. - */ -contract ERC3156FlashBorrowerMock is IERC3156FlashBorrower { - bytes32 internal constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); - - bool immutable _enableApprove; - bool immutable _enableReturn; - - event BalanceOf(address token, address account, uint256 value); - event TotalSupply(address token, uint256 value); - - constructor(bool enableReturn, bool enableApprove) { - _enableApprove = enableApprove; - _enableReturn = enableReturn; - } - - function onFlashLoan( - address, /*initiator*/ - address token, - uint256 amount, - uint256 fee, - bytes calldata data - ) public override returns (bytes32) { - require(msg.sender == token); - - emit BalanceOf(token, address(this), IERC20(token).balanceOf(address(this))); - emit TotalSupply(token, IERC20(token).totalSupply()); - - if (data.length > 0) { - // WARNING: This code is for testing purposes only! Do not use. - Address.functionCall(token, data); - } - - if (_enableApprove) { - IERC20(token).approve(token, amount + fee); - } - - return _enableReturn ? _RETURN_VALUE : bytes32(0); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721BurnableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721BurnableMock.sol deleted file mode 100644 index b30dbf53..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721BurnableMock.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Burnable.sol"; - -contract ERC721BurnableMock is ERC721Burnable { - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint( - address to, - uint256 tokenId, - bytes memory _data - ) public { - _safeMint(to, tokenId, _data); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721EnumerableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721EnumerableMock.sol deleted file mode 100644 index 73aee9d0..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721EnumerableMock.sol +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Enumerable.sol"; - -/** - * @title ERC721Mock - * This mock just provides a public safeMint, mint, and burn functions for testing purposes - */ -contract ERC721EnumerableMock is ERC721Enumerable { - string private _baseTokenURI; - - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function _baseURI() internal view virtual override returns (string memory) { - return _baseTokenURI; - } - - function setBaseURI(string calldata newBaseTokenURI) public { - _baseTokenURI = newBaseTokenURI; - } - - function baseURI() public view returns (string memory) { - return _baseURI(); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint( - address to, - uint256 tokenId, - bytes memory _data - ) public { - _safeMint(to, tokenId, _data); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721Mock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721Mock.sol deleted file mode 100644 index 74a09233..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721Mock.sol +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/ERC721.sol"; - -/** - * @title ERC721Mock - * This mock just provides a public safeMint, mint, and burn functions for testing purposes - */ -contract ERC721Mock is ERC721 { - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function baseURI() public view returns (string memory) { - return _baseURI(); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint( - address to, - uint256 tokenId, - bytes memory _data - ) public { - _safeMint(to, tokenId, _data); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721PausableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721PausableMock.sol deleted file mode 100644 index 8d8e818f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721PausableMock.sol +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Pausable.sol"; - -/** - * @title ERC721PausableMock - * This mock just provides a public mint, burn and exists functions for testing purposes - */ -contract ERC721PausableMock is ERC721Pausable { - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function pause() external { - _pause(); - } - - function unpause() external { - _unpause(); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint( - address to, - uint256 tokenId, - bytes memory _data - ) public { - _safeMint(to, tokenId, _data); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721ReceiverMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721ReceiverMock.sol deleted file mode 100644 index a4923bfd..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721ReceiverMock.sol +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/IERC721Receiver.sol"; - -contract ERC721ReceiverMock is IERC721Receiver { - enum Error { - None, - RevertWithMessage, - RevertWithoutMessage, - Panic - } - - bytes4 private immutable _retval; - Error private immutable _error; - - event Received(address operator, address from, uint256 tokenId, bytes data, uint256 gas); - - constructor(bytes4 retval, Error error) { - _retval = retval; - _error = error; - } - - function onERC721Received( - address operator, - address from, - uint256 tokenId, - bytes memory data - ) public override returns (bytes4) { - if (_error == Error.RevertWithMessage) { - revert("ERC721ReceiverMock: reverting"); - } else if (_error == Error.RevertWithoutMessage) { - revert(); - } else if (_error == Error.Panic) { - uint256 a = uint256(0) / uint256(0); - a; - } - emit Received(operator, from, tokenId, data, gasleft()); - return _retval; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721RoyaltyMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721RoyaltyMock.sol deleted file mode 100644 index 83a9074e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721RoyaltyMock.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Royalty.sol"; - -contract ERC721RoyaltyMock is ERC721Royalty { - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function setTokenRoyalty( - uint256 tokenId, - address recipient, - uint96 fraction - ) public { - _setTokenRoyalty(tokenId, recipient, fraction); - } - - function setDefaultRoyalty(address recipient, uint96 fraction) public { - _setDefaultRoyalty(recipient, fraction); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } - - function deleteDefaultRoyalty() public { - _deleteDefaultRoyalty(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721URIStorageMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721URIStorageMock.sol deleted file mode 100644 index 9c3480f7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721URIStorageMock.sol +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721URIStorage.sol"; - -/** - * @title ERC721Mock - * This mock just provides a public safeMint, mint, and burn functions for testing purposes - */ -contract ERC721URIStorageMock is ERC721URIStorage { - string private _baseTokenURI; - - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function _baseURI() internal view virtual override returns (string memory) { - return _baseTokenURI; - } - - function setBaseURI(string calldata newBaseTokenURI) public { - _baseTokenURI = newBaseTokenURI; - } - - function baseURI() public view returns (string memory) { - return _baseURI(); - } - - function setTokenURI(uint256 tokenId, string memory _tokenURI) public { - _setTokenURI(tokenId, _tokenURI); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint( - address to, - uint256 tokenId, - bytes memory _data - ) public { - _safeMint(to, tokenId, _data); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721VotesMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721VotesMock.sol deleted file mode 100644 index 0755ace6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC721VotesMock.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/draft-ERC721Votes.sol"; - -contract ERC721VotesMock is ERC721Votes { - constructor(string memory name, string memory symbol) ERC721(name, symbol) EIP712(name, "1") {} - - function getTotalSupply() public view returns (uint256) { - return _getTotalSupply(); - } - - function mint(address account, uint256 tokenId) public { - _mint(account, tokenId); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC777Mock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC777Mock.sol deleted file mode 100644 index f8a3b678..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC777Mock.sol +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Context.sol"; -import "../token/ERC777/ERC777.sol"; - -contract ERC777Mock is Context, ERC777 { - event BeforeTokenTransfer(); - - constructor( - address initialHolder, - uint256 initialBalance, - string memory name, - string memory symbol, - address[] memory defaultOperators - ) ERC777(name, symbol, defaultOperators) { - _mint(initialHolder, initialBalance, "", ""); - } - - function mintInternal( - address to, - uint256 amount, - bytes memory userData, - bytes memory operatorData - ) public { - _mint(to, amount, userData, operatorData); - } - - function mintInternalExtended( - address to, - uint256 amount, - bytes memory userData, - bytes memory operatorData, - bool requireReceptionAck - ) public { - _mint(to, amount, userData, operatorData, requireReceptionAck); - } - - function approveInternal( - address holder, - address spender, - uint256 value - ) public { - _approve(holder, spender, value); - } - - function _beforeTokenTransfer( - address, - address, - address, - uint256 - ) internal override { - emit BeforeTokenTransfer(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC777SenderRecipientMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC777SenderRecipientMock.sol deleted file mode 100644 index 169912f6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ERC777SenderRecipientMock.sol +++ /dev/null @@ -1,161 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC777/IERC777.sol"; -import "../token/ERC777/IERC777Sender.sol"; -import "../token/ERC777/IERC777Recipient.sol"; -import "../utils/Context.sol"; -import "../utils/introspection/IERC1820Registry.sol"; -import "../utils/introspection/ERC1820Implementer.sol"; - -contract ERC777SenderRecipientMock is Context, IERC777Sender, IERC777Recipient, ERC1820Implementer { - event TokensToSendCalled( - address operator, - address from, - address to, - uint256 amount, - bytes data, - bytes operatorData, - address token, - uint256 fromBalance, - uint256 toBalance - ); - - event TokensReceivedCalled( - address operator, - address from, - address to, - uint256 amount, - bytes data, - bytes operatorData, - address token, - uint256 fromBalance, - uint256 toBalance - ); - - // Emitted in ERC777Mock. Here for easier decoding - event BeforeTokenTransfer(); - - bool private _shouldRevertSend; - bool private _shouldRevertReceive; - - IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); - - bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); - bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); - - function tokensToSend( - address operator, - address from, - address to, - uint256 amount, - bytes calldata userData, - bytes calldata operatorData - ) external override { - if (_shouldRevertSend) { - revert(); - } - - IERC777 token = IERC777(_msgSender()); - - uint256 fromBalance = token.balanceOf(from); - // when called due to burn, to will be the zero address, which will have a balance of 0 - uint256 toBalance = token.balanceOf(to); - - emit TokensToSendCalled( - operator, - from, - to, - amount, - userData, - operatorData, - address(token), - fromBalance, - toBalance - ); - } - - function tokensReceived( - address operator, - address from, - address to, - uint256 amount, - bytes calldata userData, - bytes calldata operatorData - ) external override { - if (_shouldRevertReceive) { - revert(); - } - - IERC777 token = IERC777(_msgSender()); - - uint256 fromBalance = token.balanceOf(from); - // when called due to burn, to will be the zero address, which will have a balance of 0 - uint256 toBalance = token.balanceOf(to); - - emit TokensReceivedCalled( - operator, - from, - to, - amount, - userData, - operatorData, - address(token), - fromBalance, - toBalance - ); - } - - function senderFor(address account) public { - _registerInterfaceForAddress(_TOKENS_SENDER_INTERFACE_HASH, account); - - address self = address(this); - if (account == self) { - registerSender(self); - } - } - - function registerSender(address sender) public { - _erc1820.setInterfaceImplementer(address(this), _TOKENS_SENDER_INTERFACE_HASH, sender); - } - - function recipientFor(address account) public { - _registerInterfaceForAddress(_TOKENS_RECIPIENT_INTERFACE_HASH, account); - - address self = address(this); - if (account == self) { - registerRecipient(self); - } - } - - function registerRecipient(address recipient) public { - _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, recipient); - } - - function setShouldRevertSend(bool shouldRevert) public { - _shouldRevertSend = shouldRevert; - } - - function setShouldRevertReceive(bool shouldRevert) public { - _shouldRevertReceive = shouldRevert; - } - - function send( - IERC777 token, - address to, - uint256 amount, - bytes memory data - ) public { - // This is 777's send function, not the Solidity send function - token.send(to, amount, data); // solhint-disable-line check-send-result - } - - function burn( - IERC777 token, - uint256 amount, - bytes memory data - ) public { - token.burn(amount, data); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EnumerableMapMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EnumerableMapMock.sol deleted file mode 100644 index 510647b5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EnumerableMapMock.sol +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/structs/EnumerableMap.sol"; - -contract EnumerableMapMock { - using EnumerableMap for EnumerableMap.UintToAddressMap; - - event OperationResult(bool result); - - EnumerableMap.UintToAddressMap private _map; - - function contains(uint256 key) public view returns (bool) { - return _map.contains(key); - } - - function set(uint256 key, address value) public { - bool result = _map.set(key, value); - emit OperationResult(result); - } - - function remove(uint256 key) public { - bool result = _map.remove(key); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _map.length(); - } - - function at(uint256 index) public view returns (uint256 key, address value) { - return _map.at(index); - } - - function tryGet(uint256 key) public view returns (bool, address) { - return _map.tryGet(key); - } - - function get(uint256 key) public view returns (address) { - return _map.get(key); - } - - function getWithMessage(uint256 key, string calldata errorMessage) public view returns (address) { - return _map.get(key, errorMessage); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EnumerableSetMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EnumerableSetMock.sol deleted file mode 100644 index 922ce46d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EnumerableSetMock.sol +++ /dev/null @@ -1,110 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/structs/EnumerableSet.sol"; - -// Bytes32Set -contract EnumerableBytes32SetMock { - using EnumerableSet for EnumerableSet.Bytes32Set; - - event OperationResult(bool result); - - EnumerableSet.Bytes32Set private _set; - - function contains(bytes32 value) public view returns (bool) { - return _set.contains(value); - } - - function add(bytes32 value) public { - bool result = _set.add(value); - emit OperationResult(result); - } - - function remove(bytes32 value) public { - bool result = _set.remove(value); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _set.length(); - } - - function at(uint256 index) public view returns (bytes32) { - return _set.at(index); - } - - function values() public view returns (bytes32[] memory) { - return _set.values(); - } -} - -// AddressSet -contract EnumerableAddressSetMock { - using EnumerableSet for EnumerableSet.AddressSet; - - event OperationResult(bool result); - - EnumerableSet.AddressSet private _set; - - function contains(address value) public view returns (bool) { - return _set.contains(value); - } - - function add(address value) public { - bool result = _set.add(value); - emit OperationResult(result); - } - - function remove(address value) public { - bool result = _set.remove(value); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _set.length(); - } - - function at(uint256 index) public view returns (address) { - return _set.at(index); - } - - function values() public view returns (address[] memory) { - return _set.values(); - } -} - -// UintSet -contract EnumerableUintSetMock { - using EnumerableSet for EnumerableSet.UintSet; - - event OperationResult(bool result); - - EnumerableSet.UintSet private _set; - - function contains(uint256 value) public view returns (bool) { - return _set.contains(value); - } - - function add(uint256 value) public { - bool result = _set.add(value); - emit OperationResult(result); - } - - function remove(uint256 value) public { - bool result = _set.remove(value); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _set.length(); - } - - function at(uint256 index) public view returns (uint256) { - return _set.at(index); - } - - function values() public view returns (uint256[] memory) { - return _set.values(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EtherReceiverMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EtherReceiverMock.sol deleted file mode 100644 index a11e646f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/EtherReceiverMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -contract EtherReceiverMock { - bool private _acceptEther; - - function setAcceptEther(bool acceptEther) public { - _acceptEther = acceptEther; - } - - receive() external payable { - if (!_acceptEther) { - revert(); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorCompMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorCompMock.sol deleted file mode 100644 index 9dcbc536..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorCompMock.sol +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotesComp.sol"; - -contract GovernorCompMock is GovernorVotesComp, GovernorCountingSimple { - constructor(string memory name_, ERC20VotesComp token_) Governor(name_) GovernorVotesComp(token_) {} - - function quorum(uint256) public pure override returns (uint256) { - return 0; - } - - function votingDelay() public pure override returns (uint256) { - return 4; - } - - function votingPeriod() public pure override returns (uint256) { - return 16; - } - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } - - function getVotes(address account, uint256 blockNumber) - public - view - virtual - override(IGovernor, GovernorVotesComp) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorCompatibilityBravoMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorCompatibilityBravoMock.sol deleted file mode 100644 index 60afbb91..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorCompatibilityBravoMock.sol +++ /dev/null @@ -1,140 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/compatibility/GovernorCompatibilityBravo.sol"; -import "../governance/extensions/GovernorTimelockCompound.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorVotesComp.sol"; - -contract GovernorCompatibilityBravoMock is - GovernorCompatibilityBravo, - GovernorSettings, - GovernorTimelockCompound, - GovernorVotesComp -{ - constructor( - string memory name_, - ERC20VotesComp token_, - uint256 votingDelay_, - uint256 votingPeriod_, - uint256 proposalThreshold_, - ICompoundTimelock timelock_ - ) - Governor(name_) - GovernorTimelockCompound(timelock_) - GovernorSettings(votingDelay_, votingPeriod_, proposalThreshold_) - GovernorVotesComp(token_) - {} - - function supportsInterface(bytes4 interfaceId) - public - view - virtual - override(IERC165, Governor, GovernorTimelockCompound) - returns (bool) - { - return super.supportsInterface(interfaceId); - } - - function quorum(uint256) public pure override returns (uint256) { - return 0; - } - - function state(uint256 proposalId) - public - view - virtual - override(IGovernor, Governor, GovernorTimelockCompound) - returns (ProposalState) - { - return super.state(proposalId); - } - - function proposalEta(uint256 proposalId) - public - view - virtual - override(IGovernorTimelock, GovernorTimelockCompound) - returns (uint256) - { - return super.proposalEta(proposalId); - } - - function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) { - return super.proposalThreshold(); - } - - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public virtual override(IGovernor, Governor, GovernorCompatibilityBravo) returns (uint256) { - return super.propose(targets, values, calldatas, description); - } - - function queue( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public virtual override(IGovernorTimelock, GovernorTimelockCompound) returns (uint256) { - return super.queue(targets, values, calldatas, salt); - } - - function execute( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public payable virtual override(IGovernor, Governor) returns (uint256) { - return super.execute(targets, values, calldatas, salt); - } - - function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual override(Governor, GovernorTimelockCompound) { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - /** - * @notice WARNING: this is for mock purposes only. Ability to the _cancel function should be restricted for live - * deployments. - */ - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } - - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) internal virtual override(Governor, GovernorTimelockCompound) returns (uint256 proposalId) { - return super._cancel(targets, values, calldatas, salt); - } - - function getVotes(address account, uint256 blockNumber) - public - view - virtual - override(IGovernor, GovernorVotesComp) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function _executor() internal view virtual override(Governor, GovernorTimelockCompound) returns (address) { - return super._executor(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorMock.sol deleted file mode 100644 index 85233f55..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorMock.sol +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorProposalThreshold.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotesQuorumFraction.sol"; - -contract GovernorMock is - GovernorProposalThreshold, - GovernorSettings, - GovernorVotesQuorumFraction, - GovernorCountingSimple -{ - constructor( - string memory name_, - IVotes token_, - uint256 votingDelay_, - uint256 votingPeriod_, - uint256 quorumNumerator_ - ) - Governor(name_) - GovernorSettings(votingDelay_, votingPeriod_, 0) - GovernorVotes(token_) - GovernorVotesQuorumFraction(quorumNumerator_) - {} - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } - - function getVotes(address account, uint256 blockNumber) - public - view - virtual - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) { - return super.proposalThreshold(); - } - - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public virtual override(Governor, GovernorProposalThreshold) returns (uint256) { - return super.propose(targets, values, calldatas, description); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorPreventLateQuorumMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorPreventLateQuorumMock.sol deleted file mode 100644 index 7de50a01..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorPreventLateQuorumMock.sol +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorPreventLateQuorum.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotes.sol"; - -contract GovernorPreventLateQuorumMock is - GovernorSettings, - GovernorVotes, - GovernorCountingSimple, - GovernorPreventLateQuorum -{ - uint256 private _quorum; - - constructor( - string memory name_, - IVotes token_, - uint256 votingDelay_, - uint256 votingPeriod_, - uint256 quorum_, - uint64 voteExtension_ - ) - Governor(name_) - GovernorSettings(votingDelay_, votingPeriod_, 0) - GovernorVotes(token_) - GovernorPreventLateQuorum(voteExtension_) - { - _quorum = quorum_; - } - - function quorum(uint256) public view virtual override returns (uint256) { - return _quorum; - } - - function proposalDeadline(uint256 proposalId) - public - view - virtual - override(Governor, GovernorPreventLateQuorum) - returns (uint256) - { - return super.proposalDeadline(proposalId); - } - - function proposalThreshold() public view virtual override(Governor, GovernorSettings) returns (uint256) { - return super.proposalThreshold(); - } - - function _castVote( - uint256 proposalId, - address account, - uint8 support, - string memory reason - ) internal virtual override(Governor, GovernorPreventLateQuorum) returns (uint256) { - return super._castVote(proposalId, account, support, reason); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorTimelockCompoundMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorTimelockCompoundMock.sol deleted file mode 100644 index aeba5b86..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorTimelockCompoundMock.sol +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorTimelockCompound.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotesQuorumFraction.sol"; - -contract GovernorTimelockCompoundMock is - GovernorSettings, - GovernorTimelockCompound, - GovernorVotesQuorumFraction, - GovernorCountingSimple -{ - constructor( - string memory name_, - IVotes token_, - uint256 votingDelay_, - uint256 votingPeriod_, - ICompoundTimelock timelock_, - uint256 quorumNumerator_ - ) - Governor(name_) - GovernorTimelockCompound(timelock_) - GovernorSettings(votingDelay_, votingPeriod_, 0) - GovernorVotes(token_) - GovernorVotesQuorumFraction(quorumNumerator_) - {} - - function supportsInterface(bytes4 interfaceId) - public - view - virtual - override(Governor, GovernorTimelockCompound) - returns (bool) - { - return super.supportsInterface(interfaceId); - } - - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } - - /** - * Overriding nightmare - */ - function state(uint256 proposalId) - public - view - virtual - override(Governor, GovernorTimelockCompound) - returns (ProposalState) - { - return super.state(proposalId); - } - - function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) { - return super.proposalThreshold(); - } - - function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual override(Governor, GovernorTimelockCompound) { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) internal virtual override(Governor, GovernorTimelockCompound) returns (uint256 proposalId) { - return super._cancel(targets, values, calldatas, salt); - } - - function getVotes(address account, uint256 blockNumber) - public - view - virtual - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function _executor() internal view virtual override(Governor, GovernorTimelockCompound) returns (address) { - return super._executor(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorTimelockControlMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorTimelockControlMock.sol deleted file mode 100644 index 97376c82..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorTimelockControlMock.sol +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorTimelockControl.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotesQuorumFraction.sol"; - -contract GovernorTimelockControlMock is - GovernorSettings, - GovernorTimelockControl, - GovernorVotesQuorumFraction, - GovernorCountingSimple -{ - constructor( - string memory name_, - IVotes token_, - uint256 votingDelay_, - uint256 votingPeriod_, - TimelockController timelock_, - uint256 quorumNumerator_ - ) - Governor(name_) - GovernorTimelockControl(timelock_) - GovernorSettings(votingDelay_, votingPeriod_, 0) - GovernorVotes(token_) - GovernorVotesQuorumFraction(quorumNumerator_) - {} - - function supportsInterface(bytes4 interfaceId) - public - view - virtual - override(Governor, GovernorTimelockControl) - returns (bool) - { - return super.supportsInterface(interfaceId); - } - - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, descriptionHash); - } - - /** - * Overriding nightmare - */ - function state(uint256 proposalId) - public - view - virtual - override(Governor, GovernorTimelockControl) - returns (ProposalState) - { - return super.state(proposalId); - } - - function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) { - return super.proposalThreshold(); - } - - function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual override(Governor, GovernorTimelockControl) { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal virtual override(Governor, GovernorTimelockControl) returns (uint256 proposalId) { - return super._cancel(targets, values, calldatas, descriptionHash); - } - - function getVotes(address account, uint256 blockNumber) - public - view - virtual - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function _executor() internal view virtual override(Governor, GovernorTimelockControl) returns (address) { - return super._executor(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorVoteMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorVoteMock.sol deleted file mode 100644 index 23ccf6bc..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/GovernorVoteMock.sol +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotes.sol"; - -contract GovernorVoteMocks is GovernorVotes, GovernorCountingSimple { - constructor(string memory name_, IVotes token_) Governor(name_) GovernorVotes(token_) {} - - function quorum(uint256) public pure override returns (uint256) { - return 0; - } - - function votingDelay() public pure override returns (uint256) { - return 4; - } - - function votingPeriod() public pure override returns (uint256) { - return 16; - } - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } - - function getVotes(address account, uint256 blockNumber) - public - view - virtual - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/InitializableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/InitializableMock.sol deleted file mode 100644 index 630e8bbf..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/InitializableMock.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../proxy/utils/Initializable.sol"; - -/** - * @title InitializableMock - * @dev This contract is a mock to test initializable functionality - */ -contract InitializableMock is Initializable { - bool public initializerRan; - bool public onlyInitializingRan; - uint256 public x; - - function initialize() public initializer { - initializerRan = true; - } - - function initializeOnlyInitializing() public onlyInitializing { - onlyInitializingRan = true; - } - - function initializerNested() public initializer { - initialize(); - } - - function onlyInitializingNested() public initializer { - initializeOnlyInitializing(); - } - - function initializeWithX(uint256 _x) public payable initializer { - x = _x; - } - - function nonInitializable(uint256 _x) public payable { - x = _x; - } - - function fail() public pure { - require(false, "InitializableMock forced failure"); - } -} - -contract ConstructorInitializableMock is Initializable { - bool public initializerRan; - bool public onlyInitializingRan; - - constructor() initializer { - initialize(); - initializeOnlyInitializing(); - } - - function initialize() public initializer { - initializerRan = true; - } - - function initializeOnlyInitializing() public onlyInitializing { - onlyInitializingRan = true; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MathMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MathMock.sol deleted file mode 100644 index c651b6bb..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MathMock.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/Math.sol"; - -contract MathMock { - function max(uint256 a, uint256 b) public pure returns (uint256) { - return Math.max(a, b); - } - - function min(uint256 a, uint256 b) public pure returns (uint256) { - return Math.min(a, b); - } - - function average(uint256 a, uint256 b) public pure returns (uint256) { - return Math.average(a, b); - } - - function ceilDiv(uint256 a, uint256 b) public pure returns (uint256) { - return Math.ceilDiv(a, b); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MerkleProofWrapper.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MerkleProofWrapper.sol deleted file mode 100644 index 1e188df3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MerkleProofWrapper.sol +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/cryptography/MerkleProof.sol"; - -contract MerkleProofWrapper { - function verify( - bytes32[] memory proof, - bytes32 root, - bytes32 leaf - ) public pure returns (bool) { - return MerkleProof.verify(proof, root, leaf); - } - - function processProof(bytes32[] memory proof, bytes32 leaf) public pure returns (bytes32) { - return MerkleProof.processProof(proof, leaf); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MulticallTest.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MulticallTest.sol deleted file mode 100644 index f1a3a9cf..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MulticallTest.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./MulticallTokenMock.sol"; - -contract MulticallTest { - function testReturnValues( - MulticallTokenMock multicallToken, - address[] calldata recipients, - uint256[] calldata amounts - ) external { - bytes[] memory calls = new bytes[](recipients.length); - for (uint256 i = 0; i < recipients.length; i++) { - calls[i] = abi.encodeWithSignature("transfer(address,uint256)", recipients[i], amounts[i]); - } - - bytes[] memory results = multicallToken.multicall(calls); - for (uint256 i = 0; i < results.length; i++) { - require(abi.decode(results[i], (bool))); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MulticallTokenMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MulticallTokenMock.sol deleted file mode 100644 index de379681..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MulticallTokenMock.sol +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Multicall.sol"; -import "./ERC20Mock.sol"; - -contract MulticallTokenMock is ERC20Mock, Multicall { - constructor(uint256 initialBalance) ERC20Mock("MulticallToken", "BCT", msg.sender, initialBalance) {} -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MultipleInheritanceInitializableMocks.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MultipleInheritanceInitializableMocks.sol deleted file mode 100644 index f8b6e465..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/MultipleInheritanceInitializableMocks.sol +++ /dev/null @@ -1,136 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../proxy/utils/Initializable.sol"; - -// Sample contracts showing upgradeability with multiple inheritance. -// Child contract inherits from Father and Mother contracts, and Father extends from Gramps. -// -// Human -// / \ -// | Gramps -// | | -// Mother Father -// | | -// -- Child -- - -/** - * Sample base intializable contract that is a human - */ -contract SampleHuman is Initializable { - bool public isHuman; - - function initialize() public initializer { - __SampleHuman_init(); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleHuman_init() internal onlyInitializing { - __SampleHuman_init_unchained(); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleHuman_init_unchained() internal onlyInitializing { - isHuman = true; - } -} - -/** - * Sample base intializable contract that defines a field mother - */ -contract SampleMother is Initializable, SampleHuman { - uint256 public mother; - - function initialize(uint256 value) public virtual initializer { - __SampleMother_init(value); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleMother_init(uint256 value) internal onlyInitializing { - __SampleHuman_init(); - __SampleMother_init_unchained(value); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleMother_init_unchained(uint256 value) internal onlyInitializing { - mother = value; - } -} - -/** - * Sample base intializable contract that defines a field gramps - */ -contract SampleGramps is Initializable, SampleHuman { - string public gramps; - - function initialize(string memory value) public virtual initializer { - __SampleGramps_init(value); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleGramps_init(string memory value) internal onlyInitializing { - __SampleHuman_init(); - __SampleGramps_init_unchained(value); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleGramps_init_unchained(string memory value) internal onlyInitializing { - gramps = value; - } -} - -/** - * Sample base intializable contract that defines a field father and extends from gramps - */ -contract SampleFather is Initializable, SampleGramps { - uint256 public father; - - function initialize(string memory _gramps, uint256 _father) public initializer { - __SampleFather_init(_gramps, _father); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleFather_init(string memory _gramps, uint256 _father) internal onlyInitializing { - __SampleGramps_init(_gramps); - __SampleFather_init_unchained(_father); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleFather_init_unchained(uint256 _father) internal onlyInitializing { - father = _father; - } -} - -/** - * Child extends from mother, father (gramps) - */ -contract SampleChild is Initializable, SampleMother, SampleFather { - uint256 public child; - - function initialize( - uint256 _mother, - string memory _gramps, - uint256 _father, - uint256 _child - ) public initializer { - __SampleChild_init(_mother, _gramps, _father, _child); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleChild_init( - uint256 _mother, - string memory _gramps, - uint256 _father, - uint256 _child - ) internal onlyInitializing { - __SampleMother_init(_mother); - __SampleFather_init(_gramps, _father); - __SampleChild_init_unchained(_child); - } - - // solhint-disable-next-line func-name-mixedcase - function __SampleChild_init_unchained(uint256 _child) internal onlyInitializing { - child = _child; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/OwnableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/OwnableMock.sol deleted file mode 100644 index d60f1c40..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/OwnableMock.sol +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../access/Ownable.sol"; - -contract OwnableMock is Ownable {} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/PausableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/PausableMock.sol deleted file mode 100644 index 98bcfd59..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/PausableMock.sol +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../security/Pausable.sol"; - -contract PausableMock is Pausable { - bool public drasticMeasureTaken; - uint256 public count; - - constructor() { - drasticMeasureTaken = false; - count = 0; - } - - function normalProcess() external whenNotPaused { - count++; - } - - function drasticMeasure() external whenPaused { - drasticMeasureTaken = true; - } - - function pause() external { - _pause(); - } - - function unpause() external { - _unpause(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/PullPaymentMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/PullPaymentMock.sol deleted file mode 100644 index 8a708e30..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/PullPaymentMock.sol +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../security/PullPayment.sol"; - -// mock class using PullPayment -contract PullPaymentMock is PullPayment { - constructor() payable {} - - // test helper function to call asyncTransfer - function callTransfer(address dest, uint256 amount) public { - _asyncTransfer(dest, amount); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ReentrancyAttack.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ReentrancyAttack.sol deleted file mode 100644 index 4de18120..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ReentrancyAttack.sol +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Context.sol"; - -contract ReentrancyAttack is Context { - function callSender(bytes4 data) public { - (bool success, ) = _msgSender().call(abi.encodeWithSelector(data)); - require(success, "ReentrancyAttack: failed call"); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ReentrancyMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ReentrancyMock.sol deleted file mode 100644 index 43425dd6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/ReentrancyMock.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../security/ReentrancyGuard.sol"; -import "./ReentrancyAttack.sol"; - -contract ReentrancyMock is ReentrancyGuard { - uint256 public counter; - - constructor() { - counter = 0; - } - - function callback() external nonReentrant { - _count(); - } - - function countLocalRecursive(uint256 n) public nonReentrant { - if (n > 0) { - _count(); - countLocalRecursive(n - 1); - } - } - - function countThisRecursive(uint256 n) public nonReentrant { - if (n > 0) { - _count(); - (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); - require(success, "ReentrancyMock: failed call"); - } - } - - function countAndCall(ReentrancyAttack attacker) public nonReentrant { - _count(); - bytes4 func = bytes4(keccak256("callback()")); - attacker.callSender(func); - } - - function _count() private { - counter += 1; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/RegressionImplementation.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/RegressionImplementation.sol deleted file mode 100644 index be6b501c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/RegressionImplementation.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../proxy/utils/Initializable.sol"; - -contract Implementation1 is Initializable { - uint256 internal _value; - - function initialize() public initializer {} - - function setValue(uint256 _number) public { - _value = _number; - } -} - -contract Implementation2 is Initializable { - uint256 internal _value; - - function initialize() public initializer {} - - function setValue(uint256 _number) public { - _value = _number; - } - - function getValue() public view returns (uint256) { - return _value; - } -} - -contract Implementation3 is Initializable { - uint256 internal _value; - - function initialize() public initializer {} - - function setValue(uint256 _number) public { - _value = _number; - } - - function getValue(uint256 _number) public view returns (uint256) { - return _value + _number; - } -} - -contract Implementation4 is Initializable { - uint256 internal _value; - - function initialize() public initializer {} - - function setValue(uint256 _number) public { - _value = _number; - } - - function getValue() public view returns (uint256) { - return _value; - } - - fallback() external { - _value = 1; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeCastMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeCastMock.sol deleted file mode 100644 index d1f1aaab..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeCastMock.sol +++ /dev/null @@ -1,66 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/SafeCast.sol"; - -contract SafeCastMock { - using SafeCast for uint256; - using SafeCast for int256; - - function toUint256(int256 a) public pure returns (uint256) { - return a.toUint256(); - } - - function toUint224(uint256 a) public pure returns (uint224) { - return a.toUint224(); - } - - function toUint128(uint256 a) public pure returns (uint128) { - return a.toUint128(); - } - - function toUint96(uint256 a) public pure returns (uint96) { - return a.toUint96(); - } - - function toUint64(uint256 a) public pure returns (uint64) { - return a.toUint64(); - } - - function toUint32(uint256 a) public pure returns (uint32) { - return a.toUint32(); - } - - function toUint16(uint256 a) public pure returns (uint16) { - return a.toUint16(); - } - - function toUint8(uint256 a) public pure returns (uint8) { - return a.toUint8(); - } - - function toInt256(uint256 a) public pure returns (int256) { - return a.toInt256(); - } - - function toInt128(int256 a) public pure returns (int128) { - return a.toInt128(); - } - - function toInt64(int256 a) public pure returns (int64) { - return a.toInt64(); - } - - function toInt32(int256 a) public pure returns (int32) { - return a.toInt32(); - } - - function toInt16(int256 a) public pure returns (int16) { - return a.toInt16(); - } - - function toInt8(int256 a) public pure returns (int8) { - return a.toInt8(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeERC20Helper.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeERC20Helper.sol deleted file mode 100644 index f3bcc397..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeERC20Helper.sol +++ /dev/null @@ -1,144 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Context.sol"; -import "../token/ERC20/IERC20.sol"; -import "../token/ERC20/utils/SafeERC20.sol"; - -contract ERC20ReturnFalseMock is Context { - uint256 private _allowance; - - // IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings, - // we write to a dummy state variable. - uint256 private _dummy; - - function transfer(address, uint256) public returns (bool) { - _dummy = 0; - return false; - } - - function transferFrom( - address, - address, - uint256 - ) public returns (bool) { - _dummy = 0; - return false; - } - - function approve(address, uint256) public returns (bool) { - _dummy = 0; - return false; - } - - function allowance(address, address) public view returns (uint256) { - require(_dummy == 0); // Dummy read from a state variable so that the function is view - return 0; - } -} - -contract ERC20ReturnTrueMock is Context { - mapping(address => uint256) private _allowances; - - // IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings, - // we write to a dummy state variable. - uint256 private _dummy; - - function transfer(address, uint256) public returns (bool) { - _dummy = 0; - return true; - } - - function transferFrom( - address, - address, - uint256 - ) public returns (bool) { - _dummy = 0; - return true; - } - - function approve(address, uint256) public returns (bool) { - _dummy = 0; - return true; - } - - function setAllowance(uint256 allowance_) public { - _allowances[_msgSender()] = allowance_; - } - - function allowance(address owner, address) public view returns (uint256) { - return _allowances[owner]; - } -} - -contract ERC20NoReturnMock is Context { - mapping(address => uint256) private _allowances; - - // IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings, - // we write to a dummy state variable. - uint256 private _dummy; - - function transfer(address, uint256) public { - _dummy = 0; - } - - function transferFrom( - address, - address, - uint256 - ) public { - _dummy = 0; - } - - function approve(address, uint256) public { - _dummy = 0; - } - - function setAllowance(uint256 allowance_) public { - _allowances[_msgSender()] = allowance_; - } - - function allowance(address owner, address) public view returns (uint256) { - return _allowances[owner]; - } -} - -contract SafeERC20Wrapper is Context { - using SafeERC20 for IERC20; - - IERC20 private _token; - - constructor(IERC20 token) { - _token = token; - } - - function transfer() public { - _token.safeTransfer(address(0), 0); - } - - function transferFrom() public { - _token.safeTransferFrom(address(0), address(0), 0); - } - - function approve(uint256 amount) public { - _token.safeApprove(address(0), amount); - } - - function increaseAllowance(uint256 amount) public { - _token.safeIncreaseAllowance(address(0), amount); - } - - function decreaseAllowance(uint256 amount) public { - _token.safeDecreaseAllowance(address(0), amount); - } - - function setAllowance(uint256 allowance_) public { - ERC20ReturnTrueMock(address(_token)).setAllowance(allowance_); - } - - function allowance() public view returns (uint256) { - return _token.allowance(address(0), address(0)); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeMathMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeMathMock.sol deleted file mode 100644 index 3d1f4727..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SafeMathMock.sol +++ /dev/null @@ -1,138 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/SafeMath.sol"; - -contract SafeMathMock { - function tryAdd(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.tryAdd(a, b); - } - - function trySub(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.trySub(a, b); - } - - function tryMul(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.tryMul(a, b); - } - - function tryDiv(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.tryDiv(a, b); - } - - function tryMod(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.tryMod(a, b); - } - - // using the do* naming convention to avoid warnings due to clashing opcode names - - function doAdd(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.add(a, b); - } - - function doSub(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.sub(a, b); - } - - function doMul(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.mul(a, b); - } - - function doDiv(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.div(a, b); - } - - function doMod(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.mod(a, b); - } - - function subWithMessage( - uint256 a, - uint256 b, - string memory errorMessage - ) public pure returns (uint256) { - return SafeMath.sub(a, b, errorMessage); - } - - function divWithMessage( - uint256 a, - uint256 b, - string memory errorMessage - ) public pure returns (uint256) { - return SafeMath.div(a, b, errorMessage); - } - - function modWithMessage( - uint256 a, - uint256 b, - string memory errorMessage - ) public pure returns (uint256) { - return SafeMath.mod(a, b, errorMessage); - } - - function addMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.add(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } - - function subMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.sub(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } - - function mulMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.mul(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } - - function divMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.div(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } - - function modMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.mod(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignatureCheckerMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignatureCheckerMock.sol deleted file mode 100644 index 3b399c1a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignatureCheckerMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/cryptography/SignatureChecker.sol"; - -contract SignatureCheckerMock { - using SignatureChecker for address; - - function isValidSignatureNow( - address signer, - bytes32 hash, - bytes memory signature - ) public view returns (bool) { - return signer.isValidSignatureNow(hash, signature); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignedMathMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignedMathMock.sol deleted file mode 100644 index 5a0b2709..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignedMathMock.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/SignedMath.sol"; - -contract SignedMathMock { - function max(int256 a, int256 b) public pure returns (int256) { - return SignedMath.max(a, b); - } - - function min(int256 a, int256 b) public pure returns (int256) { - return SignedMath.min(a, b); - } - - function average(int256 a, int256 b) public pure returns (int256) { - return SignedMath.average(a, b); - } - - function abs(int256 n) public pure returns (uint256) { - return SignedMath.abs(n); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignedSafeMathMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignedSafeMathMock.sol deleted file mode 100644 index 8d102179..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SignedSafeMathMock.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/SignedSafeMath.sol"; - -contract SignedSafeMathMock { - function mul(int256 a, int256 b) public pure returns (int256) { - return SignedSafeMath.mul(a, b); - } - - function div(int256 a, int256 b) public pure returns (int256) { - return SignedSafeMath.div(a, b); - } - - function sub(int256 a, int256 b) public pure returns (int256) { - return SignedSafeMath.sub(a, b); - } - - function add(int256 a, int256 b) public pure returns (int256) { - return SignedSafeMath.add(a, b); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SingleInheritanceInitializableMocks.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SingleInheritanceInitializableMocks.sol deleted file mode 100644 index 6c82dd20..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/SingleInheritanceInitializableMocks.sol +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../proxy/utils/Initializable.sol"; - -/** - * @title MigratableMockV1 - * @dev This contract is a mock to test initializable functionality through migrations - */ -contract MigratableMockV1 is Initializable { - uint256 public x; - - function initialize(uint256 value) public payable initializer { - x = value; - } -} - -/** - * @title MigratableMockV2 - * @dev This contract is a mock to test migratable functionality with params - */ -contract MigratableMockV2 is MigratableMockV1 { - bool internal _migratedV2; - uint256 public y; - - function migrate(uint256 value, uint256 anotherValue) public payable { - require(!_migratedV2); - x = value; - y = anotherValue; - _migratedV2 = true; - } -} - -/** - * @title MigratableMockV3 - * @dev This contract is a mock to test migratable functionality without params - */ -contract MigratableMockV3 is MigratableMockV2 { - bool internal _migratedV3; - - function migrate() public payable { - require(!_migratedV3); - uint256 oldX = x; - x = y; - y = oldX; - _migratedV3 = true; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/StorageSlotMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/StorageSlotMock.sol deleted file mode 100644 index 5d099fca..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/StorageSlotMock.sol +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/StorageSlot.sol"; - -contract StorageSlotMock { - using StorageSlot for bytes32; - - function setBoolean(bytes32 slot, bool value) public { - slot.getBooleanSlot().value = value; - } - - function setAddress(bytes32 slot, address value) public { - slot.getAddressSlot().value = value; - } - - function setBytes32(bytes32 slot, bytes32 value) public { - slot.getBytes32Slot().value = value; - } - - function setUint256(bytes32 slot, uint256 value) public { - slot.getUint256Slot().value = value; - } - - function getBoolean(bytes32 slot) public view returns (bool) { - return slot.getBooleanSlot().value; - } - - function getAddress(bytes32 slot) public view returns (address) { - return slot.getAddressSlot().value; - } - - function getBytes32(bytes32 slot) public view returns (bytes32) { - return slot.getBytes32Slot().value; - } - - function getUint256(bytes32 slot) public view returns (uint256) { - return slot.getUint256Slot().value; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/StringsMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/StringsMock.sol deleted file mode 100644 index f257734e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/StringsMock.sol +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Strings.sol"; - -contract StringsMock { - function fromUint256(uint256 value) public pure returns (string memory) { - return Strings.toString(value); - } - - function fromUint256Hex(uint256 value) public pure returns (string memory) { - return Strings.toHexString(value); - } - - function fromUint256HexFixed(uint256 value, uint256 length) public pure returns (string memory) { - return Strings.toHexString(value, length); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/TimersBlockNumberImpl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/TimersBlockNumberImpl.sol deleted file mode 100644 index 84633e6f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/TimersBlockNumberImpl.sol +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Timers.sol"; - -contract TimersBlockNumberImpl { - using Timers for Timers.BlockNumber; - - Timers.BlockNumber private _timer; - - function getDeadline() public view returns (uint64) { - return _timer.getDeadline(); - } - - function setDeadline(uint64 timestamp) public { - _timer.setDeadline(timestamp); - } - - function reset() public { - _timer.reset(); - } - - function isUnset() public view returns (bool) { - return _timer.isUnset(); - } - - function isStarted() public view returns (bool) { - return _timer.isStarted(); - } - - function isPending() public view returns (bool) { - return _timer.isPending(); - } - - function isExpired() public view returns (bool) { - return _timer.isExpired(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/TimersTimestampImpl.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/TimersTimestampImpl.sol deleted file mode 100644 index 07f9a1b3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/TimersTimestampImpl.sol +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Timers.sol"; - -contract TimersTimestampImpl { - using Timers for Timers.Timestamp; - - Timers.Timestamp private _timer; - - function getDeadline() public view returns (uint64) { - return _timer.getDeadline(); - } - - function setDeadline(uint64 timestamp) public { - _timer.setDeadline(timestamp); - } - - function reset() public { - _timer.reset(); - } - - function isUnset() public view returns (bool) { - return _timer.isUnset(); - } - - function isStarted() public view returns (bool) { - return _timer.isStarted(); - } - - function isPending() public view returns (bool) { - return _timer.isPending(); - } - - function isExpired() public view returns (bool) { - return _timer.isExpired(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/UUPS/UUPSLegacy.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/UUPS/UUPSLegacy.sol deleted file mode 100644 index 550a6221..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/UUPS/UUPSLegacy.sol +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./UUPSUpgradeableMock.sol"; - -// This contract implements the pre-4.5 UUPS upgrade function with a rollback test. -// It's used to test that newer UUPS contracts are considered valid upgrades by older UUPS contracts. -contract UUPSUpgradeableLegacyMock is UUPSUpgradeableMock { - // Inlined from ERC1967Upgrade - bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; - - // ERC1967Upgrade._setImplementation is private so we reproduce it here. - // An extra underscore prevents a name clash error. - function __setImplementation(address newImplementation) private { - require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); - StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; - } - - function _upgradeToAndCallSecureLegacyV1( - address newImplementation, - bytes memory data, - bool forceCall - ) internal { - address oldImplementation = _getImplementation(); - - // Initial upgrade and setup call - __setImplementation(newImplementation); - if (data.length > 0 || forceCall) { - Address.functionDelegateCall(newImplementation, data); - } - - // Perform rollback test if not already in progress - StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); - if (!rollbackTesting.value) { - // Trigger rollback using upgradeTo from the new implementation - rollbackTesting.value = true; - Address.functionDelegateCall( - newImplementation, - abi.encodeWithSignature("upgradeTo(address)", oldImplementation) - ); - rollbackTesting.value = false; - // Check rollback was effective - require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); - // Finally reset to the new implementation and log the upgrade - _upgradeTo(newImplementation); - } - } - - // hooking into the old mechanism - function upgradeTo(address newImplementation) external virtual override { - _upgradeToAndCallSecureLegacyV1(newImplementation, bytes(""), false); - } - - function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual override { - _upgradeToAndCallSecureLegacyV1(newImplementation, data, false); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/UUPS/UUPSUpgradeableMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/UUPS/UUPSUpgradeableMock.sol deleted file mode 100644 index 367303ec..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/UUPS/UUPSUpgradeableMock.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../CountersImpl.sol"; -import "../../proxy/utils/UUPSUpgradeable.sol"; - -contract UUPSUpgradeableMock is CountersImpl, UUPSUpgradeable { - // Not having any checks in this function is dangerous! Do not do this outside tests! - function _authorizeUpgrade(address) internal virtual override {} -} - -contract UUPSUpgradeableUnsafeMock is UUPSUpgradeableMock { - function upgradeTo(address newImplementation) external virtual override { - ERC1967Upgrade._upgradeToAndCall(newImplementation, bytes(""), false); - } - - function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual override { - ERC1967Upgrade._upgradeToAndCall(newImplementation, data, false); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/VotesMock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/VotesMock.sol deleted file mode 100644 index db06ee9a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/VotesMock.sol +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/utils/Votes.sol"; - -contract VotesMock is Votes { - mapping(address => uint256) private _balances; - mapping(uint256 => address) private _owners; - - constructor(string memory name) EIP712(name, "1") {} - - function getTotalSupply() public view returns (uint256) { - return _getTotalSupply(); - } - - function delegate(address account, address newDelegation) public { - return _delegate(account, newDelegation); - } - - function _getVotingUnits(address account) internal virtual override returns (uint256) { - return _balances[account]; - } - - function mint(address account, uint256 voteId) external { - _balances[account] += 1; - _owners[voteId] = account; - _transferVotingUnits(address(0), account, 1); - } - - function burn(uint256 voteId) external { - address owner = _owners[voteId]; - _balances[owner] -= 1; - _transferVotingUnits(owner, address(0), 1); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/compound/CompTimelock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/compound/CompTimelock.sol deleted file mode 100644 index 49ffa4b7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/compound/CompTimelock.sol +++ /dev/null @@ -1,174 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause -// solhint-disable private-vars-leading-underscore -/** - * Copyright 2020 Compound Labs, Inc. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the - * following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following - * disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote - * products derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -pragma solidity ^0.8.0; - -contract CompTimelock { - event NewAdmin(address indexed newAdmin); - event NewPendingAdmin(address indexed newPendingAdmin); - event NewDelay(uint256 indexed newDelay); - event CancelTransaction( - bytes32 indexed txHash, - address indexed target, - uint256 value, - string signature, - bytes data, - uint256 eta - ); - event ExecuteTransaction( - bytes32 indexed txHash, - address indexed target, - uint256 value, - string signature, - bytes data, - uint256 eta - ); - event QueueTransaction( - bytes32 indexed txHash, - address indexed target, - uint256 value, - string signature, - bytes data, - uint256 eta - ); - - uint256 public constant GRACE_PERIOD = 14 days; - uint256 public constant MINIMUM_DELAY = 2 days; - uint256 public constant MAXIMUM_DELAY = 30 days; - - address public admin; - address public pendingAdmin; - uint256 public delay; - - mapping(bytes32 => bool) public queuedTransactions; - - constructor(address admin_, uint256 delay_) { - require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); - require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); - - admin = admin_; - delay = delay_; - } - - receive() external payable {} - - function setDelay(uint256 delay_) public { - require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); - require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); - require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); - delay = delay_; - - emit NewDelay(delay); - } - - function acceptAdmin() public { - require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); - admin = msg.sender; - pendingAdmin = address(0); - - emit NewAdmin(admin); - } - - function setPendingAdmin(address pendingAdmin_) public { - require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); - pendingAdmin = pendingAdmin_; - - emit NewPendingAdmin(pendingAdmin); - } - - function queueTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) public returns (bytes32) { - require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); - require( - eta >= getBlockTimestamp() + delay, - "Timelock::queueTransaction: Estimated execution block must satisfy delay." - ); - - bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); - queuedTransactions[txHash] = true; - - emit QueueTransaction(txHash, target, value, signature, data, eta); - return txHash; - } - - function cancelTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) public { - require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); - - bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); - queuedTransactions[txHash] = false; - - emit CancelTransaction(txHash, target, value, signature, data, eta); - } - - function executeTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) public payable returns (bytes memory) { - require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); - - bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); - require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); - require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); - require(getBlockTimestamp() <= eta + GRACE_PERIOD, "Timelock::executeTransaction: Transaction is stale."); - - queuedTransactions[txHash] = false; - - bytes memory callData; - - if (bytes(signature).length == 0) { - callData = data; - } else { - callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); - } - - // solium-disable-next-line security/no-call-value - (bool success, bytes memory returnData) = target.call{value: value}(callData); - require(success, "Timelock::executeTransaction: Transaction execution reverted."); - - emit ExecuteTransaction(txHash, target, value, signature, data, eta); - - return returnData; - } - - function getBlockTimestamp() internal view returns (uint256) { - // solium-disable-next-line security/no-block-members - return block.timestamp; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor1.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor1.sol deleted file mode 100644 index bd524ee5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor1.sol +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.2; - -import "../../governance/Governor.sol"; -import "../../governance/extensions/GovernorCountingSimple.sol"; -import "../../governance/extensions/GovernorVotes.sol"; -import "../../governance/extensions/GovernorVotesQuorumFraction.sol"; -import "../../governance/extensions/GovernorTimelockControl.sol"; - -contract MyGovernor1 is - Governor, - GovernorTimelockControl, - GovernorVotes, - GovernorVotesQuorumFraction, - GovernorCountingSimple -{ - constructor(IVotes _token, TimelockController _timelock) - Governor("MyGovernor") - GovernorVotes(_token) - GovernorVotesQuorumFraction(4) - GovernorTimelockControl(_timelock) - {} - - function votingDelay() public pure override returns (uint256) { - return 1; // 1 block - } - - function votingPeriod() public pure override returns (uint256) { - return 45818; // 1 week - } - - // The following functions are overrides required by Solidity. - - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function getVotes(address account, uint256 blockNumber) - public - view - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function state(uint256 proposalId) public view override(Governor, GovernorTimelockControl) returns (ProposalState) { - return super.state(proposalId); - } - - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public override(Governor, IGovernor) returns (uint256) { - return super.propose(targets, values, calldatas, description); - } - - function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal override(Governor, GovernorTimelockControl) { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal override(Governor, GovernorTimelockControl) returns (uint256) { - return super._cancel(targets, values, calldatas, descriptionHash); - } - - function _executor() internal view override(Governor, GovernorTimelockControl) returns (address) { - return super._executor(); - } - - function supportsInterface(bytes4 interfaceId) - public - view - override(Governor, GovernorTimelockControl) - returns (bool) - { - return super.supportsInterface(interfaceId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor2.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor2.sol deleted file mode 100644 index 3a5c983e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor2.sol +++ /dev/null @@ -1,102 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.2; - -import "../../governance/Governor.sol"; -import "../../governance/extensions/GovernorProposalThreshold.sol"; -import "../../governance/extensions/GovernorCountingSimple.sol"; -import "../../governance/extensions/GovernorVotes.sol"; -import "../../governance/extensions/GovernorVotesQuorumFraction.sol"; -import "../../governance/extensions/GovernorTimelockControl.sol"; - -contract MyGovernor2 is - Governor, - GovernorTimelockControl, - GovernorProposalThreshold, - GovernorVotes, - GovernorVotesQuorumFraction, - GovernorCountingSimple -{ - constructor(IVotes _token, TimelockController _timelock) - Governor("MyGovernor") - GovernorVotes(_token) - GovernorVotesQuorumFraction(4) - GovernorTimelockControl(_timelock) - {} - - function votingDelay() public pure override returns (uint256) { - return 1; // 1 block - } - - function votingPeriod() public pure override returns (uint256) { - return 45818; // 1 week - } - - function proposalThreshold() public pure override returns (uint256) { - return 1000e18; - } - - // The following functions are overrides required by Solidity. - - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function getVotes(address account, uint256 blockNumber) - public - view - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function state(uint256 proposalId) public view override(Governor, GovernorTimelockControl) returns (ProposalState) { - return super.state(proposalId); - } - - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public override(Governor, GovernorProposalThreshold, IGovernor) returns (uint256) { - return super.propose(targets, values, calldatas, description); - } - - function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal override(Governor, GovernorTimelockControl) { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal override(Governor, GovernorTimelockControl) returns (uint256) { - return super._cancel(targets, values, calldatas, descriptionHash); - } - - function _executor() internal view override(Governor, GovernorTimelockControl) returns (address) { - return super._executor(); - } - - function supportsInterface(bytes4 interfaceId) - public - view - override(Governor, GovernorTimelockControl) - returns (bool) - { - return super.supportsInterface(interfaceId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor3.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor3.sol deleted file mode 100644 index 835a893a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/mocks/wizard/MyGovernor3.sol +++ /dev/null @@ -1,105 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.2; - -import "../../governance/Governor.sol"; -import "../../governance/compatibility/GovernorCompatibilityBravo.sol"; -import "../../governance/extensions/GovernorVotes.sol"; -import "../../governance/extensions/GovernorVotesQuorumFraction.sol"; -import "../../governance/extensions/GovernorTimelockControl.sol"; - -contract MyGovernor is - Governor, - GovernorTimelockControl, - GovernorCompatibilityBravo, - GovernorVotes, - GovernorVotesQuorumFraction -{ - constructor(IVotes _token, TimelockController _timelock) - Governor("MyGovernor") - GovernorVotes(_token) - GovernorVotesQuorumFraction(4) - GovernorTimelockControl(_timelock) - {} - - function votingDelay() public pure override returns (uint256) { - return 1; // 1 block - } - - function votingPeriod() public pure override returns (uint256) { - return 45818; // 1 week - } - - function proposalThreshold() public pure override returns (uint256) { - return 1000e18; - } - - // The following functions are overrides required by Solidity. - - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function getVotes(address account, uint256 blockNumber) - public - view - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function state(uint256 proposalId) - public - view - override(Governor, IGovernor, GovernorTimelockControl) - returns (ProposalState) - { - return super.state(proposalId); - } - - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public override(Governor, GovernorCompatibilityBravo, IGovernor) returns (uint256) { - return super.propose(targets, values, calldatas, description); - } - - function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal override(Governor, GovernorTimelockControl) { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) internal override(Governor, GovernorTimelockControl) returns (uint256) { - return super._cancel(targets, values, calldatas, descriptionHash); - } - - function _executor() internal view override(Governor, GovernorTimelockControl) returns (address) { - return super._executor(); - } - - function supportsInterface(bytes4 interfaceId) - public - view - override(Governor, IERC165, GovernorTimelockControl) - returns (bool) - { - return super.supportsInterface(interfaceId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/package.json b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/package.json deleted file mode 100644 index 6f4fcf35..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "@openzeppelin/contracts", - "description": "Secure Smart Contract library for Solidity", - "version": "4.5.0", - "files": [ - "**/*.sol", - "/build/contracts/*.json", - "!/mocks/**/*" - ], - "scripts": { - "prepare": "bash ../scripts/prepare-contracts-package.sh", - "prepare-docs": "cd ..; npm run prepare-docs" - }, - "repository": { - "type": "git", - "url": "https://github.com/OpenZeppelin/openzeppelin-contracts.git" - }, - "keywords": [ - "solidity", - "ethereum", - "smart", - "contracts", - "security", - "zeppelin" - ], - "author": "OpenZeppelin Community ", - "license": "MIT", - "bugs": { - "url": "https://github.com/OpenZeppelin/openzeppelin-contracts/issues" - }, - "homepage": "https://openzeppelin.com/contracts/" -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/Clones.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/Clones.sol deleted file mode 100644 index 31ece8f8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/Clones.sol +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol) - -pragma solidity ^0.8.0; - -/** - * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for - * deploying minimal proxy contracts, also known as "clones". - * - * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies - * > a minimal bytecode implementation that delegates all calls to a known, fixed address. - * - * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` - * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the - * deterministic method. - * - * _Available since v3.4._ - */ -library Clones { - /** - * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. - * - * This function uses the create opcode, which should never revert. - */ - function clone(address implementation) internal returns (address instance) { - assembly { - let ptr := mload(0x40) - mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) - mstore(add(ptr, 0x14), shl(0x60, implementation)) - mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) - instance := create(0, ptr, 0x37) - } - require(instance != address(0), "ERC1167: create failed"); - } - - /** - * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. - * - * This function uses the create2 opcode and a `salt` to deterministically deploy - * the clone. Using the same `implementation` and `salt` multiple time will revert, since - * the clones cannot be deployed twice at the same address. - */ - function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { - assembly { - let ptr := mload(0x40) - mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) - mstore(add(ptr, 0x14), shl(0x60, implementation)) - mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) - instance := create2(0, ptr, 0x37, salt) - } - require(instance != address(0), "ERC1167: create2 failed"); - } - - /** - * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. - */ - function predictDeterministicAddress( - address implementation, - bytes32 salt, - address deployer - ) internal pure returns (address predicted) { - assembly { - let ptr := mload(0x40) - mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) - mstore(add(ptr, 0x14), shl(0x60, implementation)) - mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) - mstore(add(ptr, 0x38), shl(0x60, deployer)) - mstore(add(ptr, 0x4c), salt) - mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) - predicted := keccak256(add(ptr, 0x37), 0x55) - } - } - - /** - * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. - */ - function predictDeterministicAddress(address implementation, bytes32 salt) - internal - view - returns (address predicted) - { - return predictDeterministicAddress(implementation, salt, address(this)); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol deleted file mode 100644 index 64e9d9f6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol) - -pragma solidity ^0.8.0; - -import "../Proxy.sol"; -import "./ERC1967Upgrade.sol"; - -/** - * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an - * implementation address that can be changed. This address is stored in storage in the location specified by - * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the - * implementation behind the proxy. - */ -contract ERC1967Proxy is Proxy, ERC1967Upgrade { - /** - * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. - * - * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded - * function call, and allows initializating the storage of the proxy like a Solidity constructor. - */ - constructor(address _logic, bytes memory _data) payable { - assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); - _upgradeToAndCall(_logic, _data, false); - } - - /** - * @dev Returns the current implementation address. - */ - function _implementation() internal view virtual override returns (address impl) { - return ERC1967Upgrade._getImplementation(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol deleted file mode 100644 index 77fbdd16..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol +++ /dev/null @@ -1,185 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) - -pragma solidity ^0.8.2; - -import "../beacon/IBeacon.sol"; -import "../../interfaces/draft-IERC1822.sol"; -import "../../utils/Address.sol"; -import "../../utils/StorageSlot.sol"; - -/** - * @dev This abstract contract provides getters and event emitting update functions for - * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. - * - * _Available since v4.1._ - * - * @custom:oz-upgrades-unsafe-allow delegatecall - */ -abstract contract ERC1967Upgrade { - // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 - bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; - - /** - * @dev Storage slot with the address of the current implementation. - * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is - * validated in the constructor. - */ - bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - - /** - * @dev Emitted when the implementation is upgraded. - */ - event Upgraded(address indexed implementation); - - /** - * @dev Returns the current implementation address. - */ - function _getImplementation() internal view returns (address) { - return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; - } - - /** - * @dev Stores a new address in the EIP1967 implementation slot. - */ - function _setImplementation(address newImplementation) private { - require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); - StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; - } - - /** - * @dev Perform implementation upgrade - * - * Emits an {Upgraded} event. - */ - function _upgradeTo(address newImplementation) internal { - _setImplementation(newImplementation); - emit Upgraded(newImplementation); - } - - /** - * @dev Perform implementation upgrade with additional setup call. - * - * Emits an {Upgraded} event. - */ - function _upgradeToAndCall( - address newImplementation, - bytes memory data, - bool forceCall - ) internal { - _upgradeTo(newImplementation); - if (data.length > 0 || forceCall) { - Address.functionDelegateCall(newImplementation, data); - } - } - - /** - * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. - * - * Emits an {Upgraded} event. - */ - function _upgradeToAndCallUUPS( - address newImplementation, - bytes memory data, - bool forceCall - ) internal { - // Upgrades from old implementations will perform a rollback test. This test requires the new - // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing - // this special case will break upgrade paths from old UUPS implementation to new ones. - if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { - _setImplementation(newImplementation); - } else { - try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { - require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); - } catch { - revert("ERC1967Upgrade: new implementation is not UUPS"); - } - _upgradeToAndCall(newImplementation, data, forceCall); - } - } - - /** - * @dev Storage slot with the admin of the contract. - * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is - * validated in the constructor. - */ - bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; - - /** - * @dev Emitted when the admin account has changed. - */ - event AdminChanged(address previousAdmin, address newAdmin); - - /** - * @dev Returns the current admin. - */ - function _getAdmin() internal view returns (address) { - return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; - } - - /** - * @dev Stores a new address in the EIP1967 admin slot. - */ - function _setAdmin(address newAdmin) private { - require(newAdmin != address(0), "ERC1967: new admin is the zero address"); - StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; - } - - /** - * @dev Changes the admin of the proxy. - * - * Emits an {AdminChanged} event. - */ - function _changeAdmin(address newAdmin) internal { - emit AdminChanged(_getAdmin(), newAdmin); - _setAdmin(newAdmin); - } - - /** - * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. - * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. - */ - bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; - - /** - * @dev Emitted when the beacon is upgraded. - */ - event BeaconUpgraded(address indexed beacon); - - /** - * @dev Returns the current beacon. - */ - function _getBeacon() internal view returns (address) { - return StorageSlot.getAddressSlot(_BEACON_SLOT).value; - } - - /** - * @dev Stores a new beacon in the EIP1967 beacon slot. - */ - function _setBeacon(address newBeacon) private { - require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); - require( - Address.isContract(IBeacon(newBeacon).implementation()), - "ERC1967: beacon implementation is not a contract" - ); - StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; - } - - /** - * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does - * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). - * - * Emits a {BeaconUpgraded} event. - */ - function _upgradeBeaconToAndCall( - address newBeacon, - bytes memory data, - bool forceCall - ) internal { - _setBeacon(newBeacon); - emit BeaconUpgraded(newBeacon); - if (data.length > 0 || forceCall) { - Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/Proxy.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/Proxy.sol deleted file mode 100644 index 9e8aa912..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/Proxy.sol +++ /dev/null @@ -1,86 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol) - -pragma solidity ^0.8.0; - -/** - * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM - * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to - * be specified by overriding the virtual {_implementation} function. - * - * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a - * different contract through the {_delegate} function. - * - * The success and return data of the delegated call will be returned back to the caller of the proxy. - */ -abstract contract Proxy { - /** - * @dev Delegates the current call to `implementation`. - * - * This function does not return to its internal call site, it will return directly to the external caller. - */ - function _delegate(address implementation) internal virtual { - assembly { - // Copy msg.data. We take full control of memory in this inline assembly - // block because it will not return to Solidity code. We overwrite the - // Solidity scratch pad at memory position 0. - calldatacopy(0, 0, calldatasize()) - - // Call the implementation. - // out and outsize are 0 because we don't know the size yet. - let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) - - // Copy the returned data. - returndatacopy(0, 0, returndatasize()) - - switch result - // delegatecall returns 0 on error. - case 0 { - revert(0, returndatasize()) - } - default { - return(0, returndatasize()) - } - } - } - - /** - * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function - * and {_fallback} should delegate. - */ - function _implementation() internal view virtual returns (address); - - /** - * @dev Delegates the current call to the address returned by `_implementation()`. - * - * This function does not return to its internall call site, it will return directly to the external caller. - */ - function _fallback() internal virtual { - _beforeFallback(); - _delegate(_implementation()); - } - - /** - * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other - * function in the contract matches the call data. - */ - fallback() external payable virtual { - _fallback(); - } - - /** - * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data - * is empty. - */ - receive() external payable virtual { - _fallback(); - } - - /** - * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` - * call, or as part of the Solidity `fallback` or `receive` functions. - * - * If overriden should call `super._beforeFallback()`. - */ - function _beforeFallback() internal virtual {} -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/README.adoc deleted file mode 100644 index 9f37b267..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/README.adoc +++ /dev/null @@ -1,85 +0,0 @@ -= Proxies - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/proxy - -This is a low-level set of contracts implementing different proxy patterns with and without upgradeability. For an in-depth overview of this pattern check out the xref:upgrades-plugins::proxies.adoc[Proxy Upgrade Pattern] page. - -Most of the proxies below are built on an abstract base contract. - -- {Proxy}: Abstract contract implementing the core delegation functionality. - -In order to avoid clashes with the storage variables of the implementation contract behind a proxy, we use https://eips.ethereum.org/EIPS/eip-1967[EIP1967] storage slots. - -- {ERC1967Upgrade}: Internal functions to get and set the storage slots defined in EIP1967. -- {ERC1967Proxy}: A proxy using EIP1967 storage slots. Not upgradeable by default. - -There are two alternative ways to add upgradeability to an ERC1967 proxy. Their differences are explained below in <>. - -- {TransparentUpgradeableProxy}: A proxy with a built in admin and upgrade interface. -- {UUPSUpgradeable}: An upgradeability mechanism to be included in the implementation contract. - -CAUTION: Using upgradeable proxies correctly and securely is a difficult task that requires deep knowledge of the proxy pattern, Solidity, and the EVM. Unless you want a lot of low level control, we recommend using the xref:upgrades-plugins::index.adoc[OpenZeppelin Upgrades Plugins] for Truffle and Hardhat. - -A different family of proxies are beacon proxies. This pattern, popularized by Dharma, allows multiple proxies to be upgraded to a different implementation in a single transaction. - -- {BeaconProxy}: A proxy that retreives its implementation from a beacon contract. -- {UpgradeableBeacon}: A beacon contract with a built in admin that can upgrade the {BeaconProxy} pointing to it. - -In this pattern, the proxy contract doesn't hold the implementation address in storage like an ERC1967 proxy, instead the address is stored in a separate beacon contract. The `upgrade` operations that are sent to the beacon instead of to the proxy contract, and all proxies that follow that beacon are automatically upgraded. - -Outside the realm of upgradeability, proxies can also be useful to make cheap contract clones, such as those created by an on-chain factory contract that creates many instances of the same contract. These instances are designed to be both cheap to deploy, and cheap to call. - -- {Clones}: A library that can deploy cheap minimal non-upgradeable proxies. - -[[transparent-vs-uups]] -== Transparent vs UUPS Proxies - -The original proxies included in OpenZeppelin followed the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[Transparent Proxy Pattern]. While this pattern is still provided, our recommendation is now shifting towards UUPS proxies, which are both lightweight and versatile. The name UUPS comes from https://eips.ethereum.org/EIPS/eip-1822[EIP1822], which first documented the pattern. - -While both of these share the same interface for upgrades, in UUPS proxies the upgrade is handled by the implementation, and can eventually be removed. Transparent proxies, on the other hand, include the upgrade and admin logic in the proxy itself. This means {TransparentUpgradeableProxy} is more expensive to deploy than what is possible with UUPS proxies. - -UUPS proxies are implemented using an {ERC1967Proxy}. Note that this proxy is not by itself upgradeable. It is the role of the implementation to include, alongside the contract's logic, all the code necessary to update the implementation's address that is stored at a specific slot in the proxy's storage space. This is where the {UUPSUpgradeable} contract comes in. Inheriting from it (and overriding the {xref-UUPSUpgradeable-_authorizeUpgrade-address-}[`_authorizeUpgrade`] function with the relevant access control mechanism) will turn your contract into a UUPS compliant implementation. - -Note that since both proxies use the same storage slot for the implementation address, using a UUPS compliant implementation with a {TransparentUpgradeableProxy} might allow non-admins to perform upgrade operations. - -By default, the upgrade functionality included in {UUPSUpgradeable} contains a security mechanism that will prevent any upgrades to a non UUPS compliant implementation. This prevents upgrades to an implementation contract that wouldn't contain the necessary upgrade mechanism, as it would lock the upgradeability of the proxy forever. This security mechanism can be bypassed by either of: - -- Adding a flag mechanism in the implementation that will disable the upgrade function when triggered. -- Upgrading to an implementation that features an upgrade mechanism without the additional security check, and then upgrading again to another implementation without the upgrade mechanism. - -The current implementation of this security mechanism uses https://eips.ethereum.org/EIPS/eip-1822[EIP1822] to detect the storage slot used by the implementation. A previous implementation, now deprecated, relied on a rollback check. It is possible to upgrade from a contract using the old mechanism to a new one. The inverse is however not possible, as old implementations (before version 4.5) did not include the `ERC1822` interface. - -== Core - -{{Proxy}} - -== ERC1967 - -{{ERC1967Proxy}} - -{{ERC1967Upgrade}} - -== Transparent Proxy - -{{TransparentUpgradeableProxy}} - -{{ProxyAdmin}} - -== Beacon - -{{BeaconProxy}} - -{{IBeacon}} - -{{UpgradeableBeacon}} - -== Minimal Clones - -{{Clones}} - -== Utils - -{{Initializable}} - -{{UUPSUpgradeable}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/BeaconProxy.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/BeaconProxy.sol deleted file mode 100644 index 32eaa8e6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/BeaconProxy.sol +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol) - -pragma solidity ^0.8.0; - -import "./IBeacon.sol"; -import "../Proxy.sol"; -import "../ERC1967/ERC1967Upgrade.sol"; - -/** - * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. - * - * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't - * conflict with the storage layout of the implementation behind the proxy. - * - * _Available since v3.4._ - */ -contract BeaconProxy is Proxy, ERC1967Upgrade { - /** - * @dev Initializes the proxy with `beacon`. - * - * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This - * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity - * constructor. - * - * Requirements: - * - * - `beacon` must be a contract with the interface {IBeacon}. - */ - constructor(address beacon, bytes memory data) payable { - assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); - _upgradeBeaconToAndCall(beacon, data, false); - } - - /** - * @dev Returns the current beacon address. - */ - function _beacon() internal view virtual returns (address) { - return _getBeacon(); - } - - /** - * @dev Returns the current implementation address of the associated beacon. - */ - function _implementation() internal view virtual override returns (address) { - return IBeacon(_getBeacon()).implementation(); - } - - /** - * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. - * - * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. - * - * Requirements: - * - * - `beacon` must be a contract. - * - The implementation returned by `beacon` must be a contract. - */ - function _setBeacon(address beacon, bytes memory data) internal virtual { - _upgradeBeaconToAndCall(beacon, data, false); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol deleted file mode 100644 index fba3ee2a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) - -pragma solidity ^0.8.0; - -/** - * @dev This is the interface that {BeaconProxy} expects of its beacon. - */ -interface IBeacon { - /** - * @dev Must return an address that can be used as a delegate call target. - * - * {BeaconProxy} will check that this address is a contract. - */ - function implementation() external view returns (address); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/UpgradeableBeacon.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/UpgradeableBeacon.sol deleted file mode 100644 index 5d83ceb3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/beacon/UpgradeableBeacon.sol +++ /dev/null @@ -1,65 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol) - -pragma solidity ^0.8.0; - -import "./IBeacon.sol"; -import "../../access/Ownable.sol"; -import "../../utils/Address.sol"; - -/** - * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their - * implementation contract, which is where they will delegate all function calls. - * - * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. - */ -contract UpgradeableBeacon is IBeacon, Ownable { - address private _implementation; - - /** - * @dev Emitted when the implementation returned by the beacon is changed. - */ - event Upgraded(address indexed implementation); - - /** - * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the - * beacon. - */ - constructor(address implementation_) { - _setImplementation(implementation_); - } - - /** - * @dev Returns the current implementation address. - */ - function implementation() public view virtual override returns (address) { - return _implementation; - } - - /** - * @dev Upgrades the beacon to a new implementation. - * - * Emits an {Upgraded} event. - * - * Requirements: - * - * - msg.sender must be the owner of the contract. - * - `newImplementation` must be a contract. - */ - function upgradeTo(address newImplementation) public virtual onlyOwner { - _setImplementation(newImplementation); - emit Upgraded(newImplementation); - } - - /** - * @dev Sets the implementation contract address for this beacon - * - * Requirements: - * - * - `newImplementation` must be a contract. - */ - function _setImplementation(address newImplementation) private { - require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); - _implementation = newImplementation; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/transparent/ProxyAdmin.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/transparent/ProxyAdmin.sol deleted file mode 100644 index 83953429..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/transparent/ProxyAdmin.sol +++ /dev/null @@ -1,81 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol) - -pragma solidity ^0.8.0; - -import "./TransparentUpgradeableProxy.sol"; -import "../../access/Ownable.sol"; - -/** - * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an - * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. - */ -contract ProxyAdmin is Ownable { - /** - * @dev Returns the current implementation of `proxy`. - * - * Requirements: - * - * - This contract must be the admin of `proxy`. - */ - function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { - // We need to manually run the static call since the getter cannot be flagged as view - // bytes4(keccak256("implementation()")) == 0x5c60da1b - (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); - require(success); - return abi.decode(returndata, (address)); - } - - /** - * @dev Returns the current admin of `proxy`. - * - * Requirements: - * - * - This contract must be the admin of `proxy`. - */ - function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { - // We need to manually run the static call since the getter cannot be flagged as view - // bytes4(keccak256("admin()")) == 0xf851a440 - (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); - require(success); - return abi.decode(returndata, (address)); - } - - /** - * @dev Changes the admin of `proxy` to `newAdmin`. - * - * Requirements: - * - * - This contract must be the current admin of `proxy`. - */ - function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { - proxy.changeAdmin(newAdmin); - } - - /** - * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. - * - * Requirements: - * - * - This contract must be the admin of `proxy`. - */ - function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { - proxy.upgradeTo(implementation); - } - - /** - * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See - * {TransparentUpgradeableProxy-upgradeToAndCall}. - * - * Requirements: - * - * - This contract must be the admin of `proxy`. - */ - function upgradeAndCall( - TransparentUpgradeableProxy proxy, - address implementation, - bytes memory data - ) public payable virtual onlyOwner { - proxy.upgradeToAndCall{value: msg.value}(implementation, data); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/transparent/TransparentUpgradeableProxy.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/transparent/TransparentUpgradeableProxy.sol deleted file mode 100644 index 10808d58..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/transparent/TransparentUpgradeableProxy.sol +++ /dev/null @@ -1,125 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol) - -pragma solidity ^0.8.0; - -import "../ERC1967/ERC1967Proxy.sol"; - -/** - * @dev This contract implements a proxy that is upgradeable by an admin. - * - * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector - * clashing], which can potentially be used in an attack, this contract uses the - * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two - * things that go hand in hand: - * - * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if - * that call matches one of the admin functions exposed by the proxy itself. - * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the - * implementation. If the admin tries to call a function on the implementation it will fail with an error that says - * "admin cannot fallback to proxy target". - * - * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing - * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due - * to sudden errors when trying to call a function from the proxy implementation. - * - * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, - * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. - */ -contract TransparentUpgradeableProxy is ERC1967Proxy { - /** - * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and - * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. - */ - constructor( - address _logic, - address admin_, - bytes memory _data - ) payable ERC1967Proxy(_logic, _data) { - assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); - _changeAdmin(admin_); - } - - /** - * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. - */ - modifier ifAdmin() { - if (msg.sender == _getAdmin()) { - _; - } else { - _fallback(); - } - } - - /** - * @dev Returns the current admin. - * - * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. - * - * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the - * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. - * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` - */ - function admin() external ifAdmin returns (address admin_) { - admin_ = _getAdmin(); - } - - /** - * @dev Returns the current implementation. - * - * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. - * - * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the - * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. - * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` - */ - function implementation() external ifAdmin returns (address implementation_) { - implementation_ = _implementation(); - } - - /** - * @dev Changes the admin of the proxy. - * - * Emits an {AdminChanged} event. - * - * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. - */ - function changeAdmin(address newAdmin) external virtual ifAdmin { - _changeAdmin(newAdmin); - } - - /** - * @dev Upgrade the implementation of the proxy. - * - * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. - */ - function upgradeTo(address newImplementation) external ifAdmin { - _upgradeToAndCall(newImplementation, bytes(""), false); - } - - /** - * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified - * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the - * proxied contract. - * - * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. - */ - function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { - _upgradeToAndCall(newImplementation, data, true); - } - - /** - * @dev Returns the current admin. - */ - function _admin() internal view virtual returns (address) { - return _getAdmin(); - } - - /** - * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. - */ - function _beforeFallback() internal virtual override { - require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); - super._beforeFallback(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol deleted file mode 100644 index 1fe4583a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) - -pragma solidity ^0.8.0; - -import "../../utils/Address.sol"; - -/** - * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed - * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an - * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer - * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. - * - * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as - * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. - * - * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure - * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. - * - * [CAUTION] - * ==== - * Avoid leaving a contract uninitialized. - * - * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation - * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the - * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: - * - * [.hljs-theme-light.nopadding] - * ``` - * /// @custom:oz-upgrades-unsafe-allow constructor - * constructor() initializer {} - * ``` - * ==== - */ -abstract contract Initializable { - /** - * @dev Indicates that the contract has been initialized. - */ - bool private _initialized; - - /** - * @dev Indicates that the contract is in the process of being initialized. - */ - bool private _initializing; - - /** - * @dev Modifier to protect an initializer function from being invoked twice. - */ - modifier initializer() { - // If the contract is initializing we ignore whether _initialized is set in order to support multiple - // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the - // contract may have been reentered. - require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); - - bool isTopLevelCall = !_initializing; - if (isTopLevelCall) { - _initializing = true; - _initialized = true; - } - - _; - - if (isTopLevelCall) { - _initializing = false; - } - } - - /** - * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the - * {initializer} modifier, directly or indirectly. - */ - modifier onlyInitializing() { - require(_initializing, "Initializable: contract is not initializing"); - _; - } - - function _isConstructor() private view returns (bool) { - return !Address.isContract(address(this)); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol deleted file mode 100644 index 7ccc5031..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol +++ /dev/null @@ -1,95 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) - -pragma solidity ^0.8.0; - -import "../../interfaces/draft-IERC1822.sol"; -import "../ERC1967/ERC1967Upgrade.sol"; - -/** - * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an - * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. - * - * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is - * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing - * `UUPSUpgradeable` with a custom implementation of upgrades. - * - * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. - * - * _Available since v4.1._ - */ -abstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Upgrade { - /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment - address private immutable __self = address(this); - - /** - * @dev Check that the execution is being performed through a delegatecall call and that the execution context is - * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case - * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a - * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to - * fail. - */ - modifier onlyProxy() { - require(address(this) != __self, "Function must be called through delegatecall"); - require(_getImplementation() == __self, "Function must be called through active proxy"); - _; - } - - /** - * @dev Check that the execution is not being performed through a delegate call. This allows a function to be - * callable on the implementing contract but not through proxies. - */ - modifier notDelegated() { - require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); - _; - } - - /** - * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the - * implementation. It is used to validate that the this implementation remains valid after an upgrade. - * - * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks - * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this - * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. - */ - function proxiableUUID() external view virtual override notDelegated returns (bytes32) { - return _IMPLEMENTATION_SLOT; - } - - /** - * @dev Upgrade the implementation of the proxy to `newImplementation`. - * - * Calls {_authorizeUpgrade}. - * - * Emits an {Upgraded} event. - */ - function upgradeTo(address newImplementation) external virtual onlyProxy { - _authorizeUpgrade(newImplementation); - _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); - } - - /** - * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call - * encoded in `data`. - * - * Calls {_authorizeUpgrade}. - * - * Emits an {Upgraded} event. - */ - function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { - _authorizeUpgrade(newImplementation); - _upgradeToAndCallUUPS(newImplementation, data, true); - } - - /** - * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by - * {upgradeTo} and {upgradeToAndCall}. - * - * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. - * - * ```solidity - * function _authorizeUpgrade(address) internal override onlyOwner {} - * ``` - */ - function _authorizeUpgrade(address newImplementation) internal virtual; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/Pausable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/Pausable.sol deleted file mode 100644 index 0c09e6c8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/Pausable.sol +++ /dev/null @@ -1,91 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) - -pragma solidity ^0.8.0; - -import "../utils/Context.sol"; - -/** - * @dev Contract module which allows children to implement an emergency stop - * mechanism that can be triggered by an authorized account. - * - * This module is used through inheritance. It will make available the - * modifiers `whenNotPaused` and `whenPaused`, which can be applied to - * the functions of your contract. Note that they will not be pausable by - * simply including this module, only once the modifiers are put in place. - */ -abstract contract Pausable is Context { - /** - * @dev Emitted when the pause is triggered by `account`. - */ - event Paused(address account); - - /** - * @dev Emitted when the pause is lifted by `account`. - */ - event Unpaused(address account); - - bool private _paused; - - /** - * @dev Initializes the contract in unpaused state. - */ - constructor() { - _paused = false; - } - - /** - * @dev Returns true if the contract is paused, and false otherwise. - */ - function paused() public view virtual returns (bool) { - return _paused; - } - - /** - * @dev Modifier to make a function callable only when the contract is not paused. - * - * Requirements: - * - * - The contract must not be paused. - */ - modifier whenNotPaused() { - require(!paused(), "Pausable: paused"); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is paused. - * - * Requirements: - * - * - The contract must be paused. - */ - modifier whenPaused() { - require(paused(), "Pausable: not paused"); - _; - } - - /** - * @dev Triggers stopped state. - * - * Requirements: - * - * - The contract must not be paused. - */ - function _pause() internal virtual whenNotPaused { - _paused = true; - emit Paused(_msgSender()); - } - - /** - * @dev Returns to normal state. - * - * Requirements: - * - * - The contract must be paused. - */ - function _unpause() internal virtual whenPaused { - _paused = false; - emit Unpaused(_msgSender()); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/PullPayment.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/PullPayment.sol deleted file mode 100644 index 6a50f2cb..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/PullPayment.sol +++ /dev/null @@ -1,70 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (security/PullPayment.sol) - -pragma solidity ^0.8.0; - -import "../utils/escrow/Escrow.sol"; - -/** - * @dev Simple implementation of a - * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] - * strategy, where the paying contract doesn't interact directly with the - * receiver account, which must withdraw its payments itself. - * - * Pull-payments are often considered the best practice when it comes to sending - * Ether, security-wise. It prevents recipients from blocking execution, and - * eliminates reentrancy concerns. - * - * TIP: If you would like to learn more about reentrancy and alternative ways - * to protect against it, check out our blog post - * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. - * - * To use, derive from the `PullPayment` contract, and use {_asyncTransfer} - * instead of Solidity's `transfer` function. Payees can query their due - * payments with {payments}, and retrieve them with {withdrawPayments}. - */ -abstract contract PullPayment { - Escrow private immutable _escrow; - - constructor() { - _escrow = new Escrow(); - } - - /** - * @dev Withdraw accumulated payments, forwarding all gas to the recipient. - * - * Note that _any_ account can call this function, not just the `payee`. - * This means that contracts unaware of the `PullPayment` protocol can still - * receive funds this way, by having a separate account call - * {withdrawPayments}. - * - * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. - * Make sure you trust the recipient, or are either following the - * checks-effects-interactions pattern or using {ReentrancyGuard}. - * - * @param payee Whose payments will be withdrawn. - */ - function withdrawPayments(address payable payee) public virtual { - _escrow.withdraw(payee); - } - - /** - * @dev Returns the payments owed to an address. - * @param dest The creditor's address. - */ - function payments(address dest) public view returns (uint256) { - return _escrow.depositsOf(dest); - } - - /** - * @dev Called by the payer to store the sent amount as credit to be pulled. - * Funds sent in this way are stored in an intermediate {Escrow} contract, so - * there is no danger of them being spent before withdrawal. - * - * @param dest The destination address of the funds. - * @param amount The amount to transfer. - */ - function _asyncTransfer(address dest, uint256 amount) internal virtual { - _escrow.deposit{value: amount}(dest); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/README.adoc deleted file mode 100644 index 66f398fe..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/security/README.adoc +++ /dev/null @@ -1,20 +0,0 @@ -= Security - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/security - -These contracts aim to cover common security practices. - -* {PullPayment}: A pattern that can be used to avoid reentrancy attacks. -* {ReentrancyGuard}: A modifier that can prevent reentrancy during certain functions. -* {Pausable}: A common emergency response mechanism that can pause functionality while a remediation is pending. - -TIP: For an overview on reentrancy and the possible mechanisms to prevent it, read our article https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. - -== Contracts - -{{PullPayment}} - -{{ReentrancyGuard}} - -{{Pausable}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/ERC1155.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/ERC1155.sol deleted file mode 100644 index ffdd8cd7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/ERC1155.sol +++ /dev/null @@ -1,464 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) - -pragma solidity ^0.8.0; - -import "./IERC1155.sol"; -import "./IERC1155Receiver.sol"; -import "./extensions/IERC1155MetadataURI.sol"; -import "../../utils/Address.sol"; -import "../../utils/Context.sol"; -import "../../utils/introspection/ERC165.sol"; - -/** - * @dev Implementation of the basic standard multi-token. - * See https://eips.ethereum.org/EIPS/eip-1155 - * Originally based on code by Enjin: https://github.com/enjin/erc-1155 - * - * _Available since v3.1._ - */ -contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { - using Address for address; - - // Mapping from token ID to account balances - mapping(uint256 => mapping(address => uint256)) private _balances; - - // Mapping from account to operator approvals - mapping(address => mapping(address => bool)) private _operatorApprovals; - - // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json - string private _uri; - - /** - * @dev See {_setURI}. - */ - constructor(string memory uri_) { - _setURI(uri_); - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { - return - interfaceId == type(IERC1155).interfaceId || - interfaceId == type(IERC1155MetadataURI).interfaceId || - super.supportsInterface(interfaceId); - } - - /** - * @dev See {IERC1155MetadataURI-uri}. - * - * This implementation returns the same URI for *all* token types. It relies - * on the token type ID substitution mechanism - * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. - * - * Clients calling this function must replace the `\{id\}` substring with the - * actual token type ID. - */ - function uri(uint256) public view virtual override returns (string memory) { - return _uri; - } - - /** - * @dev See {IERC1155-balanceOf}. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { - require(account != address(0), "ERC1155: balance query for the zero address"); - return _balances[id][account]; - } - - /** - * @dev See {IERC1155-balanceOfBatch}. - * - * Requirements: - * - * - `accounts` and `ids` must have the same length. - */ - function balanceOfBatch(address[] memory accounts, uint256[] memory ids) - public - view - virtual - override - returns (uint256[] memory) - { - require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); - - uint256[] memory batchBalances = new uint256[](accounts.length); - - for (uint256 i = 0; i < accounts.length; ++i) { - batchBalances[i] = balanceOf(accounts[i], ids[i]); - } - - return batchBalances; - } - - /** - * @dev See {IERC1155-setApprovalForAll}. - */ - function setApprovalForAll(address operator, bool approved) public virtual override { - _setApprovalForAll(_msgSender(), operator, approved); - } - - /** - * @dev See {IERC1155-isApprovedForAll}. - */ - function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { - return _operatorApprovals[account][operator]; - } - - /** - * @dev See {IERC1155-safeTransferFrom}. - */ - function safeTransferFrom( - address from, - address to, - uint256 id, - uint256 amount, - bytes memory data - ) public virtual override { - require( - from == _msgSender() || isApprovedForAll(from, _msgSender()), - "ERC1155: caller is not owner nor approved" - ); - _safeTransferFrom(from, to, id, amount, data); - } - - /** - * @dev See {IERC1155-safeBatchTransferFrom}. - */ - function safeBatchTransferFrom( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) public virtual override { - require( - from == _msgSender() || isApprovedForAll(from, _msgSender()), - "ERC1155: transfer caller is not owner nor approved" - ); - _safeBatchTransferFrom(from, to, ids, amounts, data); - } - - /** - * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. - * - * Emits a {TransferSingle} event. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - `from` must have a balance of tokens of type `id` of at least `amount`. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the - * acceptance magic value. - */ - function _safeTransferFrom( - address from, - address to, - uint256 id, - uint256 amount, - bytes memory data - ) internal virtual { - require(to != address(0), "ERC1155: transfer to the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); - - uint256 fromBalance = _balances[id][from]; - require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); - unchecked { - _balances[id][from] = fromBalance - amount; - } - _balances[id][to] += amount; - - emit TransferSingle(operator, from, to, id, amount); - - _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); - } - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. - * - * Emits a {TransferBatch} event. - * - * Requirements: - * - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the - * acceptance magic value. - */ - function _safeBatchTransferFrom( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual { - require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); - require(to != address(0), "ERC1155: transfer to the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, from, to, ids, amounts, data); - - for (uint256 i = 0; i < ids.length; ++i) { - uint256 id = ids[i]; - uint256 amount = amounts[i]; - - uint256 fromBalance = _balances[id][from]; - require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); - unchecked { - _balances[id][from] = fromBalance - amount; - } - _balances[id][to] += amount; - } - - emit TransferBatch(operator, from, to, ids, amounts); - - _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); - } - - /** - * @dev Sets a new URI for all token types, by relying on the token type ID - * substitution mechanism - * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. - * - * By this mechanism, any occurrence of the `\{id\}` substring in either the - * URI or any of the amounts in the JSON file at said URI will be replaced by - * clients with the token type ID. - * - * For example, the `https://token-cdn-domain/\{id\}.json` URI would be - * interpreted by clients as - * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` - * for token type ID 0x4cce0. - * - * See {uri}. - * - * Because these URIs cannot be meaningfully represented by the {URI} event, - * this function emits no events. - */ - function _setURI(string memory newuri) internal virtual { - _uri = newuri; - } - - /** - * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. - * - * Emits a {TransferSingle} event. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the - * acceptance magic value. - */ - function _mint( - address to, - uint256 id, - uint256 amount, - bytes memory data - ) internal virtual { - require(to != address(0), "ERC1155: mint to the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); - - _balances[id][to] += amount; - emit TransferSingle(operator, address(0), to, id, amount); - - _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); - } - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. - * - * Requirements: - * - * - `ids` and `amounts` must have the same length. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the - * acceptance magic value. - */ - function _mintBatch( - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual { - require(to != address(0), "ERC1155: mint to the zero address"); - require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); - - for (uint256 i = 0; i < ids.length; i++) { - _balances[ids[i]][to] += amounts[i]; - } - - emit TransferBatch(operator, address(0), to, ids, amounts); - - _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); - } - - /** - * @dev Destroys `amount` tokens of token type `id` from `from` - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `from` must have at least `amount` tokens of token type `id`. - */ - function _burn( - address from, - uint256 id, - uint256 amount - ) internal virtual { - require(from != address(0), "ERC1155: burn from the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); - - uint256 fromBalance = _balances[id][from]; - require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); - unchecked { - _balances[id][from] = fromBalance - amount; - } - - emit TransferSingle(operator, from, address(0), id, amount); - } - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. - * - * Requirements: - * - * - `ids` and `amounts` must have the same length. - */ - function _burnBatch( - address from, - uint256[] memory ids, - uint256[] memory amounts - ) internal virtual { - require(from != address(0), "ERC1155: burn from the zero address"); - require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); - - for (uint256 i = 0; i < ids.length; i++) { - uint256 id = ids[i]; - uint256 amount = amounts[i]; - - uint256 fromBalance = _balances[id][from]; - require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); - unchecked { - _balances[id][from] = fromBalance - amount; - } - } - - emit TransferBatch(operator, from, address(0), ids, amounts); - } - - /** - * @dev Approve `operator` to operate on all of `owner` tokens - * - * Emits a {ApprovalForAll} event. - */ - function _setApprovalForAll( - address owner, - address operator, - bool approved - ) internal virtual { - require(owner != operator, "ERC1155: setting approval status for self"); - _operatorApprovals[owner][operator] = approved; - emit ApprovalForAll(owner, operator, approved); - } - - /** - * @dev Hook that is called before any token transfer. This includes minting - * and burning, as well as batched variants. - * - * The same hook is called on both single and batched variants. For single - * transfers, the length of the `id` and `amount` arrays will be 1. - * - * Calling conditions (for each `id` and `amount` pair): - * - * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * of token type `id` will be transferred to `to`. - * - When `from` is zero, `amount` tokens of token type `id` will be minted - * for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` - * will be burned. - * - `from` and `to` are never both zero. - * - `ids` and `amounts` have the same, non-zero length. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual {} - - function _doSafeTransferAcceptanceCheck( - address operator, - address from, - address to, - uint256 id, - uint256 amount, - bytes memory data - ) private { - if (to.isContract()) { - try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { - if (response != IERC1155Receiver.onERC1155Received.selector) { - revert("ERC1155: ERC1155Receiver rejected tokens"); - } - } catch Error(string memory reason) { - revert(reason); - } catch { - revert("ERC1155: transfer to non ERC1155Receiver implementer"); - } - } - } - - function _doSafeBatchTransferAcceptanceCheck( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) private { - if (to.isContract()) { - try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( - bytes4 response - ) { - if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { - revert("ERC1155: ERC1155Receiver rejected tokens"); - } - } catch Error(string memory reason) { - revert(reason); - } catch { - revert("ERC1155: transfer to non ERC1155Receiver implementer"); - } - } - } - - function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { - uint256[] memory array = new uint256[](1); - array[0] = element; - - return array; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol deleted file mode 100644 index f2190a4f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol +++ /dev/null @@ -1,125 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) - -pragma solidity ^0.8.0; - -import "../../utils/introspection/IERC165.sol"; - -/** - * @dev Required interface of an ERC1155 compliant contract, as defined in the - * https://eips.ethereum.org/EIPS/eip-1155[EIP]. - * - * _Available since v3.1._ - */ -interface IERC1155 is IERC165 { - /** - * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. - */ - event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); - - /** - * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all - * transfers. - */ - event TransferBatch( - address indexed operator, - address indexed from, - address indexed to, - uint256[] ids, - uint256[] values - ); - - /** - * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to - * `approved`. - */ - event ApprovalForAll(address indexed account, address indexed operator, bool approved); - - /** - * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. - * - * If an {URI} event was emitted for `id`, the standard - * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value - * returned by {IERC1155MetadataURI-uri}. - */ - event URI(string value, uint256 indexed id); - - /** - * @dev Returns the amount of tokens of token type `id` owned by `account`. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function balanceOf(address account, uint256 id) external view returns (uint256); - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. - * - * Requirements: - * - * - `accounts` and `ids` must have the same length. - */ - function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) - external - view - returns (uint256[] memory); - - /** - * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, - * - * Emits an {ApprovalForAll} event. - * - * Requirements: - * - * - `operator` cannot be the caller. - */ - function setApprovalForAll(address operator, bool approved) external; - - /** - * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. - * - * See {setApprovalForAll}. - */ - function isApprovedForAll(address account, address operator) external view returns (bool); - - /** - * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. - * - * Emits a {TransferSingle} event. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. - * - `from` must have a balance of tokens of type `id` of at least `amount`. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the - * acceptance magic value. - */ - function safeTransferFrom( - address from, - address to, - uint256 id, - uint256 amount, - bytes calldata data - ) external; - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. - * - * Emits a {TransferBatch} event. - * - * Requirements: - * - * - `ids` and `amounts` must have the same length. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the - * acceptance magic value. - */ - function safeBatchTransferFrom( - address from, - address to, - uint256[] calldata ids, - uint256[] calldata amounts, - bytes calldata data - ) external; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol deleted file mode 100644 index 0dd271d0..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) - -pragma solidity ^0.8.0; - -import "../../utils/introspection/IERC165.sol"; - -/** - * @dev _Available since v3.1._ - */ -interface IERC1155Receiver is IERC165 { - /** - * @dev Handles the receipt of a single ERC1155 token type. This function is - * called at the end of a `safeTransferFrom` after the balance has been updated. - * - * NOTE: To accept the transfer, this must return - * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` - * (i.e. 0xf23a6e61, or its own function selector). - * - * @param operator The address which initiated the transfer (i.e. msg.sender) - * @param from The address which previously owned the token - * @param id The ID of the token being transferred - * @param value The amount of tokens being transferred - * @param data Additional data with no specified format - * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed - */ - function onERC1155Received( - address operator, - address from, - uint256 id, - uint256 value, - bytes calldata data - ) external returns (bytes4); - - /** - * @dev Handles the receipt of a multiple ERC1155 token types. This function - * is called at the end of a `safeBatchTransferFrom` after the balances have - * been updated. - * - * NOTE: To accept the transfer(s), this must return - * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` - * (i.e. 0xbc197c81, or its own function selector). - * - * @param operator The address which initiated the batch transfer (i.e. msg.sender) - * @param from The address which previously owned the token - * @param ids An array containing ids of each token being transferred (order and length must match values array) - * @param values An array containing amounts of each token being transferred (order and length must match ids array) - * @param data Additional data with no specified format - * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed - */ - function onERC1155BatchReceived( - address operator, - address from, - uint256[] calldata ids, - uint256[] calldata values, - bytes calldata data - ) external returns (bytes4); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/README.adoc deleted file mode 100644 index 2e0b22ba..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/README.adoc +++ /dev/null @@ -1,47 +0,0 @@ -= ERC 1155 - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc1155 - -This set of interfaces and contracts are all related to the https://eips.ethereum.org/EIPS/eip-1155[ERC1155 Multi Token Standard]. - -The EIP consists of three interfaces which fulfill different roles, found here as {IERC1155}, {IERC1155MetadataURI} and {IERC1155Receiver}. - -{ERC1155} implements the mandatory {IERC1155} interface, as well as the optional extension {IERC1155MetadataURI}, by relying on the substitution mechanism to use the same URI for all token types, dramatically reducing gas costs. - -Additionally there are multiple custom extensions, including: - -* designation of addresses that can pause token transfers for all users ({ERC1155Pausable}). -* destruction of own tokens ({ERC1155Burnable}). - -NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC1155 (such as <>) and expose them as external functions in the way they prefer. On the other hand, xref:ROOT:erc1155.adoc#Presets[ERC1155 Presets] (such as {ERC1155PresetMinterPauser}) are designed using opinionated patterns to provide developers with ready to use, deployable contracts. - -== Core - -{{IERC1155}} - -{{IERC1155MetadataURI}} - -{{ERC1155}} - -{{IERC1155Receiver}} - -{{ERC1155Receiver}} - -== Extensions - -{{ERC1155Pausable}} - -{{ERC1155Burnable}} - -{{ERC1155Supply}} - -== Presets - -These contracts are preconfigured combinations of the above features. They can be used through inheritance or as models to copy and paste their source code. - -{{ERC1155PresetMinterPauser}} - -== Utilities - -{{ERC1155Holder}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Burnable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Burnable.sol deleted file mode 100644 index 4a7c86e1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Burnable.sol +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol) - -pragma solidity ^0.8.0; - -import "../ERC1155.sol"; - -/** - * @dev Extension of {ERC1155} that allows token holders to destroy both their - * own tokens and those that they have been approved to use. - * - * _Available since v3.1._ - */ -abstract contract ERC1155Burnable is ERC1155 { - function burn( - address account, - uint256 id, - uint256 value - ) public virtual { - require( - account == _msgSender() || isApprovedForAll(account, _msgSender()), - "ERC1155: caller is not owner nor approved" - ); - - _burn(account, id, value); - } - - function burnBatch( - address account, - uint256[] memory ids, - uint256[] memory values - ) public virtual { - require( - account == _msgSender() || isApprovedForAll(account, _msgSender()), - "ERC1155: caller is not owner nor approved" - ); - - _burnBatch(account, ids, values); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Pausable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Pausable.sol deleted file mode 100644 index 64790e2a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Pausable.sol +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Pausable.sol) - -pragma solidity ^0.8.0; - -import "../ERC1155.sol"; -import "../../../security/Pausable.sol"; - -/** - * @dev ERC1155 token with pausable token transfers, minting and burning. - * - * Useful for scenarios such as preventing trades until the end of an evaluation - * period, or having an emergency switch for freezing all token transfers in the - * event of a large bug. - * - * _Available since v3.1._ - */ -abstract contract ERC1155Pausable is ERC1155, Pausable { - /** - * @dev See {ERC1155-_beforeTokenTransfer}. - * - * Requirements: - * - * - the contract must not be paused. - */ - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual override { - super._beforeTokenTransfer(operator, from, to, ids, amounts, data); - - require(!paused(), "ERC1155Pausable: token transfer while paused"); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Supply.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Supply.sol deleted file mode 100644 index 822c3bb0..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/ERC1155Supply.sol +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) - -pragma solidity ^0.8.0; - -import "../ERC1155.sol"; - -/** - * @dev Extension of ERC1155 that adds tracking of total supply per id. - * - * Useful for scenarios where Fungible and Non-fungible tokens have to be - * clearly identified. Note: While a totalSupply of 1 might mean the - * corresponding is an NFT, there is no guarantees that no other token with the - * same id are not going to be minted. - */ -abstract contract ERC1155Supply is ERC1155 { - mapping(uint256 => uint256) private _totalSupply; - - /** - * @dev Total amount of tokens in with a given id. - */ - function totalSupply(uint256 id) public view virtual returns (uint256) { - return _totalSupply[id]; - } - - /** - * @dev Indicates whether any token exist with a given id, or not. - */ - function exists(uint256 id) public view virtual returns (bool) { - return ERC1155Supply.totalSupply(id) > 0; - } - - /** - * @dev See {ERC1155-_beforeTokenTransfer}. - */ - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual override { - super._beforeTokenTransfer(operator, from, to, ids, amounts, data); - - if (from == address(0)) { - for (uint256 i = 0; i < ids.length; ++i) { - _totalSupply[ids[i]] += amounts[i]; - } - } - - if (to == address(0)) { - for (uint256 i = 0; i < ids.length; ++i) { - _totalSupply[ids[i]] -= amounts[i]; - } - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol deleted file mode 100644 index 520a2971..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) - -pragma solidity ^0.8.0; - -import "../IERC1155.sol"; - -/** - * @dev Interface of the optional ERC1155MetadataExtension interface, as defined - * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. - * - * _Available since v3.1._ - */ -interface IERC1155MetadataURI is IERC1155 { - /** - * @dev Returns the URI for token type `id`. - * - * If the `\{id\}` substring is present in the URI, it must be replaced by - * clients with the actual token type ID. - */ - function uri(uint256 id) external view returns (string memory); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol deleted file mode 100644 index e57fdcc3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol +++ /dev/null @@ -1,128 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/presets/ERC1155PresetMinterPauser.sol) - -pragma solidity ^0.8.0; - -import "../ERC1155.sol"; -import "../extensions/ERC1155Burnable.sol"; -import "../extensions/ERC1155Pausable.sol"; -import "../../../access/AccessControlEnumerable.sol"; -import "../../../utils/Context.sol"; - -/** - * @dev {ERC1155} token, including: - * - * - ability for holders to burn (destroy) their tokens - * - a minter role that allows for token minting (creation) - * - a pauser role that allows to stop all token transfers - * - * This contract uses {AccessControl} to lock permissioned functions using the - * different roles - head to its documentation for details. - * - * The account that deploys the contract will be granted the minter and pauser - * roles, as well as the default admin role, which will let it grant both minter - * and pauser roles to other accounts. - * - * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._ - */ -contract ERC1155PresetMinterPauser is Context, AccessControlEnumerable, ERC1155Burnable, ERC1155Pausable { - bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); - bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); - - /** - * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that - * deploys the contract. - */ - constructor(string memory uri) ERC1155(uri) { - _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); - - _setupRole(MINTER_ROLE, _msgSender()); - _setupRole(PAUSER_ROLE, _msgSender()); - } - - /** - * @dev Creates `amount` new tokens for `to`, of token type `id`. - * - * See {ERC1155-_mint}. - * - * Requirements: - * - * - the caller must have the `MINTER_ROLE`. - */ - function mint( - address to, - uint256 id, - uint256 amount, - bytes memory data - ) public virtual { - require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); - - _mint(to, id, amount, data); - } - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}. - */ - function mintBatch( - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) public virtual { - require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); - - _mintBatch(to, ids, amounts, data); - } - - /** - * @dev Pauses all token transfers. - * - * See {ERC1155Pausable} and {Pausable-_pause}. - * - * Requirements: - * - * - the caller must have the `PAUSER_ROLE`. - */ - function pause() public virtual { - require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause"); - _pause(); - } - - /** - * @dev Unpauses all token transfers. - * - * See {ERC1155Pausable} and {Pausable-_unpause}. - * - * Requirements: - * - * - the caller must have the `PAUSER_ROLE`. - */ - function unpause() public virtual { - require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause"); - _unpause(); - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) - public - view - virtual - override(AccessControlEnumerable, ERC1155) - returns (bool) - { - return super.supportsInterface(interfaceId); - } - - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual override(ERC1155, ERC1155Pausable) { - super._beforeTokenTransfer(operator, from, to, ids, amounts, data); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/presets/README.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/presets/README.md deleted file mode 100644 index 468200b7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/presets/README.md +++ /dev/null @@ -1 +0,0 @@ -Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol deleted file mode 100644 index 7249de84..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol) - -pragma solidity ^0.8.0; - -import "./ERC1155Receiver.sol"; - -/** - * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens. - * - * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be - * stuck. - * - * @dev _Available since v3.1._ - */ -contract ERC1155Holder is ERC1155Receiver { - function onERC1155Received( - address, - address, - uint256, - uint256, - bytes memory - ) public virtual override returns (bytes4) { - return this.onERC1155Received.selector; - } - - function onERC1155BatchReceived( - address, - address, - uint256[] memory, - uint256[] memory, - bytes memory - ) public virtual override returns (bytes4) { - return this.onERC1155BatchReceived.selector; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Receiver.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Receiver.sol deleted file mode 100644 index 2e6804a2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Receiver.sol +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol) - -pragma solidity ^0.8.0; - -import "../IERC1155Receiver.sol"; -import "../../../utils/introspection/ERC165.sol"; - -/** - * @dev _Available since v3.1._ - */ -abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { - return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/README.adoc deleted file mode 100644 index f2892293..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/README.adoc +++ /dev/null @@ -1,83 +0,0 @@ -= ERC 20 - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc20 - -This set of interfaces, contracts, and utilities are all related to the https://eips.ethereum.org/EIPS/eip-20[ERC20 Token Standard]. - -TIP: For an overview of ERC20 tokens and a walk through on how to create a token contract read our xref:ROOT:erc20.adoc[ERC20 guide]. - -There a few core contracts that implement the behavior specified in the EIP: - -* {IERC20}: the interface all ERC20 implementations should conform to. -* {IERC20Metadata}: the extended ERC20 interface including the <>, <> and <> functions. -* {ERC20}: the implementation of the ERC20 interface, including the <>, <> and <> optional standard extension to the base interface. - -Additionally there are multiple custom extensions, including: - -* {ERC20Burnable}: destruction of own tokens. -* {ERC20Capped}: enforcement of a cap to the total supply when minting tokens. -* {ERC20Pausable}: ability to pause token transfers. -* {ERC20Snapshot}: efficient storage of past token balances to be later queried at any point in time. -* {ERC20Permit}: gasless approval of tokens (standardized as ERC2612). -* {ERC20FlashMint}: token level support for flash loans through the minting and burning of ephemeral tokens (standardized as ERC3156). -* {ERC20Votes}: support for voting and vote delegation. -* {ERC20VotesComp}: support for voting and vote delegation (compatible with Compound's token, with uint96 restrictions). -* {ERC20Wrapper}: wrapper to create an ERC20 backed by another ERC20, with deposit and withdraw methods. Useful in conjunction with {ERC20Votes}. - -Finally, there are some utilities to interact with ERC20 contracts in various ways. - -* {SafeERC20}: a wrapper around the interface that eliminates the need to handle boolean return values. -* {TokenTimelock}: hold tokens for a beneficiary until a specified time. - -The following related EIPs are in draft status. - -- {ERC20Permit} - -NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC20 (such as <>) and expose them as external functions in the way they prefer. On the other hand, xref:ROOT:erc20.adoc#Presets[ERC20 Presets] (such as {ERC20PresetMinterPauser}) are designed using opinionated patterns to provide developers with ready to use, deployable contracts. - -== Core - -{{IERC20}} - -{{IERC20Metadata}} - -{{ERC20}} - -== Extensions - -{{ERC20Burnable}} - -{{ERC20Capped}} - -{{ERC20Pausable}} - -{{ERC20Snapshot}} - -{{ERC20Votes}} - -{{ERC20VotesComp}} - -{{ERC20Wrapper}} - -{{ERC20FlashMint}} - -== Draft EIPs - -The following EIPs are still in Draft status. Due to their nature as drafts, the details of these contracts may change and we cannot guarantee their xref:ROOT:releases-stability.adoc[stability]. Minor releases of OpenZeppelin Contracts may contain breaking changes for the contracts in this directory, which will be duly announced in the https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CHANGELOG.md[changelog]. The EIPs included here are used by projects in production and this may make them less likely to change significantly. - -{{ERC20Permit}} - -== Presets - -These contracts are preconfigured combinations of the above features. They can be used through inheritance or as models to copy and paste their source code. - -{{ERC20PresetMinterPauser}} - -{{ERC20PresetFixedSupply}} - -== Utilities - -{{SafeERC20}} - -{{TokenTimelock}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Burnable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Burnable.sol deleted file mode 100644 index 1cd08ee8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Burnable.sol +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) - -pragma solidity ^0.8.0; - -import "../ERC20.sol"; -import "../../../utils/Context.sol"; - -/** - * @dev Extension of {ERC20} that allows token holders to destroy both their own - * tokens and those that they have an allowance for, in a way that can be - * recognized off-chain (via event analysis). - */ -abstract contract ERC20Burnable is Context, ERC20 { - /** - * @dev Destroys `amount` tokens from the caller. - * - * See {ERC20-_burn}. - */ - function burn(uint256 amount) public virtual { - _burn(_msgSender(), amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, deducting from the caller's - * allowance. - * - * See {ERC20-_burn} and {ERC20-allowance}. - * - * Requirements: - * - * - the caller must have allowance for ``accounts``'s tokens of at least - * `amount`. - */ - function burnFrom(address account, uint256 amount) public virtual { - _spendAllowance(account, _msgSender(), amount); - _burn(account, amount); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Capped.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Capped.sol deleted file mode 100644 index 16f830d1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Capped.sol +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Capped.sol) - -pragma solidity ^0.8.0; - -import "../ERC20.sol"; - -/** - * @dev Extension of {ERC20} that adds a cap to the supply of tokens. - */ -abstract contract ERC20Capped is ERC20 { - uint256 private immutable _cap; - - /** - * @dev Sets the value of the `cap`. This value is immutable, it can only be - * set once during construction. - */ - constructor(uint256 cap_) { - require(cap_ > 0, "ERC20Capped: cap is 0"); - _cap = cap_; - } - - /** - * @dev Returns the cap on the token's total supply. - */ - function cap() public view virtual returns (uint256) { - return _cap; - } - - /** - * @dev See {ERC20-_mint}. - */ - function _mint(address account, uint256 amount) internal virtual override { - require(ERC20.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded"); - super._mint(account, amount); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20FlashMint.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20FlashMint.sol deleted file mode 100644 index 61aeea13..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20FlashMint.sol +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20FlashMint.sol) - -pragma solidity ^0.8.0; - -import "../../../interfaces/IERC3156.sol"; -import "../ERC20.sol"; - -/** - * @dev Implementation of the ERC3156 Flash loans extension, as defined in - * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. - * - * Adds the {flashLoan} method, which provides flash loan support at the token - * level. By default there is no fee, but this can be changed by overriding {flashFee}. - * - * _Available since v4.1._ - */ -abstract contract ERC20FlashMint is ERC20, IERC3156FlashLender { - bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); - - /** - * @dev Returns the maximum amount of tokens available for loan. - * @param token The address of the token that is requested. - * @return The amont of token that can be loaned. - */ - function maxFlashLoan(address token) public view virtual override returns (uint256) { - return token == address(this) ? type(uint256).max - ERC20.totalSupply() : 0; - } - - /** - * @dev Returns the fee applied when doing flash loans. By default this - * implementation has 0 fees. This function can be overloaded to make - * the flash loan mechanism deflationary. - * @param token The token to be flash loaned. - * @param amount The amount of tokens to be loaned. - * @return The fees applied to the corresponding flash loan. - */ - function flashFee(address token, uint256 amount) public view virtual override returns (uint256) { - require(token == address(this), "ERC20FlashMint: wrong token"); - // silence warning about unused variable without the addition of bytecode. - amount; - return 0; - } - - /** - * @dev Performs a flash loan. New tokens are minted and sent to the - * `receiver`, who is required to implement the {IERC3156FlashBorrower} - * interface. By the end of the flash loan, the receiver is expected to own - * amount + fee tokens and have them approved back to the token contract itself so - * they can be burned. - * @param receiver The receiver of the flash loan. Should implement the - * {IERC3156FlashBorrower.onFlashLoan} interface. - * @param token The token to be flash loaned. Only `address(this)` is - * supported. - * @param amount The amount of tokens to be loaned. - * @param data An arbitrary datafield that is passed to the receiver. - * @return `true` is the flash loan was successful. - */ - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) public virtual override returns (bool) { - require(amount <= maxFlashLoan(token), "ERC20FlashMint: amount exceeds maxFlashLoan"); - uint256 fee = flashFee(token, amount); - _mint(address(receiver), amount); - require( - receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE, - "ERC20FlashMint: invalid return value" - ); - uint256 currentAllowance = allowance(address(receiver), address(this)); - require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund"); - _approve(address(receiver), address(this), currentAllowance - amount - fee); - _burn(address(receiver), amount + fee); - return true; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Pausable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Pausable.sol deleted file mode 100644 index e448e96a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Pausable.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol) - -pragma solidity ^0.8.0; - -import "../ERC20.sol"; -import "../../../security/Pausable.sol"; - -/** - * @dev ERC20 token with pausable token transfers, minting and burning. - * - * Useful for scenarios such as preventing trades until the end of an evaluation - * period, or having an emergency switch for freezing all token transfers in the - * event of a large bug. - */ -abstract contract ERC20Pausable is ERC20, Pausable { - /** - * @dev See {ERC20-_beforeTokenTransfer}. - * - * Requirements: - * - * - the contract must not be paused. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual override { - super._beforeTokenTransfer(from, to, amount); - - require(!paused(), "ERC20Pausable: token transfer while paused"); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Snapshot.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Snapshot.sol deleted file mode 100644 index 96524bb2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Snapshot.sol +++ /dev/null @@ -1,195 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Snapshot.sol) - -pragma solidity ^0.8.0; - -import "../ERC20.sol"; -import "../../../utils/Arrays.sol"; -import "../../../utils/Counters.sol"; - -/** - * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and - * total supply at the time are recorded for later access. - * - * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. - * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different - * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be - * used to create an efficient ERC20 forking mechanism. - * - * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a - * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot - * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id - * and the account address. - * - * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it - * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this - * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract. - * - * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient - * alternative consider {ERC20Votes}. - * - * ==== Gas Costs - * - * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log - * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much - * smaller since identical balances in subsequent snapshots are stored as a single entry. - * - * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is - * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent - * transfers will have normal cost until the next snapshot, and so on. - */ - -abstract contract ERC20Snapshot is ERC20 { - // Inspired by Jordi Baylina's MiniMeToken to record historical balances: - // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol - - using Arrays for uint256[]; - using Counters for Counters.Counter; - - // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a - // Snapshot struct, but that would impede usage of functions that work on an array. - struct Snapshots { - uint256[] ids; - uint256[] values; - } - - mapping(address => Snapshots) private _accountBalanceSnapshots; - Snapshots private _totalSupplySnapshots; - - // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. - Counters.Counter private _currentSnapshotId; - - /** - * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. - */ - event Snapshot(uint256 id); - - /** - * @dev Creates a new snapshot and returns its snapshot id. - * - * Emits a {Snapshot} event that contains the same id. - * - * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a - * set of accounts, for example using {AccessControl}, or it may be open to the public. - * - * [WARNING] - * ==== - * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, - * you must consider that it can potentially be used by attackers in two ways. - * - * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow - * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target - * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs - * section above. - * - * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. - * ==== - */ - function _snapshot() internal virtual returns (uint256) { - _currentSnapshotId.increment(); - - uint256 currentId = _getCurrentSnapshotId(); - emit Snapshot(currentId); - return currentId; - } - - /** - * @dev Get the current snapshotId - */ - function _getCurrentSnapshotId() internal view virtual returns (uint256) { - return _currentSnapshotId.current(); - } - - /** - * @dev Retrieves the balance of `account` at the time `snapshotId` was created. - */ - function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { - (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); - - return snapshotted ? value : balanceOf(account); - } - - /** - * @dev Retrieves the total supply at the time `snapshotId` was created. - */ - function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) { - (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); - - return snapshotted ? value : totalSupply(); - } - - // Update balance and/or total supply snapshots before the values are modified. This is implemented - // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual override { - super._beforeTokenTransfer(from, to, amount); - - if (from == address(0)) { - // mint - _updateAccountSnapshot(to); - _updateTotalSupplySnapshot(); - } else if (to == address(0)) { - // burn - _updateAccountSnapshot(from); - _updateTotalSupplySnapshot(); - } else { - // transfer - _updateAccountSnapshot(from); - _updateAccountSnapshot(to); - } - } - - function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { - require(snapshotId > 0, "ERC20Snapshot: id is 0"); - require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id"); - - // When a valid snapshot is queried, there are three possibilities: - // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never - // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds - // to this id is the current one. - // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the - // requested id, and its value is the one to return. - // c) More snapshots were created after the requested one, and the queried value was later modified. There will be - // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is - // larger than the requested one. - // - // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if - // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does - // exactly this. - - uint256 index = snapshots.ids.findUpperBound(snapshotId); - - if (index == snapshots.ids.length) { - return (false, 0); - } else { - return (true, snapshots.values[index]); - } - } - - function _updateAccountSnapshot(address account) private { - _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); - } - - function _updateTotalSupplySnapshot() private { - _updateSnapshot(_totalSupplySnapshots, totalSupply()); - } - - function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { - uint256 currentId = _getCurrentSnapshotId(); - if (_lastSnapshotId(snapshots.ids) < currentId) { - snapshots.ids.push(currentId); - snapshots.values.push(currentValue); - } - } - - function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { - if (ids.length == 0) { - return 0; - } else { - return ids[ids.length - 1]; - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Votes.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Votes.sol deleted file mode 100644 index c0e88bc1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Votes.sol +++ /dev/null @@ -1,249 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Votes.sol) - -pragma solidity ^0.8.0; - -import "./draft-ERC20Permit.sol"; -import "../../../utils/math/Math.sol"; -import "../../../governance/utils/IVotes.sol"; -import "../../../utils/math/SafeCast.sol"; -import "../../../utils/cryptography/ECDSA.sol"; - -/** - * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, - * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. - * - * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. - * - * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either - * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting - * power can be queried through the public accessors {getVotes} and {getPastVotes}. - * - * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it - * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. - * - * _Available since v4.2._ - */ -abstract contract ERC20Votes is IVotes, ERC20Permit { - struct Checkpoint { - uint32 fromBlock; - uint224 votes; - } - - bytes32 private constant _DELEGATION_TYPEHASH = - keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); - - mapping(address => address) private _delegates; - mapping(address => Checkpoint[]) private _checkpoints; - Checkpoint[] private _totalSupplyCheckpoints; - - /** - * @dev Get the `pos`-th checkpoint for `account`. - */ - function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { - return _checkpoints[account][pos]; - } - - /** - * @dev Get number of checkpoints for `account`. - */ - function numCheckpoints(address account) public view virtual returns (uint32) { - return SafeCast.toUint32(_checkpoints[account].length); - } - - /** - * @dev Get the address `account` is currently delegating to. - */ - function delegates(address account) public view virtual override returns (address) { - return _delegates[account]; - } - - /** - * @dev Gets the current votes balance for `account` - */ - function getVotes(address account) public view virtual override returns (uint256) { - uint256 pos = _checkpoints[account].length; - return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; - } - - /** - * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. - * - * Requirements: - * - * - `blockNumber` must have been already mined - */ - function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { - require(blockNumber < block.number, "ERC20Votes: block not yet mined"); - return _checkpointsLookup(_checkpoints[account], blockNumber); - } - - /** - * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. - * It is but NOT the sum of all the delegated votes! - * - * Requirements: - * - * - `blockNumber` must have been already mined - */ - function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) { - require(blockNumber < block.number, "ERC20Votes: block not yet mined"); - return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); - } - - /** - * @dev Lookup a value in a list of (sorted) checkpoints. - */ - function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { - // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. - // - // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). - // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. - // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) - // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) - // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not - // out of bounds (in which case we're looking too far in the past and the result is 0). - // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is - // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out - // the same. - uint256 high = ckpts.length; - uint256 low = 0; - while (low < high) { - uint256 mid = Math.average(low, high); - if (ckpts[mid].fromBlock > blockNumber) { - high = mid; - } else { - low = mid + 1; - } - } - - return high == 0 ? 0 : ckpts[high - 1].votes; - } - - /** - * @dev Delegate votes from the sender to `delegatee`. - */ - function delegate(address delegatee) public virtual override { - _delegate(_msgSender(), delegatee); - } - - /** - * @dev Delegates votes from signer to `delegatee` - */ - function delegateBySig( - address delegatee, - uint256 nonce, - uint256 expiry, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual override { - require(block.timestamp <= expiry, "ERC20Votes: signature expired"); - address signer = ECDSA.recover( - _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), - v, - r, - s - ); - require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); - _delegate(signer, delegatee); - } - - /** - * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). - */ - function _maxSupply() internal view virtual returns (uint224) { - return type(uint224).max; - } - - /** - * @dev Snapshots the totalSupply after it has been increased. - */ - function _mint(address account, uint256 amount) internal virtual override { - super._mint(account, amount); - require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); - - _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); - } - - /** - * @dev Snapshots the totalSupply after it has been decreased. - */ - function _burn(address account, uint256 amount) internal virtual override { - super._burn(account, amount); - - _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); - } - - /** - * @dev Move voting power when tokens are transferred. - * - * Emits a {DelegateVotesChanged} event. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual override { - super._afterTokenTransfer(from, to, amount); - - _moveVotingPower(delegates(from), delegates(to), amount); - } - - /** - * @dev Change delegation for `delegator` to `delegatee`. - * - * Emits events {DelegateChanged} and {DelegateVotesChanged}. - */ - function _delegate(address delegator, address delegatee) internal virtual { - address currentDelegate = delegates(delegator); - uint256 delegatorBalance = balanceOf(delegator); - _delegates[delegator] = delegatee; - - emit DelegateChanged(delegator, currentDelegate, delegatee); - - _moveVotingPower(currentDelegate, delegatee, delegatorBalance); - } - - function _moveVotingPower( - address src, - address dst, - uint256 amount - ) private { - if (src != dst && amount > 0) { - if (src != address(0)) { - (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); - emit DelegateVotesChanged(src, oldWeight, newWeight); - } - - if (dst != address(0)) { - (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); - emit DelegateVotesChanged(dst, oldWeight, newWeight); - } - } - } - - function _writeCheckpoint( - Checkpoint[] storage ckpts, - function(uint256, uint256) view returns (uint256) op, - uint256 delta - ) private returns (uint256 oldWeight, uint256 newWeight) { - uint256 pos = ckpts.length; - oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; - newWeight = op(oldWeight, delta); - - if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { - ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); - } else { - ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); - } - } - - function _add(uint256 a, uint256 b) private pure returns (uint256) { - return a + b; - } - - function _subtract(uint256 a, uint256 b) private pure returns (uint256) { - return a - b; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20VotesComp.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20VotesComp.sol deleted file mode 100644 index 0461310a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20VotesComp.sol +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20VotesComp.sol) - -pragma solidity ^0.8.0; - -import "./ERC20Votes.sol"; - -/** - * @dev Extension of ERC20 to support Compound's voting and delegation. This version exactly matches Compound's - * interface, with the drawback of only supporting supply up to (2^96^ - 1). - * - * NOTE: You should use this contract if you need exact compatibility with COMP (for example in order to use your token - * with Governor Alpha or Bravo) and if you are sure the supply cap of 2^96^ is enough for you. Otherwise, use the - * {ERC20Votes} variant of this module. - * - * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either - * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting - * power can be queried through the public accessors {getCurrentVotes} and {getPriorVotes}. - * - * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it - * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. - * - * _Available since v4.2._ - */ -abstract contract ERC20VotesComp is ERC20Votes { - /** - * @dev Comp version of the {getVotes} accessor, with `uint96` return type. - */ - function getCurrentVotes(address account) external view virtual returns (uint96) { - return SafeCast.toUint96(getVotes(account)); - } - - /** - * @dev Comp version of the {getPastVotes} accessor, with `uint96` return type. - */ - function getPriorVotes(address account, uint256 blockNumber) external view virtual returns (uint96) { - return SafeCast.toUint96(getPastVotes(account, blockNumber)); - } - - /** - * @dev Maximum token supply. Reduced to `type(uint96).max` (2^96^ - 1) to fit COMP interface. - */ - function _maxSupply() internal view virtual override returns (uint224) { - return type(uint96).max; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Wrapper.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Wrapper.sol deleted file mode 100644 index 151c96d8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Wrapper.sol +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Wrapper.sol) - -pragma solidity ^0.8.0; - -import "../ERC20.sol"; -import "../utils/SafeERC20.sol"; - -/** - * @dev Extension of the ERC20 token contract to support token wrapping. - * - * Users can deposit and withdraw "underlying tokens" and receive a matching number of "wrapped tokens". This is useful - * in conjunction with other modules. For example, combining this wrapping mechanism with {ERC20Votes} will allow the - * wrapping of an existing "basic" ERC20 into a governance token. - * - * _Available since v4.2._ - */ -abstract contract ERC20Wrapper is ERC20 { - IERC20 public immutable underlying; - - constructor(IERC20 underlyingToken) { - underlying = underlyingToken; - } - - /** - * @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens. - */ - function depositFor(address account, uint256 amount) public virtual returns (bool) { - SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount); - _mint(account, amount); - return true; - } - - /** - * @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens. - */ - function withdrawTo(address account, uint256 amount) public virtual returns (bool) { - _burn(_msgSender(), amount); - SafeERC20.safeTransfer(underlying, account, amount); - return true; - } - - /** - * @dev Mint wrapped token to cover any underlyingTokens that would have been transfered by mistake. Internal - * function that can be exposed with access control if desired. - */ - function _recover(address account) internal virtual returns (uint256) { - uint256 value = underlying.balanceOf(address(this)) - totalSupply(); - _mint(account, value); - return value; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-ERC20Permit.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-ERC20Permit.sol deleted file mode 100644 index cf72fc08..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-ERC20Permit.sol +++ /dev/null @@ -1,87 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) - -pragma solidity ^0.8.0; - -import "./draft-IERC20Permit.sol"; -import "../ERC20.sol"; -import "../../../utils/cryptography/draft-EIP712.sol"; -import "../../../utils/cryptography/ECDSA.sol"; -import "../../../utils/Counters.sol"; - -/** - * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in - * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. - * - * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by - * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't - * need to send a transaction, and thus is not required to hold Ether at all. - * - * _Available since v3.4._ - */ -abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { - using Counters for Counters.Counter; - - mapping(address => Counters.Counter) private _nonces; - - // solhint-disable-next-line var-name-mixedcase - bytes32 private immutable _PERMIT_TYPEHASH = - keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); - - /** - * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. - * - * It's a good idea to use the same `name` that is defined as the ERC20 token name. - */ - constructor(string memory name) EIP712(name, "1") {} - - /** - * @dev See {IERC20Permit-permit}. - */ - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual override { - require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); - - bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); - - bytes32 hash = _hashTypedDataV4(structHash); - - address signer = ECDSA.recover(hash, v, r, s); - require(signer == owner, "ERC20Permit: invalid signature"); - - _approve(owner, spender, value); - } - - /** - * @dev See {IERC20Permit-nonces}. - */ - function nonces(address owner) public view virtual override returns (uint256) { - return _nonces[owner].current(); - } - - /** - * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. - */ - // solhint-disable-next-line func-name-mixedcase - function DOMAIN_SEPARATOR() external view override returns (bytes32) { - return _domainSeparatorV4(); - } - - /** - * @dev "Consume a nonce": return the current value and increment. - * - * _Available since v4.1._ - */ - function _useNonce(address owner) internal virtual returns (uint256 current) { - Counters.Counter storage nonce = _nonces[owner]; - current = nonce.current(); - nonce.increment(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol deleted file mode 100644 index 6363b140..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in - * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. - * - * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by - * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't - * need to send a transaction, and thus is not required to hold Ether at all. - */ -interface IERC20Permit { - /** - * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, - * given ``owner``'s signed approval. - * - * IMPORTANT: The same issues {IERC20-approve} has related to transaction - * ordering also apply here. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `deadline` must be a timestamp in the future. - * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` - * over the EIP712-formatted function arguments. - * - the signature must use ``owner``'s current nonce (see {nonces}). - * - * For more information on the signature format, see the - * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP - * section]. - */ - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external; - - /** - * @dev Returns the current nonce for `owner`. This value must be - * included whenever a signature is generated for {permit}. - * - * Every successful call to {permit} increases ``owner``'s nonce by one. This - * prevents a signature from being used multiple times. - */ - function nonces(address owner) external view returns (uint256); - - /** - * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. - */ - // solhint-disable-next-line func-name-mixedcase - function DOMAIN_SEPARATOR() external view returns (bytes32); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/ERC20PresetFixedSupply.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/ERC20PresetFixedSupply.sol deleted file mode 100644 index 52afef3a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/ERC20PresetFixedSupply.sol +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetFixedSupply.sol) -pragma solidity ^0.8.0; - -import "../extensions/ERC20Burnable.sol"; - -/** - * @dev {ERC20} token, including: - * - * - Preminted initial supply - * - Ability for holders to burn (destroy) their tokens - * - No access control mechanism (for minting/pausing) and hence no governance - * - * This contract uses {ERC20Burnable} to include burn capabilities - head to - * its documentation for details. - * - * _Available since v3.4._ - * - * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._ - */ -contract ERC20PresetFixedSupply is ERC20Burnable { - /** - * @dev Mints `initialSupply` amount of token and transfers them to `owner`. - * - * See {ERC20-constructor}. - */ - constructor( - string memory name, - string memory symbol, - uint256 initialSupply, - address owner - ) ERC20(name, symbol) { - _mint(owner, initialSupply); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol deleted file mode 100644 index e711a894..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol +++ /dev/null @@ -1,94 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol) - -pragma solidity ^0.8.0; - -import "../ERC20.sol"; -import "../extensions/ERC20Burnable.sol"; -import "../extensions/ERC20Pausable.sol"; -import "../../../access/AccessControlEnumerable.sol"; -import "../../../utils/Context.sol"; - -/** - * @dev {ERC20} token, including: - * - * - ability for holders to burn (destroy) their tokens - * - a minter role that allows for token minting (creation) - * - a pauser role that allows to stop all token transfers - * - * This contract uses {AccessControl} to lock permissioned functions using the - * different roles - head to its documentation for details. - * - * The account that deploys the contract will be granted the minter and pauser - * roles, as well as the default admin role, which will let it grant both minter - * and pauser roles to other accounts. - * - * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._ - */ -contract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable { - bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); - bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); - - /** - * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the - * account that deploys the contract. - * - * See {ERC20-constructor}. - */ - constructor(string memory name, string memory symbol) ERC20(name, symbol) { - _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); - - _setupRole(MINTER_ROLE, _msgSender()); - _setupRole(PAUSER_ROLE, _msgSender()); - } - - /** - * @dev Creates `amount` new tokens for `to`. - * - * See {ERC20-_mint}. - * - * Requirements: - * - * - the caller must have the `MINTER_ROLE`. - */ - function mint(address to, uint256 amount) public virtual { - require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); - _mint(to, amount); - } - - /** - * @dev Pauses all token transfers. - * - * See {ERC20Pausable} and {Pausable-_pause}. - * - * Requirements: - * - * - the caller must have the `PAUSER_ROLE`. - */ - function pause() public virtual { - require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); - _pause(); - } - - /** - * @dev Unpauses all token transfers. - * - * See {ERC20Pausable} and {Pausable-_unpause}. - * - * Requirements: - * - * - the caller must have the `PAUSER_ROLE`. - */ - function unpause() public virtual { - require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); - _unpause(); - } - - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual override(ERC20, ERC20Pausable) { - super._beforeTokenTransfer(from, to, amount); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/README.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/README.md deleted file mode 100644 index 468200b7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/presets/README.md +++ /dev/null @@ -1 +0,0 @@ -Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol deleted file mode 100644 index 5752d931..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol +++ /dev/null @@ -1,99 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) - -pragma solidity ^0.8.0; - -import "../IERC20.sol"; -import "../../../utils/Address.sol"; - -/** - * @title SafeERC20 - * @dev Wrappers around ERC20 operations that throw on failure (when the token - * contract returns false). Tokens that return no value (and instead revert or - * throw on failure) are also supported, non-reverting calls are assumed to be - * successful. - * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, - * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. - */ -library SafeERC20 { - using Address for address; - - function safeTransfer( - IERC20 token, - address to, - uint256 value - ) internal { - _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); - } - - function safeTransferFrom( - IERC20 token, - address from, - address to, - uint256 value - ) internal { - _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); - } - - /** - * @dev Deprecated. This function has issues similar to the ones found in - * {IERC20-approve}, and its usage is discouraged. - * - * Whenever possible, use {safeIncreaseAllowance} and - * {safeDecreaseAllowance} instead. - */ - function safeApprove( - IERC20 token, - address spender, - uint256 value - ) internal { - // safeApprove should only be called when setting an initial allowance, - // or when resetting it to zero. To increase and decrease it, use - // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' - require( - (value == 0) || (token.allowance(address(this), spender) == 0), - "SafeERC20: approve from non-zero to non-zero allowance" - ); - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); - } - - function safeIncreaseAllowance( - IERC20 token, - address spender, - uint256 value - ) internal { - uint256 newAllowance = token.allowance(address(this), spender) + value; - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); - } - - function safeDecreaseAllowance( - IERC20 token, - address spender, - uint256 value - ) internal { - unchecked { - uint256 oldAllowance = token.allowance(address(this), spender); - require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); - uint256 newAllowance = oldAllowance - value; - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); - } - } - - /** - * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement - * on the return value: the return value is optional (but if data is returned, it must not be false). - * @param token The token targeted by the call. - * @param data The call data (encoded using abi.encode or one of its variants). - */ - function _callOptionalReturn(IERC20 token, bytes memory data) private { - // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since - // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that - // the target address contains contract code and also asserts for success in the low-level call. - - bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); - if (returndata.length > 0) { - // Return data is optional - require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/utils/TokenTimelock.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/utils/TokenTimelock.sol deleted file mode 100644 index d879a7e7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC20/utils/TokenTimelock.sol +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/utils/TokenTimelock.sol) - -pragma solidity ^0.8.0; - -import "./SafeERC20.sol"; - -/** - * @dev A token holder contract that will allow a beneficiary to extract the - * tokens after a given release time. - * - * Useful for simple vesting schedules like "advisors get all of their tokens - * after 1 year". - */ -contract TokenTimelock { - using SafeERC20 for IERC20; - - // ERC20 basic token contract being held - IERC20 private immutable _token; - - // beneficiary of tokens after they are released - address private immutable _beneficiary; - - // timestamp when token release is enabled - uint256 private immutable _releaseTime; - - /** - * @dev Deploys a timelock instance that is able to hold the token specified, and will only release it to - * `beneficiary_` when {release} is invoked after `releaseTime_`. The release time is specified as a Unix timestamp - * (in seconds). - */ - constructor( - IERC20 token_, - address beneficiary_, - uint256 releaseTime_ - ) { - require(releaseTime_ > block.timestamp, "TokenTimelock: release time is before current time"); - _token = token_; - _beneficiary = beneficiary_; - _releaseTime = releaseTime_; - } - - /** - * @dev Returns the token being held. - */ - function token() public view virtual returns (IERC20) { - return _token; - } - - /** - * @dev Returns the beneficiary that will receive the tokens. - */ - function beneficiary() public view virtual returns (address) { - return _beneficiary; - } - - /** - * @dev Returns the time when the tokens are released in seconds since Unix epoch (i.e. Unix timestamp). - */ - function releaseTime() public view virtual returns (uint256) { - return _releaseTime; - } - - /** - * @dev Transfers tokens held by the timelock to the beneficiary. Will only succeed if invoked after the release - * time. - */ - function release() public virtual { - require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); - - uint256 amount = token().balanceOf(address(this)); - require(amount > 0, "TokenTimelock: no tokens to release"); - - token().safeTransfer(beneficiary(), amount); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol deleted file mode 100644 index 111007dc..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol +++ /dev/null @@ -1,447 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) - -pragma solidity ^0.8.0; - -import "./IERC721.sol"; -import "./IERC721Receiver.sol"; -import "./extensions/IERC721Metadata.sol"; -import "../../utils/Address.sol"; -import "../../utils/Context.sol"; -import "../../utils/Strings.sol"; -import "../../utils/introspection/ERC165.sol"; - -/** - * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including - * the Metadata extension, but not including the Enumerable extension, which is available separately as - * {ERC721Enumerable}. - */ -contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { - using Address for address; - using Strings for uint256; - - // Token name - string private _name; - - // Token symbol - string private _symbol; - - // Mapping from token ID to owner address - mapping(uint256 => address) private _owners; - - // Mapping owner address to token count - mapping(address => uint256) private _balances; - - // Mapping from token ID to approved address - mapping(uint256 => address) private _tokenApprovals; - - // Mapping from owner to operator approvals - mapping(address => mapping(address => bool)) private _operatorApprovals; - - /** - * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. - */ - constructor(string memory name_, string memory symbol_) { - _name = name_; - _symbol = symbol_; - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { - return - interfaceId == type(IERC721).interfaceId || - interfaceId == type(IERC721Metadata).interfaceId || - super.supportsInterface(interfaceId); - } - - /** - * @dev See {IERC721-balanceOf}. - */ - function balanceOf(address owner) public view virtual override returns (uint256) { - require(owner != address(0), "ERC721: balance query for the zero address"); - return _balances[owner]; - } - - /** - * @dev See {IERC721-ownerOf}. - */ - function ownerOf(uint256 tokenId) public view virtual override returns (address) { - address owner = _owners[tokenId]; - require(owner != address(0), "ERC721: owner query for nonexistent token"); - return owner; - } - - /** - * @dev See {IERC721Metadata-name}. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev See {IERC721Metadata-symbol}. - */ - function symbol() public view virtual override returns (string memory) { - return _symbol; - } - - /** - * @dev See {IERC721Metadata-tokenURI}. - */ - function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { - require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); - - string memory baseURI = _baseURI(); - return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; - } - - /** - * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each - * token will be the concatenation of the `baseURI` and the `tokenId`. Empty - * by default, can be overriden in child contracts. - */ - function _baseURI() internal view virtual returns (string memory) { - return ""; - } - - /** - * @dev See {IERC721-approve}. - */ - function approve(address to, uint256 tokenId) public virtual override { - address owner = ERC721.ownerOf(tokenId); - require(to != owner, "ERC721: approval to current owner"); - - require( - _msgSender() == owner || isApprovedForAll(owner, _msgSender()), - "ERC721: approve caller is not owner nor approved for all" - ); - - _approve(to, tokenId); - } - - /** - * @dev See {IERC721-getApproved}. - */ - function getApproved(uint256 tokenId) public view virtual override returns (address) { - require(_exists(tokenId), "ERC721: approved query for nonexistent token"); - - return _tokenApprovals[tokenId]; - } - - /** - * @dev See {IERC721-setApprovalForAll}. - */ - function setApprovalForAll(address operator, bool approved) public virtual override { - _setApprovalForAll(_msgSender(), operator, approved); - } - - /** - * @dev See {IERC721-isApprovedForAll}. - */ - function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { - return _operatorApprovals[owner][operator]; - } - - /** - * @dev See {IERC721-transferFrom}. - */ - function transferFrom( - address from, - address to, - uint256 tokenId - ) public virtual override { - //solhint-disable-next-line max-line-length - require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); - - _transfer(from, to, tokenId); - } - - /** - * @dev See {IERC721-safeTransferFrom}. - */ - function safeTransferFrom( - address from, - address to, - uint256 tokenId - ) public virtual override { - safeTransferFrom(from, to, tokenId, ""); - } - - /** - * @dev See {IERC721-safeTransferFrom}. - */ - function safeTransferFrom( - address from, - address to, - uint256 tokenId, - bytes memory _data - ) public virtual override { - require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); - _safeTransfer(from, to, tokenId, _data); - } - - /** - * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients - * are aware of the ERC721 protocol to prevent tokens from being forever locked. - * - * `_data` is additional data, it has no specified format and it is sent in call to `to`. - * - * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. - * implement alternative mechanisms to perform token transfer, such as signature-based. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `tokenId` token must exist and be owned by `from`. - * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. - * - * Emits a {Transfer} event. - */ - function _safeTransfer( - address from, - address to, - uint256 tokenId, - bytes memory _data - ) internal virtual { - _transfer(from, to, tokenId); - require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); - } - - /** - * @dev Returns whether `tokenId` exists. - * - * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. - * - * Tokens start existing when they are minted (`_mint`), - * and stop existing when they are burned (`_burn`). - */ - function _exists(uint256 tokenId) internal view virtual returns (bool) { - return _owners[tokenId] != address(0); - } - - /** - * @dev Returns whether `spender` is allowed to manage `tokenId`. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { - require(_exists(tokenId), "ERC721: operator query for nonexistent token"); - address owner = ERC721.ownerOf(tokenId); - return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); - } - - /** - * @dev Safely mints `tokenId` and transfers it to `to`. - * - * Requirements: - * - * - `tokenId` must not exist. - * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. - * - * Emits a {Transfer} event. - */ - function _safeMint(address to, uint256 tokenId) internal virtual { - _safeMint(to, tokenId, ""); - } - - /** - * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is - * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. - */ - function _safeMint( - address to, - uint256 tokenId, - bytes memory _data - ) internal virtual { - _mint(to, tokenId); - require( - _checkOnERC721Received(address(0), to, tokenId, _data), - "ERC721: transfer to non ERC721Receiver implementer" - ); - } - - /** - * @dev Mints `tokenId` and transfers it to `to`. - * - * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible - * - * Requirements: - * - * - `tokenId` must not exist. - * - `to` cannot be the zero address. - * - * Emits a {Transfer} event. - */ - function _mint(address to, uint256 tokenId) internal virtual { - require(to != address(0), "ERC721: mint to the zero address"); - require(!_exists(tokenId), "ERC721: token already minted"); - - _beforeTokenTransfer(address(0), to, tokenId); - - _balances[to] += 1; - _owners[tokenId] = to; - - emit Transfer(address(0), to, tokenId); - - _afterTokenTransfer(address(0), to, tokenId); - } - - /** - * @dev Destroys `tokenId`. - * The approval is cleared when the token is burned. - * - * Requirements: - * - * - `tokenId` must exist. - * - * Emits a {Transfer} event. - */ - function _burn(uint256 tokenId) internal virtual { - address owner = ERC721.ownerOf(tokenId); - - _beforeTokenTransfer(owner, address(0), tokenId); - - // Clear approvals - _approve(address(0), tokenId); - - _balances[owner] -= 1; - delete _owners[tokenId]; - - emit Transfer(owner, address(0), tokenId); - - _afterTokenTransfer(owner, address(0), tokenId); - } - - /** - * @dev Transfers `tokenId` from `from` to `to`. - * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - `tokenId` token must be owned by `from`. - * - * Emits a {Transfer} event. - */ - function _transfer( - address from, - address to, - uint256 tokenId - ) internal virtual { - require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); - require(to != address(0), "ERC721: transfer to the zero address"); - - _beforeTokenTransfer(from, to, tokenId); - - // Clear approvals from the previous owner - _approve(address(0), tokenId); - - _balances[from] -= 1; - _balances[to] += 1; - _owners[tokenId] = to; - - emit Transfer(from, to, tokenId); - - _afterTokenTransfer(from, to, tokenId); - } - - /** - * @dev Approve `to` to operate on `tokenId` - * - * Emits a {Approval} event. - */ - function _approve(address to, uint256 tokenId) internal virtual { - _tokenApprovals[tokenId] = to; - emit Approval(ERC721.ownerOf(tokenId), to, tokenId); - } - - /** - * @dev Approve `operator` to operate on all of `owner` tokens - * - * Emits a {ApprovalForAll} event. - */ - function _setApprovalForAll( - address owner, - address operator, - bool approved - ) internal virtual { - require(owner != operator, "ERC721: approve to caller"); - _operatorApprovals[owner][operator] = approved; - emit ApprovalForAll(owner, operator, approved); - } - - /** - * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. - * The call is not executed if the target address is not a contract. - * - * @param from address representing the previous owner of the given token ID - * @param to target address that will receive the tokens - * @param tokenId uint256 ID of the token to be transferred - * @param _data bytes optional data to send along with the call - * @return bool whether the call correctly returned the expected magic value - */ - function _checkOnERC721Received( - address from, - address to, - uint256 tokenId, - bytes memory _data - ) private returns (bool) { - if (to.isContract()) { - try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { - return retval == IERC721Receiver.onERC721Received.selector; - } catch (bytes memory reason) { - if (reason.length == 0) { - revert("ERC721: transfer to non ERC721Receiver implementer"); - } else { - assembly { - revert(add(32, reason), mload(reason)) - } - } - } - } else { - return true; - } - } - - /** - * @dev Hook that is called before any token transfer. This includes minting - * and burning. - * - * Calling conditions: - * - * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be - * transferred to `to`. - * - When `from` is zero, `tokenId` will be minted for `to`. - * - When `to` is zero, ``from``'s `tokenId` will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual {} - - /** - * @dev Hook that is called after any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual {} -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol deleted file mode 100644 index fc58b032..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol +++ /dev/null @@ -1,143 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) - -pragma solidity ^0.8.0; - -import "../../utils/introspection/IERC165.sol"; - -/** - * @dev Required interface of an ERC721 compliant contract. - */ -interface IERC721 is IERC165 { - /** - * @dev Emitted when `tokenId` token is transferred from `from` to `to`. - */ - event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); - - /** - * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. - */ - event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); - - /** - * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. - */ - event ApprovalForAll(address indexed owner, address indexed operator, bool approved); - - /** - * @dev Returns the number of tokens in ``owner``'s account. - */ - function balanceOf(address owner) external view returns (uint256 balance); - - /** - * @dev Returns the owner of the `tokenId` token. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function ownerOf(uint256 tokenId) external view returns (address owner); - - /** - * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients - * are aware of the ERC721 protocol to prevent tokens from being forever locked. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `tokenId` token must exist and be owned by `from`. - * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. - * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. - * - * Emits a {Transfer} event. - */ - function safeTransferFrom( - address from, - address to, - uint256 tokenId - ) external; - - /** - * @dev Transfers `tokenId` token from `from` to `to`. - * - * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `tokenId` token must be owned by `from`. - * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. - * - * Emits a {Transfer} event. - */ - function transferFrom( - address from, - address to, - uint256 tokenId - ) external; - - /** - * @dev Gives permission to `to` to transfer `tokenId` token to another account. - * The approval is cleared when the token is transferred. - * - * Only a single account can be approved at a time, so approving the zero address clears previous approvals. - * - * Requirements: - * - * - The caller must own the token or be an approved operator. - * - `tokenId` must exist. - * - * Emits an {Approval} event. - */ - function approve(address to, uint256 tokenId) external; - - /** - * @dev Returns the account approved for `tokenId` token. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function getApproved(uint256 tokenId) external view returns (address operator); - - /** - * @dev Approve or remove `operator` as an operator for the caller. - * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. - * - * Requirements: - * - * - The `operator` cannot be the caller. - * - * Emits an {ApprovalForAll} event. - */ - function setApprovalForAll(address operator, bool _approved) external; - - /** - * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. - * - * See {setApprovalForAll} - */ - function isApprovedForAll(address owner, address operator) external view returns (bool); - - /** - * @dev Safely transfers `tokenId` token from `from` to `to`. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `tokenId` token must exist and be owned by `from`. - * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. - * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. - * - * Emits a {Transfer} event. - */ - function safeTransferFrom( - address from, - address to, - uint256 tokenId, - bytes calldata data - ) external; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol deleted file mode 100644 index a42cb52f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) - -pragma solidity ^0.8.0; - -/** - * @title ERC721 token receiver interface - * @dev Interface for any contract that wants to support safeTransfers - * from ERC721 asset contracts. - */ -interface IERC721Receiver { - /** - * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} - * by `operator` from `from`, this function is called. - * - * It must return its Solidity selector to confirm the token transfer. - * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. - * - * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. - */ - function onERC721Received( - address operator, - address from, - uint256 tokenId, - bytes calldata data - ) external returns (bytes4); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/README.adoc deleted file mode 100644 index 92959576..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/README.adoc +++ /dev/null @@ -1,67 +0,0 @@ -= ERC 721 - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc721 - -This set of interfaces, contracts, and utilities are all related to the https://eips.ethereum.org/EIPS/eip-721[ERC721 Non-Fungible Token Standard]. - -TIP: For a walk through on how to create an ERC721 token read our xref:ROOT:erc721.adoc[ERC721 guide]. - -The EIP specifies four interfaces: - -* {IERC721}: Core functionality required in all compliant implementation. -* {IERC721Metadata}: Optional extension that adds name, symbol, and token URI, almost always included. -* {IERC721Enumerable}: Optional extension that allows enumerating the tokens on chain, often not included since it requires large gas overhead. -* {IERC721Receiver}: An interface that must be implemented by contracts if they want to accept tokens through `safeTransferFrom`. - -OpenZeppelin Contracts provides implementations of all four interfaces: - -* {ERC721}: The core and metadata extensions, with a base URI mechanism. -* {ERC721Enumerable}: The enumerable extension. -* {ERC721Holder}: A bare bones implementation of the receiver interface. - -Additionally there are a few of other extensions: - -* {ERC721URIStorage}: A more flexible but more expensive way of storing metadata. -* {ERC721Votes}: Support for voting and vote delegation. -* {ERC721Royalty}: A way to signal royalty information following ERC2981. -* {ERC721Pausable}: A primitive to pause contract operation. -* {ERC721Burnable}: A way for token holders to burn their own tokens. - -NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC721 (such as <>) and expose them as external functions in the way they prefer. On the other hand, xref:ROOT:erc721.adoc#Presets[ERC721 Presets] (such as {ERC721PresetMinterPauserAutoId}) are designed using opinionated patterns to provide developers with ready to use, deployable contracts. - -== Core - -{{IERC721}} - -{{IERC721Metadata}} - -{{IERC721Enumerable}} - -{{ERC721}} - -{{ERC721Enumerable}} - -{{IERC721Receiver}} - -== Extensions - -{{ERC721Pausable}} - -{{ERC721Burnable}} - -{{ERC721URIStorage}} - -{{ERC721Votes}} - -{{ERC721Royalty}} - -== Presets - -These contracts are preconfigured combinations of the above features. They can be used through inheritance or as models to copy and paste their source code. - -{{ERC721PresetMinterPauserAutoId}} - -== Utilities - -{{ERC721Holder}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Burnable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Burnable.sol deleted file mode 100644 index 063997dd..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Burnable.sol +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) - -pragma solidity ^0.8.0; - -import "../ERC721.sol"; -import "../../../utils/Context.sol"; - -/** - * @title ERC721 Burnable Token - * @dev ERC721 Token that can be irreversibly burned (destroyed). - */ -abstract contract ERC721Burnable is Context, ERC721 { - /** - * @dev Burns `tokenId`. See {ERC721-_burn}. - * - * Requirements: - * - * - The caller must own `tokenId` or be an approved operator. - */ - function burn(uint256 tokenId) public virtual { - //solhint-disable-next-line max-line-length - require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); - _burn(tokenId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Enumerable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Enumerable.sol deleted file mode 100644 index 46afd5d0..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Enumerable.sol +++ /dev/null @@ -1,163 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) - -pragma solidity ^0.8.0; - -import "../ERC721.sol"; -import "./IERC721Enumerable.sol"; - -/** - * @dev This implements an optional extension of {ERC721} defined in the EIP that adds - * enumerability of all the token ids in the contract as well as all token ids owned by each - * account. - */ -abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { - // Mapping from owner to list of owned token IDs - mapping(address => mapping(uint256 => uint256)) private _ownedTokens; - - // Mapping from token ID to index of the owner tokens list - mapping(uint256 => uint256) private _ownedTokensIndex; - - // Array with all token ids, used for enumeration - uint256[] private _allTokens; - - // Mapping from token id to position in the allTokens array - mapping(uint256 => uint256) private _allTokensIndex; - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { - return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. - */ - function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { - require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); - return _ownedTokens[owner][index]; - } - - /** - * @dev See {IERC721Enumerable-totalSupply}. - */ - function totalSupply() public view virtual override returns (uint256) { - return _allTokens.length; - } - - /** - * @dev See {IERC721Enumerable-tokenByIndex}. - */ - function tokenByIndex(uint256 index) public view virtual override returns (uint256) { - require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); - return _allTokens[index]; - } - - /** - * @dev Hook that is called before any token transfer. This includes minting - * and burning. - * - * Calling conditions: - * - * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be - * transferred to `to`. - * - When `from` is zero, `tokenId` will be minted for `to`. - * - When `to` is zero, ``from``'s `tokenId` will be burned. - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual override { - super._beforeTokenTransfer(from, to, tokenId); - - if (from == address(0)) { - _addTokenToAllTokensEnumeration(tokenId); - } else if (from != to) { - _removeTokenFromOwnerEnumeration(from, tokenId); - } - if (to == address(0)) { - _removeTokenFromAllTokensEnumeration(tokenId); - } else if (to != from) { - _addTokenToOwnerEnumeration(to, tokenId); - } - } - - /** - * @dev Private function to add a token to this extension's ownership-tracking data structures. - * @param to address representing the new owner of the given token ID - * @param tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { - uint256 length = ERC721.balanceOf(to); - _ownedTokens[to][length] = tokenId; - _ownedTokensIndex[tokenId] = length; - } - - /** - * @dev Private function to add a token to this extension's token tracking data structures. - * @param tokenId uint256 ID of the token to be added to the tokens list - */ - function _addTokenToAllTokensEnumeration(uint256 tokenId) private { - _allTokensIndex[tokenId] = _allTokens.length; - _allTokens.push(tokenId); - } - - /** - * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that - * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for - * gas optimizations e.g. when performing a transfer operation (avoiding double writes). - * This has O(1) time complexity, but alters the order of the _ownedTokens array. - * @param from address representing the previous owner of the given token ID - * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { - // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and - // then delete the last slot (swap and pop). - - uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; - uint256 tokenIndex = _ownedTokensIndex[tokenId]; - - // When the token to delete is the last token, the swap operation is unnecessary - if (tokenIndex != lastTokenIndex) { - uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; - - _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token - _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index - } - - // This also deletes the contents at the last position of the array - delete _ownedTokensIndex[tokenId]; - delete _ownedTokens[from][lastTokenIndex]; - } - - /** - * @dev Private function to remove a token from this extension's token tracking data structures. - * This has O(1) time complexity, but alters the order of the _allTokens array. - * @param tokenId uint256 ID of the token to be removed from the tokens list - */ - function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { - // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and - // then delete the last slot (swap and pop). - - uint256 lastTokenIndex = _allTokens.length - 1; - uint256 tokenIndex = _allTokensIndex[tokenId]; - - // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so - // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding - // an 'if' statement (like in _removeTokenFromOwnerEnumeration) - uint256 lastTokenId = _allTokens[lastTokenIndex]; - - _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token - _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index - - // This also deletes the contents at the last position of the array - delete _allTokensIndex[tokenId]; - _allTokens.pop(); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Pausable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Pausable.sol deleted file mode 100644 index fbf8b638..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Pausable.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol) - -pragma solidity ^0.8.0; - -import "../ERC721.sol"; -import "../../../security/Pausable.sol"; - -/** - * @dev ERC721 token with pausable token transfers, minting and burning. - * - * Useful for scenarios such as preventing trades until the end of an evaluation - * period, or having an emergency switch for freezing all token transfers in the - * event of a large bug. - */ -abstract contract ERC721Pausable is ERC721, Pausable { - /** - * @dev See {ERC721-_beforeTokenTransfer}. - * - * Requirements: - * - * - the contract must not be paused. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual override { - super._beforeTokenTransfer(from, to, tokenId); - - require(!paused(), "ERC721Pausable: token transfer while paused"); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Royalty.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Royalty.sol deleted file mode 100644 index f9414da0..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Royalty.sol +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/ERC721Royalty.sol) - -pragma solidity ^0.8.0; - -import "../ERC721.sol"; -import "../../common/ERC2981.sol"; -import "../../../utils/introspection/ERC165.sol"; - -/** - * @dev Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty payment - * information. - * - * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for - * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. - * - * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See - * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to - * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. - * - * _Available since v4.5._ - */ -abstract contract ERC721Royalty is ERC2981, ERC721 { - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { - return super.supportsInterface(interfaceId); - } - - /** - * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token. - */ - function _burn(uint256 tokenId) internal virtual override { - super._burn(tokenId); - _resetTokenRoyalty(tokenId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721URIStorage.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721URIStorage.sol deleted file mode 100644 index bc0e07e7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721URIStorage.sol +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) - -pragma solidity ^0.8.0; - -import "../ERC721.sol"; - -/** - * @dev ERC721 token with storage based token URI management. - */ -abstract contract ERC721URIStorage is ERC721 { - using Strings for uint256; - - // Optional mapping for token URIs - mapping(uint256 => string) private _tokenURIs; - - /** - * @dev See {IERC721Metadata-tokenURI}. - */ - function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { - require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); - - string memory _tokenURI = _tokenURIs[tokenId]; - string memory base = _baseURI(); - - // If there is no base URI, return the token URI. - if (bytes(base).length == 0) { - return _tokenURI; - } - // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). - if (bytes(_tokenURI).length > 0) { - return string(abi.encodePacked(base, _tokenURI)); - } - - return super.tokenURI(tokenId); - } - - /** - * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { - require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); - _tokenURIs[tokenId] = _tokenURI; - } - - /** - * @dev Destroys `tokenId`. - * The approval is cleared when the token is burned. - * - * Requirements: - * - * - `tokenId` must exist. - * - * Emits a {Transfer} event. - */ - function _burn(uint256 tokenId) internal virtual override { - super._burn(tokenId); - - if (bytes(_tokenURIs[tokenId]).length != 0) { - delete _tokenURIs[tokenId]; - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Enumerable.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Enumerable.sol deleted file mode 100644 index dfea427b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Enumerable.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) - -pragma solidity ^0.8.0; - -import "../IERC721.sol"; - -/** - * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension - * @dev See https://eips.ethereum.org/EIPS/eip-721 - */ -interface IERC721Enumerable is IERC721 { - /** - * @dev Returns the total amount of tokens stored by the contract. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns a token ID owned by `owner` at a given `index` of its token list. - * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. - */ - function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); - - /** - * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. - * Use along with {totalSupply} to enumerate all tokens. - */ - function tokenByIndex(uint256 index) external view returns (uint256); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol deleted file mode 100644 index dca77ba5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) - -pragma solidity ^0.8.0; - -import "../IERC721.sol"; - -/** - * @title ERC-721 Non-Fungible Token Standard, optional metadata extension - * @dev See https://eips.ethereum.org/EIPS/eip-721 - */ -interface IERC721Metadata is IERC721 { - /** - * @dev Returns the token collection name. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the token collection symbol. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. - */ - function tokenURI(uint256 tokenId) external view returns (string memory); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/draft-ERC721Votes.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/draft-ERC721Votes.sol deleted file mode 100644 index 7d23c492..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/draft-ERC721Votes.sol +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/draft-ERC721Votes.sol) - -pragma solidity ^0.8.0; - -import "../ERC721.sol"; -import "../../../governance/utils/Votes.sol"; - -/** - * @dev Extension of ERC721 to support voting and delegation as implemented by {Votes}, where each individual NFT counts - * as 1 vote unit. - * - * Tokens do not count as votes until they are delegated, because votes must be tracked which incurs an additional cost - * on every transfer. Token holders can either delegate to a trusted representative who will decide how to make use of - * the votes in governance decisions, or they can delegate to themselves to be their own representative. - * - * _Available since v4.5._ - */ -abstract contract ERC721Votes is ERC721, Votes { - /** - * @dev Adjusts votes when tokens are transferred. - * - * Emits a {Votes-DelegateVotesChanged} event. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual override { - _transferVotingUnits(from, to, 1); - super._afterTokenTransfer(from, to, tokenId); - } - - /** - * @dev Returns the balance of `account`. - */ - function _getVotingUnits(address account) internal virtual override returns (uint256) { - return balanceOf(account); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol deleted file mode 100644 index 11b97878..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol +++ /dev/null @@ -1,139 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol) - -pragma solidity ^0.8.0; - -import "../ERC721.sol"; -import "../extensions/ERC721Enumerable.sol"; -import "../extensions/ERC721Burnable.sol"; -import "../extensions/ERC721Pausable.sol"; -import "../../../access/AccessControlEnumerable.sol"; -import "../../../utils/Context.sol"; -import "../../../utils/Counters.sol"; - -/** - * @dev {ERC721} token, including: - * - * - ability for holders to burn (destroy) their tokens - * - a minter role that allows for token minting (creation) - * - a pauser role that allows to stop all token transfers - * - token ID and URI autogeneration - * - * This contract uses {AccessControl} to lock permissioned functions using the - * different roles - head to its documentation for details. - * - * The account that deploys the contract will be granted the minter and pauser - * roles, as well as the default admin role, which will let it grant both minter - * and pauser roles to other accounts. - * - * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._ - */ -contract ERC721PresetMinterPauserAutoId is - Context, - AccessControlEnumerable, - ERC721Enumerable, - ERC721Burnable, - ERC721Pausable -{ - using Counters for Counters.Counter; - - bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); - bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); - - Counters.Counter private _tokenIdTracker; - - string private _baseTokenURI; - - /** - * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the - * account that deploys the contract. - * - * Token URIs will be autogenerated based on `baseURI` and their token IDs. - * See {ERC721-tokenURI}. - */ - constructor( - string memory name, - string memory symbol, - string memory baseTokenURI - ) ERC721(name, symbol) { - _baseTokenURI = baseTokenURI; - - _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); - - _setupRole(MINTER_ROLE, _msgSender()); - _setupRole(PAUSER_ROLE, _msgSender()); - } - - function _baseURI() internal view virtual override returns (string memory) { - return _baseTokenURI; - } - - /** - * @dev Creates a new token for `to`. Its token ID will be automatically - * assigned (and available on the emitted {IERC721-Transfer} event), and the token - * URI autogenerated based on the base URI passed at construction. - * - * See {ERC721-_mint}. - * - * Requirements: - * - * - the caller must have the `MINTER_ROLE`. - */ - function mint(address to) public virtual { - require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); - - // We cannot just use balanceOf to create the new tokenId because tokens - // can be burned (destroyed), so we need a separate counter. - _mint(to, _tokenIdTracker.current()); - _tokenIdTracker.increment(); - } - - /** - * @dev Pauses all token transfers. - * - * See {ERC721Pausable} and {Pausable-_pause}. - * - * Requirements: - * - * - the caller must have the `PAUSER_ROLE`. - */ - function pause() public virtual { - require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); - _pause(); - } - - /** - * @dev Unpauses all token transfers. - * - * See {ERC721Pausable} and {Pausable-_unpause}. - * - * Requirements: - * - * - the caller must have the `PAUSER_ROLE`. - */ - function unpause() public virtual { - require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); - _unpause(); - } - - function _beforeTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { - super._beforeTokenTransfer(from, to, tokenId); - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) - public - view - virtual - override(AccessControlEnumerable, ERC721, ERC721Enumerable) - returns (bool) - { - return super.supportsInterface(interfaceId); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/presets/README.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/presets/README.md deleted file mode 100644 index 468200b7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/presets/README.md +++ /dev/null @@ -1 +0,0 @@ -Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol deleted file mode 100644 index 394926d5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) - -pragma solidity ^0.8.0; - -import "../IERC721Receiver.sol"; - -/** - * @dev Implementation of the {IERC721Receiver} interface. - * - * Accepts all token transfers. - * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. - */ -contract ERC721Holder is IERC721Receiver { - /** - * @dev See {IERC721Receiver-onERC721Received}. - * - * Always returns `IERC721Receiver.onERC721Received.selector`. - */ - function onERC721Received( - address, - address, - uint256, - bytes memory - ) public virtual override returns (bytes4) { - return this.onERC721Received.selector; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/ERC777.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/ERC777.sol deleted file mode 100644 index a676d623..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/ERC777.sol +++ /dev/null @@ -1,565 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC777/ERC777.sol) - -pragma solidity ^0.8.0; - -import "./IERC777.sol"; -import "./IERC777Recipient.sol"; -import "./IERC777Sender.sol"; -import "../ERC20/IERC20.sol"; -import "../../utils/Address.sol"; -import "../../utils/Context.sol"; -import "../../utils/introspection/IERC1820Registry.sol"; - -/** - * @dev Implementation of the {IERC777} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * - * Support for ERC20 is included in this contract, as specified by the EIP: both - * the ERC777 and ERC20 interfaces can be safely used when interacting with it. - * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token - * movements. - * - * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there - * are no special restrictions in the amount of tokens that created, moved, or - * destroyed. This makes integration with ERC20 applications seamless. - */ -contract ERC777 is Context, IERC777, IERC20 { - using Address for address; - - IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); - - mapping(address => uint256) private _balances; - - uint256 private _totalSupply; - - string private _name; - string private _symbol; - - bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); - bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); - - // This isn't ever read from - it's only used to respond to the defaultOperators query. - address[] private _defaultOperatorsArray; - - // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). - mapping(address => bool) private _defaultOperators; - - // For each account, a mapping of its operators and revoked default operators. - mapping(address => mapping(address => bool)) private _operators; - mapping(address => mapping(address => bool)) private _revokedDefaultOperators; - - // ERC20-allowances - mapping(address => mapping(address => uint256)) private _allowances; - - /** - * @dev `defaultOperators` may be an empty array. - */ - constructor( - string memory name_, - string memory symbol_, - address[] memory defaultOperators_ - ) { - _name = name_; - _symbol = symbol_; - - _defaultOperatorsArray = defaultOperators_; - for (uint256 i = 0; i < defaultOperators_.length; i++) { - _defaultOperators[defaultOperators_[i]] = true; - } - - // register interfaces - _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); - _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); - } - - /** - * @dev See {IERC777-name}. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev See {IERC777-symbol}. - */ - function symbol() public view virtual override returns (string memory) { - return _symbol; - } - - /** - * @dev See {ERC20-decimals}. - * - * Always returns 18, as per the - * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). - */ - function decimals() public pure virtual returns (uint8) { - return 18; - } - - /** - * @dev See {IERC777-granularity}. - * - * This implementation always returns `1`. - */ - function granularity() public view virtual override returns (uint256) { - return 1; - } - - /** - * @dev See {IERC777-totalSupply}. - */ - function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) { - return _totalSupply; - } - - /** - * @dev Returns the amount of tokens owned by an account (`tokenHolder`). - */ - function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) { - return _balances[tokenHolder]; - } - - /** - * @dev See {IERC777-send}. - * - * Also emits a {IERC20-Transfer} event for ERC20 compatibility. - */ - function send( - address recipient, - uint256 amount, - bytes memory data - ) public virtual override { - _send(_msgSender(), recipient, amount, data, "", true); - } - - /** - * @dev See {IERC20-transfer}. - * - * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} - * interface if it is a contract. - * - * Also emits a {Sent} event. - */ - function transfer(address recipient, uint256 amount) public virtual override returns (bool) { - require(recipient != address(0), "ERC777: transfer to the zero address"); - - address from = _msgSender(); - - _callTokensToSend(from, from, recipient, amount, "", ""); - - _move(from, from, recipient, amount, "", ""); - - _callTokensReceived(from, from, recipient, amount, "", "", false); - - return true; - } - - /** - * @dev See {IERC777-burn}. - * - * Also emits a {IERC20-Transfer} event for ERC20 compatibility. - */ - function burn(uint256 amount, bytes memory data) public virtual override { - _burn(_msgSender(), amount, data, ""); - } - - /** - * @dev See {IERC777-isOperatorFor}. - */ - function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { - return - operator == tokenHolder || - (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || - _operators[tokenHolder][operator]; - } - - /** - * @dev See {IERC777-authorizeOperator}. - */ - function authorizeOperator(address operator) public virtual override { - require(_msgSender() != operator, "ERC777: authorizing self as operator"); - - if (_defaultOperators[operator]) { - delete _revokedDefaultOperators[_msgSender()][operator]; - } else { - _operators[_msgSender()][operator] = true; - } - - emit AuthorizedOperator(operator, _msgSender()); - } - - /** - * @dev See {IERC777-revokeOperator}. - */ - function revokeOperator(address operator) public virtual override { - require(operator != _msgSender(), "ERC777: revoking self as operator"); - - if (_defaultOperators[operator]) { - _revokedDefaultOperators[_msgSender()][operator] = true; - } else { - delete _operators[_msgSender()][operator]; - } - - emit RevokedOperator(operator, _msgSender()); - } - - /** - * @dev See {IERC777-defaultOperators}. - */ - function defaultOperators() public view virtual override returns (address[] memory) { - return _defaultOperatorsArray; - } - - /** - * @dev See {IERC777-operatorSend}. - * - * Emits {Sent} and {IERC20-Transfer} events. - */ - function operatorSend( - address sender, - address recipient, - uint256 amount, - bytes memory data, - bytes memory operatorData - ) public virtual override { - require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); - _send(sender, recipient, amount, data, operatorData, true); - } - - /** - * @dev See {IERC777-operatorBurn}. - * - * Emits {Burned} and {IERC20-Transfer} events. - */ - function operatorBurn( - address account, - uint256 amount, - bytes memory data, - bytes memory operatorData - ) public virtual override { - require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); - _burn(account, amount, data, operatorData); - } - - /** - * @dev See {IERC20-allowance}. - * - * Note that operator and allowance concepts are orthogonal: operators may - * not have allowance, and accounts with allowance may not be operators - * themselves. - */ - function allowance(address holder, address spender) public view virtual override returns (uint256) { - return _allowances[holder][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on - * `transferFrom`. This is semantically equivalent to an infinite approval. - * - * Note that accounts cannot have allowance issued by their operators. - */ - function approve(address spender, uint256 value) public virtual override returns (bool) { - address holder = _msgSender(); - _approve(holder, spender, value); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * NOTE: Does not update the allowance if the current allowance - * is the maximum `uint256`. - * - * Note that operator and allowance concepts are orthogonal: operators cannot - * call `transferFrom` (unless they have allowance), and accounts with - * allowance cannot call `operatorSend` (unless they are operators). - * - * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. - */ - function transferFrom( - address holder, - address recipient, - uint256 amount - ) public virtual override returns (bool) { - require(recipient != address(0), "ERC777: transfer to the zero address"); - require(holder != address(0), "ERC777: transfer from the zero address"); - - address spender = _msgSender(); - - _callTokensToSend(spender, holder, recipient, amount, "", ""); - - _spendAllowance(holder, spender, amount); - - _move(spender, holder, recipient, amount, "", ""); - - _callTokensReceived(spender, holder, recipient, amount, "", "", false); - - return true; - } - - /** - * @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * If a send hook is registered for `account`, the corresponding function - * will be called with `operator`, `data` and `operatorData`. - * - * See {IERC777Sender} and {IERC777Recipient}. - * - * Emits {Minted} and {IERC20-Transfer} events. - * - * Requirements - * - * - `account` cannot be the zero address. - * - if `account` is a contract, it must implement the {IERC777Recipient} - * interface. - */ - function _mint( - address account, - uint256 amount, - bytes memory userData, - bytes memory operatorData - ) internal virtual { - _mint(account, amount, userData, operatorData, true); - } - - /** - * @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * If `requireReceptionAck` is set to true, and if a send hook is - * registered for `account`, the corresponding function will be called with - * `operator`, `data` and `operatorData`. - * - * See {IERC777Sender} and {IERC777Recipient}. - * - * Emits {Minted} and {IERC20-Transfer} events. - * - * Requirements - * - * - `account` cannot be the zero address. - * - if `account` is a contract, it must implement the {IERC777Recipient} - * interface. - */ - function _mint( - address account, - uint256 amount, - bytes memory userData, - bytes memory operatorData, - bool requireReceptionAck - ) internal virtual { - require(account != address(0), "ERC777: mint to the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, address(0), account, amount); - - // Update state variables - _totalSupply += amount; - _balances[account] += amount; - - _callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck); - - emit Minted(operator, account, amount, userData, operatorData); - emit Transfer(address(0), account, amount); - } - - /** - * @dev Send tokens - * @param from address token holder address - * @param to address recipient address - * @param amount uint256 amount of tokens to transfer - * @param userData bytes extra information provided by the token holder (if any) - * @param operatorData bytes extra information provided by the operator (if any) - * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient - */ - function _send( - address from, - address to, - uint256 amount, - bytes memory userData, - bytes memory operatorData, - bool requireReceptionAck - ) internal virtual { - require(from != address(0), "ERC777: send from the zero address"); - require(to != address(0), "ERC777: send to the zero address"); - - address operator = _msgSender(); - - _callTokensToSend(operator, from, to, amount, userData, operatorData); - - _move(operator, from, to, amount, userData, operatorData); - - _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); - } - - /** - * @dev Burn tokens - * @param from address token holder address - * @param amount uint256 amount of tokens to burn - * @param data bytes extra information provided by the token holder - * @param operatorData bytes extra information provided by the operator (if any) - */ - function _burn( - address from, - uint256 amount, - bytes memory data, - bytes memory operatorData - ) internal virtual { - require(from != address(0), "ERC777: burn from the zero address"); - - address operator = _msgSender(); - - _callTokensToSend(operator, from, address(0), amount, data, operatorData); - - _beforeTokenTransfer(operator, from, address(0), amount); - - // Update state variables - uint256 fromBalance = _balances[from]; - require(fromBalance >= amount, "ERC777: burn amount exceeds balance"); - unchecked { - _balances[from] = fromBalance - amount; - } - _totalSupply -= amount; - - emit Burned(operator, from, amount, data, operatorData); - emit Transfer(from, address(0), amount); - } - - function _move( - address operator, - address from, - address to, - uint256 amount, - bytes memory userData, - bytes memory operatorData - ) private { - _beforeTokenTransfer(operator, from, to, amount); - - uint256 fromBalance = _balances[from]; - require(fromBalance >= amount, "ERC777: transfer amount exceeds balance"); - unchecked { - _balances[from] = fromBalance - amount; - } - _balances[to] += amount; - - emit Sent(operator, from, to, amount, userData, operatorData); - emit Transfer(from, to, amount); - } - - /** - * @dev See {ERC20-_approve}. - * - * Note that accounts cannot have allowance issued by their operators. - */ - function _approve( - address holder, - address spender, - uint256 value - ) internal virtual { - require(holder != address(0), "ERC777: approve from the zero address"); - require(spender != address(0), "ERC777: approve to the zero address"); - - _allowances[holder][spender] = value; - emit Approval(holder, spender, value); - } - - /** - * @dev Call from.tokensToSend() if the interface is registered - * @param operator address operator requesting the transfer - * @param from address token holder address - * @param to address recipient address - * @param amount uint256 amount of tokens to transfer - * @param userData bytes extra information provided by the token holder (if any) - * @param operatorData bytes extra information provided by the operator (if any) - */ - function _callTokensToSend( - address operator, - address from, - address to, - uint256 amount, - bytes memory userData, - bytes memory operatorData - ) private { - address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); - if (implementer != address(0)) { - IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); - } - } - - /** - * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but - * tokensReceived() was not registered for the recipient - * @param operator address operator requesting the transfer - * @param from address token holder address - * @param to address recipient address - * @param amount uint256 amount of tokens to transfer - * @param userData bytes extra information provided by the token holder (if any) - * @param operatorData bytes extra information provided by the operator (if any) - * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient - */ - function _callTokensReceived( - address operator, - address from, - address to, - uint256 amount, - bytes memory userData, - bytes memory operatorData, - bool requireReceptionAck - ) private { - address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); - if (implementer != address(0)) { - IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); - } else if (requireReceptionAck) { - require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); - } - } - - /** - * @dev Spend `amount` form the allowance of `owner` toward `spender`. - * - * Does not update the allowance amount in case of infinite allowance. - * Revert if not enough allowance is available. - * - * Might emit an {Approval} event. - */ - function _spendAllowance( - address owner, - address spender, - uint256 amount - ) internal virtual { - uint256 currentAllowance = allowance(owner, spender); - if (currentAllowance != type(uint256).max) { - require(currentAllowance >= amount, "ERC777: insufficient allowance"); - unchecked { - _approve(owner, spender, currentAllowance - amount); - } - } - } - - /** - * @dev Hook that is called before any token transfer. This includes - * calls to {send}, {transfer}, {operatorSend}, minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be to transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256 amount - ) internal virtual {} -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777.sol deleted file mode 100644 index 5a729176..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777.sol +++ /dev/null @@ -1,193 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC777Token standard as defined in the EIP. - * - * This contract uses the - * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let - * token holders and recipients react to token movements by using setting implementers - * for the associated interfaces in said registry. See {IERC1820Registry} and - * {ERC1820Implementer}. - */ -interface IERC777 { - /** - * @dev Returns the name of the token. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the smallest part of the token that is not divisible. This - * means all token operations (creation, movement and destruction) must have - * amounts that are a multiple of this number. - * - * For most token contracts, this value will equal 1. - */ - function granularity() external view returns (uint256); - - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by an account (`owner`). - */ - function balanceOf(address owner) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `recipient`. - * - * If send or receive hooks are registered for the caller and `recipient`, - * the corresponding functions will be called with `data` and empty - * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. - * - * Emits a {Sent} event. - * - * Requirements - * - * - the caller must have at least `amount` tokens. - * - `recipient` cannot be the zero address. - * - if `recipient` is a contract, it must implement the {IERC777Recipient} - * interface. - */ - function send( - address recipient, - uint256 amount, - bytes calldata data - ) external; - - /** - * @dev Destroys `amount` tokens from the caller's account, reducing the - * total supply. - * - * If a send hook is registered for the caller, the corresponding function - * will be called with `data` and empty `operatorData`. See {IERC777Sender}. - * - * Emits a {Burned} event. - * - * Requirements - * - * - the caller must have at least `amount` tokens. - */ - function burn(uint256 amount, bytes calldata data) external; - - /** - * @dev Returns true if an account is an operator of `tokenHolder`. - * Operators can send and burn tokens on behalf of their owners. All - * accounts are their own operator. - * - * See {operatorSend} and {operatorBurn}. - */ - function isOperatorFor(address operator, address tokenHolder) external view returns (bool); - - /** - * @dev Make an account an operator of the caller. - * - * See {isOperatorFor}. - * - * Emits an {AuthorizedOperator} event. - * - * Requirements - * - * - `operator` cannot be calling address. - */ - function authorizeOperator(address operator) external; - - /** - * @dev Revoke an account's operator status for the caller. - * - * See {isOperatorFor} and {defaultOperators}. - * - * Emits a {RevokedOperator} event. - * - * Requirements - * - * - `operator` cannot be calling address. - */ - function revokeOperator(address operator) external; - - /** - * @dev Returns the list of default operators. These accounts are operators - * for all token holders, even if {authorizeOperator} was never called on - * them. - * - * This list is immutable, but individual holders may revoke these via - * {revokeOperator}, in which case {isOperatorFor} will return false. - */ - function defaultOperators() external view returns (address[] memory); - - /** - * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must - * be an operator of `sender`. - * - * If send or receive hooks are registered for `sender` and `recipient`, - * the corresponding functions will be called with `data` and - * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. - * - * Emits a {Sent} event. - * - * Requirements - * - * - `sender` cannot be the zero address. - * - `sender` must have at least `amount` tokens. - * - the caller must be an operator for `sender`. - * - `recipient` cannot be the zero address. - * - if `recipient` is a contract, it must implement the {IERC777Recipient} - * interface. - */ - function operatorSend( - address sender, - address recipient, - uint256 amount, - bytes calldata data, - bytes calldata operatorData - ) external; - - /** - * @dev Destroys `amount` tokens from `account`, reducing the total supply. - * The caller must be an operator of `account`. - * - * If a send hook is registered for `account`, the corresponding function - * will be called with `data` and `operatorData`. See {IERC777Sender}. - * - * Emits a {Burned} event. - * - * Requirements - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - * - the caller must be an operator for `account`. - */ - function operatorBurn( - address account, - uint256 amount, - bytes calldata data, - bytes calldata operatorData - ) external; - - event Sent( - address indexed operator, - address indexed from, - address indexed to, - uint256 amount, - bytes data, - bytes operatorData - ); - - event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); - - event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); - - event AuthorizedOperator(address indexed operator, address indexed tokenHolder); - - event RevokedOperator(address indexed operator, address indexed tokenHolder); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777Recipient.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777Recipient.sol deleted file mode 100644 index 717dd8f8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777Recipient.sol +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. - * - * Accounts can be notified of {IERC777} tokens being sent to them by having a - * contract implement this interface (contract holders can be their own - * implementer) and registering it on the - * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. - * - * See {IERC1820Registry} and {ERC1820Implementer}. - */ -interface IERC777Recipient { - /** - * @dev Called by an {IERC777} token contract whenever tokens are being - * moved or created into a registered account (`to`). The type of operation - * is conveyed by `from` being the zero address or not. - * - * This call occurs _after_ the token contract's state is updated, so - * {IERC777-balanceOf}, etc., can be used to query the post-operation state. - * - * This function may revert to prevent the operation from being executed. - */ - function tokensReceived( - address operator, - address from, - address to, - uint256 amount, - bytes calldata userData, - bytes calldata operatorData - ) external; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777Sender.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777Sender.sol deleted file mode 100644 index 969e3e36..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/IERC777Sender.sol +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Sender.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC777TokensSender standard as defined in the EIP. - * - * {IERC777} Token holders can be notified of operations performed on their - * tokens by having a contract implement this interface (contract holders can be - * their own implementer) and registering it on the - * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. - * - * See {IERC1820Registry} and {ERC1820Implementer}. - */ -interface IERC777Sender { - /** - * @dev Called by an {IERC777} token contract whenever a registered holder's - * (`from`) tokens are about to be moved or destroyed. The type of operation - * is conveyed by `to` being the zero address or not. - * - * This call occurs _before_ the token contract's state is updated, so - * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. - * - * This function may revert to prevent the operation from being executed. - */ - function tokensToSend( - address operator, - address from, - address to, - uint256 amount, - bytes calldata userData, - bytes calldata operatorData - ) external; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/README.adoc deleted file mode 100644 index d8f25f06..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/README.adoc +++ /dev/null @@ -1,30 +0,0 @@ -= ERC 777 - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc777 - -This set of interfaces and contracts are all related to the [ERC777 token standard](https://eips.ethereum.org/EIPS/eip-777). - -TIP: For an overview of ERC777 tokens and a walk through on how to create a token contract read our xref:ROOT:erc777.adoc[ERC777 guide]. - -The token behavior itself is implemented in the core contracts: {IERC777}, {ERC777}. - -Additionally there are interfaces used to develop contracts that react to token movements: {IERC777Sender}, {IERC777Recipient}. - -== Core - -{{IERC777}} - -{{ERC777}} - -== Hooks - -{{IERC777Sender}} - -{{IERC777Recipient}} - -== Presets - -These contracts are preconfigured combinations of features. They can be used through inheritance or as models to copy and paste their source code. - -{{ERC777PresetFixedSupply}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/presets/ERC777PresetFixedSupply.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/presets/ERC777PresetFixedSupply.sol deleted file mode 100644 index 8bd4b79a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/ERC777/presets/ERC777PresetFixedSupply.sol +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC777/presets/ERC777PresetFixedSupply.sol) -pragma solidity ^0.8.0; - -import "../ERC777.sol"; - -/** - * @dev {ERC777} token, including: - * - * - Preminted initial supply - * - No access control mechanism (for minting/pausing) and hence no governance - * - * _Available since v3.4._ - */ -contract ERC777PresetFixedSupply is ERC777 { - /** - * @dev Mints `initialSupply` amount of token and transfers them to `owner`. - * - * See {ERC777-constructor}. - */ - constructor( - string memory name, - string memory symbol, - address[] memory defaultOperators, - uint256 initialSupply, - address owner - ) ERC777(name, symbol, defaultOperators) { - _mint(owner, initialSupply, "", ""); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/common/ERC2981.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/common/ERC2981.sol deleted file mode 100644 index 90d7ed34..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/common/ERC2981.sol +++ /dev/null @@ -1,118 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol) - -pragma solidity ^0.8.0; - -import "../../interfaces/IERC2981.sol"; -import "../../utils/introspection/ERC165.sol"; - -/** - * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. - * - * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for - * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. - * - * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the - * fee is specified in basis points by default. - * - * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See - * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to - * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. - * - * _Available since v4.5._ - */ -abstract contract ERC2981 is IERC2981, ERC165 { - struct RoyaltyInfo { - address receiver; - uint96 royaltyFraction; - } - - RoyaltyInfo private _defaultRoyaltyInfo; - mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { - return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @inheritdoc IERC2981 - */ - function royaltyInfo(uint256 _tokenId, uint256 _salePrice) - external - view - virtual - override - returns (address, uint256) - { - RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; - - if (royalty.receiver == address(0)) { - royalty = _defaultRoyaltyInfo; - } - - uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); - - return (royalty.receiver, royaltyAmount); - } - - /** - * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a - * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an - * override. - */ - function _feeDenominator() internal pure virtual returns (uint96) { - return 10000; - } - - /** - * @dev Sets the royalty information that all ids in this contract will default to. - * - * Requirements: - * - * - `receiver` cannot be the zero address. - * - `feeNumerator` cannot be greater than the fee denominator. - */ - function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { - require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); - require(receiver != address(0), "ERC2981: invalid receiver"); - - _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); - } - - /** - * @dev Removes default royalty information. - */ - function _deleteDefaultRoyalty() internal virtual { - delete _defaultRoyaltyInfo; - } - - /** - * @dev Sets the royalty information for a specific token id, overriding the global default. - * - * Requirements: - * - * - `tokenId` must be already minted. - * - `receiver` cannot be the zero address. - * - `feeNumerator` cannot be greater than the fee denominator. - */ - function _setTokenRoyalty( - uint256 tokenId, - address receiver, - uint96 feeNumerator - ) internal virtual { - require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); - require(receiver != address(0), "ERC2981: Invalid parameters"); - - _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); - } - - /** - * @dev Resets royalty information for the token id back to the global default. - */ - function _resetTokenRoyalty(uint256 tokenId) internal virtual { - delete _tokenRoyaltyInfo[tokenId]; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/common/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/common/README.adoc deleted file mode 100644 index af616746..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/token/common/README.adoc +++ /dev/null @@ -1,10 +0,0 @@ -= Common (Tokens) - -Functionality that is common to multiple token standards. - -* {ERC2981}: NFT Royalties compatible with both ERC721 and ERC1155. -** For ERC721 consider {ERC721Royalty} which clears the royalty information from storage on burn. - -== Contracts - -{{ERC2981}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Address.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Address.sol deleted file mode 100644 index daea7f31..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Address.sol +++ /dev/null @@ -1,222 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) - -pragma solidity ^0.8.1; - -/** - * @dev Collection of functions related to the address type - */ -library Address { - /** - * @dev Returns true if `account` is a contract. - * - * [IMPORTANT] - * ==== - * It is unsafe to assume that an address for which this function returns - * false is an externally-owned account (EOA) and not a contract. - * - * Among others, `isContract` will return false for the following - * types of addresses: - * - * - an externally-owned account - * - a contract in construction - * - an address where a contract will be created - * - an address where a contract lived, but was destroyed - * ==== - * - * [IMPORTANT] - * ==== - * You shouldn't rely on `isContract` to protect against flash loan attacks! - * - * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets - * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract - * constructor. - * ==== - */ - function isContract(address account) internal view returns (bool) { - // This method relies on extcodesize/address.code.length, which returns 0 - // for contracts in construction, since the code is only stored at the end - // of the constructor execution. - - return account.code.length > 0; - } - - /** - * @dev Replacement for Solidity's `transfer`: sends `amount` wei to - * `recipient`, forwarding all available gas and reverting on errors. - * - * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost - * of certain opcodes, possibly making contracts go over the 2300 gas limit - * imposed by `transfer`, making them unable to receive funds via - * `transfer`. {sendValue} removes this limitation. - * - * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. - * - * IMPORTANT: because control is transferred to `recipient`, care must be - * taken to not create reentrancy vulnerabilities. Consider using - * {ReentrancyGuard} or the - * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. - */ - function sendValue(address payable recipient, uint256 amount) internal { - require(address(this).balance >= amount, "Address: insufficient balance"); - - (bool success, ) = recipient.call{value: amount}(""); - require(success, "Address: unable to send value, recipient may have reverted"); - } - - /** - * @dev Performs a Solidity function call using a low level `call`. A - * plain `call` is an unsafe replacement for a function call: use this - * function instead. - * - * If `target` reverts with a revert reason, it is bubbled up by this - * function (like regular Solidity function calls). - * - * Returns the raw returned data. To convert to the expected return value, - * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. - * - * Requirements: - * - * - `target` must be a contract. - * - calling `target` with `data` must not revert. - * - * _Available since v3.1._ - */ - function functionCall(address target, bytes memory data) internal returns (bytes memory) { - return functionCall(target, data, "Address: low-level call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with - * `errorMessage` as a fallback revert reason when `target` reverts. - * - * _Available since v3.1._ - */ - function functionCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - return functionCallWithValue(target, data, 0, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but also transferring `value` wei to `target`. - * - * Requirements: - * - * - the calling contract must have an ETH balance of at least `value`. - * - the called Solidity function must be `payable`. - * - * _Available since v3.1._ - */ - function functionCallWithValue( - address target, - bytes memory data, - uint256 value - ) internal returns (bytes memory) { - return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); - } - - /** - * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but - * with `errorMessage` as a fallback revert reason when `target` reverts. - * - * _Available since v3.1._ - */ - function functionCallWithValue( - address target, - bytes memory data, - uint256 value, - string memory errorMessage - ) internal returns (bytes memory) { - require(address(this).balance >= value, "Address: insufficient balance for call"); - require(isContract(target), "Address: call to non-contract"); - - (bool success, bytes memory returndata) = target.call{value: value}(data); - return verifyCallResult(success, returndata, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but performing a static call. - * - * _Available since v3.3._ - */ - function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { - return functionStaticCall(target, data, "Address: low-level static call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], - * but performing a static call. - * - * _Available since v3.3._ - */ - function functionStaticCall( - address target, - bytes memory data, - string memory errorMessage - ) internal view returns (bytes memory) { - require(isContract(target), "Address: static call to non-contract"); - - (bool success, bytes memory returndata) = target.staticcall(data); - return verifyCallResult(success, returndata, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but performing a delegate call. - * - * _Available since v3.4._ - */ - function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { - return functionDelegateCall(target, data, "Address: low-level delegate call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], - * but performing a delegate call. - * - * _Available since v3.4._ - */ - function functionDelegateCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - require(isContract(target), "Address: delegate call to non-contract"); - - (bool success, bytes memory returndata) = target.delegatecall(data); - return verifyCallResult(success, returndata, errorMessage); - } - - /** - * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the - * revert reason using the provided one. - * - * _Available since v4.3._ - */ - function verifyCallResult( - bool success, - bytes memory returndata, - string memory errorMessage - ) internal pure returns (bytes memory) { - if (success) { - return returndata; - } else { - // Look for revert reason and bubble it up if present - if (returndata.length > 0) { - // The easiest way to bubble the revert reason is using memory via assembly - - assembly { - let returndata_size := mload(returndata) - revert(add(32, returndata), returndata_size) - } - } else { - revert(errorMessage); - } - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Arrays.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Arrays.sol deleted file mode 100644 index 0783614c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Arrays.sol +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/Arrays.sol) - -pragma solidity ^0.8.0; - -import "./math/Math.sol"; - -/** - * @dev Collection of functions related to array types. - */ -library Arrays { - /** - * @dev Searches a sorted `array` and returns the first index that contains - * a value greater or equal to `element`. If no such index exists (i.e. all - * values in the array are strictly less than `element`), the array length is - * returned. Time complexity O(log n). - * - * `array` is expected to be sorted in ascending order, and to contain no - * repeated elements. - */ - function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { - if (array.length == 0) { - return 0; - } - - uint256 low = 0; - uint256 high = array.length; - - while (low < high) { - uint256 mid = Math.average(low, high); - - // Note that mid will always be strictly less than high (i.e. it will be a valid array index) - // because Math.average rounds down (it does integer division with truncation). - if (array[mid] > element) { - high = mid; - } else { - low = mid + 1; - } - } - - // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. - if (low > 0 && array[low - 1] == element) { - return low - 1; - } else { - return low; - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Base64.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Base64.sol deleted file mode 100644 index 2de471d1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Base64.sol +++ /dev/null @@ -1,91 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/Base64.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Provides a set of functions to operate with Base64 strings. - * - * _Available since v4.5._ - */ -library Base64 { - /** - * @dev Base64 Encoding/Decoding Table - */ - string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - /** - * @dev Converts a `bytes` to its Bytes64 `string` representation. - */ - function encode(bytes memory data) internal pure returns (string memory) { - /** - * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence - * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol - */ - if (data.length == 0) return ""; - - // Loads the table into memory - string memory table = _TABLE; - - // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter - // and split into 4 numbers of 6 bits. - // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up - // - `data.length + 2` -> Round up - // - `/ 3` -> Number of 3-bytes chunks - // - `4 *` -> 4 characters for each chunk - string memory result = new string(4 * ((data.length + 2) / 3)); - - assembly { - // Prepare the lookup table (skip the first "length" byte) - let tablePtr := add(table, 1) - - // Prepare result pointer, jump over length - let resultPtr := add(result, 32) - - // Run over the input, 3 bytes at a time - for { - let dataPtr := data - let endPtr := add(data, mload(data)) - } lt(dataPtr, endPtr) { - - } { - // Advance 3 bytes - dataPtr := add(dataPtr, 3) - let input := mload(dataPtr) - - // To write each character, shift the 3 bytes (18 bits) chunk - // 4 times in blocks of 6 bits for each character (18, 12, 6, 0) - // and apply logical AND with 0x3F which is the number of - // the previous character in the ASCII table prior to the Base64 Table - // The result is then added to the table to get the character to write, - // and finally write it in the result pointer but with a left shift - // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits - - mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - } - - // When data `bytes` is not exactly 3 bytes long - // it is padded with `=` characters at the end - switch mod(mload(data), 3) - case 1 { - mstore8(sub(resultPtr, 1), 0x3d) - mstore8(sub(resultPtr, 2), 0x3d) - } - case 2 { - mstore8(sub(resultPtr, 1), 0x3d) - } - } - - return result; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Checkpoints.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Checkpoints.sol deleted file mode 100644 index 606098bc..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Checkpoints.sol +++ /dev/null @@ -1,86 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/Checkpoints.sol) -pragma solidity ^0.8.0; - -import "./math/Math.sol"; -import "./math/SafeCast.sol"; - -/** - * @dev This library defines the `History` struct, for checkpointing values as they change at different points in - * time, and later looking up past values by block number. See {Votes} as an example. - * - * To create a history of checkpoints define a variable type `Checkpoints.History` in your contract, and store a new - * checkpoint for the current transaction block using the {push} function. - * - * _Available since v4.5._ - */ -library Checkpoints { - struct Checkpoint { - uint32 _blockNumber; - uint224 _value; - } - - struct History { - Checkpoint[] _checkpoints; - } - - /** - * @dev Returns the value in the latest checkpoint, or zero if there are no checkpoints. - */ - function latest(History storage self) internal view returns (uint256) { - uint256 pos = self._checkpoints.length; - return pos == 0 ? 0 : self._checkpoints[pos - 1]._value; - } - - /** - * @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one - * before it is returned, or zero otherwise. - */ - function getAtBlock(History storage self, uint256 blockNumber) internal view returns (uint256) { - require(blockNumber < block.number, "Checkpoints: block not yet mined"); - - uint256 high = self._checkpoints.length; - uint256 low = 0; - while (low < high) { - uint256 mid = Math.average(low, high); - if (self._checkpoints[mid]._blockNumber > blockNumber) { - high = mid; - } else { - low = mid + 1; - } - } - return high == 0 ? 0 : self._checkpoints[high - 1]._value; - } - - /** - * @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block. - * - * Returns previous value and new value. - */ - function push(History storage self, uint256 value) internal returns (uint256, uint256) { - uint256 pos = self._checkpoints.length; - uint256 old = latest(self); - if (pos > 0 && self._checkpoints[pos - 1]._blockNumber == block.number) { - self._checkpoints[pos - 1]._value = SafeCast.toUint224(value); - } else { - self._checkpoints.push( - Checkpoint({_blockNumber: SafeCast.toUint32(block.number), _value: SafeCast.toUint224(value)}) - ); - } - return (old, value); - } - - /** - * @dev Pushes a value onto a History, by updating the latest value using binary operation `op`. The new value will - * be set to `op(latest, delta)`. - * - * Returns previous value and new value. - */ - function push( - History storage self, - function(uint256, uint256) view returns (uint256) op, - uint256 delta - ) internal returns (uint256, uint256) { - return push(self, op(latest(self), delta)); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Counters.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Counters.sol deleted file mode 100644 index 8a4f2a2e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Counters.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) - -pragma solidity ^0.8.0; - -/** - * @title Counters - * @author Matt Condon (@shrugs) - * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number - * of elements in a mapping, issuing ERC721 ids, or counting request ids. - * - * Include with `using Counters for Counters.Counter;` - */ -library Counters { - struct Counter { - // This variable should never be directly accessed by users of the library: interactions must be restricted to - // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add - // this feature: see https://github.com/ethereum/solidity/issues/4637 - uint256 _value; // default: 0 - } - - function current(Counter storage counter) internal view returns (uint256) { - return counter._value; - } - - function increment(Counter storage counter) internal { - unchecked { - counter._value += 1; - } - } - - function decrement(Counter storage counter) internal { - uint256 value = counter._value; - require(value > 0, "Counter: decrement overflow"); - unchecked { - counter._value = value - 1; - } - } - - function reset(Counter storage counter) internal { - counter._value = 0; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Create2.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Create2.sol deleted file mode 100644 index 40164c1e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Create2.sol +++ /dev/null @@ -1,65 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/Create2.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. - * `CREATE2` can be used to compute in advance the address where a smart - * contract will be deployed, which allows for interesting new mechanisms known - * as 'counterfactual interactions'. - * - * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more - * information. - */ -library Create2 { - /** - * @dev Deploys a contract using `CREATE2`. The address where the contract - * will be deployed can be known in advance via {computeAddress}. - * - * The bytecode for a contract can be obtained from Solidity with - * `type(contractName).creationCode`. - * - * Requirements: - * - * - `bytecode` must not be empty. - * - `salt` must have not been used for `bytecode` already. - * - the factory must have a balance of at least `amount`. - * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. - */ - function deploy( - uint256 amount, - bytes32 salt, - bytes memory bytecode - ) internal returns (address) { - address addr; - require(address(this).balance >= amount, "Create2: insufficient balance"); - require(bytecode.length != 0, "Create2: bytecode length is zero"); - assembly { - addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) - } - require(addr != address(0), "Create2: Failed on deploy"); - return addr; - } - - /** - * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the - * `bytecodeHash` or `salt` will result in a new destination address. - */ - function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { - return computeAddress(salt, bytecodeHash, address(this)); - } - - /** - * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at - * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. - */ - function computeAddress( - bytes32 salt, - bytes32 bytecodeHash, - address deployer - ) internal pure returns (address) { - bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)); - return address(uint160(uint256(_data))); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Multicall.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Multicall.sol deleted file mode 100644 index bdb82013..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Multicall.sol +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol) - -pragma solidity ^0.8.0; - -import "./Address.sol"; - -/** - * @dev Provides a function to batch together multiple calls in a single external call. - * - * _Available since v4.1._ - */ -abstract contract Multicall { - /** - * @dev Receives and executes a batch of function calls on this contract. - */ - function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) { - results = new bytes[](data.length); - for (uint256 i = 0; i < data.length; i++) { - results[i] = Address.functionDelegateCall(address(this), data[i]); - } - return results; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/README.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/README.adoc deleted file mode 100644 index 83e30e78..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/README.adoc +++ /dev/null @@ -1,109 +0,0 @@ -= Utilities - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/utils - -Miscellaneous contracts and libraries containing utility functions you can use to improve security, work with new data types, or safely use low-level primitives. - -The {Address}, {Arrays}, {Base64} and {Strings} libraries provide more operations related to these native data types, while {SafeCast} adds ways to safely convert between the different signed and unsigned numeric types. -{Multicall} provides a function to batch together multiple calls in a single external call. - -For new data types: - - * {Counters}: a simple way to get a counter that can only be incremented, decremented or reset. Very useful for ID generation, counting contract activity, among others. - * {EnumerableMap}: like Solidity's https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] type, but with key-value _enumeration_: this will let you know how many entries a mapping has, and iterate over them (which is not possible with `mapping`). - * {EnumerableSet}: like {EnumerableMap}, but for https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets]. Can be used to store privileged accounts, issued IDs, etc. - -[NOTE] -==== -Because Solidity does not support generic types, {EnumerableMap} and {EnumerableSet} are specialized to a limited number of key-value types. - -As of v3.0, {EnumerableMap} supports `uint256 -> address` (`UintToAddressMap`), and {EnumerableSet} supports `address` and `uint256` (`AddressSet` and `UintSet`). -==== - -Finally, {Create2} contains all necessary utilities to safely use the https://blog.openzeppelin.com/getting-the-most-out-of-create2/[`CREATE2` EVM opcode], without having to deal with low-level assembly. - -== Math - -{{Math}} - -{{SignedMath}} - -{{SafeCast}} - -{{SafeMath}} - -{{SignedSafeMath}} - -== Cryptography - -{{ECDSA}} - -{{SignatureChecker}} - -{{MerkleProof}} - -{{EIP712}} - -== Escrow - -{{ConditionalEscrow}} - -{{Escrow}} - -{{RefundEscrow}} - -== Introspection - -This set of interfaces and contracts deal with https://en.wikipedia.org/wiki/Type_introspection[type introspection] of contracts, that is, examining which functions can be called on them. This is usually referred to as a contract's _interface_. - -Ethereum contracts have no native concept of an interface, so applications must usually simply trust they are not making an incorrect call. For trusted setups this is a non-issue, but often unknown and untrusted third-party addresses need to be interacted with. There may even not be any direct calls to them! (e.g. `ERC20` tokens may be sent to a contract that lacks a way to transfer them out of it, locking them forever). In these cases, a contract _declaring_ its interface can be very helpful in preventing errors. - -There are two main ways to approach this. - -* Locally, where a contract implements `IERC165` and declares an interface, and a second one queries it directly via `ERC165Checker`. -* Globally, where a global and unique registry (`IERC1820Registry`) is used to register implementers of a certain interface (`IERC1820Implementer`). It is then the registry that is queried, which allows for more complex setups, like contracts implementing interfaces for externally-owned accounts. - -Note that, in all cases, accounts simply _declare_ their interfaces, but they are not required to actually implement them. This mechanism can therefore be used to both prevent errors and allow for complex interactions (see `ERC777`), but it must not be relied on for security. - -{{IERC165}} - -{{ERC165}} - -{{ERC165Storage}} - -{{ERC165Checker}} - -{{IERC1820Registry}} - -{{IERC1820Implementer}} - -{{ERC1820Implementer}} - -== Data Structures - -{{BitMaps}} - -{{EnumerableMap}} - -{{EnumerableSet}} - -{{Checkpoints}} - -== Libraries - -{{Create2}} - -{{Address}} - -{{Arrays}} - -{{Base64}} - -{{Counters}} - -{{Strings}} - -{{StorageSlot}} - -{{Multicall}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol deleted file mode 100644 index 28239dbc..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Library for reading and writing primitive types to specific storage slots. - * - * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. - * This library helps with reading and writing to such slots without the need for inline assembly. - * - * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. - * - * Example usage to set ERC1967 implementation slot: - * ``` - * contract ERC1967 { - * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - * - * function _getImplementation() internal view returns (address) { - * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; - * } - * - * function _setImplementation(address newImplementation) internal { - * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); - * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; - * } - * } - * ``` - * - * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ - */ -library StorageSlot { - struct AddressSlot { - address value; - } - - struct BooleanSlot { - bool value; - } - - struct Bytes32Slot { - bytes32 value; - } - - struct Uint256Slot { - uint256 value; - } - - /** - * @dev Returns an `AddressSlot` with member `value` located at `slot`. - */ - function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `BooleanSlot` with member `value` located at `slot`. - */ - function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. - */ - function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Uint256Slot` with member `value` located at `slot`. - */ - function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { - assembly { - r.slot := slot - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Strings.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Strings.sol deleted file mode 100644 index d38bbe82..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Strings.sol +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) - -pragma solidity ^0.8.0; - -/** - * @dev String operations. - */ -library Strings { - bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; - - /** - * @dev Converts a `uint256` to its ASCII `string` decimal representation. - */ - function toString(uint256 value) internal pure returns (string memory) { - // Inspired by OraclizeAPI's implementation - MIT licence - // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol - - if (value == 0) { - return "0"; - } - uint256 temp = value; - uint256 digits; - while (temp != 0) { - digits++; - temp /= 10; - } - bytes memory buffer = new bytes(digits); - while (value != 0) { - digits -= 1; - buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); - value /= 10; - } - return string(buffer); - } - - /** - * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. - */ - function toHexString(uint256 value) internal pure returns (string memory) { - if (value == 0) { - return "0x00"; - } - uint256 temp = value; - uint256 length = 0; - while (temp != 0) { - length++; - temp >>= 8; - } - return toHexString(value, length); - } - - /** - * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. - */ - function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { - bytes memory buffer = new bytes(2 * length + 2); - buffer[0] = "0"; - buffer[1] = "x"; - for (uint256 i = 2 * length + 1; i > 1; --i) { - buffer[i] = _HEX_SYMBOLS[value & 0xf]; - value >>= 4; - } - require(value == 0, "Strings: hex length insufficient"); - return string(buffer); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Timers.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Timers.sol deleted file mode 100644 index 4bc86f20..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/Timers.sol +++ /dev/null @@ -1,73 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/Timers.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Tooling for timepoints, timers and delays - */ -library Timers { - struct Timestamp { - uint64 _deadline; - } - - function getDeadline(Timestamp memory timer) internal pure returns (uint64) { - return timer._deadline; - } - - function setDeadline(Timestamp storage timer, uint64 timestamp) internal { - timer._deadline = timestamp; - } - - function reset(Timestamp storage timer) internal { - timer._deadline = 0; - } - - function isUnset(Timestamp memory timer) internal pure returns (bool) { - return timer._deadline == 0; - } - - function isStarted(Timestamp memory timer) internal pure returns (bool) { - return timer._deadline > 0; - } - - function isPending(Timestamp memory timer) internal view returns (bool) { - return timer._deadline > block.timestamp; - } - - function isExpired(Timestamp memory timer) internal view returns (bool) { - return isStarted(timer) && timer._deadline <= block.timestamp; - } - - struct BlockNumber { - uint64 _deadline; - } - - function getDeadline(BlockNumber memory timer) internal pure returns (uint64) { - return timer._deadline; - } - - function setDeadline(BlockNumber storage timer, uint64 timestamp) internal { - timer._deadline = timestamp; - } - - function reset(BlockNumber storage timer) internal { - timer._deadline = 0; - } - - function isUnset(BlockNumber memory timer) internal pure returns (bool) { - return timer._deadline == 0; - } - - function isStarted(BlockNumber memory timer) internal pure returns (bool) { - return timer._deadline > 0; - } - - function isPending(BlockNumber memory timer) internal view returns (bool) { - return timer._deadline > block.number; - } - - function isExpired(BlockNumber memory timer) internal view returns (bool) { - return isStarted(timer) && timer._deadline <= block.number; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol deleted file mode 100644 index b2db6bd7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol +++ /dev/null @@ -1,230 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) - -pragma solidity ^0.8.0; - -import "../Strings.sol"; - -/** - * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. - * - * These functions can be used to verify that a message was signed by the holder - * of the private keys of a given address. - */ -library ECDSA { - enum RecoverError { - NoError, - InvalidSignature, - InvalidSignatureLength, - InvalidSignatureS, - InvalidSignatureV - } - - function _throwError(RecoverError error) private pure { - if (error == RecoverError.NoError) { - return; // no error: do nothing - } else if (error == RecoverError.InvalidSignature) { - revert("ECDSA: invalid signature"); - } else if (error == RecoverError.InvalidSignatureLength) { - revert("ECDSA: invalid signature length"); - } else if (error == RecoverError.InvalidSignatureS) { - revert("ECDSA: invalid signature 's' value"); - } else if (error == RecoverError.InvalidSignatureV) { - revert("ECDSA: invalid signature 'v' value"); - } - } - - /** - * @dev Returns the address that signed a hashed message (`hash`) with - * `signature` or error string. This address can then be used for verification purposes. - * - * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: - * this function rejects them by requiring the `s` value to be in the lower - * half order, and the `v` value to be either 27 or 28. - * - * IMPORTANT: `hash` _must_ be the result of a hash operation for the - * verification to be secure: it is possible to craft signatures that - * recover to arbitrary addresses for non-hashed data. A safe way to ensure - * this is by receiving a hash of the original message (which may otherwise - * be too long), and then calling {toEthSignedMessageHash} on it. - * - * Documentation for signature generation: - * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] - * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] - * - * _Available since v4.3._ - */ - function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { - // Check the signature length - // - case 65: r,s,v signature (standard) - // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ - if (signature.length == 65) { - bytes32 r; - bytes32 s; - uint8 v; - // ecrecover takes the signature parameters, and the only way to get them - // currently is to use assembly. - assembly { - r := mload(add(signature, 0x20)) - s := mload(add(signature, 0x40)) - v := byte(0, mload(add(signature, 0x60))) - } - return tryRecover(hash, v, r, s); - } else if (signature.length == 64) { - bytes32 r; - bytes32 vs; - // ecrecover takes the signature parameters, and the only way to get them - // currently is to use assembly. - assembly { - r := mload(add(signature, 0x20)) - vs := mload(add(signature, 0x40)) - } - return tryRecover(hash, r, vs); - } else { - return (address(0), RecoverError.InvalidSignatureLength); - } - } - - /** - * @dev Returns the address that signed a hashed message (`hash`) with - * `signature`. This address can then be used for verification purposes. - * - * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: - * this function rejects them by requiring the `s` value to be in the lower - * half order, and the `v` value to be either 27 or 28. - * - * IMPORTANT: `hash` _must_ be the result of a hash operation for the - * verification to be secure: it is possible to craft signatures that - * recover to arbitrary addresses for non-hashed data. A safe way to ensure - * this is by receiving a hash of the original message (which may otherwise - * be too long), and then calling {toEthSignedMessageHash} on it. - */ - function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { - (address recovered, RecoverError error) = tryRecover(hash, signature); - _throwError(error); - return recovered; - } - - /** - * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. - * - * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] - * - * _Available since v4.3._ - */ - function tryRecover( - bytes32 hash, - bytes32 r, - bytes32 vs - ) internal pure returns (address, RecoverError) { - bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); - uint8 v = uint8((uint256(vs) >> 255) + 27); - return tryRecover(hash, v, r, s); - } - - /** - * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. - * - * _Available since v4.2._ - */ - function recover( - bytes32 hash, - bytes32 r, - bytes32 vs - ) internal pure returns (address) { - (address recovered, RecoverError error) = tryRecover(hash, r, vs); - _throwError(error); - return recovered; - } - - /** - * @dev Overload of {ECDSA-tryRecover} that receives the `v`, - * `r` and `s` signature fields separately. - * - * _Available since v4.3._ - */ - function tryRecover( - bytes32 hash, - uint8 v, - bytes32 r, - bytes32 s - ) internal pure returns (address, RecoverError) { - // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature - // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines - // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most - // signatures from current libraries generate a unique signature with an s-value in the lower half order. - // - // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value - // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or - // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept - // these malleable signatures as well. - if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { - return (address(0), RecoverError.InvalidSignatureS); - } - if (v != 27 && v != 28) { - return (address(0), RecoverError.InvalidSignatureV); - } - - // If the signature is valid (and not malleable), return the signer address - address signer = ecrecover(hash, v, r, s); - if (signer == address(0)) { - return (address(0), RecoverError.InvalidSignature); - } - - return (signer, RecoverError.NoError); - } - - /** - * @dev Overload of {ECDSA-recover} that receives the `v`, - * `r` and `s` signature fields separately. - */ - function recover( - bytes32 hash, - uint8 v, - bytes32 r, - bytes32 s - ) internal pure returns (address) { - (address recovered, RecoverError error) = tryRecover(hash, v, r, s); - _throwError(error); - return recovered; - } - - /** - * @dev Returns an Ethereum Signed Message, created from a `hash`. This - * produces hash corresponding to the one signed with the - * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] - * JSON-RPC method as part of EIP-191. - * - * See {recover}. - */ - function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { - // 32 is the length in bytes of hash, - // enforced by the type signature above - return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); - } - - /** - * @dev Returns an Ethereum Signed Message, created from `s`. This - * produces hash corresponding to the one signed with the - * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] - * JSON-RPC method as part of EIP-191. - * - * See {recover}. - */ - function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { - return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); - } - - /** - * @dev Returns an Ethereum Signed Typed Data, created from a - * `domainSeparator` and a `structHash`. This produces hash corresponding - * to the one signed with the - * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] - * JSON-RPC method as part of EIP-712. - * - * See {recover}. - */ - function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { - return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol deleted file mode 100644 index 08096db5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) - -pragma solidity ^0.8.0; - -/** - * @dev These functions deal with verification of Merkle Trees proofs. - * - * The proofs can be generated using the JavaScript library - * https://github.com/miguelmota/merkletreejs[merkletreejs]. - * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. - * - * See `test/utils/cryptography/MerkleProof.test.js` for some examples. - */ -library MerkleProof { - /** - * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree - * defined by `root`. For this, a `proof` must be provided, containing - * sibling hashes on the branch from the leaf to the root of the tree. Each - * pair of leaves and each pair of pre-images are assumed to be sorted. - */ - function verify( - bytes32[] memory proof, - bytes32 root, - bytes32 leaf - ) internal pure returns (bool) { - return processProof(proof, leaf) == root; - } - - /** - * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up - * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt - * hash matches the root of the tree. When processing the proof, the pairs - * of leafs & pre-images are assumed to be sorted. - * - * _Available since v4.4._ - */ - function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { - bytes32 computedHash = leaf; - for (uint256 i = 0; i < proof.length; i++) { - bytes32 proofElement = proof[i]; - if (computedHash <= proofElement) { - // Hash(current computed hash + current element of the proof) - computedHash = _efficientHash(computedHash, proofElement); - } else { - // Hash(current element of the proof + current computed hash) - computedHash = _efficientHash(proofElement, computedHash); - } - } - return computedHash; - } - - function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { - assembly { - mstore(0x00, a) - mstore(0x20, b) - value := keccak256(0x00, 0x40) - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol deleted file mode 100644 index 3ed6e719..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) - -pragma solidity ^0.8.0; - -import "./ECDSA.sol"; -import "../Address.sol"; -import "../../interfaces/IERC1271.sol"; - -/** - * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA - * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like - * Argent and Gnosis Safe. - * - * _Available since v4.1._ - */ -library SignatureChecker { - /** - * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the - * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. - * - * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus - * change through time. It could return true at block N and false at block N+1 (or the opposite). - */ - function isValidSignatureNow( - address signer, - bytes32 hash, - bytes memory signature - ) internal view returns (bool) { - (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); - if (error == ECDSA.RecoverError.NoError && recovered == signer) { - return true; - } - - (bool success, bytes memory result) = signer.staticcall( - abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) - ); - return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/draft-EIP712.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/draft-EIP712.sol deleted file mode 100644 index a32c25b7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/cryptography/draft-EIP712.sol +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) - -pragma solidity ^0.8.0; - -import "./ECDSA.sol"; - -/** - * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. - * - * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, - * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding - * they need in their contracts using a combination of `abi.encode` and `keccak256`. - * - * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding - * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA - * ({_hashTypedDataV4}). - * - * The implementation of the domain separator was designed to be as efficient as possible while still properly updating - * the chain id to protect against replay attacks on an eventual fork of the chain. - * - * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method - * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. - * - * _Available since v3.4._ - */ -abstract contract EIP712 { - /* solhint-disable var-name-mixedcase */ - // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to - // invalidate the cached domain separator if the chain id changes. - bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; - uint256 private immutable _CACHED_CHAIN_ID; - address private immutable _CACHED_THIS; - - bytes32 private immutable _HASHED_NAME; - bytes32 private immutable _HASHED_VERSION; - bytes32 private immutable _TYPE_HASH; - - /* solhint-enable var-name-mixedcase */ - - /** - * @dev Initializes the domain separator and parameter caches. - * - * The meaning of `name` and `version` is specified in - * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: - * - * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. - * - `version`: the current major version of the signing domain. - * - * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart - * contract upgrade]. - */ - constructor(string memory name, string memory version) { - bytes32 hashedName = keccak256(bytes(name)); - bytes32 hashedVersion = keccak256(bytes(version)); - bytes32 typeHash = keccak256( - "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" - ); - _HASHED_NAME = hashedName; - _HASHED_VERSION = hashedVersion; - _CACHED_CHAIN_ID = block.chainid; - _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); - _CACHED_THIS = address(this); - _TYPE_HASH = typeHash; - } - - /** - * @dev Returns the domain separator for the current chain. - */ - function _domainSeparatorV4() internal view returns (bytes32) { - if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { - return _CACHED_DOMAIN_SEPARATOR; - } else { - return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); - } - } - - function _buildDomainSeparator( - bytes32 typeHash, - bytes32 nameHash, - bytes32 versionHash - ) private view returns (bytes32) { - return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); - } - - /** - * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this - * function returns the hash of the fully encoded EIP712 message for this domain. - * - * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: - * - * ```solidity - * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( - * keccak256("Mail(address to,string contents)"), - * mailTo, - * keccak256(bytes(mailContents)) - * ))); - * address signer = ECDSA.recover(digest, signature); - * ``` - */ - function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { - return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/ConditionalEscrow.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/ConditionalEscrow.sol deleted file mode 100644 index 87f53815..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/ConditionalEscrow.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/escrow/ConditionalEscrow.sol) - -pragma solidity ^0.8.0; - -import "./Escrow.sol"; - -/** - * @title ConditionalEscrow - * @dev Base abstract escrow to only allow withdrawal if a condition is met. - * @dev Intended usage: See {Escrow}. Same usage guidelines apply here. - */ -abstract contract ConditionalEscrow is Escrow { - /** - * @dev Returns whether an address is allowed to withdraw their funds. To be - * implemented by derived contracts. - * @param payee The destination address of the funds. - */ - function withdrawalAllowed(address payee) public view virtual returns (bool); - - function withdraw(address payable payee) public virtual override { - require(withdrawalAllowed(payee), "ConditionalEscrow: payee is not allowed to withdraw"); - super.withdraw(payee); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/Escrow.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/Escrow.sol deleted file mode 100644 index c90a7461..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/Escrow.sol +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/escrow/Escrow.sol) - -pragma solidity ^0.8.0; - -import "../../access/Ownable.sol"; -import "../Address.sol"; - -/** - * @title Escrow - * @dev Base escrow contract, holds funds designated for a payee until they - * withdraw them. - * - * Intended usage: This contract (and derived escrow contracts) should be a - * standalone contract, that only interacts with the contract that instantiated - * it. That way, it is guaranteed that all Ether will be handled according to - * the `Escrow` rules, and there is no need to check for payable functions or - * transfers in the inheritance tree. The contract that uses the escrow as its - * payment method should be its owner, and provide public methods redirecting - * to the escrow's deposit and withdraw. - */ -contract Escrow is Ownable { - using Address for address payable; - - event Deposited(address indexed payee, uint256 weiAmount); - event Withdrawn(address indexed payee, uint256 weiAmount); - - mapping(address => uint256) private _deposits; - - function depositsOf(address payee) public view returns (uint256) { - return _deposits[payee]; - } - - /** - * @dev Stores the sent amount as credit to be withdrawn. - * @param payee The destination address of the funds. - */ - function deposit(address payee) public payable virtual onlyOwner { - uint256 amount = msg.value; - _deposits[payee] += amount; - emit Deposited(payee, amount); - } - - /** - * @dev Withdraw accumulated balance for a payee, forwarding all gas to the - * recipient. - * - * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. - * Make sure you trust the recipient, or are either following the - * checks-effects-interactions pattern or using {ReentrancyGuard}. - * - * @param payee The address whose funds will be withdrawn and transferred to. - */ - function withdraw(address payable payee) public virtual onlyOwner { - uint256 payment = _deposits[payee]; - - _deposits[payee] = 0; - - payee.sendValue(payment); - - emit Withdrawn(payee, payment); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/RefundEscrow.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/RefundEscrow.sol deleted file mode 100644 index 0e9621fe..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/escrow/RefundEscrow.sol +++ /dev/null @@ -1,100 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/escrow/RefundEscrow.sol) - -pragma solidity ^0.8.0; - -import "./ConditionalEscrow.sol"; - -/** - * @title RefundEscrow - * @dev Escrow that holds funds for a beneficiary, deposited from multiple - * parties. - * @dev Intended usage: See {Escrow}. Same usage guidelines apply here. - * @dev The owner account (that is, the contract that instantiates this - * contract) may deposit, close the deposit period, and allow for either - * withdrawal by the beneficiary, or refunds to the depositors. All interactions - * with `RefundEscrow` will be made through the owner contract. - */ -contract RefundEscrow is ConditionalEscrow { - using Address for address payable; - - enum State { - Active, - Refunding, - Closed - } - - event RefundsClosed(); - event RefundsEnabled(); - - State private _state; - address payable private immutable _beneficiary; - - /** - * @dev Constructor. - * @param beneficiary_ The beneficiary of the deposits. - */ - constructor(address payable beneficiary_) { - require(beneficiary_ != address(0), "RefundEscrow: beneficiary is the zero address"); - _beneficiary = beneficiary_; - _state = State.Active; - } - - /** - * @return The current state of the escrow. - */ - function state() public view virtual returns (State) { - return _state; - } - - /** - * @return The beneficiary of the escrow. - */ - function beneficiary() public view virtual returns (address payable) { - return _beneficiary; - } - - /** - * @dev Stores funds that may later be refunded. - * @param refundee The address funds will be sent to if a refund occurs. - */ - function deposit(address refundee) public payable virtual override { - require(state() == State.Active, "RefundEscrow: can only deposit while active"); - super.deposit(refundee); - } - - /** - * @dev Allows for the beneficiary to withdraw their funds, rejecting - * further deposits. - */ - function close() public virtual onlyOwner { - require(state() == State.Active, "RefundEscrow: can only close while active"); - _state = State.Closed; - emit RefundsClosed(); - } - - /** - * @dev Allows for refunds to take place, rejecting further deposits. - */ - function enableRefunds() public virtual onlyOwner { - require(state() == State.Active, "RefundEscrow: can only enable refunds while active"); - _state = State.Refunding; - emit RefundsEnabled(); - } - - /** - * @dev Withdraws the beneficiary's funds. - */ - function beneficiaryWithdraw() public virtual { - require(state() == State.Closed, "RefundEscrow: beneficiary can only withdraw while closed"); - beneficiary().sendValue(address(this).balance); - } - - /** - * @dev Returns whether refundees can withdraw their deposits (be refunded). The overridden function receives a - * 'payee' argument, but we ignore it here since the condition is global, not per-payee. - */ - function withdrawalAllowed(address) public view override returns (bool) { - return state() == State.Refunding; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol deleted file mode 100644 index 3bf5613a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) - -pragma solidity ^0.8.0; - -import "./IERC165.sol"; - -/** - * @dev Implementation of the {IERC165} interface. - * - * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check - * for the additional interface id that will be supported. For example: - * - * ```solidity - * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); - * } - * ``` - * - * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. - */ -abstract contract ERC165 is IERC165 { - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IERC165).interfaceId; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol deleted file mode 100644 index 6a240e15..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol +++ /dev/null @@ -1,113 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol) - -pragma solidity ^0.8.0; - -import "./IERC165.sol"; - -/** - * @dev Library used to query support of an interface declared via {IERC165}. - * - * Note that these functions return the actual result of the query: they do not - * `revert` if an interface is not supported. It is up to the caller to decide - * what to do in these cases. - */ -library ERC165Checker { - // As per the EIP-165 spec, no interface should ever match 0xffffffff - bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; - - /** - * @dev Returns true if `account` supports the {IERC165} interface, - */ - function supportsERC165(address account) internal view returns (bool) { - // Any contract that implements ERC165 must explicitly indicate support of - // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid - return - _supportsERC165Interface(account, type(IERC165).interfaceId) && - !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); - } - - /** - * @dev Returns true if `account` supports the interface defined by - * `interfaceId`. Support for {IERC165} itself is queried automatically. - * - * See {IERC165-supportsInterface}. - */ - function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { - // query support of both ERC165 as per the spec and support of _interfaceId - return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); - } - - /** - * @dev Returns a boolean array where each value corresponds to the - * interfaces passed in and whether they're supported or not. This allows - * you to batch check interfaces for a contract where your expectation - * is that some interfaces may not be supported. - * - * See {IERC165-supportsInterface}. - * - * _Available since v3.4._ - */ - function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) - internal - view - returns (bool[] memory) - { - // an array of booleans corresponding to interfaceIds and whether they're supported or not - bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); - - // query support of ERC165 itself - if (supportsERC165(account)) { - // query support of each interface in interfaceIds - for (uint256 i = 0; i < interfaceIds.length; i++) { - interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); - } - } - - return interfaceIdsSupported; - } - - /** - * @dev Returns true if `account` supports all the interfaces defined in - * `interfaceIds`. Support for {IERC165} itself is queried automatically. - * - * Batch-querying can lead to gas savings by skipping repeated checks for - * {IERC165} support. - * - * See {IERC165-supportsInterface}. - */ - function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { - // query support of ERC165 itself - if (!supportsERC165(account)) { - return false; - } - - // query support of each interface in _interfaceIds - for (uint256 i = 0; i < interfaceIds.length; i++) { - if (!_supportsERC165Interface(account, interfaceIds[i])) { - return false; - } - } - - // all interfaces supported - return true; - } - - /** - * @notice Query if a contract implements an interface, does not check ERC165 support - * @param account The address of the contract to query for support of an interface - * @param interfaceId The interface identifier, as specified in ERC-165 - * @return true if the contract at account indicates support of the interface with - * identifier interfaceId, false otherwise - * @dev Assumes that account contains a contract that supports ERC165, otherwise - * the behavior of this method is undefined. This precondition can be checked - * with {supportsERC165}. - * Interface identification is specified in ERC-165. - */ - function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { - bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); - (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); - if (result.length < 32) return false; - return success && abi.decode(result, (bool)); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Storage.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Storage.sol deleted file mode 100644 index c99d9f3f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Storage.sol +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Storage.sol) - -pragma solidity ^0.8.0; - -import "./ERC165.sol"; - -/** - * @dev Storage based implementation of the {IERC165} interface. - * - * Contracts may inherit from this and call {_registerInterface} to declare - * their support of an interface. - */ -abstract contract ERC165Storage is ERC165 { - /** - * @dev Mapping of interface ids to whether or not it's supported. - */ - mapping(bytes4 => bool) private _supportedInterfaces; - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId]; - } - - /** - * @dev Registers the contract as an implementer of the interface defined by - * `interfaceId`. Support of the actual ERC165 interface is automatic and - * registering its interface id is not required. - * - * See {IERC165-supportsInterface}. - * - * Requirements: - * - * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). - */ - function _registerInterface(bytes4 interfaceId) internal virtual { - require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); - _supportedInterfaces[interfaceId] = true; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC1820Implementer.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC1820Implementer.sol deleted file mode 100644 index 1b513965..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/ERC1820Implementer.sol +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC1820Implementer.sol) - -pragma solidity ^0.8.0; - -import "./IERC1820Implementer.sol"; - -/** - * @dev Implementation of the {IERC1820Implementer} interface. - * - * Contracts may inherit from this and call {_registerInterfaceForAddress} to - * declare their willingness to be implementers. - * {IERC1820Registry-setInterfaceImplementer} should then be called for the - * registration to be complete. - */ -contract ERC1820Implementer is IERC1820Implementer { - bytes32 private constant _ERC1820_ACCEPT_MAGIC = keccak256("ERC1820_ACCEPT_MAGIC"); - - mapping(bytes32 => mapping(address => bool)) private _supportedInterfaces; - - /** - * @dev See {IERC1820Implementer-canImplementInterfaceForAddress}. - */ - function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) - public - view - virtual - override - returns (bytes32) - { - return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00); - } - - /** - * @dev Declares the contract as willing to be an implementer of - * `interfaceHash` for `account`. - * - * See {IERC1820Registry-setInterfaceImplementer} and - * {IERC1820Registry-interfaceHash}. - */ - function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual { - _supportedInterfaces[interfaceHash][account] = true; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol deleted file mode 100644 index e8cdbdbf..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC165 standard, as defined in the - * https://eips.ethereum.org/EIPS/eip-165[EIP]. - * - * Implementers can declare support of contract interfaces, which can then be - * queried by others ({ERC165Checker}). - * - * For an implementation, see {ERC165}. - */ -interface IERC165 { - /** - * @dev Returns true if this contract implements the interface defined by - * `interfaceId`. See the corresponding - * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] - * to learn more about how these ids are created. - * - * This function call must use less than 30 000 gas. - */ - function supportsInterface(bytes4 interfaceId) external view returns (bool); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC1820Implementer.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC1820Implementer.sol deleted file mode 100644 index c4d0b302..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC1820Implementer.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Implementer.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface for an ERC1820 implementer, as defined in the - * https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP]. - * Used by contracts that will be registered as implementers in the - * {IERC1820Registry}. - */ -interface IERC1820Implementer { - /** - * @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract - * implements `interfaceHash` for `account`. - * - * See {IERC1820Registry-setInterfaceImplementer}. - */ - function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC1820Registry.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC1820Registry.sol deleted file mode 100644 index 26dc8e62..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/introspection/IERC1820Registry.sol +++ /dev/null @@ -1,116 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the global ERC1820 Registry, as defined in the - * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register - * implementers for interfaces in this registry, as well as query support. - * - * Implementers may be shared by multiple accounts, and can also implement more - * than a single interface for each account. Contracts can implement interfaces - * for themselves, but externally-owned accounts (EOA) must delegate this to a - * contract. - * - * {IERC165} interfaces can also be queried via the registry. - * - * For an in-depth explanation and source code analysis, see the EIP text. - */ -interface IERC1820Registry { - /** - * @dev Sets `newManager` as the manager for `account`. A manager of an - * account is able to set interface implementers for it. - * - * By default, each account is its own manager. Passing a value of `0x0` in - * `newManager` will reset the manager to this initial state. - * - * Emits a {ManagerChanged} event. - * - * Requirements: - * - * - the caller must be the current manager for `account`. - */ - function setManager(address account, address newManager) external; - - /** - * @dev Returns the manager for `account`. - * - * See {setManager}. - */ - function getManager(address account) external view returns (address); - - /** - * @dev Sets the `implementer` contract as ``account``'s implementer for - * `interfaceHash`. - * - * `account` being the zero address is an alias for the caller's address. - * The zero address can also be used in `implementer` to remove an old one. - * - * See {interfaceHash} to learn how these are created. - * - * Emits an {InterfaceImplementerSet} event. - * - * Requirements: - * - * - the caller must be the current manager for `account`. - * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not - * end in 28 zeroes). - * - `implementer` must implement {IERC1820Implementer} and return true when - * queried for support, unless `implementer` is the caller. See - * {IERC1820Implementer-canImplementInterfaceForAddress}. - */ - function setInterfaceImplementer( - address account, - bytes32 _interfaceHash, - address implementer - ) external; - - /** - * @dev Returns the implementer of `interfaceHash` for `account`. If no such - * implementer is registered, returns the zero address. - * - * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 - * zeroes), `account` will be queried for support of it. - * - * `account` being the zero address is an alias for the caller's address. - */ - function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); - - /** - * @dev Returns the interface hash for an `interfaceName`, as defined in the - * corresponding - * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. - */ - function interfaceHash(string calldata interfaceName) external pure returns (bytes32); - - /** - * @notice Updates the cache with whether the contract implements an ERC165 interface or not. - * @param account Address of the contract for which to update the cache. - * @param interfaceId ERC165 interface for which to update the cache. - */ - function updateERC165Cache(address account, bytes4 interfaceId) external; - - /** - * @notice Checks whether a contract implements an ERC165 interface or not. - * If the result is not cached a direct lookup on the contract address is performed. - * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling - * {updateERC165Cache} with the contract address. - * @param account Address of the contract to check. - * @param interfaceId ERC165 interface to check. - * @return True if `account` implements `interfaceId`, false otherwise. - */ - function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); - - /** - * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. - * @param account Address of the contract to check. - * @param interfaceId ERC165 interface to check. - * @return True if `account` implements `interfaceId`, false otherwise. - */ - function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); - - event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); - - event ManagerChanged(address indexed account, address indexed newManager); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/Math.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/Math.sol deleted file mode 100644 index 291d257b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/Math.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Standard math utilities missing in the Solidity language. - */ -library Math { - /** - * @dev Returns the largest of two numbers. - */ - function max(uint256 a, uint256 b) internal pure returns (uint256) { - return a >= b ? a : b; - } - - /** - * @dev Returns the smallest of two numbers. - */ - function min(uint256 a, uint256 b) internal pure returns (uint256) { - return a < b ? a : b; - } - - /** - * @dev Returns the average of two numbers. The result is rounded towards - * zero. - */ - function average(uint256 a, uint256 b) internal pure returns (uint256) { - // (a + b) / 2 can overflow. - return (a & b) + (a ^ b) / 2; - } - - /** - * @dev Returns the ceiling of the division of two numbers. - * - * This differs from standard division with `/` in that it rounds up instead - * of rounding down. - */ - function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { - // (a + b - 1) / b can overflow on addition, so we distribute. - return a / b + (a % b == 0 ? 0 : 1); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol deleted file mode 100644 index 3cd64735..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol +++ /dev/null @@ -1,241 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow - * checks. - * - * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can - * easily result in undesired exploitation or bugs, since developers usually - * assume that overflows raise errors. `SafeCast` restores this intuition by - * reverting the transaction when such an operation overflows. - * - * Using this library instead of the unchecked operations eliminates an entire - * class of bugs, so it's recommended to use it always. - * - * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing - * all math on `uint256` and `int256` and then downcasting. - */ -library SafeCast { - /** - * @dev Returns the downcasted uint224 from uint256, reverting on - * overflow (when the input is greater than largest uint224). - * - * Counterpart to Solidity's `uint224` operator. - * - * Requirements: - * - * - input must fit into 224 bits - */ - function toUint224(uint256 value) internal pure returns (uint224) { - require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); - return uint224(value); - } - - /** - * @dev Returns the downcasted uint128 from uint256, reverting on - * overflow (when the input is greater than largest uint128). - * - * Counterpart to Solidity's `uint128` operator. - * - * Requirements: - * - * - input must fit into 128 bits - */ - function toUint128(uint256 value) internal pure returns (uint128) { - require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); - return uint128(value); - } - - /** - * @dev Returns the downcasted uint96 from uint256, reverting on - * overflow (when the input is greater than largest uint96). - * - * Counterpart to Solidity's `uint96` operator. - * - * Requirements: - * - * - input must fit into 96 bits - */ - function toUint96(uint256 value) internal pure returns (uint96) { - require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); - return uint96(value); - } - - /** - * @dev Returns the downcasted uint64 from uint256, reverting on - * overflow (when the input is greater than largest uint64). - * - * Counterpart to Solidity's `uint64` operator. - * - * Requirements: - * - * - input must fit into 64 bits - */ - function toUint64(uint256 value) internal pure returns (uint64) { - require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); - return uint64(value); - } - - /** - * @dev Returns the downcasted uint32 from uint256, reverting on - * overflow (when the input is greater than largest uint32). - * - * Counterpart to Solidity's `uint32` operator. - * - * Requirements: - * - * - input must fit into 32 bits - */ - function toUint32(uint256 value) internal pure returns (uint32) { - require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); - return uint32(value); - } - - /** - * @dev Returns the downcasted uint16 from uint256, reverting on - * overflow (when the input is greater than largest uint16). - * - * Counterpart to Solidity's `uint16` operator. - * - * Requirements: - * - * - input must fit into 16 bits - */ - function toUint16(uint256 value) internal pure returns (uint16) { - require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); - return uint16(value); - } - - /** - * @dev Returns the downcasted uint8 from uint256, reverting on - * overflow (when the input is greater than largest uint8). - * - * Counterpart to Solidity's `uint8` operator. - * - * Requirements: - * - * - input must fit into 8 bits. - */ - function toUint8(uint256 value) internal pure returns (uint8) { - require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); - return uint8(value); - } - - /** - * @dev Converts a signed int256 into an unsigned uint256. - * - * Requirements: - * - * - input must be greater than or equal to 0. - */ - function toUint256(int256 value) internal pure returns (uint256) { - require(value >= 0, "SafeCast: value must be positive"); - return uint256(value); - } - - /** - * @dev Returns the downcasted int128 from int256, reverting on - * overflow (when the input is less than smallest int128 or - * greater than largest int128). - * - * Counterpart to Solidity's `int128` operator. - * - * Requirements: - * - * - input must fit into 128 bits - * - * _Available since v3.1._ - */ - function toInt128(int256 value) internal pure returns (int128) { - require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); - return int128(value); - } - - /** - * @dev Returns the downcasted int64 from int256, reverting on - * overflow (when the input is less than smallest int64 or - * greater than largest int64). - * - * Counterpart to Solidity's `int64` operator. - * - * Requirements: - * - * - input must fit into 64 bits - * - * _Available since v3.1._ - */ - function toInt64(int256 value) internal pure returns (int64) { - require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); - return int64(value); - } - - /** - * @dev Returns the downcasted int32 from int256, reverting on - * overflow (when the input is less than smallest int32 or - * greater than largest int32). - * - * Counterpart to Solidity's `int32` operator. - * - * Requirements: - * - * - input must fit into 32 bits - * - * _Available since v3.1._ - */ - function toInt32(int256 value) internal pure returns (int32) { - require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); - return int32(value); - } - - /** - * @dev Returns the downcasted int16 from int256, reverting on - * overflow (when the input is less than smallest int16 or - * greater than largest int16). - * - * Counterpart to Solidity's `int16` operator. - * - * Requirements: - * - * - input must fit into 16 bits - * - * _Available since v3.1._ - */ - function toInt16(int256 value) internal pure returns (int16) { - require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); - return int16(value); - } - - /** - * @dev Returns the downcasted int8 from int256, reverting on - * overflow (when the input is less than smallest int8 or - * greater than largest int8). - * - * Counterpart to Solidity's `int8` operator. - * - * Requirements: - * - * - input must fit into 8 bits. - * - * _Available since v3.1._ - */ - function toInt8(int256 value) internal pure returns (int8) { - require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); - return int8(value); - } - - /** - * @dev Converts an unsigned uint256 into a signed int256. - * - * Requirements: - * - * - input must be less than or equal to maxInt256. - */ - function toInt256(uint256 value) internal pure returns (int256) { - // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive - require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); - return int256(value); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol deleted file mode 100644 index 6eb0aa6b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol +++ /dev/null @@ -1,227 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) - -pragma solidity ^0.8.0; - -// CAUTION -// This version of SafeMath should only be used with Solidity 0.8 or later, -// because it relies on the compiler's built in overflow checks. - -/** - * @dev Wrappers over Solidity's arithmetic operations. - * - * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler - * now has built in overflow checking. - */ -library SafeMath { - /** - * @dev Returns the addition of two unsigned integers, with an overflow flag. - * - * _Available since v3.4._ - */ - function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - uint256 c = a + b; - if (c < a) return (false, 0); - return (true, c); - } - } - - /** - * @dev Returns the substraction of two unsigned integers, with an overflow flag. - * - * _Available since v3.4._ - */ - function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b > a) return (false, 0); - return (true, a - b); - } - } - - /** - * @dev Returns the multiplication of two unsigned integers, with an overflow flag. - * - * _Available since v3.4._ - */ - function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - // Gas optimization: this is cheaper than requiring 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 - if (a == 0) return (true, 0); - uint256 c = a * b; - if (c / a != b) return (false, 0); - return (true, c); - } - } - - /** - * @dev Returns the division of two unsigned integers, with a division by zero flag. - * - * _Available since v3.4._ - */ - function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b == 0) return (false, 0); - return (true, a / b); - } - } - - /** - * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. - * - * _Available since v3.4._ - */ - function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b == 0) return (false, 0); - return (true, a % b); - } - } - - /** - * @dev Returns the addition of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `+` operator. - * - * Requirements: - * - * - Addition cannot overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256) { - return a + b; - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - return a - b; - } - - /** - * @dev Returns the multiplication of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `*` operator. - * - * Requirements: - * - * - Multiplication cannot overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256) { - return a * b; - } - - /** - * @dev Returns the integer division of two unsigned integers, reverting on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. - * - * Requirements: - * - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - return a / b; - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * reverting when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b) internal pure returns (uint256) { - return a % b; - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting with custom message on - * overflow (when the result is negative). - * - * CAUTION: This function is deprecated because it requires allocating memory for the error - * message unnecessarily. For custom revert reasons use {trySub}. - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - * - Subtraction cannot overflow. - */ - function sub( - uint256 a, - uint256 b, - string memory errorMessage - ) internal pure returns (uint256) { - unchecked { - require(b <= a, errorMessage); - return a - b; - } - } - - /** - * @dev Returns the integer division of two unsigned integers, reverting with custom message on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - * - The divisor cannot be zero. - */ - function div( - uint256 a, - uint256 b, - string memory errorMessage - ) internal pure returns (uint256) { - unchecked { - require(b > 0, errorMessage); - return a / b; - } - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * reverting with custom message when dividing by zero. - * - * CAUTION: This function is deprecated because it requires allocating memory for the error - * message unnecessarily. For custom revert reasons use {tryMod}. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - * - The divisor cannot be zero. - */ - function mod( - uint256 a, - uint256 b, - string memory errorMessage - ) internal pure returns (uint256) { - unchecked { - require(b > 0, errorMessage); - return a % b; - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol deleted file mode 100644 index 5a9d6068..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/SignedMath.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Standard signed math utilities missing in the Solidity language. - */ -library SignedMath { - /** - * @dev Returns the largest of two signed numbers. - */ - function max(int256 a, int256 b) internal pure returns (int256) { - return a >= b ? a : b; - } - - /** - * @dev Returns the smallest of two signed numbers. - */ - function min(int256 a, int256 b) internal pure returns (int256) { - return a < b ? a : b; - } - - /** - * @dev Returns the average of two signed numbers without overflow. - * The result is rounded towards zero. - */ - function average(int256 a, int256 b) internal pure returns (int256) { - // Formula from the book "Hacker's Delight" - int256 x = (a & b) + ((a ^ b) >> 1); - return x + (int256(uint256(x) >> 255) & (a ^ b)); - } - - /** - * @dev Returns the absolute unsigned value of a signed value. - */ - function abs(int256 n) internal pure returns (uint256) { - unchecked { - // must be unchecked in order to support `n = type(int256).min` - return uint256(n >= 0 ? n : -n); - } - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SignedSafeMath.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SignedSafeMath.sol deleted file mode 100644 index 6704d4ce..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/math/SignedSafeMath.sol +++ /dev/null @@ -1,68 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/math/SignedSafeMath.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Wrappers over Solidity's arithmetic operations. - * - * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler - * now has built in overflow checking. - */ -library SignedSafeMath { - /** - * @dev Returns the multiplication of two signed integers, reverting on - * overflow. - * - * Counterpart to Solidity's `*` operator. - * - * Requirements: - * - * - Multiplication cannot overflow. - */ - function mul(int256 a, int256 b) internal pure returns (int256) { - return a * b; - } - - /** - * @dev Returns the integer division of two signed integers. Reverts on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. - * - * Requirements: - * - * - The divisor cannot be zero. - */ - function div(int256 a, int256 b) internal pure returns (int256) { - return a / b; - } - - /** - * @dev Returns the subtraction of two signed integers, reverting on - * overflow. - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - * - Subtraction cannot overflow. - */ - function sub(int256 a, int256 b) internal pure returns (int256) { - return a - b; - } - - /** - * @dev Returns the addition of two signed integers, reverting on - * overflow. - * - * Counterpart to Solidity's `+` operator. - * - * Requirements: - * - * - Addition cannot overflow. - */ - function add(int256 a, int256 b) internal pure returns (int256) { - return a + b; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/BitMaps.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/BitMaps.sol deleted file mode 100644 index 9721b831..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/BitMaps.sol +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol) -pragma solidity ^0.8.0; - -/** - * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. - * Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor]. - */ -library BitMaps { - struct BitMap { - mapping(uint256 => uint256) _data; - } - - /** - * @dev Returns whether the bit at `index` is set. - */ - function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { - uint256 bucket = index >> 8; - uint256 mask = 1 << (index & 0xff); - return bitmap._data[bucket] & mask != 0; - } - - /** - * @dev Sets the bit at `index` to the boolean `value`. - */ - function setTo( - BitMap storage bitmap, - uint256 index, - bool value - ) internal { - if (value) { - set(bitmap, index); - } else { - unset(bitmap, index); - } - } - - /** - * @dev Sets the bit at `index`. - */ - function set(BitMap storage bitmap, uint256 index) internal { - uint256 bucket = index >> 8; - uint256 mask = 1 << (index & 0xff); - bitmap._data[bucket] |= mask; - } - - /** - * @dev Unsets the bit at `index`. - */ - function unset(BitMap storage bitmap, uint256 index) internal { - uint256 bucket = index >> 8; - uint256 mask = 1 << (index & 0xff); - bitmap._data[bucket] &= ~mask; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableMap.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableMap.sol deleted file mode 100644 index 1bc57159..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableMap.sol +++ /dev/null @@ -1,240 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableMap.sol) - -pragma solidity ^0.8.0; - -import "./EnumerableSet.sol"; - -/** - * @dev Library for managing an enumerable variant of Solidity's - * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] - * type. - * - * Maps have the following properties: - * - * - Entries are added, removed, and checked for existence in constant time - * (O(1)). - * - Entries are enumerated in O(n). No guarantees are made on the ordering. - * - * ``` - * contract Example { - * // Add the library methods - * using EnumerableMap for EnumerableMap.UintToAddressMap; - * - * // Declare a set state variable - * EnumerableMap.UintToAddressMap private myMap; - * } - * ``` - * - * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are - * supported. - */ -library EnumerableMap { - using EnumerableSet for EnumerableSet.Bytes32Set; - - // To implement this library for multiple types with as little code - // repetition as possible, we write it in terms of a generic Map type with - // bytes32 keys and values. - // The Map implementation uses private functions, and user-facing - // implementations (such as Uint256ToAddressMap) are just wrappers around - // the underlying Map. - // This means that we can only create new EnumerableMaps for types that fit - // in bytes32. - - struct Map { - // Storage of keys - EnumerableSet.Bytes32Set _keys; - mapping(bytes32 => bytes32) _values; - } - - /** - * @dev Adds a key-value pair to a map, or updates the value for an existing - * key. O(1). - * - * Returns true if the key was added to the map, that is if it was not - * already present. - */ - function _set( - Map storage map, - bytes32 key, - bytes32 value - ) private returns (bool) { - map._values[key] = value; - return map._keys.add(key); - } - - /** - * @dev Removes a key-value pair from a map. O(1). - * - * Returns true if the key was removed from the map, that is if it was present. - */ - function _remove(Map storage map, bytes32 key) private returns (bool) { - delete map._values[key]; - return map._keys.remove(key); - } - - /** - * @dev Returns true if the key is in the map. O(1). - */ - function _contains(Map storage map, bytes32 key) private view returns (bool) { - return map._keys.contains(key); - } - - /** - * @dev Returns the number of key-value pairs in the map. O(1). - */ - function _length(Map storage map) private view returns (uint256) { - return map._keys.length(); - } - - /** - * @dev Returns the key-value pair stored at position `index` in the map. O(1). - * - * Note that there are no guarantees on the ordering of entries inside the - * array, and it may change when more entries are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { - bytes32 key = map._keys.at(index); - return (key, map._values[key]); - } - - /** - * @dev Tries to returns the value associated with `key`. O(1). - * Does not revert if `key` is not in the map. - */ - function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { - bytes32 value = map._values[key]; - if (value == bytes32(0)) { - return (_contains(map, key), bytes32(0)); - } else { - return (true, value); - } - } - - /** - * @dev Returns the value associated with `key`. O(1). - * - * Requirements: - * - * - `key` must be in the map. - */ - function _get(Map storage map, bytes32 key) private view returns (bytes32) { - bytes32 value = map._values[key]; - require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); - return value; - } - - /** - * @dev Same as {_get}, with a custom error message when `key` is not in the map. - * - * CAUTION: This function is deprecated because it requires allocating memory for the error - * message unnecessarily. For custom revert reasons use {_tryGet}. - */ - function _get( - Map storage map, - bytes32 key, - string memory errorMessage - ) private view returns (bytes32) { - bytes32 value = map._values[key]; - require(value != 0 || _contains(map, key), errorMessage); - return value; - } - - // UintToAddressMap - - struct UintToAddressMap { - Map _inner; - } - - /** - * @dev Adds a key-value pair to a map, or updates the value for an existing - * key. O(1). - * - * Returns true if the key was added to the map, that is if it was not - * already present. - */ - function set( - UintToAddressMap storage map, - uint256 key, - address value - ) internal returns (bool) { - return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the key was removed from the map, that is if it was present. - */ - function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { - return _remove(map._inner, bytes32(key)); - } - - /** - * @dev Returns true if the key is in the map. O(1). - */ - function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { - return _contains(map._inner, bytes32(key)); - } - - /** - * @dev Returns the number of elements in the map. O(1). - */ - function length(UintToAddressMap storage map) internal view returns (uint256) { - return _length(map._inner); - } - - /** - * @dev Returns the element stored at position `index` in the set. O(1). - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { - (bytes32 key, bytes32 value) = _at(map._inner, index); - return (uint256(key), address(uint160(uint256(value)))); - } - - /** - * @dev Tries to returns the value associated with `key`. O(1). - * Does not revert if `key` is not in the map. - * - * _Available since v3.4._ - */ - function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { - (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); - return (success, address(uint160(uint256(value)))); - } - - /** - * @dev Returns the value associated with `key`. O(1). - * - * Requirements: - * - * - `key` must be in the map. - */ - function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { - return address(uint160(uint256(_get(map._inner, bytes32(key))))); - } - - /** - * @dev Same as {get}, with a custom error message when `key` is not in the map. - * - * CAUTION: This function is deprecated because it requires allocating memory for the error - * message unnecessarily. For custom revert reasons use {tryGet}. - */ - function get( - UintToAddressMap storage map, - uint256 key, - string memory errorMessage - ) internal view returns (address) { - return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol deleted file mode 100644 index 68148e94..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol +++ /dev/null @@ -1,357 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Library for managing - * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive - * types. - * - * Sets have the following properties: - * - * - Elements are added, removed, and checked for existence in constant time - * (O(1)). - * - Elements are enumerated in O(n). No guarantees are made on the ordering. - * - * ``` - * contract Example { - * // Add the library methods - * using EnumerableSet for EnumerableSet.AddressSet; - * - * // Declare a set state variable - * EnumerableSet.AddressSet private mySet; - * } - * ``` - * - * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) - * and `uint256` (`UintSet`) are supported. - */ -library EnumerableSet { - // To implement this library for multiple types with as little code - // repetition as possible, we write it in terms of a generic Set type with - // bytes32 values. - // The Set implementation uses private functions, and user-facing - // implementations (such as AddressSet) are just wrappers around the - // underlying Set. - // This means that we can only create new EnumerableSets for types that fit - // in bytes32. - - struct Set { - // Storage of set values - bytes32[] _values; - // Position of the value in the `values` array, plus 1 because index 0 - // means a value is not in the set. - mapping(bytes32 => uint256) _indexes; - } - - /** - * @dev Add a value to a set. O(1). - * - * Returns true if the value was added to the set, that is if it was not - * already present. - */ - function _add(Set storage set, bytes32 value) private returns (bool) { - if (!_contains(set, value)) { - set._values.push(value); - // The value is stored at length-1, but we add 1 to all indexes - // and use 0 as a sentinel value - set._indexes[value] = set._values.length; - return true; - } else { - return false; - } - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the value was removed from the set, that is if it was - * present. - */ - function _remove(Set storage set, bytes32 value) private returns (bool) { - // We read and store the value's index to prevent multiple reads from the same storage slot - uint256 valueIndex = set._indexes[value]; - - if (valueIndex != 0) { - // Equivalent to contains(set, value) - // To delete an element from the _values array in O(1), we swap the element to delete with the last one in - // the array, and then remove the last element (sometimes called as 'swap and pop'). - // This modifies the order of the array, as noted in {at}. - - uint256 toDeleteIndex = valueIndex - 1; - uint256 lastIndex = set._values.length - 1; - - if (lastIndex != toDeleteIndex) { - bytes32 lastvalue = set._values[lastIndex]; - - // Move the last value to the index where the value to delete is - set._values[toDeleteIndex] = lastvalue; - // Update the index for the moved value - set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex - } - - // Delete the slot where the moved value was stored - set._values.pop(); - - // Delete the index for the deleted slot - delete set._indexes[value]; - - return true; - } else { - return false; - } - } - - /** - * @dev Returns true if the value is in the set. O(1). - */ - function _contains(Set storage set, bytes32 value) private view returns (bool) { - return set._indexes[value] != 0; - } - - /** - * @dev Returns the number of values on the set. O(1). - */ - function _length(Set storage set) private view returns (uint256) { - return set._values.length; - } - - /** - * @dev Returns the value stored at position `index` in the set. O(1). - * - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function _at(Set storage set, uint256 index) private view returns (bytes32) { - return set._values[index]; - } - - /** - * @dev Return the entire set in an array - * - * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed - * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that - * this function has an unbounded cost, and using it as part of a state-changing function may render the function - * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function _values(Set storage set) private view returns (bytes32[] memory) { - return set._values; - } - - // Bytes32Set - - struct Bytes32Set { - Set _inner; - } - - /** - * @dev Add a value to a set. O(1). - * - * Returns true if the value was added to the set, that is if it was not - * already present. - */ - function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { - return _add(set._inner, value); - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the value was removed from the set, that is if it was - * present. - */ - function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { - return _remove(set._inner, value); - } - - /** - * @dev Returns true if the value is in the set. O(1). - */ - function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { - return _contains(set._inner, value); - } - - /** - * @dev Returns the number of values in the set. O(1). - */ - function length(Bytes32Set storage set) internal view returns (uint256) { - return _length(set._inner); - } - - /** - * @dev Returns the value stored at position `index` in the set. O(1). - * - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { - return _at(set._inner, index); - } - - /** - * @dev Return the entire set in an array - * - * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed - * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that - * this function has an unbounded cost, and using it as part of a state-changing function may render the function - * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { - return _values(set._inner); - } - - // AddressSet - - struct AddressSet { - Set _inner; - } - - /** - * @dev Add a value to a set. O(1). - * - * Returns true if the value was added to the set, that is if it was not - * already present. - */ - function add(AddressSet storage set, address value) internal returns (bool) { - return _add(set._inner, bytes32(uint256(uint160(value)))); - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the value was removed from the set, that is if it was - * present. - */ - function remove(AddressSet storage set, address value) internal returns (bool) { - return _remove(set._inner, bytes32(uint256(uint160(value)))); - } - - /** - * @dev Returns true if the value is in the set. O(1). - */ - function contains(AddressSet storage set, address value) internal view returns (bool) { - return _contains(set._inner, bytes32(uint256(uint160(value)))); - } - - /** - * @dev Returns the number of values in the set. O(1). - */ - function length(AddressSet storage set) internal view returns (uint256) { - return _length(set._inner); - } - - /** - * @dev Returns the value stored at position `index` in the set. O(1). - * - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(AddressSet storage set, uint256 index) internal view returns (address) { - return address(uint160(uint256(_at(set._inner, index)))); - } - - /** - * @dev Return the entire set in an array - * - * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed - * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that - * this function has an unbounded cost, and using it as part of a state-changing function may render the function - * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function values(AddressSet storage set) internal view returns (address[] memory) { - bytes32[] memory store = _values(set._inner); - address[] memory result; - - assembly { - result := store - } - - return result; - } - - // UintSet - - struct UintSet { - Set _inner; - } - - /** - * @dev Add a value to a set. O(1). - * - * Returns true if the value was added to the set, that is if it was not - * already present. - */ - function add(UintSet storage set, uint256 value) internal returns (bool) { - return _add(set._inner, bytes32(value)); - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the value was removed from the set, that is if it was - * present. - */ - function remove(UintSet storage set, uint256 value) internal returns (bool) { - return _remove(set._inner, bytes32(value)); - } - - /** - * @dev Returns true if the value is in the set. O(1). - */ - function contains(UintSet storage set, uint256 value) internal view returns (bool) { - return _contains(set._inner, bytes32(value)); - } - - /** - * @dev Returns the number of values on the set. O(1). - */ - function length(UintSet storage set) internal view returns (uint256) { - return _length(set._inner); - } - - /** - * @dev Returns the value stored at position `index` in the set. O(1). - * - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(UintSet storage set, uint256 index) internal view returns (uint256) { - return uint256(_at(set._inner, index)); - } - - /** - * @dev Return the entire set in an array - * - * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed - * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that - * this function has an unbounded cost, and using it as part of a state-changing function may render the function - * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function values(UintSet storage set) internal view returns (uint256[] memory) { - bytes32[] memory store = _values(set._inner); - uint256[] memory result; - - assembly { - result := store - } - - return result; - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/antora.yml b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/antora.yml deleted file mode 100644 index 513a997d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/antora.yml +++ /dev/null @@ -1,6 +0,0 @@ -name: contracts -title: Contracts -version: 4.x -nav: - - modules/ROOT/nav.adoc - - modules/api/nav.adoc diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/contract.hbs b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/contract.hbs deleted file mode 100644 index 8690cf8a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/contract.hbs +++ /dev/null @@ -1,91 +0,0 @@ -{{~#*inline "typed-variable-array"~}} -{{#each .}}{{typeName}}{{#if name}} {{name}}{{/if}}{{#unless @last}}, {{/unless}}{{/each}} -{{~/inline~}} - -{{#each linkable}} -:{{name}}: pass:normal[xref:#{{anchor}}[`++{{name}}++`]] -{{/each}} - -[.contract] -[[{{anchor}}]] -=== `++{{name}}++` link:{{github-link file.path}}[{github-icon},role=heading-link] - -[.hljs-theme-light.nopadding] -```solidity -import "@openzeppelin/contracts/{{file.path}}"; -``` - -{{natspec.devdoc}} - -{{#if ownModifiers}} -[.contract-index] -.Modifiers --- -{{#each ownModifiers}} -* {xref-{{slug anchor~}} }[`++{{name}}({{args.names}})++`] -{{/each}} --- -{{/if}} - -{{#if functions}} -[.contract-index] -.Functions --- -{{#each inheritedItems}} -{{#if (or @first (ne contract.name "Context"))}} -{{#unless @first}} -[.contract-subindex-inherited] -.{{contract.name}} -{{/unless}} -{{#each functions}} -* {xref-{{slug anchor~}} }[`++{{name}}({{args.names}})++`] -{{/each}} - -{{/if}} -{{/each}} --- -{{/if}} - -{{#if events}} -[.contract-index] -.Events --- -{{#each inheritedItems}} -{{#unless @first}} -[.contract-subindex-inherited] -.{{contract.name}} -{{/unless}} -{{#each events}} -* {xref-{{slug anchor~}} }[`++{{name}}({{args.names}})++`] -{{/each}} - -{{/each}} --- -{{/if}} - -{{#each ownModifiers}} -[.contract-item] -[[{{anchor}}]] -==== `[.contract-item-name]#++{{name}}++#++({{> typed-variable-array args}})++` [.item-kind]#modifier# - -{{natspec.devdoc}} - -{{/each}} - -{{#each ownFunctions}} -[.contract-item] -[[{{anchor}}]] -==== `[.contract-item-name]#++{{name}}++#++({{> typed-variable-array args}}){{#if outputs}} → {{> typed-variable-array outputs}}{{/if}}++` [.item-kind]#{{visibility}}# - -{{natspec.devdoc}} - -{{/each}} - -{{#each ownEvents}} -[.contract-item] -[[{{anchor}}]] -==== `[.contract-item-name]#++{{name}}++#++({{> typed-variable-array args}})++` [.item-kind]#event# - -{{natspec.devdoc}} - -{{/each}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/helpers.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/helpers.js deleted file mode 100644 index 9b71f44f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/helpers.js +++ /dev/null @@ -1,10 +0,0 @@ -const { version } = require('../package.json'); - -module.exports = { - 'github-link': (contractPath) => { - if (typeof contractPath !== 'string') { - throw new Error('Missing argument'); - } - return `https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v${version}/contracts/${contractPath}`; - }, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/images/tally-admin.png b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/images/tally-admin.png deleted file mode 100644 index 82652593..00000000 Binary files a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/images/tally-admin.png and /dev/null differ diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/images/tally-vote.png b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/images/tally-vote.png deleted file mode 100644 index 76e9b3a9..00000000 Binary files a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/images/tally-vote.png and /dev/null differ diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/nav.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/nav.adoc deleted file mode 100644 index 3804c7d9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/nav.adoc +++ /dev/null @@ -1,19 +0,0 @@ -* xref:index.adoc[Overview] -* xref:wizard.adoc[Wizard] -* xref:extending-contracts.adoc[Extending Contracts] -* xref:upgradeable.adoc[Using with Upgrades] - -* xref:releases-stability.adoc[Releases & Stability] - -* xref:access-control.adoc[Access Control] - -* xref:tokens.adoc[Tokens] -** xref:erc20.adoc[ERC20] -*** xref:erc20-supply.adoc[Creating Supply] -** xref:erc721.adoc[ERC721] -** xref:erc777.adoc[ERC777] -** xref:erc1155.adoc[ERC1155] - -* xref:governance.adoc[Governance] - -* xref:utilities.adoc[Utilities] diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/access-control.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/access-control.adoc deleted file mode 100644 index 822bb84b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/access-control.adoc +++ /dev/null @@ -1,217 +0,0 @@ -= Access Control - -Access control—that is, "who is allowed to do this thing"—is incredibly important in the world of smart contracts. The access control of your contract may govern who can mint tokens, vote on proposals, freeze transfers, and many other things. It is therefore *critical* to understand how you implement it, lest someone else https://blog.openzeppelin.com/on-the-parity-wallet-multisig-hack-405a8c12e8f7[steals your whole system]. - -[[ownership-and-ownable]] -== Ownership and `Ownable` - -The most common and basic form of access control is the concept of _ownership_: there's an account that is the `owner` of a contract and can do administrative tasks on it. This approach is perfectly reasonable for contracts that have a single administrative user. - -OpenZeppelin Contracts provides xref:api:access.adoc#Ownable[`Ownable`] for implementing ownership in your contracts. - -[source,solidity] ----- -// contracts/MyContract.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/access/Ownable.sol"; - -contract MyContract is Ownable { - function normalThing() public { - // anyone can call this normalThing() - } - - function specialThing() public onlyOwner { - // only the owner can call specialThing()! - } -} ----- - -By default, the xref:api:access.adoc#Ownable-owner--[`owner`] of an `Ownable` contract is the account that deployed it, which is usually exactly what you want. - -Ownable also lets you: - -* xref:api:access.adoc#Ownable-transferOwnership-address-[`transferOwnership`] from the owner account to a new one, and -* xref:api:access.adoc#Ownable-renounceOwnership--[`renounceOwnership`] for the owner to relinquish this administrative privilege, a common pattern after an initial stage with centralized administration is over. - -WARNING: Removing the owner altogether will mean that administrative tasks that are protected by `onlyOwner` will no longer be callable! - -Note that *a contract can also be the owner of another one*! This opens the door to using, for example, a https://github.com/gnosis/MultiSigWallet[Gnosis Multisig] or https://safe.gnosis.io[Gnosis Safe], an https://aragon.org[Aragon DAO], an https://www.uport.me[ERC725/uPort] identity contract, or a totally custom contract that _you_ create. - -In this way you can use _composability_ to add additional layers of access control complexity to your contracts. Instead of having a single regular Ethereum account (Externally Owned Account, or EOA) as the owner, you could use a 2-of-3 multisig run by your project leads, for example. Prominent projects in the space, such as https://makerdao.com[MakerDAO], use systems similar to this one. - -[[role-based-access-control]] -== Role-Based Access Control - -While the simplicity of _ownership_ can be useful for simple systems or quick prototyping, different levels of authorization are often needed. You may want for an account to have permission to ban users from a system, but not create new tokens. https://en.wikipedia.org/wiki/Role-based_access_control[_Role-Based Access Control (RBAC)_] offers flexibility in this regard. - -In essence, we will be defining multiple _roles_, each allowed to perform different sets of actions. An account may have, for example, 'moderator', 'minter' or 'admin' roles, which you will then check for instead of simply using `onlyOwner`. This check can be enforced through the `onlyRole` modifier. Separately, you will be able to define rules for how accounts can be granted a role, have it revoked, and more. - -Most software uses access control systems that are role-based: some users are regular users, some may be supervisors or managers, and a few will often have administrative privileges. - -[[using-access-control]] -=== Using `AccessControl` - -OpenZeppelin Contracts provides xref:api:access.adoc#AccessControl[`AccessControl`] for implementing role-based access control. Its usage is straightforward: for each role that you want to define, -you will create a new _role identifier_ that is used to grant, revoke, and check if an account has that role. - -Here's a simple example of using `AccessControl` in an xref:tokens.adoc#ERC20[`ERC20` token] to define a 'minter' role, which allows accounts that have it create new tokens: - -[source,solidity] ----- -// contracts/MyToken.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/access/AccessControl.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20, AccessControl { - // Create a new role identifier for the minter role - bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); - - constructor(address minter) ERC20("MyToken", "TKN") { - // Grant the minter role to a specified account - _setupRole(MINTER_ROLE, minter); - } - - function mint(address to, uint256 amount) public { - // Check that the calling account has the minter role - require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter"); - _mint(to, amount); - } -} ----- - -NOTE: Make sure you fully understand how xref:api:access.adoc#AccessControl[`AccessControl`] works before using it on your system, or copy-pasting the examples from this guide. - -While clear and explicit, this isn't anything we wouldn't have been able to achieve with `Ownable`. Indeed, where `AccessControl` shines is in scenarios where granular permissions are required, which can be implemented by defining _multiple_ roles. - -Let's augment our ERC20 token example by also defining a 'burner' role, which lets accounts destroy tokens, and by using the `onlyRole` modifier: - -[source,solidity] ----- -// contracts/MyToken.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/access/AccessControl.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20, AccessControl { - bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); - bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); - - constructor(address minter, address burner) ERC20("MyToken", "TKN") { - _setupRole(MINTER_ROLE, minter); - _setupRole(BURNER_ROLE, burner); - } - - function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) { - _mint(to, amount); - } - - function burn(address from, uint256 amount) public onlyRole(BURNER_ROLE) { - _burn(from, amount); - } -} ----- - -So clean! By splitting concerns this way, more granular levels of permission may be implemented than were possible with the simpler _ownership_ approach to access control. Limiting what each component of a system is able to do is known as the https://en.wikipedia.org/wiki/Principle_of_least_privilege[principle of least privilege], and is a good security practice. Note that each account may still have more than one role, if so desired. - -[[granting-and-revoking]] -=== Granting and Revoking Roles - -The ERC20 token example above uses `_setupRole`, an `internal` function that is useful when programmatically assigning roles (such as during construction). But what if we later want to grant the 'minter' role to additional accounts? - -By default, **accounts with a role cannot grant it or revoke it from other accounts**: all having a role does is making the `hasRole` check pass. To grant and revoke roles dynamically, you will need help from the _role's admin_. - -Every role has an associated admin role, which grants permission to call the `grantRole` and `revokeRole` functions. A role can be granted or revoked by using these if the calling account has the corresponding admin role. Multiple roles may have the same admin role to make management easier. A role's admin can even be the same role itself, which would cause accounts with that role to be able to also grant and revoke it. - -This mechanism can be used to create complex permissioning structures resembling organizational charts, but it also provides an easy way to manage simpler applications. `AccessControl` includes a special role, called `DEFAULT_ADMIN_ROLE`, which acts as the **default admin role for all roles**. An account with this role will be able to manage any other role, unless `_setRoleAdmin` is used to select a new admin role. - -Let's take a look at the ERC20 token example, this time taking advantage of the default admin role: - -[source,solidity] ----- -// contracts/MyToken.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/access/AccessControl.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20, AccessControl { - bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); - bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); - - constructor() ERC20("MyToken", "TKN") { - // Grant the contract deployer the default admin role: it will be able - // to grant and revoke any roles - _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); - } - - function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) { - _mint(to, amount); - } - - function burn(address from, uint256 amount) public onlyRole(BURNER_ROLE) { - _burn(from, amount); - } -} ----- - -Note that, unlike the previous examples, no accounts are granted the 'minter' or 'burner' roles. However, because those roles' admin role is the default admin role, and _that_ role was granted to `msg.sender`, that same account can call `grantRole` to give minting or burning permission, and `revokeRole` to remove it. - -Dynamic role allocation is often a desirable property, for example in systems where trust in a participant may vary over time. It can also be used to support use cases such as https://en.wikipedia.org/wiki/Know_your_customer[KYC], where the list of role-bearers may not be known up-front, or may be prohibitively expensive to include in a single transaction. - -[[querying-privileged-accounts]] -=== Querying Privileged Accounts - -Because accounts might <> dynamically, it is not always possible to determine which accounts hold a particular role. This is important as it allows to prove certain properties about a system, such as that an administrative account is a multisig or a DAO, or that a certain role has been removed from all users, effectively disabling any associated functionality. - -Under the hood, `AccessControl` uses `EnumerableSet`, a more powerful variant of Solidity's `mapping` type, which allows for key enumeration. `getRoleMemberCount` can be used to retrieve the number of accounts that have a particular role, and `getRoleMember` can then be called to get the address of each of these accounts. - -```javascript -const minterCount = await myToken.getRoleMemberCount(MINTER_ROLE); - -const members = []; -for (let i = 0; i < minterCount; ++i) { - members.push(await myToken.getRoleMember(MINTER_ROLE, i)); -} -``` - -== Delayed operation - -Access control is essential to prevent unauthorized access to critical functions. These functions may be used to mint tokens, freeze transfers or perform an upgrade that completely changes the smart contract logic. While xref:api:access.adoc#Ownable[`Ownable`] and xref:api:access.adoc#AccessControl[`AccessControl`] can prevent unauthorized access, they do not address the issue of a misbehaving administrator attacking their own system to the prejudice of their users. - -This is the issue the xref:api:governance.adoc#TimelockController[`TimelockController`] is addressing. - -The xref:api:governance.adoc#TimelockController[`TimelockController`] is a proxy that is governed by proposers and executors. When set as the owner/admin/controller of a smart contract, it ensures that whichever maintenance operation is ordered by the proposers is subject to a delay. This delay protects the users of the smart contract by giving them time to review the maintenance operation and exit the system if they consider it is in their best interest to do so. - -=== Using `TimelockController` - -By default, the address that deployed the xref:api:governance.adoc#TimelockController[`TimelockController`] gets administration privileges over the timelock. This role grants the right to assign proposers, executors, and other administrators. - -The first step in configuring the xref:api:governance.adoc#TimelockController[`TimelockController`] is to assign at least one proposer and one executor. These can be assigned during construction or later by anyone with the administrator role. These roles are not exclusive, meaning an account can have both roles. - -Roles are managed using the xref:api:access.adoc#AccessControl[`AccessControl`] interface and the `bytes32` values for each role are accessible through the `ADMIN_ROLE`, `PROPOSER_ROLE` and `EXECUTOR_ROLE` constants. - -There is an additional feature built on top of `AccessControl`: giving the executor role to `address(0)` opens access to anyone to execute a proposal once the timelock has expired. This feature, while useful, should be used with caution. - -At this point, with both a proposer and an executor assigned, the timelock can perform operations. - -An optional next step is for the deployer to renounce its administrative privileges and leave the timelock self-administered. If the deployer decides to do so, all further maintenance, including assigning new proposers/schedulers or changing the timelock duration will have to follow the timelock workflow. This links the governance of the timelock to the governance of contracts attached to the timelock, and enforce a delay on timelock maintenance operations. - -WARNING: If the deployer renounces administrative rights in favour of timelock itself, assigning new proposers or executors will require a timelocked operation. This means that if the accounts in charge of any of these two roles become unavailable, then the entire contract (and any contract it controls) becomes locked indefinitely. - -With both the proposer and executor roles assigned and the timelock in charge of its own administration, you can now transfer the ownership/control of any contract to the timelock. - -TIP: A recommended configuration is to grant both roles to a secure governance contract such as a DAO or a multisig, and to additionally grant the executor role to a few EOAs held by people in charge of helping with the maintenance operations. These wallets cannot take over control of the timelock but they can help smoothen the workflow. - -=== Minimum delay - -Operations executed by the xref:api:governance.adoc#TimelockController[`TimelockController`] are not subject to a fixed delay but rather a minimum delay. Some major updates might call for a longer delay. For example, if a delay of just a few days might be sufficient for users to audit a minting operation, it makes sense to use a delay of a few weeks, or even a few months, when scheduling a smart contract upgrade. - -The minimum delay (accessible through the xref:api:governance.adoc#TimelockController-getMinDelay--[`getMinDelay`] method) can be updated by calling the xref:api:governance.adoc#TimelockController-updateDelay-uint256-[`updateDelay`] function. Bear in mind that access to this function is only accessible by the timelock itself, meaning this maintenance operation has to go through the timelock itself. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/crowdsales.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/crowdsales.adoc deleted file mode 100644 index 37579211..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/crowdsales.adoc +++ /dev/null @@ -1,11 +0,0 @@ -= Crowdsales - -All crowdsale-related contracts were removed from the OpenZeppelin Contracts library on the https://forum.openzeppelin.com/t/openzeppelin-contracts-v3-0-beta-release/2256[v3.0.0 release] due to both a decline in their usage and the complexity associated with migrating them to Solidity v0.6. - -They are however still available on the v2.5 release of OpenZeppelin Contracts, which you can install by running: - -```console -$ npm install @openzeppelin/contracts@v2.5 -``` - -Refer to the https://docs.openzeppelin.com/contracts/2.x/crowdsales[v2.x documentation] when working with them. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/drafts.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/drafts.adoc deleted file mode 100644 index b2c1ae62..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/drafts.adoc +++ /dev/null @@ -1,19 +0,0 @@ -= Drafts - -All draft contracts were either moved into a different directory or removed from the OpenZeppelin Contracts library on the https://forum.openzeppelin.com/t/openzeppelin-contracts-v3-0-beta-release/2256[v3.0.0 release]. - -* `ERC20Migrator`: removed. -* xref:api:token/ERC20.adoc#ERC20Snapshot[`ERC20Snapshot`]: moved to `token/ERC20`. -* `ERC20Detailed` and `ERC1046`: removed. -* `TokenVesting`: removed. Pending a replacement that is being discussed in https://github.com/OpenZeppelin/openzeppelin-contracts/issues/1214[`#1214`]. -* xref:api:utils.adoc#Counters[`Counters`]: moved to xref:api:utils.adoc[`utils`]. -* xref:api:utils.adoc#Strings[`Strings`]: moved to xref:api:utils.adoc[`utils`]. -* xref:api:utils.adoc#SignedSafeMath[`SignedSafeMath`]: moved to xref:api:utils.adoc[`utils`]. - -Removed contracts are still available on the v2.5 release of OpenZeppelin Contracts, which you can install by running: - -```console -$ npm install @openzeppelin/contracts@v2.5 -``` - -Refer to the xref:2.x@contracts:api:drafts.adoc[v2.x documentation] when working with them. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc1155.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc1155.adoc deleted file mode 100644 index ee2e3d2e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc1155.adoc +++ /dev/null @@ -1,151 +0,0 @@ -= ERC1155 - -ERC1155 is a novel token standard that aims to take the best from previous standards to create a xref:tokens.adoc#different-kinds-of-tokens[*fungibility-agnostic*] and *gas-efficient* xref:tokens.adoc#but_first_coffee_a_primer_on_token_contracts[token contract]. - -TIP: ERC1155 draws ideas from all of xref:erc20.adoc[ERC20], xref:erc721.adoc[ERC721], and xref:erc777.adoc[ERC777]. If you're unfamiliar with those standards, head to their guides before moving on. - -[[multi-token-standard]] -== Multi Token Standard - -The distinctive feature of ERC1155 is that it uses a single smart contract to represent multiple tokens at once. This is why its xref:api:token/ERC1155.adoc#IERC1155-balanceOf-address-uint256-[`balanceOf`] function differs from ERC20's and ERC777's: it has an additional `id` argument for the identifier of the token that you want to query the balance of. - -This is similar to how ERC721 does things, but in that standard a token `id` has no concept of balance: each token is non-fungible and exists or doesn't. The ERC721 xref:api:token/ERC721.adoc#IERC721-balanceOf-address-[`balanceOf`] function refers to _how many different tokens_ an account has, not how many of each. On the other hand, in ERC1155 accounts have a distinct balance for each token `id`, and non-fungible tokens are implemented by simply minting a single one of them. - -This approach leads to massive gas savings for projects that require multiple tokens. Instead of deploying a new contract for each token type, a single ERC1155 token contract can hold the entire system state, reducing deployment costs and complexity. - -[[batch-operations]] -== Batch Operations - -Because all state is held in a single contract, it is possible to operate over multiple tokens in a single transaction very efficiently. The standard provides two functions, xref:api:token/ERC1155.adoc#IERC1155-balanceOfBatch-address---uint256---[`balanceOfBatch`] and xref:api:token/ERC1155.adoc#IERC1155-safeBatchTransferFrom-address-address-uint256---uint256---bytes-[`safeBatchTransferFrom`], that make querying multiple balances and transferring multiple tokens simpler and less gas-intensive. - -In the spirit of the standard, we've also included batch operations in the non-standard functions, such as xref:api:token/ERC1155.adoc#ERC1155-_mintBatch-address-uint256---uint256---bytes-[`_mintBatch`]. - -== Constructing an ERC1155 Token Contract - -We'll use ERC1155 to track multiple items in our game, which will each have their own unique attributes. We mint all items to the deployer of the contract, which we can later transfer to players. Players are free to keep their tokens or trade them with other people as they see fit, as they would any other asset on the blockchain! - -For simplicity we will mint all items in the constructor but you could add minting functionality to the contract to mint on demand to players. - -TIP: For an overview of minting mechanisms check out xref:erc20-supply.adoc[Creating ERC20 Supply]. - -Here's what a contract for tokenized items might look like: - -[source,solidity] ----- -// contracts/GameItems.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; - -contract GameItems is ERC1155 { - uint256 public constant GOLD = 0; - uint256 public constant SILVER = 1; - uint256 public constant THORS_HAMMER = 2; - uint256 public constant SWORD = 3; - uint256 public constant SHIELD = 4; - - constructor() ERC1155("https://game.example/api/item/{id}.json") { - _mint(msg.sender, GOLD, 10**18, ""); - _mint(msg.sender, SILVER, 10**27, ""); - _mint(msg.sender, THORS_HAMMER, 1, ""); - _mint(msg.sender, SWORD, 10**9, ""); - _mint(msg.sender, SHIELD, 10**9, ""); - } -} ----- - -Note that for our Game Items, Gold is a fungible token whilst Thor's Hammer is a non-fungible token as we minted only one. - -The xref:api:token/ERC1155.adoc#ERC1155[`ERC1155`] contract includes the optional extension xref:api:token/ERC1155.adoc#IERC1155MetadataURI[`IERC1155MetadataURI`]. That's where the xref:api:token/ERC1155.adoc#IERC1155MetadataURI-uri-uint256-[`uri`] function comes from: we use it to retrieve the metadata uri. - -Also note that, unlike ERC20, ERC1155 lacks a `decimals` field, since each token is distinct and cannot be partitioned. - -Once deployed, we will be able to query the deployer’s balance: -[source,javascript] ----- -> gameItems.balanceOf(deployerAddress,3) -1000000000 ----- - -We can transfer items to player accounts: -[source,javascript] ----- -> gameItems.safeTransferFrom(deployerAddress, playerAddress, 2, 1, "0x0") -> gameItems.balanceOf(playerAddress, 2) -1 -> gameItems.balanceOf(deployerAddress, 2) -0 ----- - -We can also batch transfer items to player accounts and get the balance of batches: -[source,javascript] ----- -> gameItems.safeBatchTransferFrom(deployerAddress, playerAddress, [0,1,3,4], [50,100,1,1], "0x0") -> gameItems.balanceOfBatch([playerAddress,playerAddress,playerAddress,playerAddress,playerAddress], [0,1,2,3,4]) -[50,100,1,1,1] ----- - -The metadata uri can be obtained: - -[source,javascript] ----- -> gameItems.uri(2) -"https://game.example/api/item/{id}.json" ----- - -The `uri` can include the string `++{id}++` which clients must replace with the actual token ID, in lowercase hexadecimal (with no 0x prefix) and leading zero padded to 64 hex characters. - -For token ID `2` and uri `++https://game.example/api/item/{id}.json++` clients would replace `++{id}++` with `0000000000000000000000000000000000000000000000000000000000000002` to retrieve JSON at `https://game.example/api/item/0000000000000000000000000000000000000000000000000000000000000002.json`. - -The JSON document for token ID 2 might look something like: - -[source,json] ----- -{ - "name": "Thor's hammer", - "description": "Mjölnir, the legendary hammer of the Norse god of thunder.", - "image": "https://game.example/item-id-8u5h2m.png", - "strength": 20 -} ----- - -For more information about the metadata JSON Schema, check out the https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md#erc-1155-metadata-uri-json-schema[ERC-1155 Metadata URI JSON Schema]. - -NOTE: You'll notice that the item's information is included in the metadata, but that information isn't on-chain! So a game developer could change the underlying metadata, changing the rules of the game! - -TIP: If you'd like to put all item information on-chain, you can extend ERC721 to do so (though it will be rather costly) by providing a xref:utilities.adoc#base64[`Base64`] Data URI with the JSON schema encoded. You could also leverage IPFS to store the URI information, but these techniques are out of the scope of this overview guide - -[[sending-to-contracts]] -== Sending Tokens to Contracts - -A key difference when using xref:api:token/ERC1155.adoc#IERC1155-safeTransferFrom-address-address-uint256-uint256-bytes-[`safeTransferFrom`] is that token transfers to other contracts may revert with the following message: - -[source,text] ----- -ERC1155: transfer to non ERC1155Receiver implementer ----- - -This is a good thing! It means that the recipient contract has not registered itself as aware of the ERC1155 protocol, so transfers to it are disabled to *prevent tokens from being locked forever*. As an example, https://etherscan.io/token/0xa74476443119A942dE498590Fe1f2454d7D4aC0d?a=0xa74476443119A942dE498590Fe1f2454d7D4aC0d[the Golem contract currently holds over 350k `GNT` tokens], worth multiple tens of thousands of dollars, and lacks methods to get them out of there. This has happened to virtually every ERC20-backed project, usually due to user error. - -In order for our contract to receive ERC1155 tokens we can inherit from the convenience contract xref:api:token/ERC1155.adoc#ERC1155Holder[`ERC1155Holder`] which handles the registering for us. Though we need to remember to implement functionality to allow tokens to be transferred out of our contract: - -[source,solidity] ----- -// contracts/MyContract.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; - -contract MyContract is ERC1155Holder { -} ----- - -We can also implement more complex scenarios using the xref:api:token/ERC1155.adoc#IERC1155Receiver-onERC1155Received-address-address-uint256-uint256-bytes-[`onERC1155Received`] and xref:api:token/ERC1155.adoc#IERC1155Receiver-onERC1155BatchReceived-address-address-uint256---uint256---bytes-[`onERC1155BatchReceived`] functions. - -[[Presets]] -== Preset ERC1155 contract -A preset ERC1155 is available, xref:api:presets#ERC1155PresetMinterPauser[`ERC1155PresetMinterPauser`]. It is preset to allow for token minting (create) - including batch minting, stop all token transfers (pause) and allow holders to burn (destroy) their tokens. The contract uses xref:access-control.adoc[Access Control] to control access to the minting and pausing functionality. The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role. - -This contract is ready to deploy without having to write any Solidity code. It can be used as-is for quick prototyping and testing, but is also suitable for production environments. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc20-supply.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc20-supply.adoc deleted file mode 100644 index 60052fd1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc20-supply.adoc +++ /dev/null @@ -1,113 +0,0 @@ -= Creating ERC20 Supply - -In this guide you will learn how to create an ERC20 token with a custom supply mechanism. We will showcase two idiomatic ways to use OpenZeppelin Contracts for this purpose that you will be able to apply to your smart contract development practice. - -The standard interface implemented by tokens built on Ethereum is called ERC20, and Contracts includes a widely used implementation of it: the aptly named xref:api:token/ERC20.adoc[`ERC20`] contract. This contract, like the standard itself, is quite simple and bare-bones. In fact, if you try to deploy an instance of `ERC20` as-is it will be quite literally useless... it will have no supply! What use is a token with no supply? - -The way that supply is created is not defined in the ERC20 document. Every token is free to experiment with its own mechanisms, ranging from the most decentralized to the most centralized, from the most naive to the most researched, and more. - -[[fixed-supply]] -== Fixed Supply - -Let's say we want a token with a fixed supply of 1000, initially allocated to the account that deploys the contract. If you've used Contracts v1, you may have written code like the following: - -[source,solidity] ----- -contract ERC20FixedSupply is ERC20 { - constructor() { - totalSupply += 1000; - balances[msg.sender] += 1000; - } -} ----- - -Starting with Contracts v2 this pattern is not only discouraged, but disallowed. The variables `totalSupply` and `balances` are now private implementation details of `ERC20`, and you can't directly write to them. Instead, there is an internal xref:api:token/ERC20.adoc#ERC20-_mint-address-uint256-[`_mint`] function that will do exactly this: - -[source,solidity] ----- -contract ERC20FixedSupply is ERC20 { - constructor() ERC20("Fixed", "FIX") { - _mint(msg.sender, 1000); - } -} ----- - -Encapsulating state like this makes it safer to extend contracts. For instance, in the first example we had to manually keep the `totalSupply` in sync with the modified balances, which is easy to forget. In fact, we omitted something else that is also easily forgotten: the `Transfer` event that is required by the standard, and which is relied on by some clients. The second example does not have this bug, because the internal `_mint` function takes care of it. - -[[rewarding-miners]] -== Rewarding Miners - -The internal xref:api:token/ERC20.adoc#ERC20-_mint-address-uint256-[`_mint`] function is the key building block that allows us to write ERC20 extensions that implement a supply mechanism. - -The mechanism we will implement is a token reward for the miners that produce Ethereum blocks. In Solidity we can access the address of the current block's miner in the global variable `block.coinbase`. We will mint a token reward to this address whenever someone calls the function `mintMinerReward()` on our token. The mechanism may sound silly, but you never know what kind of dynamic this might result in, and it's worth analyzing and experimenting with! - -[source,solidity] ----- -contract ERC20WithMinerReward is ERC20 { - constructor() ERC20("Reward", "RWD") {} - - function mintMinerReward() public { - _mint(block.coinbase, 1000); - } -} ----- - -As we can see, `_mint` makes it super easy to do this correctly. - -[[modularizing-the-mechanism]] -== Modularizing the Mechanism - -There is one supply mechanism already included in Contracts: `ERC20PresetMinterPauser`. This is a generic mechanism in which a set of accounts is assigned the `minter` role, granting them the permission to call a `mint` function, an external version of `_mint`. - -This can be used for centralized minting, where an externally owned account (i.e. someone with a pair of cryptographic keys) decides how much supply to create and for whom. There are very legitimate use cases for this mechanism, such as https://medium.com/reserve-currency/why-another-stablecoin-866f774afede#3aea[traditional asset-backed stablecoins]. - -The accounts with the minter role don't need to be externally owned, though, and can just as well be smart contracts that implement a trustless mechanism. We can in fact implement the same behavior as the previous section. - -[source,solidity] ----- -contract MinerRewardMinter { - ERC20PresetMinterPauser _token; - - constructor(ERC20PresetMinterPauser token) { - _token = token; - } - - function mintMinerReward() public { - _token.mint(block.coinbase, 1000); - } -} ----- - -This contract, when initialized with an `ERC20PresetMinterPauser` instance, and granted the `minter` role for that contract, will result in exactly the same behavior implemented in the previous section. What is interesting about using `ERC20PresetMinterPauser` is that we can easily combine multiple supply mechanisms by assigning the role to multiple contracts, and moreover that we can do this dynamically. - -TIP: To learn more about roles and permissioned systems, head to our xref:access-control.adoc[Access Control guide]. - -[[automating-the-reward]] -== Automating the Reward - -So far our supply mechanisms were triggered manually, but `ERC20` also allows us to extend the core functionality of the token through the xref:api:token/ERC20.adoc#ERC20-_beforeTokenTransfer-address-address-uint256-[`_beforeTokenTransfer`] hook (see xref:extending-contracts.adoc#using-hooks[Using Hooks]). - -Adding to the supply mechanism from previous sections, we can use this hook to mint a miner reward for every token transfer that is included in the blockchain. - -[source,solidity] ----- -contract ERC20WithAutoMinerReward is ERC20 { - constructor() ERC20("Reward", "RWD") {} - - function _mintMinerReward() internal { - _mint(block.coinbase, 1000); - } - - function _beforeTokenTransfer(address from, address to, uint256 value) internal virtual override { - if (!(from == address(0) && to == block.coinbase)) { - _mintMinerReward(); - } - super._beforeTokenTransfer(from, to, value); - } -} ----- - -[[wrapping-up]] -== Wrapping Up - -We've seen two ways to implement ERC20 supply mechanisms: internally through `_mint`, and externally through `ERC20PresetMinterPauser`. Hopefully this has helped you understand how to use OpenZeppelin Contracts and some of the design principles behind it, and you can apply them to your own smart contracts. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc20.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc20.adoc deleted file mode 100644 index 11b650a1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc20.adoc +++ /dev/null @@ -1,83 +0,0 @@ -= ERC20 - -An ERC20 token contract keeps track of xref:tokens.adoc#different-kinds-of-tokens[_fungible_ tokens]: any one token is exactly equal to any other token; no tokens have special rights or behavior associated with them. This makes ERC20 tokens useful for things like a *medium of exchange currency*, *voting rights*, *staking*, and more. - -OpenZeppelin Contracts provides many ERC20-related contracts. On the xref:api:token/ERC20.adoc[`API reference`] you'll find detailed information on their properties and usage. - -[[constructing-an-erc20-token-contract]] -== Constructing an ERC20 Token Contract - -Using Contracts, we can easily create our own ERC20 token contract, which will be used to track _Gold_ (GLD), an internal currency in a hypothetical game. - -Here's what our GLD token might look like. - -[source,solidity] ----- -// contracts/GLDToken.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract GLDToken is ERC20 { - constructor(uint256 initialSupply) ERC20("Gold", "GLD") { - _mint(msg.sender, initialSupply); - } -} ----- - -Our contracts are often used via https://solidity.readthedocs.io/en/latest/contracts.html#inheritance[inheritance], and here we're reusing xref:api:token/ERC20.adoc#erc20[`ERC20`] for both the basic standard implementation and the xref:api:token/ERC20.adoc#ERC20-name--[`name`], xref:api:token/ERC20.adoc#ERC20-symbol--[`symbol`], and xref:api:token/ERC20.adoc#ERC20-decimals--[`decimals`] optional extensions. Additionally, we're creating an `initialSupply` of tokens, which will be assigned to the address that deploys the contract. - -TIP: For a more complete discussion of ERC20 supply mechanisms, see xref:erc20-supply.adoc[Creating ERC20 Supply]. - -That's it! Once deployed, we will be able to query the deployer's balance: - -[source,javascript] ----- -> GLDToken.balanceOf(deployerAddress) -1000000000000000000000 ----- - -We can also xref:api:token/ERC20.adoc#IERC20-transfer-address-uint256-[transfer] these tokens to other accounts: - -[source,javascript] ----- -> GLDToken.transfer(otherAddress, 300000000000000000000) -> GLDToken.balanceOf(otherAddress) -300000000000000000000 -> GLDToken.balanceOf(deployerAddress) -700000000000000000000 ----- - -[[a-note-on-decimals]] -== A Note on `decimals` - -Often, you'll want to be able to divide your tokens into arbitrary amounts: say, if you own `5 GLD`, you may want to send `1.5 GLD` to a friend, and keep `3.5 GLD` to yourself. Unfortunately, Solidity and the EVM do not support this behavior: only integer (whole) numbers can be used, which poses an issue. You may send `1` or `2` tokens, but not `1.5`. - -To work around this, xref:api:token/ERC20.adoc#ERC20[`ERC20`] provides a xref:api:token/ERC20.adoc#ERC20-decimals--[`decimals`] field, which is used to specify how many decimal places a token has. To be able to transfer `1.5 GLD`, `decimals` must be at least `1`, since that number has a single decimal place. - -How can this be achieved? It's actually very simple: a token contract can use larger integer values, so that a balance of `50` will represent `5 GLD`, a transfer of `15` will correspond to `1.5 GLD` being sent, and so on. - -It is important to understand that `decimals` is _only used for display purposes_. All arithmetic inside the contract is still performed on integers, and it is the different user interfaces (wallets, exchanges, etc.) that must adjust the displayed values according to `decimals`. The total token supply and balance of each account are not specified in `GLD`: you need to divide by `10^decimals` to get the actual `GLD` amount. - -You'll probably want to use a `decimals` value of `18`, just like Ether and most ERC20 token contracts in use, unless you have a very special reason not to. When minting tokens or transferring them around, you will be actually sending the number `num GLD * 10^decimals`. - -NOTE: By default, `ERC20` uses a value of `18` for `decimals`. To use a different value, you will need to override the `decimals()` function in your contract. - -```solidity -function decimals() public view virtual override returns (uint8) { - return 16; -} -``` - -So if you want to send `5` tokens using a token contract with 18 decimals, the method to call will actually be: - -```solidity -transfer(recipient, 5 * 10^18); -``` - -[[Presets]] -== Preset ERC20 contract -A preset ERC20 is available, xref:api:presets#ERC20PresetMinterPauser[`ERC20PresetMinterPauser`]. It is preset to allow for token minting (create), stop all token transfers (pause) and allow holders to burn (destroy) their tokens. The contract uses xref:access-control.adoc[Access Control] to control access to the minting and pausing functionality. The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role. - -This contract is ready to deploy without having to write any Solidity code. It can be used as-is for quick prototyping and testing, but is also suitable for production environments. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc721.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc721.adoc deleted file mode 100644 index 25dde116..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc721.adoc +++ /dev/null @@ -1,90 +0,0 @@ -= ERC721 - -We've discussed how you can make a _fungible_ token using xref:erc20.adoc[ERC20], but what if not all tokens are alike? This comes up in situations like *real estate*, *voting rights*, or *collectibles*, where some items are valued more than others, due to their usefulness, rarity, etc. ERC721 is a standard for representing ownership of xref:tokens.adoc#different-kinds-of-tokens[_non-fungible_ tokens], that is, where each token is unique. - -ERC721 is a more complex standard than ERC20, with multiple optional extensions, and is split across a number of contracts. The OpenZeppelin Contracts provide flexibility regarding how these are combined, along with custom useful extensions. Check out the xref:api:token/ERC721.adoc[API Reference] to learn more about these. - -== Constructing an ERC721 Token Contract - -We'll use ERC721 to track items in our game, which will each have their own unique attributes. Whenever one is to be awarded to a player, it will be minted and sent to them. Players are free to keep their token or trade it with other people as they see fit, as they would any other asset on the blockchain! Please note any account can call `awardItem` to mint items. To restrict what accounts can mint items we can add xref:access-control.adoc[Access Control]. - -Here's what a contract for tokenized items might look like: - -[source,solidity] ----- -// contracts/GameItem.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; -import "@openzeppelin/contracts/utils/Counters.sol"; - -contract GameItem is ERC721URIStorage { - using Counters for Counters.Counter; - Counters.Counter private _tokenIds; - - constructor() ERC721("GameItem", "ITM") {} - - function awardItem(address player, string memory tokenURI) - public - returns (uint256) - { - _tokenIds.increment(); - - uint256 newItemId = _tokenIds.current(); - _mint(player, newItemId); - _setTokenURI(newItemId, tokenURI); - - return newItemId; - } -} ----- - -The xref:api:token/ERC721.adoc#ERC721URIStorage[`ERC721URIStorage`] contract is an implementation of ERC721 that includes the metadata standard extensions (xref:api:token/ERC721.adoc#IERC721Metadata[`IERC721Metadata`]) as well as a mechanism for per-token metadata. That's where the xref:api:token/ERC721.adoc#ERC721-_setTokenURI-uint256-string-[`_setTokenURI`] method comes from: we use it to store an item's metadata. - -Also note that, unlike ERC20, ERC721 lacks a `decimals` field, since each token is distinct and cannot be partitioned. - -New items can be created: - -[source,javascript] ----- -> gameItem.awardItem(playerAddress, "https://game.example/item-id-8u5h2m.json") -Transaction successful. Transaction hash: 0x... -Events emitted: - - Transfer(0x0000000000000000000000000000000000000000, playerAddress, 7) ----- - -And the owner and metadata of each item queried: - -[source,javascript] ----- -> gameItem.ownerOf(7) -playerAddress -> gameItem.tokenURI(7) -"https://game.example/item-id-8u5h2m.json" ----- - -This `tokenURI` should resolve to a JSON document that might look something like: - -[source,json] ----- -{ - "name": "Thor's hammer", - "description": "Mjölnir, the legendary hammer of the Norse god of thunder.", - "image": "https://game.example/item-id-8u5h2m.png", - "strength": 20 -} ----- - -For more information about the `tokenURI` metadata JSON Schema, check out the https://eips.ethereum.org/EIPS/eip-721[ERC721 specification]. - -NOTE: You'll notice that the item's information is included in the metadata, but that information isn't on-chain! So a game developer could change the underlying metadata, changing the rules of the game! - -TIP: If you'd like to put all item information on-chain, you can extend ERC721 to do so (though it will be rather costly) by providing a xref:utilities.adoc#base64[`Base64`] Data URI with the JSON schema encoded. You could also leverage IPFS to store the tokenURI information, but these techniques are out of the scope of this overview guide. - -[[Presets]] -== Preset ERC721 contract -A preset ERC721 is available, xref:api:presets#ERC721PresetMinterPauserAutoId[`ERC721PresetMinterPauserAutoId`]. It is preset to allow for token minting (create) with token ID and URI auto generation, stop all token transfers (pause) and allow holders to burn (destroy) their tokens. The contract uses xref:access-control.adoc[Access Control] to control access to the minting and pausing functionality. The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role. - -This contract is ready to deploy without having to write any Solidity code. It can be used as-is for quick prototyping and testing, but is also suitable for production environments. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc777.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc777.adoc deleted file mode 100644 index d79fbee2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/erc777.adoc +++ /dev/null @@ -1,73 +0,0 @@ -= ERC777 - -Like xref:erc20.adoc[ERC20], ERC777 is a standard for xref:tokens.adoc#different-kinds-of-tokens[_fungible_ tokens], and is focused around allowing more complex interactions when trading tokens. More generally, it brings tokens and Ether closer together by providing the equivalent of a `msg.value` field, but for tokens. - -The standard also brings multiple quality-of-life improvements, such as getting rid of the confusion around `decimals`, minting and burning with proper events, among others, but its killer feature is *receive hooks*. A hook is simply a function in a contract that is called when tokens are sent to it, meaning *accounts and contracts can react to receiving tokens*. - -This enables a lot of interesting use cases, including atomic purchases using tokens (no need to do `approve` and `transferFrom` in two separate transactions), rejecting reception of tokens (by reverting on the hook call), redirecting the received tokens to other addresses (similarly to how xref:api:payment#PaymentSplitter[`PaymentSplitter`] does it), among many others. - -Furthermore, since contracts are required to implement these hooks in order to receive tokens, _no tokens can get stuck in a contract that is unaware of the ERC777 protocol_, as has happened countless times when using ERC20s. - -== What If I Already Use ERC20? - -The standard has you covered! The ERC777 standard is *backwards compatible with ERC20*, meaning you can interact with these tokens as if they were ERC20, using the standard functions, while still getting all of the niceties, including send hooks. See the https://eips.ethereum.org/EIPS/eip-777#backward-compatibility[EIP's Backwards Compatibility section] to learn more. - -== Constructing an ERC777 Token Contract - -We will replicate the `GLD` example of the xref:erc20.adoc#constructing-an-erc20-token-contract[ERC20 guide], this time using ERC777. As always, check out the xref:api:token/ERC777.adoc[`API reference`] to learn more about the details of each function. - -[source,solidity] ----- -// contracts/GLDToken.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC777/ERC777.sol"; - -contract GLDToken is ERC777 { - constructor(uint256 initialSupply, address[] memory defaultOperators) - ERC777("Gold", "GLD", defaultOperators) - { - _mint(msg.sender, initialSupply, "", ""); - } -} ----- - -In this case, we'll be extending from the xref:api:token/ERC777.adoc#ERC777[`ERC777`] contract, which provides an implementation with compatibility support for ERC20. The API is quite similar to that of xref:api:token/ERC777.adoc#ERC777[`ERC777`], and we'll once again make use of xref:api:token/ERC777.adoc#ERC777-_mint-address-address-uint256-bytes-bytes-[`_mint`] to assign the `initialSupply` to the deployer account. Unlike xref:api:token/ERC20.adoc#ERC20-_mint-address-uint256-[ERC20's `_mint`], this one includes some extra parameters, but you can safely ignore those for now. - -You'll notice both xref:api:token/ERC777.adoc#IERC777-name--[`name`] and xref:api:token/ERC777.adoc#IERC777-symbol--[`symbol`] are assigned, but not xref:api:token/ERC777.adoc#ERC777-decimals--[`decimals`]. The ERC777 specification makes it mandatory to include support for these functions (unlike ERC20, where it is optional and we had to include xref:api:token/ERC20.adoc#ERC20Detailed[`ERC20Detailed`]), but also mandates that `decimals` always returns a fixed value of `18`, so there's no need to set it ourselves. For a review of ``decimals``'s role and importance, refer back to our xref:erc20.adoc#a-note-on-decimals[ERC20 guide]. - -Finally, we'll need to set the xref:api:token/ERC777.adoc#IERC777-defaultOperators--[`defaultOperators`]: special accounts (usually other smart contracts) that will be able to transfer tokens on behalf of their holders. If you're not planning on using operators in your token, you can simply pass an empty array. _Stay tuned for an upcoming in-depth guide on ERC777 operators!_ - -That's it for a basic token contract! We can now deploy it, and use the same xref:api:token/ERC777.adoc#IERC777-balanceOf-address-[`balanceOf`] method to query the deployer's balance: - -[source,javascript] ----- -> GLDToken.balanceOf(deployerAddress) -1000 ----- - -To move tokens from one account to another, we can use both xref:api:token/ERC777.adoc#ERC777-transfer-address-uint256-[``ERC20``'s `transfer`] method, or the new xref:api:token/ERC777.adoc#ERC777-send-address-uint256-bytes-[``ERC777``'s `send`], which fulfills a very similar role, but adds an optional `data` field: - -[source,javascript] ----- -> GLDToken.transfer(otherAddress, 300) -> GLDToken.send(otherAddress, 300, "") -> GLDToken.balanceOf(otherAddress) -600 -> GLDToken.balanceOf(deployerAddress) -400 ----- - -== Sending Tokens to Contracts - -A key difference when using xref:api:token/ERC777.adoc#ERC777-send-address-uint256-bytes-[`send`] is that token transfers to other contracts may revert with the following message: - -[source,text] ----- -ERC777: token recipient contract has no implementer for ERC777TokensRecipient ----- - -This is a good thing! It means that the recipient contract has not registered itself as aware of the ERC777 protocol, so transfers to it are disabled to *prevent tokens from being locked forever*. As an example, https://etherscan.io/token/0xa74476443119A942dE498590Fe1f2454d7D4aC0d?a=0xa74476443119A942dE498590Fe1f2454d7D4aC0d[the Golem contract currently holds over 350k `GNT` tokens], worth multiple tens of thousands of dollars, and lacks methods to get them out of there. This has happened to virtually every ERC20-backed project, usually due to user error. - -_An upcoming guide will cover how a contract can register itself as a recipient, send and receive hooks, and other advanced features of ERC777!_ diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/extending-contracts.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/extending-contracts.adoc deleted file mode 100644 index 7d25ae9e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/extending-contracts.adoc +++ /dev/null @@ -1,131 +0,0 @@ -= Extending Contracts - -Most of the OpenZeppelin Contracts are expected to be used via https://solidity.readthedocs.io/en/latest/contracts.html#inheritance[inheritance]: you will _inherit_ from them when writing your own contracts. - -This is the commonly found `is` syntax, like in `contract MyToken is ERC20`. - -[NOTE] -==== -Unlike ``contract``s, Solidity ``library``s are not inherited from and instead rely on the https://solidity.readthedocs.io/en/latest/contracts.html#using-for[`using for`] syntax. - -OpenZeppelin Contracts has some ``library``s: most are in the xref:api:utils.adoc[Utils] directory. -==== - -== Overriding - -Inheritance is often used to add the parent contract's functionality to your own contract, but that's not all it can do. You can also _change_ how some parts of the parent behave using _overrides_. - -For example, imagine you want to change xref:api:access.adoc#AccessControl[`AccessControl`] so that xref:api:access.adoc#AccessControl-revokeRole-bytes32-address-[`revokeRole`] can no longer be called. This can be achieved using overrides: - -```solidity -// contracts/ModifiedAccessControl.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/access/AccessControl.sol"; - -contract ModifiedAccessControl is AccessControl { - // Override the revokeRole function - function revokeRole(bytes32, address) public override { - revert("ModifiedAccessControl: cannot revoke roles"); - } -} -``` - -The old `revokeRole` is then replaced by our override, and any calls to it will immediately revert. We cannot _remove_ the function from the contract, but reverting on all calls is good enough. - -=== Calling `super` - -Sometimes you want to _extend_ a parent's behavior, instead of outright changing it to something else. This is where `super` comes in. - -The `super` keyword will let you call functions defined in a parent contract, even if they are overridden. This mechanism can be used to add additional checks to a function, emit events, or otherwise add functionality as you see fit. - -TIP: For more information on how overrides work, head over to the https://solidity.readthedocs.io/en/latest/contracts.html#index-17[official Solidity documentation]. - -Here is a modified version of xref:api:access.adoc#AccessControl[`AccessControl`] where xref:api:access.adoc#AccessControl-revokeRole-bytes32-address-[`revokeRole`] cannot be used to revoke the `DEFAULT_ADMIN_ROLE`: - - -```solidity -// contracts/ModifiedAccessControl.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/access/AccessControl.sol"; - -contract ModifiedAccessControl is AccessControl { - function revokeRole(bytes32 role, address account) public override { - require( - role != DEFAULT_ADMIN_ROLE, - "ModifiedAccessControl: cannot revoke default admin role" - ); - - super.revokeRole(role, account); - } -} -``` - -The `super.revokeRole` statement at the end will invoke ``AccessControl``'s original version of `revokeRole`, the same code that would've run if there were no overrides in place. - -NOTE: As of v3.0.0, `view` functions are not `virtual` in OpenZeppelin, and therefore cannot be overridden. We're considering https://github.com/OpenZeppelin/openzeppelin-contracts/issues/2154[lifting this restriction] in an upcoming release. Let us know if this is something you care about! - -[[using-hooks]] -== Using Hooks - -Sometimes, in order to extend a parent contract you will need to override multiple related functions, which leads to code duplication and increased likelihood of bugs. - -For example, consider implementing safe xref:api:token/ERC20.adoc#ERC20[`ERC20`] transfers in the style of xref:api:token/ERC721.adoc#IERC721Receiver[`IERC721Receiver`]. You may think overriding xref:api:token/ERC20.adoc#ERC20-transfer-address-uint256-[`transfer`] and xref:api:token/ERC20.adoc#ERC20-transferFrom-address-address-uint256-[`transferFrom`] would be enough, but what about xref:api:token/ERC20.adoc#ERC20-_transfer-address-address-uint256-[`_transfer`] and xref:api:token/ERC20.adoc#ERC20-_mint-address-uint256-[`_mint`]? To prevent you from having to deal with these details, we introduced **hooks**. - -Hooks are simply functions that are called before or after some action takes place. They provide a centralized point to _hook into_ and extend the original behavior. - -Here's how you would implement the `IERC721Receiver` pattern in `ERC20`, using the xref:api:token/ERC20.adoc#ERC20-_beforeTokenTransfer-address-address-uint256-[`_beforeTokenTransfer`] hook: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract ERC20WithSafeTransfer is ERC20 { - function _beforeTokenTransfer(address from, address to, uint256 amount) - internal virtual override - { - super._beforeTokenTransfer(from, to, amount); - - require(_validRecipient(to), "ERC20WithSafeTransfer: invalid recipient"); - } - - function _validRecipient(address to) private view returns (bool) { - ... - } - - ... -} -``` - -Using hooks this way leads to cleaner and safer code, without having to rely on a deep understanding of the parent's internals. - -[NOTE] -==== -Hooks are a new feature of OpenZeppelin Contracts v3.0.0, and we're eager to learn how you plan to use them! - -So far, the only available hook is `_beforeTransferHook`, in all of xref:api:token/ERC20.adoc#ERC20-_beforeTokenTransfer-address-address-uint256-[`ERC20`], xref:api:token/ERC721.adoc#ERC721-_beforeTokenTransfer-address-address-uint256-[`ERC721`], xref:api:token/ERC777.adoc#ERC777-_beforeTokenTransfer-address-address-address-uint256-[`ERC777`] and xref:api:token/ERC1155.adoc#ERC1155-_beforeTokenTransfer-address-address-address-uint256---uint256---bytes-[`ERC1155`]. If you have ideas for new hooks, let us know! -==== - -=== Rules of Hooks - -There's a few guidelines you should follow when writing code that uses hooks in order to prevent issues. They are very simple, but do make sure you follow them: - -1. Whenever you override a parent's hook, re-apply the `virtual` attribute to the hook. That will allow child contracts to add more functionality to the hook. -2. **Always** call the parent's hook in your override using `super`. This will make sure all hooks in the inheritance tree are called: contracts like xref:api:token/ERC20.adoc#ERC20Pausable[`ERC20Pausable`] rely on this behavior. - -```solidity -contract MyToken is ERC20 { - function _beforeTokenTransfer(address from, address to, uint256 amount) - internal virtual override // Add virtual here! - { - super._beforeTokenTransfer(from, to, amount); // Call parent hook - ... - } -} -``` -That's it! Enjoy simpler code using hooks! - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/governance.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/governance.adoc deleted file mode 100644 index b87f9169..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/governance.adoc +++ /dev/null @@ -1,339 +0,0 @@ -= How to set up on-chain governance - -In this guide we will learn how OpenZeppelin’s Governor contract works, how to set it up, and how to use it to create proposals, vote for them, and execute them, using tools provided by Ethers.js and Tally. - -NOTE: Find detailed contract documentation at xref:api:governance.adoc[Governance API]. - -== Introduction - -Decentralized protocols are in constant evolution from the moment they are publicly released. Often, the initial team retains control of this evolution in the first stages, but eventually delegates it to a community of stakeholders. The process by which this community makes decisions is called on-chain governance, and it has become a central component of decentralized protocols, fueling varied decisions such as parameter tweaking, smart contract upgrades, integrations with other protocols, treasury management, grants, etc. - -This governance protocol is generally implemented in a special-purpose contract called “Governor”. The GovernorAlpha and GovernorBravo contracts designed by Compound have been very successful and popular so far, with the downside that projects with different requirements have had to fork the code to customize it for their needs, which can pose a high risk of introducing security issues. For OpenZeppelin Contracts, we set out to build a modular system of Governor contracts so that forking is not needed, and different requirements can be accommodated by writing small modules using Solidity inheritance. You will find the most common requirements out of the box in OpenZeppelin Contracts, but writing additional ones is simple, and we will be adding new features as requested by the community in future releases. Additionally, the design of OpenZeppelin Governor requires minimal use of storage and results in more gas efficient operation. - -== Compatibility - -OpenZeppelin’s Governor system was designed with a concern for compatibility with existing systems that were based on Compound’s GovernorAlpha and GovernorBravo. Because of this, you will find that many modules are presented in two variants, one of which is built for compatibility with those systems. - -=== ERC20Votes & ERC20VotesComp - -The ERC20 extension to keep track of votes and vote delegation is one such case. The shorter one is the more generic version because it can support token supplies greater than 2^96, while the “Comp” variant is limited in that regard, but exactly fits the interface of the COMP token that is used by GovernorAlpha and Bravo. Both contract variants share the same events, so they are fully compatible when looking at events only. - -=== Governor & GovernorCompatibilityBravo - -An OpenZeppelin Governor contract is by default not interface-compatible with GovernorAlpha or Bravo, since some of the functions are different or missing, although it shares all of the same events. However, it’s possible to opt in to full compatibility by inheriting from the GovernorCompatibilityBravo module. The contract will be cheaper to deploy and use without this module. - -=== GovernorTimelockControl & GovernorTimelockCompound - -When using a timelock with your Governor contract, you can use either OpenZeppelin’s TimelockController or Compound’s Timelock. Based on the choice of timelock, you should choose the corresponding Governor module: GovernorTimelockControl or GovernorTimelockCompound respectively. This allows you to migrate an existing GovernorAlpha instance to an OpenZeppelin-based Governor without changing the timelock in use. - -=== Tally - -https://www.withtally.com[Tally] is a full-fledged application for user owned on-chain governance. It comprises a voting dashboard, proposal creation wizard, real time research and analysis, and educational content. - -For all of these options, the Governor will be compatible with Tally: users will be able to create proposals, visualize voting power and advocates, navigate proposals, and cast votes. For proposal creation in particular, projects can also use Defender Admin as an alternative interface. - -In the rest of this guide, we will focus on a fresh deploy of the vanilla OpenZeppelin Governor features without concern for compatibility with GovernorAlpha or Bravo. - -== Setup - -=== Token - -The voting power of each account in our governance setup will be determined by an ERC20 token. The token has to implement the ERC20Votes extension. This extension will keep track of historical balances so that voting power is retrieved from past snapshots rather than current balance, which is an important protection that prevents double voting. - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.2; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; -import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; - -contract MyToken is ERC20, ERC20Permit, ERC20Votes { - constructor() ERC20("MyToken", "MTK") ERC20Permit("MyToken") {} - - // The functions below are overrides required by Solidity. - - function _afterTokenTransfer(address from, address to, uint256 amount) - internal - override(ERC20, ERC20Votes) - { - super._afterTokenTransfer(from, to, amount); - } - - function _mint(address to, uint256 amount) - internal - override(ERC20, ERC20Votes) - { - super._mint(to, amount); - } - - function _burn(address account, uint256 amount) - internal - override(ERC20, ERC20Votes) - { - super._burn(account, amount); - } -} -``` - -If your project already has a live token that does not include ERC20Votes and is not upgradeable, you can wrap it in a governance token by using ERC20Wrapper. This will allow token holders to participate in governance by wrapping their tokens 1-to-1. - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.2; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; -import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; -import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Wrapper.sol"; - -contract MyToken is ERC20, ERC20Permit, ERC20Votes, ERC20Wrapper { - constructor(IERC20 wrappedToken) - ERC20("MyToken", "MTK") - ERC20Permit("MyToken") - ERC20Wrapper(wrappedToken) - {} - - // The functions below are overrides required by Solidity. - - function _afterTokenTransfer(address from, address to, uint256 amount) - internal - override(ERC20, ERC20Votes) - { - super._afterTokenTransfer(from, to, amount); - } - - function _mint(address to, uint256 amount) - internal - override(ERC20, ERC20Votes) - { - super._mint(to, amount); - } - - function _burn(address account, uint256 amount) - internal - override(ERC20, ERC20Votes) - { - super._burn(account, amount); - } -} -``` - -NOTE: Voting power could be determined in different ways: multiple ERC20 tokens, ERC721 tokens, sybil resistant identities, etc. All of these options are potentially supported by writing a custom Votes module for your Governor. The only other source of voting power available in OpenZeppelin Contracts currently is xref:api:token/ERC721.adoc#ERC721Votes[`ERC721Votes`]. - -=== Governor - -Initially, we will build a Governor without a timelock. The core logic is given by the Governor contract, but we still need to choose: 1) how voting power is determined, 2) how many votes are needed for quorum, 3) what options people have when casting a vote and how those votes are counted, and 4) what type of token should be used to vote. Each of these aspects is customizable by writing your own module, or more easily choosing one from OpenZeppelin Contracts. - -For 1) we will use the GovernorVotes module, which hooks to an IVotes instance to determine the voting power of an account based on the token balance they hold when a proposal becomes active. This module requires as a constructor parameter the address of the token. - -For 2) we will use GovernorVotesQuorumFraction which works together with ERC20Votes to define quorum as a percentage of the total supply at the block a proposal’s voting power is retrieved. This requires a constructor parameter to set the percentage. Most Governors nowadays use 4%, so we will initialize the module with parameter 4 (this indicates the percentage, resulting in 4%). - -For 3) we will use GovernorCountingSimple, a module that offers 3 options to voters: For, Against, and Abstain, and where only For and Abstain votes are counted towards quorum. - -Besides these modules, Governor itself has some parameters we must set. - -votingDelay: How long after a proposal is created should voting power be fixed. A large voting delay gives users time to unstake tokens if necessary. - -votingPeriod: How long does a proposal remain open to votes. - -These parameters are specified in number of blocks. Assuming block time of around 13.14 seconds, we will set votingDelay = 1 day = 6570 blocks, and votingPeriod = 1 week = 45992 blocks. - -We can optionally set a proposal threshold as well. This restricts proposal creation to accounts who have enough voting power. - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.2; - -import "./governance/Governor.sol"; -import "./governance/compatibility/GovernorCompatibilityBravo.sol"; -import "./governance/extensions/GovernorVotes.sol"; -import "./governance/extensions/GovernorVotesQuorumFraction.sol"; -import "./governance/extensions/GovernorTimelockControl.sol"; - -contract MyGovernor is Governor, GovernorCompatibilityBravo, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl { - constructor(IVotes _token, TimelockController _timelock) - Governor("MyGovernor") - GovernorVotes(_token) - GovernorVotesQuorumFraction(4) - GovernorTimelockControl(_timelock) - {} - - function votingDelay() public pure override returns (uint256) { - return 6575; // 1 day - } - - function votingPeriod() public pure override returns (uint256) { - return 46027; // 1 week - } - - function proposalThreshold() public pure override returns (uint256) { - return 0; - } - - // The functions below are overrides required by Solidity. - - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function getVotes(address account, uint256 blockNumber) - public - view - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - - function state(uint256 proposalId) - public - view - override(Governor, IGovernor, GovernorTimelockControl) - returns (ProposalState) - { - return super.state(proposalId); - } - - function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description) - public - override(Governor, GovernorCompatibilityBravo, IGovernor) - returns (uint256) - { - return super.propose(targets, values, calldatas, description); - } - - function _execute(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) - internal - override(Governor, GovernorTimelockControl) - { - super._execute(proposalId, targets, values, calldatas, descriptionHash); - } - - function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) - internal - override(Governor, GovernorTimelockControl) - returns (uint256) - { - return super._cancel(targets, values, calldatas, descriptionHash); - } - - function _executor() - internal - view - override(Governor, GovernorTimelockControl) - returns (address) - { - return super._executor(); - } - - function supportsInterface(bytes4 interfaceId) - public - view - override(Governor, IERC165, GovernorTimelockControl) - returns (bool) - { - return super.supportsInterface(interfaceId); - } -} - -``` - -=== Timelock - -It is good practice to add a timelock to governance decisions. This allows users to exit the system if they disagree with a decision before it is executed. We will use OpenZeppelin’s TimelockController in combination with the GovernorTimelockControl module. - -IMPORTANT: When using a timelock, it is the timelock that will execute proposals and thus the timelock that should hold any funds, ownership, and access control roles. Before version 4.5 there was no way to recover funds in the Governor contract when using a timelock! Before version 4.3, when using the Compound Timelock, ETH in the timelock was not easily accessible. - -TimelockController uses an AccessControl setup that we need to understand in order to set up roles. - -- The Proposer role is in charge of queueing operations: this is the role the Governor instance should be granted, and it should likely be the only proposer in the system. -- The Executor role is in charge of executing already available operations: we can assign this role to the special zero address to allow anyone to execute (if operations can be particularly time sensitive, the Governor should be made Executor instead). -- Lastly, there is the Admin role, which can grant and revoke the two previous roles: this is a very sensitive role that will be granted automatically to both deployer and timelock itself, but should be renounced by the deployer after setup. - -== Proposal Lifecycle - -Let’s walk through how to create and execute a proposal on our newly deployed Governor. - -A proposal is a sequence of actions that the Governor contract will perform if it passes. Each action consists of a target address, calldata encoding a function call, and an amount of ETH to include. Additionally, a proposal includes a human-readable description. - -=== Create a Proposal - -Let’s say we want to create a proposal to give a team a grant, in the form of ERC20 tokens from the governance treasury. This proposal will consist of a single action where the target is the ERC20 token, calldata is the encoded function call `transfer(, )`, and with 0 ETH attached. - -Generally a proposal will be created with the help of an interface such as Tally or Defender. Here we will show how to create the proposal using Ethers.js. - -First we get all the parameters necessary for the proposal action. - -```javascript -const tokenAddress = ...; -const token = await ethers.getContractAt(‘ERC20’, tokenAddress); - -const teamAddress = ...; -const grantAmount = ...; -const transferCalldata = token.interface.encodeFunctionData(‘transfer’, [teamAddress, grantAmount]); -``` - -Now we are ready to call the propose function of the governor. Note that we don’t pass in one array of actions, but instead three arrays corresponding to the list of targets, the list of values, and the list of calldatas. In this case it’s a single action, so it’s simple: - -```javascript -await governor.propose( - [tokenAddress], - [0], - [transferCalldata], - “Proposal #1: Give grant to team”, -); -``` - -This will create a new proposal, with a proposal id that is obtained by hashing together the proposal data, and which will also be found in an event in the logs of the transaction. - -=== Cast a Vote - -Once a proposal is active, delegates can cast their vote. Note that it is delegates who carry voting power: if a token holder wants to participate, they can set a trusted representative as their delegate, or they can become a delegate themselves by self-delegating their voting power. - -Votes are cast by interacting with the Governor contract through the `castVote` family of functions. Voters would generally invoke this from a governance UI such as Tally. - -image::tally-vote.png[Voting in Tally] - -=== Execute the Proposal - -Once the voting period is over, if quorum was reached (enough voting power participated) and the majority voted in favor, the proposal is considered successful and can proceed to be executed. This can also be done in Tally in the "Administration Panel" section of a project. - -image::tally-admin.png[Administration Panel in Tally] - -We will see now how to do this manually using Ethers.js. - -If a timelock was set up, the first step to execution is queueing. You will notice that both the queue and execute functions require passing in the entire proposal parameters, as opposed to just the proposal id. This is necessary because this data is not stored on chain, as a measure to save gas. Note that these parameters can always be found in the events emitted by the contract. The only parameter that is not sent in its entirety is the description, since this is only needed in its hashed form to compute the proposal id. - -To queue, we call the queue function: - -```javascript -const descriptionHash = ethers.utils.id(“Proposal #1: Give grant to team”); - -await governor.queue( - [tokenAddress], - [0], - [transferCalldata], - descriptionHash, -); -``` - -This will cause the governor to interact with the timelock contract and queue the actions for execution after the required delay. - -After enough time has passed (according to the timelock parameters), the proposal can be executed. If there was no timelock to begin with, this step can be ran immediately after the proposal succeeds. - -```javascript -await governor.execute( - [tokenAddress], - [0], - [transferCalldata], - descriptionHash, -); -``` - -Executing the proposal will transfer the ERC20 tokens to the chosen recipient. To wrap up: we set up a system where a treasury is controlled by the collective decision of the token holders of a project, and all actions are executed via proposals enforced by on-chain votes. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/index.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/index.adoc deleted file mode 100644 index 5b64f050..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/index.adoc +++ /dev/null @@ -1,63 +0,0 @@ -= Contracts - -*A library for secure smart contract development.* Build on a solid foundation of community-vetted code. - - * Implementations of standards like xref:erc20.adoc[ERC20] and xref:erc721.adoc[ERC721]. - * Flexible xref:access-control.adoc[role-based permissioning] scheme. - * Reusable xref:utilities.adoc[Solidity components] to build custom contracts and complex decentralized systems. - -== Overview - -[[install]] -=== Installation - -```console -$ npm install @openzeppelin/contracts -``` - -OpenZeppelin Contracts features a xref:releases-stability.adoc#api-stability[stable API], which means your contracts won't break unexpectedly when upgrading to a newer minor version. - -[[usage]] -=== Usage - -Once installed, you can use the contracts in the library by importing them: - -[source,solidity] ----- -// contracts/MyNFT.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; - -contract MyNFT is ERC721 { - constructor() ERC721("MyNFT", "MNFT") { - } -} ----- - -TIP: If you're new to smart contract development, head to xref:learn::developing-smart-contracts.adoc[Developing Smart Contracts] to learn about creating a new project and compiling your contracts. - -To keep your system secure, you should **always** use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don't need to worry about it needlessly increasing gas costs. - -[[security]] -== Security - -Please report any security issues you find via our https://www.immunefi.com/bounty/openzeppelin[bug bounty program on Immunefi] or directly to security@openzeppelin.org. - -[[next-steps]] -== Learn More - -The guides in the sidebar will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides: - -* xref:access-control.adoc[Access Control]: decide who can perform each of the actions on your system. -* xref:tokens.adoc[Tokens]: create tradable assets or collectibles, like the well known xref:erc20.adoc[ERC20] and xref:erc721.adoc[ERC721] standards. -* xref:utilities.adoc[Utilities]: generic useful tools, including non-overflowing math, signature verification, and trustless paying systems. - -The xref:api:token/ERC20.adoc[full API] is also thoroughly documented, and serves as a great reference when developing your smart contract application. You can also ask for help or follow Contracts' development in the https://forum.openzeppelin.com[community forum]. - -Finally, you may want to take a look at the https://blog.openzeppelin.com/guides/[guides on our blog], which cover several common use cases and good practices. The following articles provide great background reading, though please note, some of the referenced tools have changed as the tooling in the ecosystem continues to rapidly evolve. - -* https://blog.openzeppelin.com/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05[The Hitchhiker’s Guide to Smart Contracts in Ethereum] will help you get an overview of the various tools available for smart contract development, and help you set up your environment. -* https://blog.openzeppelin.com/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094[A Gentle Introduction to Ethereum Programming, Part 1] provides very useful information on an introductory level, including many basic concepts from the Ethereum platform. -* For a more in-depth dive, you may read the guide https://blog.openzeppelin.com/designing-the-architecture-for-your-ethereum-application-9cec086f8317[Designing the architecture for your Ethereum application], which discusses how to better structure your application and its relationship to the real world. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/releases-stability.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/releases-stability.adoc deleted file mode 100644 index 65b127fc..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/releases-stability.adoc +++ /dev/null @@ -1,85 +0,0 @@ -= New Releases and API Stability - -Developing smart contracts is hard, and a conservative approach towards dependencies is sometimes favored. However, it is also very important to stay on top of new releases: these may include bug fixes, or deprecate old patterns in favor of newer and better practices. - -Here we describe when you should expect new releases to come out, and how this affects you as a user of OpenZeppelin Contracts. - -[[release-schedule]] -== Release Schedule - -OpenZeppelin Contracts follows a <>. - -We aim for a new minor release every 1 or 2 months. - -[[minor-releases]] -=== Release Candidates - -Before every release, we publish a feature-frozen release candidate. The purpose of the release candidate is to have a period where the community can review the new code before the actual release. If important problems are discovered, several more release candidates may be required. After a week of no more changes to the release candidate, the new version is published. - -[[major-releases]] -=== Major Releases - -After several months or a year a new major release may come out. These are not scheduled, but will be based on the need to release breaking changes such as a redesign of a core feature of the library (e.g. https://github.com/OpenZeppelin/openzeppelin-contracts/pulls/2112[access control] in 3.0). Since we value stability, we aim for these to happen infrequently (expect no less than six months between majors). However, we may be forced to release one when there are big changes to the Solidity language. - -[[api-stability]] -== API Stability - -On the https://github.com/OpenZeppelin/openzeppelin-contracts/releases/tag/v2.0.0[OpenZeppelin Contracts 2.0 release], we committed ourselves to keeping a stable API. We aim to more precisely define what we understand by _stable_ and _API_ here, so users of the library can understand these guarantees and be confident their project won't break unexpectedly. - -In a nutshell, the API being stable means _if your project is working today, it will continue to do so after a minor upgrade_. New contracts and features will be added in minor releases, but only in a backwards compatible way. - -[[versioning-scheme]] -=== Versioning Scheme - -We follow https://semver.org/[SemVer], which means API breakage may occur between major releases (which <>). - -[[solidity-functions]] -=== Solidity Functions - -While the internal implementation of functions may change, their semantics and signature will remain the same. The domain of their arguments will not be less restrictive (e.g. if transferring a value of 0 is disallowed, it will remain disallowed), nor will general state restrictions be lifted (e.g. `whenPaused` modifiers). - -If new functions are added to a contract, it will be in a backwards-compatible way: their usage won't be mandatory, and they won't extend functionality in ways that may foreseeable break an application (e.g. https://github.com/OpenZeppelin/openzeppelin-contracts/issues/1512[an `internal` method may be added to make it easier to retrieve information that was already available]). - -[[internal]] -==== `internal` - -This extends not only to `external` and `public` functions, but also `internal` ones: many contracts are meant to be used by inheriting them (e.g. `Pausable`, `PullPayment`, `AccessControl`), and are therefore used by calling these functions. Similarly, since all OpenZeppelin Contracts state variables are `private`, they can only be accessed this way (e.g. to create new `ERC20` tokens, instead of manually modifying `totalSupply` and `balances`, `_mint` should be called). - -`private` functions have no guarantees on their behavior, usage, or existence. - -Finally, sometimes language limitations will force us to e.g. make `internal` a function that should be `private` in order to implement features the way we want to. These cases will be well documented, and the normal stability guarantees won't apply. - -[[libraries]] -=== Libraries - -Some of our Solidity libraries use ``struct``s to handle internal data that should not be accessed directly (e.g. `Counter`). There's an https://github.com/ethereum/solidity/issues/4637[open issue] in the Solidity repository requesting a language feature to prevent said access, but it looks like it won't be implemented any time soon. Because of this, we will use leading underscores and mark said `struct` s to make it clear to the user that its contents and layout are _not_ part of the API. - -[[events]] -=== Events - -No events will be removed, and their arguments won't be changed in any way. New events may be added in later versions, and existing events may be emitted under new, reasonable circumstances (e.g. https://github.com/OpenZeppelin/openzeppelin-contracts/issues/707[from 2.1 on, `ERC20` also emits `Approval` on `transferFrom` calls]). - -[[drafts]] -=== Drafts - -Some contracts implement EIPs that are still in Draft status, recognizable by a file name beginning with `draft-`, such as `utils/cryptography/draft-EIP712.sol`. Due to their nature as drafts, the details of these contracts may change and we cannot guarantee their stability. Minor releases of OpenZeppelin Contracts may contain breaking changes for the contracts labelled as Drafts, which will be duly announced in the https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CHANGELOG.md[changelog]. The EIPs included are used by projects in production and this may make them less likely to change significantly. - -[[gas-costs]] -=== Gas Costs - -While attempts will generally be made to lower the gas costs of working with OpenZeppelin Contracts, there are no guarantees regarding this. In particular, users should not assume gas costs will not increase when upgrading library versions. - -[[bugfixes]] -=== Bug Fixes - -The API stability guarantees may need to be broken in order to fix a bug, and we will do so. This decision won't be made lightly however, and all options will be explored to make the change as non-disruptive as possible. When sufficient, contracts or functions which may result in unsafe behavior will be deprecated instead of removed (e.g. https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1543[#1543] and https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1550[#1550]). - -[[solidity-compiler-version]] -=== Solidity Compiler Version - -Starting on version 0.5.0, the Solidity team switched to a faster release cycle, with minor releases every few weeks (v0.5.0 was released on November 2018, and v0.5.5 on March 2019), and major, breaking-change releases every couple of months (with v0.6.0 released on December 2019 and v0.7.0 on July 2020). Including the compiler version in OpenZeppelin Contract's stability guarantees would therefore force the library to either stick to old compilers, or release frequent major updates simply to keep up with newer Solidity releases. - -Because of this, *the minimum required Solidity compiler version is not part of the stability guarantees*, and users may be required to upgrade their compiler when using newer versions of Contracts. Bug fixes will still be backported to past major releases so that all versions currently in use receive these updates. - -You can read more about the rationale behind this, the other options we considered and why we went down this path https://github.com/OpenZeppelin/openzeppelin-contracts/issues/1498#issuecomment-449191611[here]. - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/tokens.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/tokens.adoc deleted file mode 100644 index b168756d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/tokens.adoc +++ /dev/null @@ -1,32 +0,0 @@ -= Tokens - -Ah, the "token": blockchain's most powerful and most misunderstood tool. - -A token is a _representation of something in the blockchain_. This something can be money, time, services, shares in a company, a virtual pet, anything. By representing things as tokens, we can allow smart contracts to interact with them, exchange them, create or destroy them. - -[[but_first_coffee_a_primer_on_token_contracts]] -== But First, [strikethrough]#Coffee# a Primer on Token Contracts - -Much of the confusion surrounding tokens comes from two concepts getting mixed up: _token contracts_ and the actual _tokens_. - -A _token contract_ is simply an Ethereum smart contract. "Sending tokens" actually means "calling a method on a smart contract that someone wrote and deployed". At the end of the day, a token contract is not much more than a mapping of addresses to balances, plus some methods to add and subtract from those balances. - -It is these balances that represent the _tokens_ themselves. Someone "has tokens" when their balance in the token contract is non-zero. That's it! These balances could be considered money, experience points in a game, deeds of ownership, or voting rights, and each of these tokens would be stored in different token contracts. - -[[different-kinds-of-tokens]] -== Different Kinds of Tokens - -Note that there's a big difference between having two voting rights and two deeds of ownership: each vote is equal to all others, but houses usually are not! This is called https://en.wikipedia.org/wiki/Fungibility[fungibility]. _Fungible goods_ are equivalent and interchangeable, like Ether, fiat currencies, and voting rights. _Non-fungible_ goods are unique and distinct, like deeds of ownership, or collectibles. - -In a nutshell, when dealing with non-fungibles (like your house) you care about _which ones_ you have, while in fungible assets (like your bank account statement) what matters is _how much_ you have. - -== Standards - -Even though the concept of a token is simple, they have a variety of complexities in the implementation. Because everything in Ethereum is just a smart contract, and there are no rules about what smart contracts have to do, the community has developed a variety of *standards* (called EIPs or ERCs) for documenting how a contract can interoperate with other contracts. - -You've probably heard of the ERC20 or ERC721 token standards, and that's why you're here. Head to our specialized guides to learn more about these: - - * xref:erc20.adoc[ERC20]: the most widespread token standard for fungible assets, albeit somewhat limited by its simplicity. - * xref:erc721.adoc[ERC721]: the de-facto solution for non-fungible tokens, often used for collectibles and games. - * xref:erc777.adoc[ERC777]: a richer standard for fungible tokens, enabling new use cases and building on past learnings. Backwards compatible with ERC20. - * xref:erc1155.adoc[ERC1155]: a novel standard for multi-tokens, allowing for a single contract to represent multiple fungible and non-fungible tokens, along with batched operations for increased gas efficiency. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/upgradeable.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/upgradeable.adoc deleted file mode 100644 index 2b8d2720..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/upgradeable.adoc +++ /dev/null @@ -1,73 +0,0 @@ -= Using with Upgrades - -If your contract is going to be deployed with upgradeability, such as using the xref:upgrades-plugins::index.adoc[OpenZeppelin Upgrades Plugins], you will need to use the Upgradeable variant of OpenZeppelin Contracts. - -This variant is available as a separate package called `@openzeppelin/contracts-upgradeable`, which is hosted in the repository https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable[OpenZeppelin/openzeppelin-contracts-upgradeable]. - -It follows all of the rules for xref:upgrades-plugins::writing-upgradeable.adoc[Writing Upgradeable Contracts]: constructors are replaced by initializer functions, state variables are initialized in initializer functions, and we additionally check for storage incompatibilities across minor versions. - -TIP: OpenZeppelin provides a full suite of tools for deploying and securing upgradeable smart contracts. xref:openzeppelin::upgrades.adoc[Check out the full list of resources]. - -== Overview - -=== Installation - -```console -$ npm install @openzeppelin/contracts-upgradeable -``` - -=== Usage - -The package replicates the structure of the main OpenZeppelin Contracts package, but every file and contract has the suffix `Upgradeable`. - -```diff --import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -+import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; - --contract MyCollectible is ERC721 { -+contract MyCollectible is ERC721Upgradeable { -``` - -Constructors are replaced by internal initializer functions following the naming convention `+__{ContractName}_init+`. Since these are internal, you must always define your own public initializer function and call the parent initializer of the contract you extend. - -```diff -- constructor() ERC721("MyCollectible", "MCO") public { -+ function initialize() initializer public { -+ __ERC721_init("MyCollectible", "MCO"); - } -``` - -CAUTION: Use with multiple inheritance requires special attention. See the section below titled <>. - -Once this contract is set up and compiled, you can deploy it using the xref:upgrades-plugins::index.adoc[Upgrades Plugins]. The following snippet shows an example deployment script using Hardhat. - -```js -// scripts/deploy-my-collectible.js -const { ethers, upgrades } = require("hardhat"); - -async function main() { - const MyCollectible = await ethers.getContractFactory("MyCollectible"); - - const mc = await upgrades.deployProxy(MyCollectible); - - await mc.deployed(); - console.log("MyCollectible deployed to:", mc.address); -} - -main(); -``` - -== Further Notes - -[[multiple-inheritance]] -=== Multiple Inheritance - -Initializer functions are not linearized by the compiler like constructors. Because of this, each `+__{ContractName}_init+` function embeds the linearized calls to all parent initializers. As a consequence, calling two of these `init` functions can potentially initialize the same contract twice. - -The function `+__{ContractName}_init_unchained+` found in every contract is the initializer function minus the calls to parent initializers, and can be used to avoid the double initialization problem, but doing this manually is not recommended. We hope to be able to implement safety checks for this in future versions of the Upgrades Plugins. - -=== Storage Gaps - -You may notice that every contract includes a state variable named `+__gap+`. This is empty reserved space in storage that is put in place in Upgradeable contracts. It allows us to freely add new state variables in the future without compromising the storage compatibility with existing deployments. - -It isn't safe to simply add a state variable because it "shifts down" all of the state variables below in the inheritance chain. This makes the storage layouts incompatible, as explained in xref:upgrades-plugins::writing-upgradeable.adoc#modifying-your-contracts[Writing Upgradeable Contracts]. The size of the `+__gap+` array is calculated so that the amount of storage used by a contract always adds up to the same number (in this case 50 storage slots). diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/utilities.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/utilities.adoc deleted file mode 100644 index 2f23ceb7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/utilities.adoc +++ /dev/null @@ -1,186 +0,0 @@ -= Utilities - -The OpenZeppelin Contracts provide a ton of useful utilities that you can use in your project. Here are some of the more popular ones. - -[[cryptography]] -== Cryptography - -=== Checking Signatures On-Chain - -xref:api:cryptography.adoc#ECDSA[`ECDSA`] provides functions for recovering and managing Ethereum account ECDSA signatures. These are often generated via https://web3js.readthedocs.io/en/v1.2.4/web3-eth.html#sign[`web3.eth.sign`], and are a 65 byte array (of type `bytes` in Solidity) arranged the following way: `[[v (1)], [r (32)], [s (32)]]`. - -The data signer can be recovered with xref:api:cryptography.adoc#ECDSA-recover-bytes32-bytes-[`ECDSA.recover`], and its address compared to verify the signature. Most wallets will hash the data to sign and add the prefix '\x19Ethereum Signed Message:\n', so when attempting to recover the signer of an Ethereum signed message hash, you'll want to use xref:api:cryptography.adoc#ECDSA-toEthSignedMessageHash-bytes32-[`toEthSignedMessageHash`]. - -[source,solidity] ----- -using ECDSA for bytes32; - -function _verify(bytes32 data, bytes memory signature, address account) internal pure returns (bool) { - return data - .toEthSignedMessageHash() - .recover(signature) == account; -} ----- - -WARNING: Getting signature verification right is not trivial: make sure you fully read and understand xref:api:cryptography.adoc#ECDSA[`ECDSA`]'s documentation. - -=== Verifying Merkle Proofs - -xref:api:cryptography.adoc#MerkleProof[`MerkleProof`] provides xref:api:cryptography.adoc#MerkleProof-verify-bytes32---bytes32-bytes32-[`verify`], which can prove that some value is part of a https://en.wikipedia.org/wiki/Merkle_tree[Merkle tree]. - -[[introspection]] -== Introspection - -In Solidity, it's frequently helpful to know whether or not a contract supports an interface you'd like to use. ERC165 is a standard that helps do runtime interface detection. Contracts provide helpers both for implementing ERC165 in your contracts and querying other contracts: - -* xref:api:introspection.adoc#IERC165[`IERC165`] — this is the ERC165 interface that defines xref:api:introspection.adoc#IERC165-supportsInterface-bytes4-[`supportsInterface`]. When implementing ERC165, you'll conform to this interface. -* xref:api:introspection.adoc#ERC165[`ERC165`] — inherit this contract if you'd like to support interface detection using a lookup table in contract storage. You can register interfaces using xref:api:introspection.adoc#ERC165-_registerInterface-bytes4-[`_registerInterface(bytes4)`]: check out example usage as part of the ERC721 implementation. -* xref:api:introspection.adoc#ERC165Checker[`ERC165Checker`] — ERC165Checker simplifies the process of checking whether or not a contract supports an interface you care about. -* include with `using ERC165Checker for address;` -* xref:api:introspection.adoc#ERC165Checker-_supportsInterface-address-bytes4-[`myAddress._supportsInterface(bytes4)`] -* xref:api:introspection.adoc#ERC165Checker-_supportsAllInterfaces-address-bytes4---[`myAddress._supportsAllInterfaces(bytes4[\])`] - -[source,solidity] ----- -contract MyContract { - using ERC165Checker for address; - - bytes4 private InterfaceId_ERC721 = 0x80ac58cd; - - /** - * @dev transfer an ERC721 token from this contract to someone else - */ - function transferERC721( - address token, - address to, - uint256 tokenId - ) - public - { - require(token.supportsInterface(InterfaceId_ERC721), "IS_NOT_721_TOKEN"); - IERC721(token).transferFrom(address(this), to, tokenId); - } -} ----- - -[[math]] -== Math - -The most popular math related library OpenZeppelin Contracts provides is xref:api:math.adoc#SafeMath[`SafeMath`], which provides mathematical functions that protect your contract from overflows and underflows. - -Include the contract with `using SafeMath for uint256;` and then call the functions: - -* `myNumber.add(otherNumber)` -* `myNumber.sub(otherNumber)` -* `myNumber.div(otherNumber)` -* `myNumber.mul(otherNumber)` -* `myNumber.mod(otherNumber)` - -Easy! - -[[payment]] -== Payment - -Want to split some payments between multiple people? Maybe you have an app that sends 30% of art purchases to the original creator and 70% of the profits to the current owner; you can build that with xref:api:payment.adoc#PaymentSplitter[`PaymentSplitter`]! - -In Solidity, there are some security concerns with blindly sending money to accounts, since it allows them to execute arbitrary code. You can read up on these security concerns in the https://consensys.github.io/smart-contract-best-practices/[Ethereum Smart Contract Best Practices] website. One of the ways to fix reentrancy and stalling problems is, instead of immediately sending Ether to accounts that need it, you can use xref:api:payment.adoc#PullPayment[`PullPayment`], which offers an xref:api:payment.adoc#PullPayment-_asyncTransfer-address-uint256-[`_asyncTransfer`] function for sending money to something and requesting that they xref:api:payment.adoc#PullPayment-withdrawPayments-address-payable-[`withdrawPayments()`] it later. - -If you want to Escrow some funds, check out xref:api:payment.adoc#Escrow[`Escrow`] and xref:api:payment.adoc#ConditionalEscrow[`ConditionalEscrow`] for governing the release of some escrowed Ether. - -[[collections]] -== Collections - -If you need support for more powerful collections than Solidity's native arrays and mappings, take a look at xref:api:utils.adoc#EnumerableSet[`EnumerableSet`] and xref:api:utils.adoc#EnumerableMap[`EnumerableMap`]. They are similar to mappings in that they store and remove elements in constant time and don't allow for repeated entries, but they also support _enumeration_, which means you can easily query all stored entries both on and off-chain. - -[[misc]] -== Misc - -Want to check if an address is a contract? Use xref:api:utils.adoc#Address[`Address`] and xref:api:utils.adoc#Address-isContract-address-[`Address.isContract()`]. - -Want to keep track of some numbers that increment by 1 every time you want another one? Check out xref:api:utils.adoc#Counters[`Counters`]. This is useful for lots of things, like creating incremental identifiers, as shown on the xref:erc721.adoc[ERC721 guide]. - -=== Base64 - -xref:api:utils.adoc#Base64[`Base64`] util allows you to transform `bytes32` data into its Base64 `string` representation. - -This is specially useful to build URL-safe tokenURIs for both xref:api:token/ERC721.adoc#IERC721Metadata-tokenURI-uint256-[`ERC721`] or xref:api:token/ERC1155.adoc#IERC1155MetadataURI-uri-uint256-[`ERC1155`]. This library provides a clever way to serve URL-safe https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs/[Data URI] compliant strings to serve on-chain data structures. - -Consider this is an example to send JSON Metadata through a Base64 Data URI using an ERC721: - -[source, solidity] ----- -// contracts/My721Token.sol -// SPDX-License-Identifier: MIT - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/utils/Strings.sol"; -import "@openzeppelin/contracts/utils/Base64.sol"; - -contract My721Token is ERC721 { - using Strings for uint256; - - constructor() ERC721("My721Token", "MTK") {} - - ... - - function tokenURI(uint256 tokenId) - public - pure - override - returns (string memory) - { - bytes memory dataURI = abi.encodePacked( - '{', - '"name": "My721Token #', tokenId.toString(), '"', - // Replace with extra ERC721 Metadata properties - '}' - ); - - return string( - abi.encodePacked( - "data:application/json;base64,", - Base64.encode(dataURI) - ) - ); - } -} ----- - -=== Multicall - -The `Multicall` abstract contract comes with a `multicall` function that bundles together multiple calls in a single external call. With it, external accounts may perform atomic operations comprising several function calls. This is not only useful for EOAs to make multiple calls in a single transaction, it's also a way to revert a previous call if a later one fails. - -Consider this dummy contract: - -[source,solidity] ----- -// contracts/Box.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/utils/Multicall.sol"; - -contract Box is Multicall { - function foo() public { - ... - } - - function bar() public { - ... - } -} ----- - -This is how to call the `multicall` function using Truffle, allowing `foo` and `bar` to be called in a single transaction: -[source,javascript] ----- -// scripts/foobar.js - -const Box = artifacts.require('Box'); -const instance = await Box.new(); - -await instance.multicall([ - instance.contract.methods.foo().encodeABI(), - instance.contract.methods.bar().encodeABI() -]); ----- diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/wizard.adoc b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/wizard.adoc deleted file mode 100644 index 26250537..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/modules/ROOT/pages/wizard.adoc +++ /dev/null @@ -1,15 +0,0 @@ -= Contracts Wizard -:page-notoc: - -Not sure where to start? Use the interactive generator below to bootstrap your -contract and learn about the components offered in OpenZeppelin Contracts. - -TIP: Place the resulting contract in your `contracts` directory in order to compile it with a tool like Hardhat or Truffle. Consider reading our guide on xref:learn::developing-smart-contracts.adoc[Developing Smart Contracts] for more guidance! - -++++ - - - -++++ - - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/prelude.hbs b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/prelude.hbs deleted file mode 100644 index f531d72f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/docs/prelude.hbs +++ /dev/null @@ -1,6 +0,0 @@ -:github-icon: pass:[] - -{{#links}} -:{{slug target.fullName}}: pass:normal[xref:{{path}}#{{target.anchor}}[`{{target.fullName}}`]] -:xref-{{slug target.anchor}}: xref:{{path}}#{{target.anchor}} -{{/links}} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/hardhat.config.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/hardhat.config.js deleted file mode 100644 index 1fbf856b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/hardhat.config.js +++ /dev/null @@ -1,86 +0,0 @@ -/// ENVVAR -// - CI: output gas report to file instead of stdout -// - COVERAGE: enable coverage report -// - ENABLE_GAS_REPORT: enable gas report -// - COMPILE_MODE: production modes enables optimizations (default: development) -// - COMPILE_VERSION: compiler version (default: 0.8.9) -// - COINMARKETCAP: coinmarkercat api key for USD value in gas report - -const fs = require('fs'); -const path = require('path'); -const argv = require('yargs/yargs')() - .env('') - .options({ - ci: { - type: 'boolean', - default: false, - }, - coverage: { - type: 'boolean', - default: false, - }, - gas: { - alias: 'enableGasReport', - type: 'boolean', - default: false, - }, - mode: { - alias: 'compileMode', - type: 'string', - choices: [ 'production', 'development' ], - default: 'development', - }, - compiler: { - alias: 'compileVersion', - type: 'string', - default: '0.8.9', - }, - coinmarketcap: { - alias: 'coinmarketcapApiKey', - type: 'string', - }, - }) - .argv; - -require('@nomiclabs/hardhat-truffle5'); - -if (argv.enableGasReport) { - require('hardhat-gas-reporter'); -} - -for (const f of fs.readdirSync(path.join(__dirname, 'hardhat'))) { - require(path.join(__dirname, 'hardhat', f)); -} - -const withOptimizations = argv.enableGasReport || argv.compileMode === 'production'; - -/** - * @type import('hardhat/config').HardhatUserConfig - */ -module.exports = { - solidity: { - version: argv.compiler, - settings: { - optimizer: { - enabled: withOptimizations, - runs: 200, - }, - }, - }, - networks: { - hardhat: { - blockGasLimit: 10000000, - allowUnlimitedContractSize: !withOptimizations, - }, - }, - gasReporter: { - currency: 'USD', - outputFile: argv.ci ? 'gas-report.txt' : undefined, - coinmarketcap: argv.coinmarketcap, - }, -}; - -if (argv.coverage) { - require('solidity-coverage'); - module.exports.networks.hardhat.initialBaseFeePerGas = 0; -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/hardhat/env-contract.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/hardhat/env-contract.js deleted file mode 100644 index 74d54cfb..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/hardhat/env-contract.js +++ /dev/null @@ -1,10 +0,0 @@ -extendEnvironment(env => { - const { contract } = env; - - env.contract = function (name, body) { - // remove the default account from the accounts list used in tests, in order - // to protect tests against accidentally passing due to the contract - // deployer being used subsequently as function caller - contract(name, accounts => body(accounts.slice(1))); - }; -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/logo.svg b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/logo.svg deleted file mode 100644 index f1e14c2b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/logo.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/migrations/.gitkeep b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/migrations/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/netlify.toml b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/netlify.toml deleted file mode 100644 index 0447f41a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/netlify.toml +++ /dev/null @@ -1,3 +0,0 @@ -[build] -command = "npm run docs" -publish = "build/site" diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/package.json b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/package.json deleted file mode 100644 index a8182ad5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/package.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "name": "openzeppelin-solidity", - "description": "Secure Smart Contract library for Solidity", - "version": "4.5.0", - "files": [ - "/contracts/**/*.sol", - "/build/contracts/*.json", - "!/contracts/mocks/**/*" - ], - "bin": { - "openzeppelin-contracts-migrate-imports": "scripts/migrate-imports.js" - }, - "scripts": { - "compile": "hardhat compile", - "coverage": "env COVERAGE=true hardhat coverage", - "docs": "oz-docs", - "docs:watch": "npm run docs watch contracts 'docs/*.hbs' docs/helpers.js", - "prepare-docs": "scripts/prepare-docs.sh", - "lint": "npm run lint:js && npm run lint:sol", - "lint:fix": "npm run lint:js:fix && npm run lint:sol:fix", - "lint:js": "eslint --ignore-path .gitignore .", - "lint:js:fix": "eslint --ignore-path .gitignore . --fix", - "lint:sol": "solhint 'contracts/**/*.sol' && prettier -c 'contracts/**/*.sol'", - "lint:sol:fix": "prettier --write \"contracts/**/*.sol\"", - "clean": "hardhat clean && rimraf build contracts/build", - "prepare": "npm run clean && env COMPILE_MODE=production npm run compile", - "prepack": "scripts/prepack.sh", - "release": "scripts/release/release.sh", - "version": "scripts/release/version.sh", - "test": "hardhat test", - "test:inheritance": "node scripts/inheritanceOrdering artifacts/build-info/*", - "gas-report": "env ENABLE_GAS_REPORT=true npm run test" - }, - "repository": { - "type": "git", - "url": "https://github.com/OpenZeppelin/openzeppelin-contracts.git" - }, - "keywords": [ - "solidity", - "ethereum", - "smart", - "contracts", - "security", - "zeppelin" - ], - "author": "OpenZeppelin Community ", - "license": "MIT", - "bugs": { - "url": "https://github.com/OpenZeppelin/openzeppelin-contracts/issues" - }, - "homepage": "https://openzeppelin.com/contracts/", - "devDependencies": { - "@nomiclabs/hardhat-truffle5": "^2.0.0", - "@nomiclabs/hardhat-web3": "^2.0.0", - "@openzeppelin/docs-utils": "^0.1.0", - "@openzeppelin/test-helpers": "^0.5.13", - "@truffle/abi-utils": "^0.2.3", - "chai": "^4.2.0", - "eslint": "^6.5.1", - "eslint-config-standard": "^14.1.1", - "eslint-plugin-import": "^2.20.0", - "eslint-plugin-mocha-no-only": "^1.1.0", - "eslint-plugin-node": "^10.0.0", - "eslint-plugin-promise": "^4.2.1", - "eslint-plugin-standard": "^4.0.1", - "eth-sig-util": "^3.0.0", - "ethereumjs-util": "^7.0.7", - "ethereumjs-wallet": "^1.0.1", - "glob": "^7.2.0", - "graphlib": "^2.1.8", - "hardhat": "^2.0.6", - "hardhat-gas-reporter": "^1.0.4", - "keccak256": "^1.0.2", - "lodash.startcase": "^4.4.0", - "lodash.zip": "^4.2.0", - "merkletreejs": "^0.2.13", - "micromatch": "^4.0.2", - "prettier": "^2.3.0", - "prettier-plugin-solidity": "^1.0.0-beta.16", - "rimraf": "^3.0.2", - "semver": "^7.3.5", - "solhint": "^3.3.6", - "solidity-ast": "^0.4.25", - "solidity-coverage": "^0.7.11", - "solidity-docgen": "^0.5.3", - "web3": "^1.3.0", - "yargs": "^16.2.0" - } -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/renovate.json b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/renovate.json deleted file mode 100644 index 0ec3e857..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/renovate.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": [ - "github>OpenZeppelin/code-style" - ], - "packageRules": [ - { - "extends": ["packages:eslint"], - "enabled": false - } - ] -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/gen-nav.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/gen-nav.js deleted file mode 100644 index a03fbd69..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/gen-nav.js +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env node - -const path = require('path'); -const proc = require('child_process'); -const startCase = require('lodash.startcase'); - -const baseDir = process.argv[2]; - -const files = proc.execFileSync( - 'find', [baseDir, '-type', 'f'], { encoding: 'utf8' }, -).split('\n').filter(s => s !== ''); - -console.log('.API'); - -function getPageTitle (directory) { - switch (directory) { - case 'metatx': - return 'Meta Transactions'; - case 'common': - return 'Common (Tokens)'; - default: - return startCase(directory); - } -} - -const links = files.map((file) => { - const doc = file.replace(baseDir, ''); - const title = path.parse(file).name; - - return { - xref: `* xref:${doc}[${getPageTitle(title)}]`, - title, - }; -}); - -// Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20') -const sortedLinks = links.sort(function (a, b) { - return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true }); -}); - -for (const link of sortedLinks) { - console.log(link.xref); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/git-user-config.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/git-user-config.sh deleted file mode 100644 index e7b81c3e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/git-user-config.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail -x - -git config user.name 'github-actions' -git config user.email '41898282+github-actions[bot]@users.noreply.github.com' diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/inheritanceOrdering.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/inheritanceOrdering.js deleted file mode 100644 index 8a052f36..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/inheritanceOrdering.js +++ /dev/null @@ -1,44 +0,0 @@ -const path = require('path'); -const graphlib = require('graphlib'); -const { findAll } = require('solidity-ast/utils'); -const { _: artifacts } = require('yargs').argv; - -for (const artifact of artifacts) { - const { output: solcOutput } = require(path.resolve(__dirname, '..', artifact)); - - const graph = new graphlib.Graph({ directed: true }); - const names = {}; - const linearized = []; - - for (const source in solcOutput.contracts) { - for (const contractDef of findAll('ContractDefinition', solcOutput.sources[source].ast)) { - names[contractDef.id] = contractDef.name; - linearized.push(contractDef.linearizedBaseContracts); - - contractDef.linearizedBaseContracts.forEach((c1, i, contracts) => contracts.slice(i + 1).forEach(c2 => { - graph.setEdge(c1, c2); - })); - } - } - - /// graphlib.alg.findCycles will not find minimal cycles. - /// We are only interested int cycles of lengths 2 (needs proof) - graph.nodes().forEach((x, i, nodes) => nodes - .slice(i + 1) - .filter(y => graph.hasEdge(x, y) && graph.hasEdge(y, x)) - .map(y => { - console.log(`Conflict between ${names[x]} and ${names[y]} detected in the following dependency chains:`); - linearized - .filter(chain => chain.includes(parseInt(x)) && chain.includes(parseInt(y))) - .forEach(chain => { - const comp = chain.indexOf(parseInt(x)) < chain.indexOf(parseInt(y)) ? '>' : '<'; - console.log(`- ${names[x]} ${comp} ${names[y]} in ${names[chain.find(Boolean)]}`); - // console.log(`- ${names[x]} ${comp} ${names[y]}: ${chain.reverse().map(id => names[id]).join(', ')}`); - }); - process.exitCode = 1; - })); -} - -if (!process.exitCode) { - console.log('Contract ordering is consistent.'); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/migrate-imports.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/migrate-imports.js deleted file mode 100755 index bc35253d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/migrate-imports.js +++ /dev/null @@ -1,177 +0,0 @@ -#!/usr/bin/env node - -const { promises: fs } = require('fs'); -const path = require('path'); - -const pathUpdates = { - // 'access/AccessControl.sol': undefined, - // 'access/Ownable.sol': undefined, - 'access/TimelockController.sol': 'governance/TimelockController.sol', - 'cryptography/ECDSA.sol': 'utils/cryptography/ECDSA.sol', - 'cryptography/MerkleProof.sol': 'utils/cryptography/MerkleProof.sol', - 'drafts/EIP712.sol': 'utils/cryptography/draft-EIP712.sol', - 'drafts/ERC20Permit.sol': 'token/ERC20/extensions/draft-ERC20Permit.sol', - 'drafts/IERC20Permit.sol': 'token/ERC20/extensions/draft-IERC20Permit.sol', - 'GSN/Context.sol': 'utils/Context.sol', - // 'GSN/GSNRecipientERC20Fee.sol': undefined, - // 'GSN/GSNRecipientSignature.sol': undefined, - // 'GSN/GSNRecipient.sol': undefined, - // 'GSN/IRelayHub.sol': undefined, - // 'GSN/IRelayRecipient.sol': undefined, - 'introspection/ERC165Checker.sol': 'utils/introspection/ERC165Checker.sol', - 'introspection/ERC165.sol': 'utils/introspection/ERC165.sol', - 'introspection/ERC1820Implementer.sol': 'utils/introspection/ERC1820Implementer.sol', - 'introspection/IERC165.sol': 'utils/introspection/IERC165.sol', - 'introspection/IERC1820Implementer.sol': 'utils/introspection/IERC1820Implementer.sol', - 'introspection/IERC1820Registry.sol': 'utils/introspection/IERC1820Registry.sol', - 'math/Math.sol': 'utils/math/Math.sol', - 'math/SafeMath.sol': 'utils/math/SafeMath.sol', - 'math/SignedSafeMath.sol': 'utils/math/SignedSafeMath.sol', - 'payment/escrow/ConditionalEscrow.sol': 'utils/escrow/ConditionalEscrow.sol', - 'payment/escrow/Escrow.sol': 'utils/escrow/Escrow.sol', - 'payment/escrow/RefundEscrow.sol': 'utils/escrow/RefundEscrow.sol', - 'payment/PaymentSplitter.sol': 'finance/PaymentSplitter.sol', - 'utils/PaymentSplitter.sol': 'finance/PaymentSplitter.sol', - 'payment/PullPayment.sol': 'security/PullPayment.sol', - 'presets/ERC1155PresetMinterPauser.sol': 'token/ERC1155/presets/ERC1155PresetMinterPauser.sol', - 'presets/ERC20PresetFixedSupply.sol': 'token/ERC20/presets/ERC20PresetFixedSupply.sol', - 'presets/ERC20PresetMinterPauser.sol': 'token/ERC20/presets/ERC20PresetMinterPauser.sol', - 'presets/ERC721PresetMinterPauserAutoId.sol': 'token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol', - 'presets/ERC777PresetFixedSupply.sol': 'token/ERC777/presets/ERC777PresetFixedSupply.sol', - 'proxy/BeaconProxy.sol': 'proxy/beacon/BeaconProxy.sol', - // 'proxy/Clones.sol': undefined, - 'proxy/IBeacon.sol': 'proxy/beacon/IBeacon.sol', - 'proxy/Initializable.sol': 'proxy/utils/Initializable.sol', - 'utils/Initializable.sol': 'proxy/utils/Initializable.sol', - 'proxy/ProxyAdmin.sol': 'proxy/transparent/ProxyAdmin.sol', - // 'proxy/Proxy.sol': undefined, - 'proxy/TransparentUpgradeableProxy.sol': 'proxy/transparent/TransparentUpgradeableProxy.sol', - 'proxy/UpgradeableBeacon.sol': 'proxy/beacon/UpgradeableBeacon.sol', - 'proxy/UpgradeableProxy.sol': 'proxy/ERC1967/ERC1967Proxy.sol', - 'token/ERC1155/ERC1155Burnable.sol': 'token/ERC1155/extensions/ERC1155Burnable.sol', - 'token/ERC1155/ERC1155Holder.sol': 'token/ERC1155/utils/ERC1155Holder.sol', - 'token/ERC1155/ERC1155Pausable.sol': 'token/ERC1155/extensions/ERC1155Pausable.sol', - 'token/ERC1155/ERC1155Receiver.sol': 'token/ERC1155/utils/ERC1155Receiver.sol', - // 'token/ERC1155/ERC1155.sol': undefined, - 'token/ERC1155/IERC1155MetadataURI.sol': 'token/ERC1155/extensions/IERC1155MetadataURI.sol', - // 'token/ERC1155/IERC1155Receiver.sol': undefined, - // 'token/ERC1155/IERC1155.sol': undefined, - 'token/ERC20/ERC20Burnable.sol': 'token/ERC20/extensions/ERC20Burnable.sol', - 'token/ERC20/ERC20Capped.sol': 'token/ERC20/extensions/ERC20Capped.sol', - 'token/ERC20/ERC20Pausable.sol': 'token/ERC20/extensions/ERC20Pausable.sol', - 'token/ERC20/ERC20Snapshot.sol': 'token/ERC20/extensions/ERC20Snapshot.sol', - // 'token/ERC20/ERC20.sol': undefined, - // 'token/ERC20/IERC20.sol': undefined, - 'token/ERC20/SafeERC20.sol': 'token/ERC20/utils/SafeERC20.sol', - 'token/ERC20/TokenTimelock.sol': 'token/ERC20/utils/TokenTimelock.sol', - 'token/ERC721/ERC721Burnable.sol': 'token/ERC721/extensions/ERC721Burnable.sol', - 'token/ERC721/ERC721Holder.sol': 'token/ERC721/utils/ERC721Holder.sol', - 'token/ERC721/ERC721Pausable.sol': 'token/ERC721/extensions/ERC721Pausable.sol', - // 'token/ERC721/ERC721.sol': undefined, - 'token/ERC721/IERC721Enumerable.sol': 'token/ERC721/extensions/IERC721Enumerable.sol', - 'token/ERC721/IERC721Metadata.sol': 'token/ERC721/extensions/IERC721Metadata.sol', - // 'token/ERC721/IERC721Receiver.sol': undefined, - // 'token/ERC721/IERC721.sol': undefined, - // 'token/ERC777/ERC777.sol': undefined, - // 'token/ERC777/IERC777Recipient.sol': undefined, - // 'token/ERC777/IERC777Sender.sol': undefined, - // 'token/ERC777/IERC777.sol': undefined, - // 'utils/Address.sol': undefined, - // 'utils/Arrays.sol': undefined, - // 'utils/Context.sol': undefined, - // 'utils/Counters.sol': undefined, - // 'utils/Create2.sol': undefined, - 'utils/EnumerableMap.sol': 'utils/structs/EnumerableMap.sol', - 'utils/EnumerableSet.sol': 'utils/structs/EnumerableSet.sol', - 'utils/Pausable.sol': 'security/Pausable.sol', - 'utils/ReentrancyGuard.sol': 'security/ReentrancyGuard.sol', - 'utils/SafeCast.sol': 'utils/math/SafeCast.sol', - // 'utils/Strings.sol': undefined, -}; - -async function main (paths = [ 'contracts' ]) { - const files = await listFilesRecursively(paths, /\.sol$/); - - const updatedFiles = []; - for (const file of files) { - if (await updateFile(file, updateImportPaths)) { - updatedFiles.push(file); - } - } - - if (updatedFiles.length > 0) { - console.log(`${updatedFiles.length} file(s) were updated`); - for (const c of updatedFiles) { - console.log('-', c); - } - } else { - console.log('No files were updated'); - } -} - -async function listFilesRecursively (paths, filter) { - const queue = paths; - const files = []; - - while (queue.length > 0) { - const top = queue.shift(); - const stat = await fs.stat(top); - if (stat.isFile()) { - if (top.match(filter)) { - files.push(top); - } - } else if (stat.isDirectory()) { - for (const name of await fs.readdir(top)) { - queue.push(path.join(top, name)); - } - } - } - - return files; -} - -async function updateFile (file, update) { - const content = await fs.readFile(file, 'utf8'); - const updatedContent = update(content); - if (updatedContent !== content) { - await fs.writeFile(file, updatedContent); - return true; - } else { - return false; - } -} - -function updateImportPaths (source) { - for (const [ oldPath, newPath ] of Object.entries(pathUpdates)) { - source = source.replace( - path.join('@openzeppelin/contracts', oldPath), - path.join('@openzeppelin/contracts', newPath), - ); - source = source.replace( - path.join('@openzeppelin/contracts-upgradeable', getUpgradeablePath(oldPath)), - path.join('@openzeppelin/contracts-upgradeable', getUpgradeablePath(newPath)), - ); - } - - return source; -} - -function getUpgradeablePath (file) { - const { dir, name, ext } = path.parse(file); - const upgradeableName = name + 'Upgradeable'; - return path.format({ dir, ext, name: upgradeableName }); -} - -module.exports = { - pathUpdates, - updateImportPaths, - getUpgradeablePath, -}; - -if (require.main === module) { - const args = process.argv.length > 2 ? process.argv.slice(2) : undefined; - main(args).catch(e => { - console.error(e); - process.exit(1); - }); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepack.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepack.sh deleted file mode 100755 index 6f1bd4c3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepack.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail -shopt -s globstar - -# cross platform `mkdir -p` -node -e 'fs.mkdirSync("build/contracts", { recursive: true })' - -cp artifacts/contracts/**/*.json build/contracts -rm build/contracts/*.dbg.json - -node scripts/remove-ignored-artifacts.js diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-contracts-package.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-contracts-package.sh deleted file mode 100755 index 3f62fd41..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-contracts-package.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash - -# cd to the root of the repo -cd "$(git rev-parse --show-toplevel)" - -# avoids re-compilation during publishing of both packages -if [[ ! -v ALREADY_COMPILED ]]; then - npm run clean - npm run prepare - npm run prepack -fi - -cp README.md contracts/ -mkdir contracts/build contracts/build/contracts -cp -r build/contracts/*.json contracts/build/contracts diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-docs-solc.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-docs-solc.js deleted file mode 100644 index 5c38383a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-docs-solc.js +++ /dev/null @@ -1,16 +0,0 @@ -const hre = require('hardhat'); - -const { getCompilersDir } = require('hardhat/internal/util/global-dir'); -const { CompilerDownloader } = require('hardhat/internal/solidity/compiler/downloader'); -const { Compiler } = require('hardhat/internal/solidity/compiler'); - -const [{ version }] = hre.config.solidity.compilers; - -async function getSolc () { - const downloader = new CompilerDownloader(await getCompilersDir(), { forceSolcJs: true }); - const { compilerPath } = await downloader.getDownloadedCompilerPath(version); - const compiler = new Compiler(compilerPath); - return compiler.getSolc(); -} - -module.exports = Object.assign(getSolc(), { __esModule: true }); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-docs.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-docs.sh deleted file mode 100755 index 2f22a008..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/prepare-docs.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bash - -set -o errexit - -OUTDIR=docs/modules/api/pages/ - -if [ ! -d node_modules ]; then - npm ci -fi - -rm -rf "$OUTDIR" - -solidity-docgen \ - -t docs \ - -o "$OUTDIR" \ - -e contracts/mocks,contracts/examples \ - --output-structure readmes \ - --helpers ./docs/helpers.js \ - --solc-module ./scripts/prepare-docs-solc.js - -node scripts/gen-nav.js "$OUTDIR" > "$OUTDIR/../nav.adoc" diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/release.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/release.sh deleted file mode 100755 index 97116d4a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/release.sh +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/env bash - -# Exit script as soon as a command fails. -set -o errexit - -# Default the prerelease version suffix to rc -: ${PRERELEASE_SUFFIX:=rc} - -log() { - # Print to stderr to prevent this from being 'returned' - echo "$@" > /dev/stderr -} - -current_version() { - echo "v$(node --print --eval "require('./package.json').version")" -} - -current_release_branch() { - v="$(current_version)" # 3.3.0-rc.0 - vf="${v%-"$PRERELEASE_SUFFIX".*}" # 3.3.0 - r="${vf%.*}" # 3.3 - echo "release-$r" -} - -assert_current_branch() { - current_branch="$(git symbolic-ref --short HEAD)" - expected_branch="$1" - if [[ "$current_branch" != "$expected_branch" ]]; then - log "Current branch '$current_branch' is not '$expected_branch'" - exit 1 - fi -} - -push_release_branch_and_tag() { - git push upstream "$(current_release_branch)" "$(current_version)" -} - -publish() { - dist_tag="$1" - - log "Publishing openzeppelin-solidity on npm" - npm publish --tag "$dist_tag" --otp "$(prompt_otp)" - - log "Publishing @openzeppelin/contracts on npm" - cd contracts - env ALREADY_COMPILED= \ - npm publish --tag "$dist_tag" --otp "$(prompt_otp)" - cd .. - - if [[ "$dist_tag" == "latest" ]]; then - otp="$(prompt_otp)" - npm dist-tag rm --otp "$otp" openzeppelin-solidity next - npm dist-tag rm --otp "$otp" @openzeppelin/contracts next - fi -} - -push_and_publish() { - dist_tag="$1" - - log "Pushing release branch and tags to upstream" - push_release_branch_and_tag - - publish "$dist_tag" -} - -prompt_otp() { - log -n "Enter npm 2FA token: " - read -r otp - echo "$otp" -} - -environment_check() { - if ! git remote get-url upstream &> /dev/null; then - log "No 'upstream' remote found" - exit 1 - fi - - if npm whoami &> /dev/null; then - log "Will publish as '$(npm whoami)'" - else - log "Not logged in into npm, run 'npm login' first" - exit 1 - fi -} - -environment_check - -if [[ "$*" == "push" ]]; then - push_and_publish next - -elif [[ "$*" == "start minor" ]]; then - log "Creating new minor pre-release" - - assert_current_branch master - - # Create temporary release branch - git checkout -b release-temp - - # This bumps minor and adds prerelease suffix, commits the changes, and tags the commit - npm version preminor --preid="$PRERELEASE_SUFFIX" - - # Rename the release branch - git branch --move "$(current_release_branch)" - - push_and_publish next - -elif [[ "$*" == "start major" ]]; then - log "Creating new major pre-release" - - assert_current_branch master - - # Create temporary release branch - git checkout -b release-temp - - # This bumps major and adds prerelease suffix, commits the changes, and tags the commit - npm version premajor --preid="$PRERELEASE_SUFFIX" - - # Rename the release branch - git branch --move "$(current_release_branch)" - - push_and_publish next - -elif [[ "$*" == "rc" ]]; then - log "Bumping pre-release" - - assert_current_branch "$(current_release_branch)" - - # Bumps prerelease number, commits and tags - npm version prerelease - - push_and_publish next - -elif [[ "$*" == "final" ]]; then - # Update changelog release date, remove prerelease suffix, tag, push to git, publish in npm, remove next dist-tag - log "Creating final release" - - assert_current_branch "$(current_release_branch)" - - # This will remove the prerelease suffix from the version - npm version patch - - push_release_branch_and_tag - - push_and_publish latest - - npm deprecate 'openzeppelin-solidity@>=4.0.0' "This package is now published as @openzeppelin/contracts. Please change your dependency." - - log "Remember to merge the release branch into master and push upstream" - -else - log "Unknown command: '$*'" - exit 1 -fi diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/synchronize-versions.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/synchronize-versions.js deleted file mode 100755 index 15915a1c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/synchronize-versions.js +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node - -// Synchronizes the version in contracts/package.json with the one in package.json. -// This is run automatically when npm version is run. - -const fs = require('fs'); -const cp = require('child_process'); - -setVersion('contracts/package.json'); - -function setVersion (file) { - const json = JSON.parse(fs.readFileSync(file)); - json.version = process.env.npm_package_version; - fs.writeFileSync(file, JSON.stringify(json, null, 2) + '\n'); - cp.execFileSync('git', ['add', file]); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/update-changelog-release-date.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/update-changelog-release-date.js deleted file mode 100755 index c368eb7b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/update-changelog-release-date.js +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env node - -// Sets the release date of the current release in the changelog. -// This is run automatically when npm version is run. - -const fs = require('fs'); -const cp = require('child_process'); - -const suffix = process.env.PRERELEASE_SUFFIX || 'rc'; - -const changelog = fs.readFileSync('CHANGELOG.md', 'utf8'); - -// The changelog entry to be updated looks like this: -// ## Unreleased -// We need to add the version and release date in a YYYY-MM-DD format, so that it looks like this: -// ## 2.5.3 (2019-04-25) - -const pkg = require('../../package.json'); -const version = pkg.version.replace(new RegExp('-' + suffix + '\\..*'), ''); - -const header = new RegExp(`^## (Unreleased|${version})$`, 'm'); - -if (!header.test(changelog)) { - console.error('Missing changelog entry'); - process.exit(1); -} - -const newHeader = pkg.version.indexOf(suffix) === -1 - ? `## ${version} (${new Date().toISOString().split('T')[0]})` - : `## ${version}`; - -fs.writeFileSync('CHANGELOG.md', changelog.replace(header, newHeader)); - -cp.execSync('git add CHANGELOG.md', { stdio: 'inherit' }); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/update-comment.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/update-comment.js deleted file mode 100755 index b3dd9efe..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/update-comment.js +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env node -const fs = require('fs'); -const proc = require('child_process'); -const semver = require('semver'); -const run = (cmd, ...args) => proc.execFileSync(cmd, args, { encoding: 'utf8' }).trim(); - -const gitStatus = run('git', 'status', '--porcelain', '-uno', 'contracts/**/*.sol'); -if (gitStatus.length > 0) { - console.error('Contracts directory is not clean'); - process.exit(1); -} - -const { version } = require('../../package.json'); - -// Get latest tag according to semver. -const [ tag ] = run('git', 'tag') - .split(/\r?\n/) - .filter(v => semver.lt(semver.coerce(v), version)) // only consider older tags, ignore current prereleases - .sort(semver.rcompare); - -// Ordering tag → HEAD is important here. -const files = run('git', 'diff', tag, 'HEAD', '--name-only', 'contracts/**/*.sol') - .split(/\r?\n/) - .filter(file => file && !file.match(/mock/i)); - -for (const file of files) { - const current = fs.readFileSync(file, 'utf8'); - const updated = current.replace( - /(\/\/ SPDX-License-Identifier:.*)$(\n\/\/ OpenZeppelin Contracts .*$)?/m, - `$1\n// OpenZeppelin Contracts (last updated v${version}) (${file.replace('contracts/', '')})`, - ); - fs.writeFileSync(file, updated); -} - -run('git', 'add', '--update', 'contracts'); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/version.sh b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/version.sh deleted file mode 100755 index 73d3026d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/release/version.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash - -set -o errexit - -scripts/release/update-changelog-release-date.js -scripts/release/synchronize-versions.js -scripts/release/update-comment.js - -oz-docs update-version diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/remove-ignored-artifacts.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/remove-ignored-artifacts.js deleted file mode 100644 index 2ef27889..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/remove-ignored-artifacts.js +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env node - -// This script removes the build artifacts of ignored contracts. - -const fs = require('fs'); -const path = require('path'); -const match = require('micromatch'); - -function readJSON (path) { - return JSON.parse(fs.readFileSync(path)); -} - -const pkgFiles = readJSON('package.json').files; - -// Get only negated patterns. -const ignorePatterns = pkgFiles - .filter(pat => pat.startsWith('!')) -// Remove the negation part. Makes micromatch usage more intuitive. - .map(pat => pat.slice(1)); - -const ignorePatternsSubtrees = ignorePatterns -// Add **/* to ignore all files contained in the directories. - .concat(ignorePatterns.map(pat => path.join(pat, '**/*'))) - .map(p => p.replace(/^\//, '')); - -const artifactsDir = 'build/contracts'; -const buildinfo = 'artifacts/build-info'; -const filenames = fs.readdirSync(buildinfo); - -let n = 0; - -for (const filename of filenames) { - const solcOutput = readJSON(path.join(buildinfo, filename)).output; - for (const sourcePath in solcOutput.contracts) { - const ignore = match.any(sourcePath, ignorePatternsSubtrees); - if (ignore) { - for (const contract in solcOutput.contracts[sourcePath]) { - fs.unlinkSync(path.join(artifactsDir, contract + '.json')); - n += 1; - } - } - } -} - -console.error(`Removed ${n} mock artifacts`); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/update-docs-branch.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/update-docs-branch.js deleted file mode 100644 index 82bb7e06..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/scripts/update-docs-branch.js +++ /dev/null @@ -1,55 +0,0 @@ -const proc = require('child_process'); -const read = cmd => proc.execSync(cmd, { encoding: 'utf8' }).trim(); -const run = cmd => { proc.execSync(cmd, { stdio: 'inherit' }); }; -const tryRead = cmd => { try { return read(cmd); } catch (e) { return undefined; } }; - -const releaseBranchRegex = /^release-v(?(?\d+)\.(?\d+)(?:\.(?\d+))?)$/; - -const currentBranch = read('git rev-parse --abbrev-ref HEAD'); -const match = currentBranch.match(releaseBranchRegex); - -if (!match) { - console.error('Not currently on a release branch'); - process.exit(1); -} - -if (/-.*$/.test(require('../package.json').version)) { - console.error('Refusing to update docs: prerelease detected'); - process.exit(0); -} - -const current = match.groups; -const docsBranch = `docs-v${current.major}.x`; - -// Fetch remotes and find the docs branch if it exists -run('git fetch --all --no-tags'); -const matchingDocsBranches = tryRead(`git rev-parse --glob='*/${docsBranch}'`); - -if (!matchingDocsBranches) { - // Create the branch - run(`git checkout --orphan ${docsBranch}`); -} else { - const [publishedRef, ...others] = new Set(matchingDocsBranches.split('\n')); - if (others.length > 0) { - console.error( - `Found conflicting ${docsBranch} branches.\n` + - 'Either local branch is outdated or there are multiple matching remote branches.', - ); - process.exit(1); - } - const publishedVersion = JSON.parse(read(`git show ${publishedRef}:package.json`)).version; - const publishedMinor = publishedVersion.match(/\d+\.(?\d+)\.\d+/).groups.minor; - if (current.minor < publishedMinor) { - console.error('Refusing to update docs: newer version is published'); - process.exit(0); - } - - run('git checkout --quiet --detach'); - run(`git reset --soft ${publishedRef}`); - run(`git checkout ${docsBranch}`); -} - -run('npm run prepare-docs'); -run('git add -f docs'); // --force needed because generated docs files are gitignored -run('git commit -m "Update docs"'); -run(`git checkout ${currentBranch}`); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/TESTING.md b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/TESTING.md deleted file mode 100644 index a5ee9323..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/TESTING.md +++ /dev/null @@ -1,3 +0,0 @@ -## Testing - -Unit test are critical to OpenZeppelin Contracts. They help ensure code quality and mitigate against security vulnerabilities. The directory structure within the `/test` directory corresponds to the `/contracts` directory. diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControl.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControl.behavior.js deleted file mode 100644 index 53dfa3dd..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControl.behavior.js +++ /dev/null @@ -1,216 +0,0 @@ -const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const { shouldSupportInterfaces } = require('../utils/introspection/SupportsInterface.behavior'); - -const DEFAULT_ADMIN_ROLE = '0x0000000000000000000000000000000000000000000000000000000000000000'; -const ROLE = web3.utils.soliditySha3('ROLE'); -const OTHER_ROLE = web3.utils.soliditySha3('OTHER_ROLE'); - -function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, otherAdmin, otherAuthorized) { - shouldSupportInterfaces(['AccessControl']); - - describe('default admin', function () { - it('deployer has default admin role', async function () { - expect(await this.accessControl.hasRole(DEFAULT_ADMIN_ROLE, admin)).to.equal(true); - }); - - it('other roles\'s admin is the default admin role', async function () { - expect(await this.accessControl.getRoleAdmin(ROLE)).to.equal(DEFAULT_ADMIN_ROLE); - }); - - it('default admin role\'s admin is itself', async function () { - expect(await this.accessControl.getRoleAdmin(DEFAULT_ADMIN_ROLE)).to.equal(DEFAULT_ADMIN_ROLE); - }); - }); - - describe('granting', function () { - beforeEach(async function () { - await this.accessControl.grantRole(ROLE, authorized, { from: admin }); - }); - - it('non-admin cannot grant role to other accounts', async function () { - await expectRevert( - this.accessControl.grantRole(ROLE, authorized, { from: other }), - `${errorPrefix}: account ${other.toLowerCase()} is missing role ${DEFAULT_ADMIN_ROLE}`, - ); - }); - - it('accounts can be granted a role multiple times', async function () { - await this.accessControl.grantRole(ROLE, authorized, { from: admin }); - const receipt = await this.accessControl.grantRole(ROLE, authorized, { from: admin }); - expectEvent.notEmitted(receipt, 'RoleGranted'); - }); - }); - - describe('revoking', function () { - it('roles that are not had can be revoked', async function () { - expect(await this.accessControl.hasRole(ROLE, authorized)).to.equal(false); - - const receipt = await this.accessControl.revokeRole(ROLE, authorized, { from: admin }); - expectEvent.notEmitted(receipt, 'RoleRevoked'); - }); - - context('with granted role', function () { - beforeEach(async function () { - await this.accessControl.grantRole(ROLE, authorized, { from: admin }); - }); - - it('admin can revoke role', async function () { - const receipt = await this.accessControl.revokeRole(ROLE, authorized, { from: admin }); - expectEvent(receipt, 'RoleRevoked', { account: authorized, role: ROLE, sender: admin }); - - expect(await this.accessControl.hasRole(ROLE, authorized)).to.equal(false); - }); - - it('non-admin cannot revoke role', async function () { - await expectRevert( - this.accessControl.revokeRole(ROLE, authorized, { from: other }), - `${errorPrefix}: account ${other.toLowerCase()} is missing role ${DEFAULT_ADMIN_ROLE}`, - ); - }); - - it('a role can be revoked multiple times', async function () { - await this.accessControl.revokeRole(ROLE, authorized, { from: admin }); - - const receipt = await this.accessControl.revokeRole(ROLE, authorized, { from: admin }); - expectEvent.notEmitted(receipt, 'RoleRevoked'); - }); - }); - }); - - describe('renouncing', function () { - it('roles that are not had can be renounced', async function () { - const receipt = await this.accessControl.renounceRole(ROLE, authorized, { from: authorized }); - expectEvent.notEmitted(receipt, 'RoleRevoked'); - }); - - context('with granted role', function () { - beforeEach(async function () { - await this.accessControl.grantRole(ROLE, authorized, { from: admin }); - }); - - it('bearer can renounce role', async function () { - const receipt = await this.accessControl.renounceRole(ROLE, authorized, { from: authorized }); - expectEvent(receipt, 'RoleRevoked', { account: authorized, role: ROLE, sender: authorized }); - - expect(await this.accessControl.hasRole(ROLE, authorized)).to.equal(false); - }); - - it('only the sender can renounce their roles', async function () { - await expectRevert( - this.accessControl.renounceRole(ROLE, authorized, { from: admin }), - `${errorPrefix}: can only renounce roles for self`, - ); - }); - - it('a role can be renounced multiple times', async function () { - await this.accessControl.renounceRole(ROLE, authorized, { from: authorized }); - - const receipt = await this.accessControl.renounceRole(ROLE, authorized, { from: authorized }); - expectEvent.notEmitted(receipt, 'RoleRevoked'); - }); - }); - }); - - describe('setting role admin', function () { - beforeEach(async function () { - const receipt = await this.accessControl.setRoleAdmin(ROLE, OTHER_ROLE); - expectEvent(receipt, 'RoleAdminChanged', { - role: ROLE, - previousAdminRole: DEFAULT_ADMIN_ROLE, - newAdminRole: OTHER_ROLE, - }); - - await this.accessControl.grantRole(OTHER_ROLE, otherAdmin, { from: admin }); - }); - - it('a role\'s admin role can be changed', async function () { - expect(await this.accessControl.getRoleAdmin(ROLE)).to.equal(OTHER_ROLE); - }); - - it('the new admin can grant roles', async function () { - const receipt = await this.accessControl.grantRole(ROLE, authorized, { from: otherAdmin }); - expectEvent(receipt, 'RoleGranted', { account: authorized, role: ROLE, sender: otherAdmin }); - }); - - it('the new admin can revoke roles', async function () { - await this.accessControl.grantRole(ROLE, authorized, { from: otherAdmin }); - const receipt = await this.accessControl.revokeRole(ROLE, authorized, { from: otherAdmin }); - expectEvent(receipt, 'RoleRevoked', { account: authorized, role: ROLE, sender: otherAdmin }); - }); - - it('a role\'s previous admins no longer grant roles', async function () { - await expectRevert( - this.accessControl.grantRole(ROLE, authorized, { from: admin }), - `${errorPrefix}: account ${admin.toLowerCase()} is missing role ${OTHER_ROLE}`, - ); - }); - - it('a role\'s previous admins no longer revoke roles', async function () { - await expectRevert( - this.accessControl.revokeRole(ROLE, authorized, { from: admin }), - `${errorPrefix}: account ${admin.toLowerCase()} is missing role ${OTHER_ROLE}`, - ); - }); - }); - - describe('onlyRole modifier', function () { - beforeEach(async function () { - await this.accessControl.grantRole(ROLE, authorized, { from: admin }); - }); - - it('do not revert if sender has role', async function () { - await this.accessControl.senderProtected(ROLE, { from: authorized }); - }); - - it('revert if sender doesn\'t have role #1', async function () { - await expectRevert( - this.accessControl.senderProtected(ROLE, { from: other }), - `${errorPrefix}: account ${other.toLowerCase()} is missing role ${ROLE}`, - ); - }); - - it('revert if sender doesn\'t have role #2', async function () { - await expectRevert( - this.accessControl.senderProtected(OTHER_ROLE, { from: authorized }), - `${errorPrefix}: account ${authorized.toLowerCase()} is missing role ${OTHER_ROLE}`, - ); - }); - }); -} - -function shouldBehaveLikeAccessControlEnumerable (errorPrefix, admin, authorized, other, otherAdmin, otherAuthorized) { - shouldSupportInterfaces(['AccessControlEnumerable']); - - describe('enumerating', function () { - it('role bearers can be enumerated', async function () { - await this.accessControl.grantRole(ROLE, authorized, { from: admin }); - await this.accessControl.grantRole(ROLE, other, { from: admin }); - await this.accessControl.grantRole(ROLE, otherAuthorized, { from: admin }); - await this.accessControl.revokeRole(ROLE, other, { from: admin }); - - const memberCount = await this.accessControl.getRoleMemberCount(ROLE); - expect(memberCount).to.bignumber.equal('2'); - - const bearers = []; - for (let i = 0; i < memberCount; ++i) { - bearers.push(await this.accessControl.getRoleMember(ROLE, i)); - } - - expect(bearers).to.have.members([authorized, otherAuthorized]); - }); - it('role enumeration should be in sync after renounceRole call', async function () { - expect(await this.accessControl.getRoleMemberCount(ROLE)).to.bignumber.equal('0'); - await this.accessControl.grantRole(ROLE, admin, { from: admin }); - expect(await this.accessControl.getRoleMemberCount(ROLE)).to.bignumber.equal('1'); - await this.accessControl.renounceRole(ROLE, admin, { from: admin }); - expect(await this.accessControl.getRoleMemberCount(ROLE)).to.bignumber.equal('0'); - }); - }); -} - -module.exports = { - shouldBehaveLikeAccessControl, - shouldBehaveLikeAccessControlEnumerable, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControl.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControl.test.js deleted file mode 100644 index cd9912ad..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControl.test.js +++ /dev/null @@ -1,13 +0,0 @@ -const { - shouldBehaveLikeAccessControl, -} = require('./AccessControl.behavior.js'); - -const AccessControlMock = artifacts.require('AccessControlMock'); - -contract('AccessControl', function (accounts) { - beforeEach(async function () { - this.accessControl = await AccessControlMock.new({ from: accounts[0] }); - }); - - shouldBehaveLikeAccessControl('AccessControl', ...accounts); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControlEnumerable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControlEnumerable.test.js deleted file mode 100644 index fa5b5469..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/AccessControlEnumerable.test.js +++ /dev/null @@ -1,15 +0,0 @@ -const { - shouldBehaveLikeAccessControl, - shouldBehaveLikeAccessControlEnumerable, -} = require('./AccessControl.behavior.js'); - -const AccessControlMock = artifacts.require('AccessControlEnumerableMock'); - -contract('AccessControl', function (accounts) { - beforeEach(async function () { - this.accessControl = await AccessControlMock.new({ from: accounts[0] }); - }); - - shouldBehaveLikeAccessControl('AccessControl', ...accounts); - shouldBehaveLikeAccessControlEnumerable('AccessControl', ...accounts); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/Ownable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/Ownable.test.js deleted file mode 100644 index 894e77c3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/access/Ownable.test.js +++ /dev/null @@ -1,57 +0,0 @@ -const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const Ownable = artifacts.require('OwnableMock'); - -contract('Ownable', function (accounts) { - const [ owner, other ] = accounts; - - beforeEach(async function () { - this.ownable = await Ownable.new({ from: owner }); - }); - - it('has an owner', async function () { - expect(await this.ownable.owner()).to.equal(owner); - }); - - describe('transfer ownership', function () { - it('changes owner after transfer', async function () { - const receipt = await this.ownable.transferOwnership(other, { from: owner }); - expectEvent(receipt, 'OwnershipTransferred'); - - expect(await this.ownable.owner()).to.equal(other); - }); - - it('prevents non-owners from transferring', async function () { - await expectRevert( - this.ownable.transferOwnership(other, { from: other }), - 'Ownable: caller is not the owner', - ); - }); - - it('guards ownership against stuck state', async function () { - await expectRevert( - this.ownable.transferOwnership(ZERO_ADDRESS, { from: owner }), - 'Ownable: new owner is the zero address', - ); - }); - }); - - describe('renounce ownership', function () { - it('loses owner after renouncement', async function () { - const receipt = await this.ownable.renounceOwnership({ from: owner }); - expectEvent(receipt, 'OwnershipTransferred'); - - expect(await this.ownable.owner()).to.equal(ZERO_ADDRESS); - }); - - it('prevents non-owners from renouncement', async function () { - await expectRevert( - this.ownable.renounceOwnership({ from: other }), - 'Ownable: caller is not the owner', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/PaymentSplitter.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/PaymentSplitter.test.js deleted file mode 100644 index 6df0c4cb..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/PaymentSplitter.test.js +++ /dev/null @@ -1,196 +0,0 @@ -const { balance, constants, ether, expectEvent, send, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const PaymentSplitter = artifacts.require('PaymentSplitter'); -const Token = artifacts.require('ERC20Mock'); - -contract('PaymentSplitter', function (accounts) { - const [ owner, payee1, payee2, payee3, nonpayee1, payer1 ] = accounts; - - const amount = ether('1'); - - it('rejects an empty set of payees', async function () { - await expectRevert(PaymentSplitter.new([], []), 'PaymentSplitter: no payees'); - }); - - it('rejects more payees than shares', async function () { - await expectRevert(PaymentSplitter.new([payee1, payee2, payee3], [20, 30]), - 'PaymentSplitter: payees and shares length mismatch', - ); - }); - - it('rejects more shares than payees', async function () { - await expectRevert(PaymentSplitter.new([payee1, payee2], [20, 30, 40]), - 'PaymentSplitter: payees and shares length mismatch', - ); - }); - - it('rejects null payees', async function () { - await expectRevert(PaymentSplitter.new([payee1, ZERO_ADDRESS], [20, 30]), - 'PaymentSplitter: account is the zero address', - ); - }); - - it('rejects zero-valued shares', async function () { - await expectRevert(PaymentSplitter.new([payee1, payee2], [20, 0]), - 'PaymentSplitter: shares are 0', - ); - }); - - it('rejects repeated payees', async function () { - await expectRevert(PaymentSplitter.new([payee1, payee1], [20, 30]), - 'PaymentSplitter: account already has shares', - ); - }); - - context('once deployed', function () { - beforeEach(async function () { - this.payees = [payee1, payee2, payee3]; - this.shares = [20, 10, 70]; - - this.contract = await PaymentSplitter.new(this.payees, this.shares); - this.token = await Token.new('MyToken', 'MT', owner, ether('1000')); - }); - - it('has total shares', async function () { - expect(await this.contract.totalShares()).to.be.bignumber.equal('100'); - }); - - it('has payees', async function () { - await Promise.all(this.payees.map(async (payee, index) => { - expect(await this.contract.payee(index)).to.equal(payee); - expect(await this.contract.released(payee)).to.be.bignumber.equal('0'); - })); - }); - - describe('accepts payments', async function () { - it('Ether', async function () { - await send.ether(owner, this.contract.address, amount); - - expect(await balance.current(this.contract.address)).to.be.bignumber.equal(amount); - }); - - it('Token', async function () { - await this.token.transfer(this.contract.address, amount, { from: owner }); - - expect(await this.token.balanceOf(this.contract.address)).to.be.bignumber.equal(amount); - }); - }); - - describe('shares', async function () { - it('stores shares if address is payee', async function () { - expect(await this.contract.shares(payee1)).to.be.bignumber.not.equal('0'); - }); - - it('does not store shares if address is not payee', async function () { - expect(await this.contract.shares(nonpayee1)).to.be.bignumber.equal('0'); - }); - }); - - describe('release', async function () { - describe('Ether', async function () { - it('reverts if no funds to claim', async function () { - await expectRevert(this.contract.release(payee1), - 'PaymentSplitter: account is not due payment', - ); - }); - it('reverts if non-payee want to claim', async function () { - await send.ether(payer1, this.contract.address, amount); - await expectRevert(this.contract.release(nonpayee1), - 'PaymentSplitter: account has no shares', - ); - }); - }); - - describe('Token', async function () { - it('reverts if no funds to claim', async function () { - await expectRevert(this.contract.release(this.token.address, payee1), - 'PaymentSplitter: account is not due payment', - ); - }); - it('reverts if non-payee want to claim', async function () { - await this.token.transfer(this.contract.address, amount, { from: owner }); - await expectRevert(this.contract.release(this.token.address, nonpayee1), - 'PaymentSplitter: account has no shares', - ); - }); - }); - }); - - describe('distributes funds to payees', async function () { - it('Ether', async function () { - await send.ether(payer1, this.contract.address, amount); - - // receive funds - const initBalance = await balance.current(this.contract.address); - expect(initBalance).to.be.bignumber.equal(amount); - - // distribute to payees - - const tracker1 = await balance.tracker(payee1); - const { logs: logs1 } = await this.contract.release(payee1); - const profit1 = await tracker1.delta(); - expect(profit1).to.be.bignumber.equal(ether('0.20')); - expectEvent.inLogs(logs1, 'PaymentReleased', { to: payee1, amount: profit1 }); - - const tracker2 = await balance.tracker(payee2); - const { logs: logs2 } = await this.contract.release(payee2); - const profit2 = await tracker2.delta(); - expect(profit2).to.be.bignumber.equal(ether('0.10')); - expectEvent.inLogs(logs2, 'PaymentReleased', { to: payee2, amount: profit2 }); - - const tracker3 = await balance.tracker(payee3); - const { logs: logs3 } = await this.contract.release(payee3); - const profit3 = await tracker3.delta(); - expect(profit3).to.be.bignumber.equal(ether('0.70')); - expectEvent.inLogs(logs3, 'PaymentReleased', { to: payee3, amount: profit3 }); - - // end balance should be zero - expect(await balance.current(this.contract.address)).to.be.bignumber.equal('0'); - - // check correct funds released accounting - expect(await this.contract.totalReleased()).to.be.bignumber.equal(initBalance); - }); - - it('Token', async function () { - expect(await this.token.balanceOf(payee1)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOf(payee2)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOf(payee3)).to.be.bignumber.equal('0'); - - await this.token.transfer(this.contract.address, amount, { from: owner }); - - expectEvent( - await this.contract.release(this.token.address, payee1), - 'ERC20PaymentReleased', - { token: this.token.address, to: payee1, amount: ether('0.20') }, - ); - - await this.token.transfer(this.contract.address, amount, { from: owner }); - - expectEvent( - await this.contract.release(this.token.address, payee1), - 'ERC20PaymentReleased', - { token: this.token.address, to: payee1, amount: ether('0.20') }, - ); - - expectEvent( - await this.contract.release(this.token.address, payee2), - 'ERC20PaymentReleased', - { token: this.token.address, to: payee2, amount: ether('0.20') }, - ); - - expectEvent( - await this.contract.release(this.token.address, payee3), - 'ERC20PaymentReleased', - { token: this.token.address, to: payee3, amount: ether('1.40') }, - ); - - expect(await this.token.balanceOf(payee1)).to.be.bignumber.equal(ether('0.40')); - expect(await this.token.balanceOf(payee2)).to.be.bignumber.equal(ether('0.20')); - expect(await this.token.balanceOf(payee3)).to.be.bignumber.equal(ether('1.40')); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/VestingWallet.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/VestingWallet.behavior.js deleted file mode 100644 index 0f07e5f4..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/VestingWallet.behavior.js +++ /dev/null @@ -1,72 +0,0 @@ -const { expectEvent } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -function releasedEvent (token, amount) { - return token - ? [ 'ERC20Released', { token: token.address, amount } ] - : [ 'EtherReleased', { amount } ]; -} - -function shouldBehaveLikeVesting (beneficiary) { - it('check vesting schedule', async function () { - const [ method, ...args ] = this.token - ? [ 'vestedAmount(address,uint64)', this.token.address ] - : [ 'vestedAmount(uint64)' ]; - - for (const timestamp of this.schedule) { - expect(await this.mock.methods[method](...args, timestamp)) - .to.be.bignumber.equal(this.vestingFn(timestamp)); - } - }); - - it('execute vesting schedule', async function () { - const [ method, ...args ] = this.token - ? [ 'release(address)', this.token.address ] - : [ 'release()' ]; - - let released = web3.utils.toBN(0); - const before = await this.getBalance(beneficiary); - - { - const receipt = await this.mock.methods[method](...args); - - await expectEvent.inTransaction( - receipt.tx, - this.mock, - ...releasedEvent(this.token, '0'), - ); - - await this.checkRelease(receipt, beneficiary, '0'); - - expect(await this.getBalance(beneficiary)).to.be.bignumber.equal(before); - } - - for (const timestamp of this.schedule) { - const vested = this.vestingFn(timestamp); - - await new Promise(resolve => web3.currentProvider.send({ - method: 'evm_setNextBlockTimestamp', - params: [ timestamp.toNumber() ], - }, resolve)); - - const receipt = await this.mock.methods[method](...args); - - await expectEvent.inTransaction( - receipt.tx, - this.mock, - ...releasedEvent(this.token, vested.sub(released)), - ); - - await this.checkRelease(receipt, beneficiary, vested.sub(released)); - - expect(await this.getBalance(beneficiary)) - .to.be.bignumber.equal(before.add(vested)); - - released = vested; - } - }); -} - -module.exports = { - shouldBehaveLikeVesting, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/VestingWallet.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/VestingWallet.test.js deleted file mode 100644 index 6aa73780..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/finance/VestingWallet.test.js +++ /dev/null @@ -1,67 +0,0 @@ -const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); -const { web3 } = require('@openzeppelin/test-helpers/src/setup'); -const { expect } = require('chai'); - -const ERC20Mock = artifacts.require('ERC20Mock'); -const VestingWallet = artifacts.require('VestingWallet'); - -const { shouldBehaveLikeVesting } = require('./VestingWallet.behavior'); - -const min = (...args) => args.slice(1).reduce((x, y) => x.lt(y) ? x : y, args[0]); - -contract('VestingWallet', function (accounts) { - const [ sender, beneficiary ] = accounts; - - const amount = web3.utils.toBN(web3.utils.toWei('100')); - const duration = web3.utils.toBN(4 * 365 * 86400); // 4 years - - beforeEach(async function () { - this.start = (await time.latest()).addn(3600); // in 1 hour - this.mock = await VestingWallet.new(beneficiary, this.start, duration); - }); - - it('rejects zero address for beneficiary', async function () { - await expectRevert( - VestingWallet.new(constants.ZERO_ADDRESS, this.start, duration), - 'VestingWallet: beneficiary is zero address', - ); - }); - - it('check vesting contract', async function () { - expect(await this.mock.beneficiary()).to.be.equal(beneficiary); - expect(await this.mock.start()).to.be.bignumber.equal(this.start); - expect(await this.mock.duration()).to.be.bignumber.equal(duration); - }); - - describe('vesting schedule', function () { - beforeEach(async function () { - this.schedule = Array(64).fill().map((_, i) => web3.utils.toBN(i).mul(duration).divn(60).add(this.start)); - this.vestingFn = timestamp => min(amount, amount.mul(timestamp.sub(this.start)).div(duration)); - }); - - describe('Eth vesting', function () { - beforeEach(async function () { - await web3.eth.sendTransaction({ from: sender, to: this.mock.address, value: amount }); - this.getBalance = account => web3.eth.getBalance(account).then(web3.utils.toBN); - this.checkRelease = () => {}; - }); - - shouldBehaveLikeVesting(beneficiary); - }); - - describe('ERC20 vesting', function () { - beforeEach(async function () { - this.token = await ERC20Mock.new('Name', 'Symbol', this.mock.address, amount); - this.getBalance = (account) => this.token.balanceOf(account); - this.checkRelease = (receipt, to, value) => expectEvent.inTransaction( - receipt.tx, - this.token, - 'Transfer', - { from: this.mock.address, to, value }, - ); - }); - - shouldBehaveLikeVesting(beneficiary); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/Governor.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/Governor.test.js deleted file mode 100644 index 6017db05..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/Governor.test.js +++ /dev/null @@ -1,946 +0,0 @@ -const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); -const ethSigUtil = require('eth-sig-util'); -const Wallet = require('ethereumjs-wallet').default; -const Enums = require('../helpers/enums'); -const { EIP712Domain } = require('../helpers/eip712'); -const { fromRpcSig } = require('ethereumjs-util'); - -const { - runGovernorWorkflow, -} = require('./GovernorWorkflow.behavior'); - -const { - shouldSupportInterfaces, -} = require('../utils/introspection/SupportsInterface.behavior'); - -const Token = artifacts.require('ERC20VotesMock'); -const Governor = artifacts.require('GovernorMock'); -const CallReceiver = artifacts.require('CallReceiverMock'); - -contract('Governor', function (accounts) { - const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts; - - const name = 'OZ-Governor'; - const version = '1'; - const tokenName = 'MockToken'; - const tokenSymbol = 'MTKN'; - const tokenSupply = web3.utils.toWei('100'); - - beforeEach(async function () { - this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); - this.mock = await Governor.new(name, this.token.address, 4, 16, 10); - this.receiver = await CallReceiver.new(); - await this.token.mint(owner, tokenSupply); - await this.token.delegate(voter1, { from: voter1 }); - await this.token.delegate(voter2, { from: voter2 }); - await this.token.delegate(voter3, { from: voter3 }); - await this.token.delegate(voter4, { from: voter4 }); - }); - - shouldSupportInterfaces([ - 'ERC165', - 'Governor', - ]); - - it('deployment check', async function () { - expect(await this.mock.name()).to.be.equal(name); - expect(await this.mock.token()).to.be.equal(this.token.address); - expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); - expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); - expect(await this.mock.COUNTING_MODE()).to.be.equal('support=bravo&quorum=for,abstain'); - }); - - describe('scenario', function () { - describe('nominal', function () { - beforeEach(async function () { - this.value = web3.utils.toWei('1'); - - await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: this.value }); - expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(this.value); - expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal('0'); - - this.settings = { - proposal: [ - [ this.receiver.address ], - [ this.value ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - proposer, - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For, reason: 'This is nice' }, - { voter: voter2, weight: web3.utils.toWei('7'), support: Enums.VoteType.For }, - { voter: voter3, weight: web3.utils.toWei('5'), support: Enums.VoteType.Against }, - { voter: voter4, weight: web3.utils.toWei('2'), support: Enums.VoteType.Abstain }, - ], - }; - this.votingDelay = await this.mock.votingDelay(); - this.votingPeriod = await this.mock.votingPeriod(); - }); - - afterEach(async function () { - expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false); - expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(true); - expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(true); - - await this.mock.proposalVotes(this.id).then(result => { - for (const [key, value] of Object.entries(Enums.VoteType)) { - expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( - Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( - (acc, { weight }) => acc.add(new BN(weight)), - new BN('0'), - ), - ); - } - }); - - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { - proposalId: this.id, - proposer, - targets: this.settings.proposal[0], - // values: this.settings.proposal[1].map(value => new BN(value)), - signatures: this.settings.proposal[2].map(() => ''), - calldatas: this.settings.proposal[2], - startBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay), - endBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay).add(this.votingPeriod), - description: this.settings.proposal[3], - }, - ); - - this.receipts.castVote.filter(Boolean).forEach(vote => { - const { voter } = vote.logs.find(Boolean).args; - expectEvent( - vote, - 'VoteCast', - this.settings.voters.find(({ address }) => address === voter), - ); - }); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - - expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0'); - expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal(this.value); - }); - runGovernorWorkflow(); - }); - - describe('vote with signature', function () { - beforeEach(async function () { - const chainId = await web3.eth.getChainId(); - // generate voter by signature wallet - const voterBySig = Wallet.generate(); - this.voter = web3.utils.toChecksumAddress(voterBySig.getAddressString()); - // use delegateBySig to enable vote delegation for this wallet - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - voterBySig.getPrivateKey(), - { - data: { - types: { - EIP712Domain, - Delegation: [ - { name: 'delegatee', type: 'address' }, - { name: 'nonce', type: 'uint256' }, - { name: 'expiry', type: 'uint256' }, - ], - }, - domain: { name: tokenName, version: '1', chainId, verifyingContract: this.token.address }, - primaryType: 'Delegation', - message: { delegatee: this.voter, nonce: 0, expiry: constants.MAX_UINT256 }, - }, - }, - )); - await this.token.delegateBySig(this.voter, 0, constants.MAX_UINT256, v, r, s); - // prepare signature for vote by signature - const signature = async (message) => { - return fromRpcSig(ethSigUtil.signTypedMessage( - voterBySig.getPrivateKey(), - { - data: { - types: { - EIP712Domain, - Ballot: [ - { name: 'proposalId', type: 'uint256' }, - { name: 'support', type: 'uint8' }, - ], - }, - domain: { name, version, chainId, verifyingContract: this.mock.address }, - primaryType: 'Ballot', - message, - }, - }, - )); - }; - - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: this.voter, signature, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - }; - }); - afterEach(async function () { - expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false); - expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(false); - expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(false); - expect(await this.mock.hasVoted(this.id, this.voter)).to.be.equal(true); - - await this.mock.proposalVotes(this.id).then(result => { - for (const [key, value] of Object.entries(Enums.VoteType)) { - expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( - Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( - (acc, { weight }) => acc.add(new BN(weight)), - new BN('0'), - ), - ); - } - }); - - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - }); - runGovernorWorkflow(); - }); - - describe('send ethers', function () { - beforeEach(async function () { - this.receiver = { address: web3.utils.toChecksumAddress(web3.utils.randomHex(20)) }; - this.value = web3.utils.toWei('1'); - - await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: this.value }); - expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(this.value); - expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal('0'); - - this.settings = { - proposal: [ - [ this.receiver.address ], - [ this.value ], - [ '0x' ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('5'), support: Enums.VoteType.For }, - { voter: voter2, weight: web3.utils.toWei('5'), support: Enums.VoteType.Abstain }, - ], - }; - }); - afterEach(async function () { - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0'); - expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal(this.value); - }); - runGovernorWorkflow(); - }); - - describe('receiver revert without reason', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ 0 ], - [ this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - steps: { - execute: { error: 'Governor: call reverted without message' }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('receiver revert with reason', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ 0 ], - [ this.receiver.contract.methods.mockFunctionRevertsReason().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - steps: { - execute: { error: 'CallReceiverMock: reverting' }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('missing proposal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { - voter: voter1, - weight: web3.utils.toWei('5'), - support: Enums.VoteType.For, - error: 'Governor: unknown proposal id', - }, - { - voter: voter2, - weight: web3.utils.toWei('5'), - support: Enums.VoteType.Abstain, - error: 'Governor: unknown proposal id', - }, - ], - steps: { - propose: { enable: false }, - wait: { enable: false }, - execute: { error: 'Governor: unknown proposal id' }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('duplicate pending proposal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - steps: { - wait: { enable: false }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - await expectRevert(this.mock.propose(...this.settings.proposal), 'Governor: proposal already exists'); - }); - runGovernorWorkflow(); - }); - - describe('duplicate executed proposal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('5'), support: Enums.VoteType.For }, - { voter: voter2, weight: web3.utils.toWei('5'), support: Enums.VoteType.Abstain }, - ], - }; - }); - afterEach(async function () { - await expectRevert(this.mock.propose(...this.settings.proposal), 'Governor: proposal already exists'); - }); - runGovernorWorkflow(); - }); - - describe('Invalid vote type', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { - voter: voter1, - weight: web3.utils.toWei('10'), - support: new BN('255'), - error: 'GovernorVotingSimple: invalid value for enum VoteType', - }, - ], - steps: { - wait: { enable: false }, - execute: { enable: false }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('double cast', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { - voter: voter1, - weight: web3.utils.toWei('5'), - support: Enums.VoteType.For, - }, - { - voter: voter1, - weight: web3.utils.toWei('5'), - support: Enums.VoteType.For, - error: 'GovernorVotingSimple: vote already cast', - }, - ], - }; - }); - runGovernorWorkflow(); - }); - - describe('quorum not reached', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('5'), support: Enums.VoteType.For }, - { voter: voter2, weight: web3.utils.toWei('4'), support: Enums.VoteType.Abstain }, - { voter: voter3, weight: web3.utils.toWei('10'), support: Enums.VoteType.Against }, - ], - steps: { - execute: { error: 'Governor: proposal not successful' }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('score not reached', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.Against }, - ], - steps: { - execute: { error: 'Governor: proposal not successful' }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('vote not over', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - steps: { - wait: { enable: false }, - execute: { error: 'Governor: proposal not successful' }, - }, - }; - }); - runGovernorWorkflow(); - }); - }); - - describe('state', function () { - describe('Unset', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - steps: { - propose: { enable: false }, - wait: { enable: false }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - await expectRevert(this.mock.state(this.id), 'Governor: unknown proposal id'); - }); - runGovernorWorkflow(); - }); - - describe('Pending & Active', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - steps: { - propose: { noadvance: true }, - wait: { enable: false }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Pending); - - await time.advanceBlockTo(this.snapshot); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Pending); - - await time.advanceBlock(); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active); - }); - runGovernorWorkflow(); - }); - - describe('Defeated', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - steps: { - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated); - }); - runGovernorWorkflow(); - }); - - describe('Succeeded', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - steps: { - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded); - }); - runGovernorWorkflow(); - }); - - describe('Executed', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Executed); - }); - runGovernorWorkflow(); - }); - }); - - describe('Cancel', function () { - describe('Before proposal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - steps: { - propose: { enable: false }, - wait: { enable: false }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - await expectRevert( - this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: unknown proposal id', - ); - }); - runGovernorWorkflow(); - }); - - describe('After proposal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - steps: { - wait: { enable: false }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash); - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); - - await expectRevert( - this.mock.castVote(this.id, new BN('100'), { from: voter1 }), - 'Governor: vote not currently active', - ); - }); - runGovernorWorkflow(); - }); - - describe('After vote', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - steps: { - wait: { enable: false }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash); - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); - - await expectRevert( - this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('After deadline', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - steps: { - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash); - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); - - await expectRevert( - this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('After execution', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - }; - }); - afterEach(async function () { - await expectRevert( - this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not active', - ); - }); - runGovernorWorkflow(); - }); - }); - - describe('Proposal length', function () { - it('empty', async function () { - await expectRevert( - this.mock.propose( - [], - [], - [], - '', - ), - 'Governor: empty proposal', - ); - }); - - it('missmatch #1', async function () { - await expectRevert( - this.mock.propose( - [ ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ), - 'Governor: invalid proposal length', - ); - }); - - it('missmatch #2', async function () { - await expectRevert( - this.mock.propose( - [ this.receiver.address ], - [ ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ), - 'Governor: invalid proposal length', - ); - }); - - it('missmatch #3', async function () { - await expectRevert( - this.mock.propose( - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ ], - '', - ), - 'Governor: invalid proposal length', - ); - }); - }); - - describe('Settings update', function () { - describe('setVotingDelay', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.mock.address ], - [ web3.utils.toWei('0') ], - [ this.mock.contract.methods.setVotingDelay('0').encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - }; - }); - afterEach(async function () { - expect(await this.mock.votingDelay()).to.be.bignumber.equal('0'); - - expectEvent( - this.receipts.execute, - 'VotingDelaySet', - { oldVotingDelay: '4', newVotingDelay: '0' }, - ); - }); - runGovernorWorkflow(); - }); - - describe('setVotingPeriod', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.mock.address ], - [ web3.utils.toWei('0') ], - [ this.mock.contract.methods.setVotingPeriod('32').encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - }; - }); - afterEach(async function () { - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('32'); - - expectEvent( - this.receipts.execute, - 'VotingPeriodSet', - { oldVotingPeriod: '16', newVotingPeriod: '32' }, - ); - }); - runGovernorWorkflow(); - }); - - describe('setVotingPeriod to 0', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.mock.address ], - [ web3.utils.toWei('0') ], - [ this.mock.contract.methods.setVotingPeriod('0').encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - steps: { - execute: { error: 'GovernorSettings: voting period too low' }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); - }); - runGovernorWorkflow(); - }); - - describe('setProposalThreshold', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.mock.address ], - [ web3.utils.toWei('0') ], - [ this.mock.contract.methods.setProposalThreshold('1000000000000000000').encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - ], - }; - }); - afterEach(async function () { - expect(await this.mock.proposalThreshold()).to.be.bignumber.equal('1000000000000000000'); - - expectEvent( - this.receipts.execute, - 'ProposalThresholdSet', - { oldProposalThreshold: '0', newProposalThreshold: '1000000000000000000' }, - ); - }); - runGovernorWorkflow(); - }); - - describe('update protected', function () { - it('setVotingDelay', async function () { - await expectRevert(this.mock.setVotingDelay('0'), 'Governor: onlyGovernance'); - }); - - it('setVotingPeriod', async function () { - await expectRevert(this.mock.setVotingPeriod('32'), 'Governor: onlyGovernance'); - }); - - it('setProposalThreshold', async function () { - await expectRevert(this.mock.setProposalThreshold('1000000000000000000'), 'Governor: onlyGovernance'); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/GovernorWorkflow.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/GovernorWorkflow.behavior.js deleted file mode 100644 index 8cfa9dca..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/GovernorWorkflow.behavior.js +++ /dev/null @@ -1,186 +0,0 @@ -const { expectRevert, time } = require('@openzeppelin/test-helpers'); - -async function getReceiptOrRevert (promise, error = undefined) { - if (error) { - await expectRevert(promise, error); - return undefined; - } else { - const { receipt } = await promise; - return receipt; - } -} - -function tryGet (obj, path = '') { - try { - return path.split('.').reduce((o, k) => o[k], obj); - } catch (_) { - return undefined; - } -} - -function zip (...args) { - return Array(Math.max(...args.map(array => array.length))) - .fill() - .map((_, i) => args.map(array => array[i])); -} - -function concatHex (...args) { - return web3.utils.bytesToHex([].concat(...args.map(h => web3.utils.hexToBytes(h || '0x')))); -} - -function runGovernorWorkflow () { - beforeEach(async function () { - this.receipts = {}; - - // distinguish depending on the proposal length - // - length 4: propose(address[], uint256[], bytes[], string) → GovernorCore - // - length 5: propose(address[], uint256[], string[], bytes[], string) → GovernorCompatibilityBravo - this.useCompatibilityInterface = this.settings.proposal.length === 5; - - // compute description hash - this.descriptionHash = web3.utils.keccak256(this.settings.proposal.slice(-1).find(Boolean)); - - // condensed proposal, used for queue and execute operation - this.settings.shortProposal = [ - // targets - this.settings.proposal[0], - // values - this.settings.proposal[1], - // calldata (prefix selector if necessary) - this.useCompatibilityInterface - ? zip( - this.settings.proposal[2].map(selector => selector && web3.eth.abi.encodeFunctionSignature(selector)), - this.settings.proposal[3], - ).map(hexs => concatHex(...hexs)) - : this.settings.proposal[2], - // descriptionHash - this.descriptionHash, - ]; - - // proposal id - this.id = await this.mock.hashProposal(...this.settings.shortProposal); - }); - - it('run', async function () { - // transfer tokens - if (tryGet(this.settings, 'voters')) { - for (const voter of this.settings.voters) { - if (voter.weight) { - await this.token.transfer(voter.voter, voter.weight, { from: this.settings.tokenHolder }); - } else if (voter.nfts) { - for (const nft of voter.nfts) { - await this.token.transferFrom(this.settings.tokenHolder, voter.voter, nft, - { from: this.settings.tokenHolder }); - } - } - } - } - - // propose - if (this.mock.propose && tryGet(this.settings, 'steps.propose.enable') !== false) { - this.receipts.propose = await getReceiptOrRevert( - this.mock.methods[ - this.useCompatibilityInterface - ? 'propose(address[],uint256[],string[],bytes[],string)' - : 'propose(address[],uint256[],bytes[],string)' - ]( - ...this.settings.proposal, - { from: this.settings.proposer }, - ), - tryGet(this.settings, 'steps.propose.error'), - ); - - if (tryGet(this.settings, 'steps.propose.error') === undefined) { - this.deadline = await this.mock.proposalDeadline(this.id); - this.snapshot = await this.mock.proposalSnapshot(this.id); - } - - if (tryGet(this.settings, 'steps.propose.delay')) { - await time.increase(tryGet(this.settings, 'steps.propose.delay')); - } - - if ( - tryGet(this.settings, 'steps.propose.error') === undefined && - tryGet(this.settings, 'steps.propose.noadvance') !== true - ) { - await time.advanceBlockTo(this.snapshot.addn(1)); - } - } - - // vote - if (tryGet(this.settings, 'voters')) { - this.receipts.castVote = []; - for (const voter of this.settings.voters.filter(({ support }) => !!support)) { - if (!voter.signature) { - this.receipts.castVote.push( - await getReceiptOrRevert( - voter.reason - ? this.mock.castVoteWithReason(this.id, voter.support, voter.reason, { from: voter.voter }) - : this.mock.castVote(this.id, voter.support, { from: voter.voter }), - voter.error, - ), - ); - } else { - const { v, r, s } = await voter.signature({ proposalId: this.id, support: voter.support }); - this.receipts.castVote.push( - await getReceiptOrRevert( - this.mock.castVoteBySig(this.id, voter.support, v, r, s), - voter.error, - ), - ); - } - if (tryGet(voter, 'delay')) { - await time.increase(tryGet(voter, 'delay')); - } - } - } - - // fast forward - if (tryGet(this.settings, 'steps.wait.enable') !== false) { - await time.advanceBlockTo(this.deadline.addn(1)); - } - - // queue - if (this.mock.queue && tryGet(this.settings, 'steps.queue.enable') !== false) { - this.receipts.queue = await getReceiptOrRevert( - this.useCompatibilityInterface - ? this.mock.methods['queue(uint256)']( - this.id, - { from: this.settings.queuer }, - ) - : this.mock.methods['queue(address[],uint256[],bytes[],bytes32)']( - ...this.settings.shortProposal, - { from: this.settings.queuer }, - ), - tryGet(this.settings, 'steps.queue.error'), - ); - this.eta = await this.mock.proposalEta(this.id); - if (tryGet(this.settings, 'steps.queue.delay')) { - await time.increase(tryGet(this.settings, 'steps.queue.delay')); - } - } - - // execute - if (this.mock.execute && tryGet(this.settings, 'steps.execute.enable') !== false) { - this.receipts.execute = await getReceiptOrRevert( - this.useCompatibilityInterface - ? this.mock.methods['execute(uint256)']( - this.id, - { from: this.settings.executer }, - ) - : this.mock.methods['execute(address[],uint256[],bytes[],bytes32)']( - ...this.settings.shortProposal, - { from: this.settings.executer }, - ), - tryGet(this.settings, 'steps.execute.error'), - ); - if (tryGet(this.settings, 'steps.execute.delay')) { - await time.increase(tryGet(this.settings, 'steps.execute.delay')); - } - } - }); -} - -module.exports = { - runGovernorWorkflow, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/TimelockController.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/TimelockController.test.js deleted file mode 100644 index f39b9634..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/TimelockController.test.js +++ /dev/null @@ -1,1032 +0,0 @@ -const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); -const { ZERO_BYTES32 } = constants; - -const { expect } = require('chai'); - -const TimelockController = artifacts.require('TimelockController'); -const CallReceiverMock = artifacts.require('CallReceiverMock'); -const Implementation2 = artifacts.require('Implementation2'); -const MINDELAY = time.duration.days(1); - -function genOperation (target, value, data, predecessor, salt) { - const id = web3.utils.keccak256(web3.eth.abi.encodeParameters([ - 'address', - 'uint256', - 'bytes', - 'uint256', - 'bytes32', - ], [ - target, - value, - data, - predecessor, - salt, - ])); - return { id, target, value, data, predecessor, salt }; -} - -function genOperationBatch (targets, values, datas, predecessor, salt) { - const id = web3.utils.keccak256(web3.eth.abi.encodeParameters([ - 'address[]', - 'uint256[]', - 'bytes[]', - 'uint256', - 'bytes32', - ], [ - targets, - values, - datas, - predecessor, - salt, - ])); - return { id, targets, values, datas, predecessor, salt }; -} - -contract('TimelockController', function (accounts) { - const [ admin, proposer, executor, other ] = accounts; - - beforeEach(async function () { - // Deploy new timelock - this.timelock = await TimelockController.new( - MINDELAY, - [ proposer ], - [ executor ], - { from: admin }, - ); - this.TIMELOCK_ADMIN_ROLE = await this.timelock.TIMELOCK_ADMIN_ROLE(); - this.PROPOSER_ROLE = await this.timelock.PROPOSER_ROLE(); - this.EXECUTOR_ROLE = await this.timelock.EXECUTOR_ROLE(); - // Mocks - this.callreceivermock = await CallReceiverMock.new({ from: admin }); - this.implementation2 = await Implementation2.new({ from: admin }); - }); - - it('initial state', async function () { - expect(await this.timelock.getMinDelay()).to.be.bignumber.equal(MINDELAY); - }); - - describe('methods', function () { - describe('operation hashing', function () { - it('hashOperation', async function () { - this.operation = genOperation( - '0x29cebefe301c6ce1bb36b58654fea275e1cacc83', - '0xf94fdd6e21da21d2', - '0xa3bc5104', - '0xba41db3be0a9929145cfe480bd0f1f003689104d275ae912099f925df424ef94', - '0x60d9109846ab510ed75c15f979ae366a8a2ace11d34ba9788c13ac296db50e6e', - ); - expect(await this.timelock.hashOperation( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - )).to.be.equal(this.operation.id); - }); - - it('hashOperationBatch', async function () { - this.operation = genOperationBatch( - Array(8).fill('0x2d5f21620e56531c1d59c2df9b8e95d129571f71'), - Array(8).fill('0x2b993cfce932ccee'), - Array(8).fill('0xcf51966b'), - '0xce8f45069cc71d25f71ba05062de1a3974f9849b004de64a70998bca9d29c2e7', - '0x8952d74c110f72bfe5accdf828c74d53a7dfb71235dfa8a1e8c75d8576b372ff', - ); - expect(await this.timelock.hashOperationBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - )).to.be.equal(this.operation.id); - }); - }); - describe('simple', function () { - describe('schedule', function () { - beforeEach(async function () { - this.operation = genOperation( - '0x31754f590B97fD975Eb86938f18Cc304E264D2F2', - 0, - '0x3bf92ccc', - ZERO_BYTES32, - '0x025e7b0be353a74631ad648c667493c0e1cd31caa4cc2d3520fdc171ea0cc726', - ); - }); - - it('proposer can schedule', async function () { - const receipt = await this.timelock.schedule( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - ); - expectEvent(receipt, 'CallScheduled', { - id: this.operation.id, - index: web3.utils.toBN(0), - target: this.operation.target, - value: web3.utils.toBN(this.operation.value), - data: this.operation.data, - predecessor: this.operation.predecessor, - delay: MINDELAY, - }); - - const block = await web3.eth.getBlock(receipt.receipt.blockHash); - - expect(await this.timelock.getTimestamp(this.operation.id)) - .to.be.bignumber.equal(web3.utils.toBN(block.timestamp).add(MINDELAY)); - }); - - it('prevent overwritting active operation', async function () { - await this.timelock.schedule( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - ); - - await expectRevert( - this.timelock.schedule( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - ), - 'TimelockController: operation already scheduled', - ); - }); - - it('prevent non-proposer from commiting', async function () { - await expectRevert( - this.timelock.schedule( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: other }, - ), - `AccessControl: account ${other.toLowerCase()} is missing role ${this.PROPOSER_ROLE}`, - ); - }); - - it('enforce minimum delay', async function () { - await expectRevert( - this.timelock.schedule( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - MINDELAY - 1, - { from: proposer }, - ), - 'TimelockController: insufficient delay', - ); - }); - }); - - describe('execute', function () { - beforeEach(async function () { - this.operation = genOperation( - '0xAe22104DCD970750610E6FE15E623468A98b15f7', - 0, - '0x13e414de', - ZERO_BYTES32, - '0xc1059ed2dc130227aa1d1d539ac94c641306905c020436c636e19e3fab56fc7f', - ); - }); - - it('revert if operation is not scheduled', async function () { - await expectRevert( - this.timelock.execute( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: operation is not ready', - ); - }); - - describe('with scheduled operation', function () { - beforeEach(async function () { - ({ receipt: this.receipt, logs: this.logs } = await this.timelock.schedule( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - )); - }); - - it('revert if execution comes too early 1/2', async function () { - await expectRevert( - this.timelock.execute( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: operation is not ready', - ); - }); - - it('revert if execution comes too early 2/2', async function () { - const timestamp = await this.timelock.getTimestamp(this.operation.id); - await time.increaseTo(timestamp - 5); // -1 is too tight, test sometime fails - - await expectRevert( - this.timelock.execute( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: operation is not ready', - ); - }); - - describe('on time', function () { - beforeEach(async function () { - const timestamp = await this.timelock.getTimestamp(this.operation.id); - await time.increaseTo(timestamp); - }); - - it('executor can reveal', async function () { - const receipt = await this.timelock.execute( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ); - expectEvent(receipt, 'CallExecuted', { - id: this.operation.id, - index: web3.utils.toBN(0), - target: this.operation.target, - value: web3.utils.toBN(this.operation.value), - data: this.operation.data, - }); - }); - - it('prevent non-executor from revealing', async function () { - await expectRevert( - this.timelock.execute( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - { from: other }, - ), - `AccessControl: account ${other.toLowerCase()} is missing role ${this.EXECUTOR_ROLE}`, - ); - }); - }); - }); - }); - }); - - describe('batch', function () { - describe('schedule', function () { - beforeEach(async function () { - this.operation = genOperationBatch( - Array(8).fill('0xEd912250835c812D4516BBD80BdaEA1bB63a293C'), - Array(8).fill(0), - Array(8).fill('0x2fcb7a88'), - ZERO_BYTES32, - '0x6cf9d042ade5de78bed9ffd075eb4b2a4f6b1736932c2dc8af517d6e066f51f5', - ); - }); - - it('proposer can schedule', async function () { - const receipt = await this.timelock.scheduleBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - ); - for (const i in this.operation.targets) { - expectEvent(receipt, 'CallScheduled', { - id: this.operation.id, - index: web3.utils.toBN(i), - target: this.operation.targets[i], - value: web3.utils.toBN(this.operation.values[i]), - data: this.operation.datas[i], - predecessor: this.operation.predecessor, - delay: MINDELAY, - }); - } - - const block = await web3.eth.getBlock(receipt.receipt.blockHash); - - expect(await this.timelock.getTimestamp(this.operation.id)) - .to.be.bignumber.equal(web3.utils.toBN(block.timestamp).add(MINDELAY)); - }); - - it('prevent overwritting active operation', async function () { - await this.timelock.scheduleBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - ); - - await expectRevert( - this.timelock.scheduleBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - ), - 'TimelockController: operation already scheduled', - ); - }); - - it('length of batch parameter must match #1', async function () { - await expectRevert( - this.timelock.scheduleBatch( - this.operation.targets, - [], - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - ), - 'TimelockController: length mismatch', - ); - }); - - it('length of batch parameter must match #1', async function () { - await expectRevert( - this.timelock.scheduleBatch( - this.operation.targets, - this.operation.values, - [], - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - ), - 'TimelockController: length mismatch', - ); - }); - - it('prevent non-proposer from commiting', async function () { - await expectRevert( - this.timelock.scheduleBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: other }, - ), - `AccessControl: account ${other.toLowerCase()} is missing role ${this.PROPOSER_ROLE}`, - ); - }); - - it('enforce minimum delay', async function () { - await expectRevert( - this.timelock.scheduleBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - MINDELAY - 1, - { from: proposer }, - ), - 'TimelockController: insufficient delay', - ); - }); - }); - - describe('execute', function () { - beforeEach(async function () { - this.operation = genOperationBatch( - Array(8).fill('0x76E53CcEb05131Ef5248553bEBDb8F70536830b1'), - Array(8).fill(0), - Array(8).fill('0x58a60f63'), - ZERO_BYTES32, - '0x9545eeabc7a7586689191f78a5532443698538e54211b5bd4d7dc0fc0102b5c7', - ); - }); - - it('revert if operation is not scheduled', async function () { - await expectRevert( - this.timelock.executeBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: operation is not ready', - ); - }); - - describe('with scheduled operation', function () { - beforeEach(async function () { - ({ receipt: this.receipt, logs: this.logs } = await this.timelock.scheduleBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - )); - }); - - it('revert if execution comes too early 1/2', async function () { - await expectRevert( - this.timelock.executeBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: operation is not ready', - ); - }); - - it('revert if execution comes too early 2/2', async function () { - const timestamp = await this.timelock.getTimestamp(this.operation.id); - await time.increaseTo(timestamp - 5); // -1 is to tight, test sometime fails - - await expectRevert( - this.timelock.executeBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: operation is not ready', - ); - }); - - describe('on time', function () { - beforeEach(async function () { - const timestamp = await this.timelock.getTimestamp(this.operation.id); - await time.increaseTo(timestamp); - }); - - it('executor can reveal', async function () { - const receipt = await this.timelock.executeBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ); - for (const i in this.operation.targets) { - expectEvent(receipt, 'CallExecuted', { - id: this.operation.id, - index: web3.utils.toBN(i), - target: this.operation.targets[i], - value: web3.utils.toBN(this.operation.values[i]), - data: this.operation.datas[i], - }); - } - }); - - it('prevent non-executor from revealing', async function () { - await expectRevert( - this.timelock.executeBatch( - this.operation.targets, - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - { from: other }, - ), - `AccessControl: account ${other.toLowerCase()} is missing role ${this.EXECUTOR_ROLE}`, - ); - }); - - it('length mismatch #1', async function () { - await expectRevert( - this.timelock.executeBatch( - [], - this.operation.values, - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: length mismatch', - ); - }); - - it('length mismatch #2', async function () { - await expectRevert( - this.timelock.executeBatch( - this.operation.targets, - [], - this.operation.datas, - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: length mismatch', - ); - }); - - it('length mismatch #3', async function () { - await expectRevert( - this.timelock.executeBatch( - this.operation.targets, - this.operation.values, - [], - this.operation.predecessor, - this.operation.salt, - { from: executor }, - ), - 'TimelockController: length mismatch', - ); - }); - }); - }); - - it('partial execution', async function () { - const operation = genOperationBatch( - [ - this.callreceivermock.address, - this.callreceivermock.address, - this.callreceivermock.address, - ], - [ - 0, - 0, - 0, - ], - [ - this.callreceivermock.contract.methods.mockFunction().encodeABI(), - this.callreceivermock.contract.methods.mockFunctionThrows().encodeABI(), - this.callreceivermock.contract.methods.mockFunction().encodeABI(), - ], - ZERO_BYTES32, - '0x8ac04aa0d6d66b8812fb41d39638d37af0a9ab11da507afd65c509f8ed079d3e', - ); - - await this.timelock.scheduleBatch( - operation.targets, - operation.values, - operation.datas, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - await expectRevert( - this.timelock.executeBatch( - operation.targets, - operation.values, - operation.datas, - operation.predecessor, - operation.salt, - { from: executor }, - ), - 'TimelockController: underlying transaction reverted', - ); - }); - }); - }); - - describe('cancel', function () { - beforeEach(async function () { - this.operation = genOperation( - '0xC6837c44AA376dbe1d2709F13879E040CAb653ca', - 0, - '0x296e58dd', - ZERO_BYTES32, - '0xa2485763600634800df9fc9646fb2c112cf98649c55f63dd1d9c7d13a64399d9', - ); - ({ receipt: this.receipt, logs: this.logs } = await this.timelock.schedule( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - MINDELAY, - { from: proposer }, - )); - }); - - it('proposer can cancel', async function () { - const receipt = await this.timelock.cancel(this.operation.id, { from: proposer }); - expectEvent(receipt, 'Cancelled', { id: this.operation.id }); - }); - - it('cannot cancel invalid operation', async function () { - await expectRevert( - this.timelock.cancel(constants.ZERO_BYTES32, { from: proposer }), - 'TimelockController: operation cannot be cancelled', - ); - }); - - it('prevent non-proposer from canceling', async function () { - await expectRevert( - this.timelock.cancel(this.operation.id, { from: other }), - `AccessControl: account ${other.toLowerCase()} is missing role ${this.PROPOSER_ROLE}`, - ); - }); - }); - }); - - describe('maintenance', function () { - it('prevent unauthorized maintenance', async function () { - await expectRevert( - this.timelock.updateDelay(0, { from: other }), - 'TimelockController: caller must be timelock', - ); - }); - - it('timelock scheduled maintenance', async function () { - const newDelay = time.duration.hours(6); - const operation = genOperation( - this.timelock.address, - 0, - this.timelock.contract.methods.updateDelay(newDelay.toString()).encodeABI(), - ZERO_BYTES32, - '0xf8e775b2c5f4d66fb5c7fa800f35ef518c262b6014b3c0aee6ea21bff157f108', - ); - - await this.timelock.schedule( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - const receipt = await this.timelock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ); - expectEvent(receipt, 'MinDelayChange', { newDuration: newDelay.toString(), oldDuration: MINDELAY }); - - expect(await this.timelock.getMinDelay()).to.be.bignumber.equal(newDelay); - }); - }); - - describe('dependency', function () { - beforeEach(async function () { - this.operation1 = genOperation( - '0xdE66bD4c97304200A95aE0AadA32d6d01A867E39', - 0, - '0x01dc731a', - ZERO_BYTES32, - '0x64e932133c7677402ead2926f86205e2ca4686aebecf5a8077627092b9bb2feb', - ); - this.operation2 = genOperation( - '0x3c7944a3F1ee7fc8c5A5134ba7c79D11c3A1FCa3', - 0, - '0x8f531849', - this.operation1.id, - '0x036e1311cac523f9548e6461e29fb1f8f9196b91910a41711ea22f5de48df07d', - ); - await this.timelock.schedule( - this.operation1.target, - this.operation1.value, - this.operation1.data, - this.operation1.predecessor, - this.operation1.salt, - MINDELAY, - { from: proposer }, - ); - await this.timelock.schedule( - this.operation2.target, - this.operation2.value, - this.operation2.data, - this.operation2.predecessor, - this.operation2.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - }); - - it('cannot execute before dependency', async function () { - await expectRevert( - this.timelock.execute( - this.operation2.target, - this.operation2.value, - this.operation2.data, - this.operation2.predecessor, - this.operation2.salt, - { from: executor }, - ), - 'TimelockController: missing dependency', - ); - }); - - it('can execute after dependency', async function () { - await this.timelock.execute( - this.operation1.target, - this.operation1.value, - this.operation1.data, - this.operation1.predecessor, - this.operation1.salt, - { from: executor }, - ); - await this.timelock.execute( - this.operation2.target, - this.operation2.value, - this.operation2.data, - this.operation2.predecessor, - this.operation2.salt, - { from: executor }, - ); - }); - }); - - describe('usage scenario', function () { - this.timeout(10000); - - it('call', async function () { - const operation = genOperation( - this.implementation2.address, - 0, - this.implementation2.contract.methods.setValue(42).encodeABI(), - ZERO_BYTES32, - '0x8043596363daefc89977b25f9d9b4d06c3910959ef0c4d213557a903e1b555e2', - ); - - await this.timelock.schedule( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - await this.timelock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ); - - expect(await this.implementation2.getValue()).to.be.bignumber.equal(web3.utils.toBN(42)); - }); - - it('call reverting', async function () { - const operation = genOperation( - this.callreceivermock.address, - 0, - this.callreceivermock.contract.methods.mockFunctionRevertsNoReason().encodeABI(), - ZERO_BYTES32, - '0xb1b1b276fdf1a28d1e00537ea73b04d56639128b08063c1a2f70a52e38cba693', - ); - - await this.timelock.schedule( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - await expectRevert( - this.timelock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ), - 'TimelockController: underlying transaction reverted', - ); - }); - - it('call throw', async function () { - const operation = genOperation( - this.callreceivermock.address, - 0, - this.callreceivermock.contract.methods.mockFunctionThrows().encodeABI(), - ZERO_BYTES32, - '0xe5ca79f295fc8327ee8a765fe19afb58f4a0cbc5053642bfdd7e73bc68e0fc67', - ); - - await this.timelock.schedule( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - await expectRevert( - this.timelock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ), - 'TimelockController: underlying transaction reverted', - ); - }); - - it('call out of gas', async function () { - const operation = genOperation( - this.callreceivermock.address, - 0, - this.callreceivermock.contract.methods.mockFunctionOutOfGas().encodeABI(), - ZERO_BYTES32, - '0xf3274ce7c394c5b629d5215723563a744b817e1730cca5587c567099a14578fd', - ); - - await this.timelock.schedule( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - await expectRevert( - this.timelock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor, gas: '70000' }, - ), - 'TimelockController: underlying transaction reverted', - ); - }); - - it('call payable with eth', async function () { - const operation = genOperation( - this.callreceivermock.address, - 1, - this.callreceivermock.contract.methods.mockFunction().encodeABI(), - ZERO_BYTES32, - '0x5ab73cd33477dcd36c1e05e28362719d0ed59a7b9ff14939de63a43073dc1f44', - ); - - await this.timelock.schedule( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - - expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - - await this.timelock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor, value: 1 }, - ); - - expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(1)); - }); - - it('call nonpayable with eth', async function () { - const operation = genOperation( - this.callreceivermock.address, - 1, - this.callreceivermock.contract.methods.mockFunctionNonPayable().encodeABI(), - ZERO_BYTES32, - '0xb78edbd920c7867f187e5aa6294ae5a656cfbf0dea1ccdca3751b740d0f2bdf8', - ); - - await this.timelock.schedule( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - - expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - - await expectRevert( - this.timelock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ), - 'TimelockController: underlying transaction reverted', - ); - - expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - }); - - it('call reverting with eth', async function () { - const operation = genOperation( - this.callreceivermock.address, - 1, - this.callreceivermock.contract.methods.mockFunctionRevertsNoReason().encodeABI(), - ZERO_BYTES32, - '0xdedb4563ef0095db01d81d3f2decf57cf83e4a72aa792af14c43a792b56f4de6', - ); - - await this.timelock.schedule( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - MINDELAY, - { from: proposer }, - ); - await time.increase(MINDELAY); - - expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - - await expectRevert( - this.timelock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ), - 'TimelockController: underlying transaction reverted', - ); - - expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/compatibility/GovernorCompatibilityBravo.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/compatibility/GovernorCompatibilityBravo.test.js deleted file mode 100644 index e877a552..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/compatibility/GovernorCompatibilityBravo.test.js +++ /dev/null @@ -1,426 +0,0 @@ -const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const Enums = require('../../helpers/enums'); -const RLP = require('rlp'); - -const { - runGovernorWorkflow, -} = require('../GovernorWorkflow.behavior'); - -const Token = artifacts.require('ERC20VotesCompMock'); -const Timelock = artifacts.require('CompTimelock'); -const Governor = artifacts.require('GovernorCompatibilityBravoMock'); -const CallReceiver = artifacts.require('CallReceiverMock'); - -function makeContractAddress (creator, nonce) { - return web3.utils.toChecksumAddress(web3.utils.sha3(RLP.encode([creator, nonce])).slice(12).substring(14)); -} - -contract('GovernorCompatibilityBravo', function (accounts) { - const [ owner, proposer, voter1, voter2, voter3, voter4, other ] = accounts; - - const name = 'OZ-Governor'; - // const version = '1'; - const tokenName = 'MockToken'; - const tokenSymbol = 'MTKN'; - const tokenSupply = web3.utils.toWei('100'); - const proposalThreshold = web3.utils.toWei('10'); - - beforeEach(async function () { - const [ deployer ] = await web3.eth.getAccounts(); - - this.token = await Token.new(tokenName, tokenSymbol); - - // Need to predict governance address to set it as timelock admin with a delayed transfer - const nonce = await web3.eth.getTransactionCount(deployer); - const predictGovernor = makeContractAddress(deployer, nonce + 1); - - this.timelock = await Timelock.new(predictGovernor, 2 * 86400); - this.mock = await Governor.new(name, this.token.address, 4, 16, proposalThreshold, this.timelock.address); - this.receiver = await CallReceiver.new(); - await this.token.mint(owner, tokenSupply); - await this.token.delegate(voter1, { from: voter1 }); - await this.token.delegate(voter2, { from: voter2 }); - await this.token.delegate(voter3, { from: voter3 }); - await this.token.delegate(voter4, { from: voter4 }); - - await this.token.transfer(proposer, proposalThreshold, { from: owner }); - await this.token.delegate(proposer, { from: proposer }); - }); - - it('deployment check', async function () { - expect(await this.mock.name()).to.be.equal(name); - expect(await this.mock.token()).to.be.equal(this.token.address); - expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); - expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); - expect(await this.mock.quorumVotes()).to.be.bignumber.equal('0'); - expect(await this.mock.COUNTING_MODE()).to.be.equal('support=bravo&quorum=bravo'); - }); - - describe('nominal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], // targets - [ web3.utils.toWei('0') ], // values - [ this.receiver.contract.methods.mockFunction().encodeABI() ], // calldatas - '', // description - ], - proposer, - tokenHolder: owner, - voters: [ - { - voter: voter1, - weight: web3.utils.toWei('1'), - support: Enums.VoteType.Abstain, - }, - { - voter: voter2, - weight: web3.utils.toWei('10'), - support: Enums.VoteType.For, - }, - { - voter: voter3, - weight: web3.utils.toWei('5'), - support: Enums.VoteType.Against, - }, - { - voter: voter4, - support: '100', - error: 'GovernorCompatibilityBravo: invalid vote type', - }, - { - voter: voter1, - support: Enums.VoteType.For, - error: 'GovernorCompatibilityBravo: vote already cast', - skip: true, - }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - this.votingDelay = await this.mock.votingDelay(); - this.votingPeriod = await this.mock.votingPeriod(); - this.receipts = {}; - }); - afterEach(async function () { - const proposal = await this.mock.proposals(this.id); - expect(proposal.id).to.be.bignumber.equal(this.id); - expect(proposal.proposer).to.be.equal(proposer); - expect(proposal.eta).to.be.bignumber.equal(this.eta); - expect(proposal.startBlock).to.be.bignumber.equal(this.snapshot); - expect(proposal.endBlock).to.be.bignumber.equal(this.deadline); - expect(proposal.canceled).to.be.equal(false); - expect(proposal.executed).to.be.equal(true); - - for (const [key, value] of Object.entries(Enums.VoteType)) { - expect(proposal[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( - Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( - (acc, { weight }) => acc.add(new BN(weight)), - new BN('0'), - ), - ); - } - - const action = await this.mock.getActions(this.id); - expect(action.targets).to.be.deep.equal(this.settings.proposal[0]); - // expect(action.values).to.be.deep.equal(this.settings.proposal[1]); - expect(action.signatures).to.be.deep.equal(Array(this.settings.proposal[2].length).fill('')); - expect(action.calldatas).to.be.deep.equal(this.settings.proposal[2]); - - for (const voter of this.settings.voters.filter(({ skip }) => !skip)) { - expect(await this.mock.hasVoted(this.id, voter.voter)).to.be.equal(voter.error === undefined); - - const receipt = await this.mock.getReceipt(this.id, voter.voter); - expect(receipt.hasVoted).to.be.equal(voter.error === undefined); - expect(receipt.support).to.be.bignumber.equal(voter.error === undefined ? voter.support : '0'); - expect(receipt.votes).to.be.bignumber.equal(voter.error === undefined ? voter.weight : '0'); - } - - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { - proposalId: this.id, - proposer, - targets: this.settings.proposal[0], - // values: this.settings.proposal[1].map(value => new BN(value)), - signatures: this.settings.proposal[2].map(() => ''), - calldatas: this.settings.proposal[2], - startBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay), - endBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay).add(this.votingPeriod), - description: this.settings.proposal[3], - }, - ); - - this.receipts.castVote.filter(Boolean).forEach(vote => { - const { voter } = vote.logs.find(Boolean).args; - expectEvent( - vote, - 'VoteCast', - this.settings.voters.find(({ address }) => address === voter), - ); - }); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - }); - runGovernorWorkflow(); - }); - - describe('with function selector and arguments', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - Array(4).fill(this.receiver.address), - Array(4).fill(web3.utils.toWei('0')), - [ - '', - '', - 'mockFunctionNonPayable()', - 'mockFunctionWithArgs(uint256,uint256)', - ], - [ - this.receiver.contract.methods.mockFunction().encodeABI(), - this.receiver.contract.methods.mockFunctionWithArgs(17, 42).encodeABI(), - '0x', - web3.eth.abi.encodeParameters(['uint256', 'uint256'], [18, 43]), - ], - '', // description - ], - proposer, - tokenHolder: owner, - voters: [ - { - voter: voter1, - weight: web3.utils.toWei('10'), - support: Enums.VoteType.For, - }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - }); - runGovernorWorkflow(); - afterEach(async function () { - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalledWithArgs', - { a: '17', b: '42' }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalledWithArgs', - { a: '18', b: '43' }, - ); - }); - }); - - describe('proposalThreshold not reached', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], // targets - [ web3.utils.toWei('0') ], // values - [ this.receiver.contract.methods.mockFunction().encodeABI() ], // calldatas - '', // description - ], - proposer: other, - steps: { - propose: { error: 'GovernorCompatibilityBravo: proposer votes below proposal threshold' }, - wait: { enable: false }, - queue: { enable: false }, - execute: { enable: false }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('cancel', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], // targets - [ web3.utils.toWei('0') ], // values - [ this.receiver.contract.methods.mockFunction().encodeABI() ], // calldatas - '', // description - ], - proposer, - tokenHolder: owner, - steps: { - wait: { enable: false }, - queue: { enable: false }, - execute: { enable: false }, - }, - }; - }); - - describe('by proposer', function () { - afterEach(async function () { - await this.mock.cancel(this.id, { from: proposer }); - }); - runGovernorWorkflow(); - }); - - describe('if proposer below threshold', function () { - afterEach(async function () { - await this.token.transfer(voter1, web3.utils.toWei('1'), { from: proposer }); - await this.mock.cancel(this.id); - }); - runGovernorWorkflow(); - }); - - describe('not if proposer above threshold', function () { - afterEach(async function () { - await expectRevert( - this.mock.cancel(this.id), - 'GovernorBravo: proposer above threshold', - ); - }); - runGovernorWorkflow(); - }); - }); - - describe('with compatibility interface', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], // targets - [ web3.utils.toWei('0') ], // values - [ 'mockFunction()' ], // signatures - [ '0x' ], // calldatas - '', // description - ], - proposer, - tokenHolder: owner, - voters: [ - { - voter: voter1, - weight: web3.utils.toWei('1'), - support: Enums.VoteType.Abstain, - }, - { - voter: voter2, - weight: web3.utils.toWei('10'), - support: Enums.VoteType.For, - }, - { - voter: voter3, - weight: web3.utils.toWei('5'), - support: Enums.VoteType.Against, - }, - { - voter: voter4, - support: '100', - error: 'GovernorCompatibilityBravo: invalid vote type', - }, - { - voter: voter1, - support: Enums.VoteType.For, - error: 'GovernorCompatibilityBravo: vote already cast', - skip: true, - }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - this.votingDelay = await this.mock.votingDelay(); - this.votingPeriod = await this.mock.votingPeriod(); - this.receipts = {}; - }); - - afterEach(async function () { - const proposal = await this.mock.proposals(this.id); - expect(proposal.id).to.be.bignumber.equal(this.id); - expect(proposal.proposer).to.be.equal(proposer); - expect(proposal.eta).to.be.bignumber.equal(this.eta); - expect(proposal.startBlock).to.be.bignumber.equal(this.snapshot); - expect(proposal.endBlock).to.be.bignumber.equal(this.deadline); - expect(proposal.canceled).to.be.equal(false); - expect(proposal.executed).to.be.equal(true); - - for (const [key, value] of Object.entries(Enums.VoteType)) { - expect(proposal[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( - Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( - (acc, { weight }) => acc.add(new BN(weight)), - new BN('0'), - ), - ); - } - - const action = await this.mock.getActions(this.id); - expect(action.targets).to.be.deep.equal(this.settings.proposal[0]); - // expect(action.values).to.be.deep.equal(this.settings.proposal[1]); - expect(action.signatures).to.be.deep.equal(this.settings.proposal[2]); - expect(action.calldatas).to.be.deep.equal(this.settings.proposal[3]); - - for (const voter of this.settings.voters.filter(({ skip }) => !skip)) { - expect(await this.mock.hasVoted(this.id, voter.voter)).to.be.equal(voter.error === undefined); - - const receipt = await this.mock.getReceipt(this.id, voter.voter); - expect(receipt.hasVoted).to.be.equal(voter.error === undefined); - expect(receipt.support).to.be.bignumber.equal(voter.error === undefined ? voter.support : '0'); - expect(receipt.votes).to.be.bignumber.equal(voter.error === undefined ? voter.weight : '0'); - } - - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { - proposalId: this.id, - proposer, - targets: this.settings.proposal[0], - // values: this.settings.proposal[1].map(value => new BN(value)), - signatures: this.settings.proposal[2].map(_ => ''), - calldatas: this.settings.shortProposal[2], - startBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay), - endBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay).add(this.votingPeriod), - description: this.settings.proposal[4], - }, - ); - - this.receipts.castVote.filter(Boolean).forEach(vote => { - const { voter } = vote.logs.find(Boolean).args; - expectEvent( - vote, - 'VoteCast', - this.settings.voters.find(({ address }) => address === voter), - ); - }); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - }); - runGovernorWorkflow(); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorComp.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorComp.test.js deleted file mode 100644 index 78cf1e93..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorComp.test.js +++ /dev/null @@ -1,87 +0,0 @@ -const { BN, expectEvent } = require('@openzeppelin/test-helpers'); -const Enums = require('../../helpers/enums'); - -const { - runGovernorWorkflow, -} = require('./../GovernorWorkflow.behavior'); - -const Token = artifacts.require('ERC20VotesCompMock'); -const Governor = artifacts.require('GovernorCompMock'); -const CallReceiver = artifacts.require('CallReceiverMock'); - -contract('GovernorComp', function (accounts) { - const [ owner, voter1, voter2, voter3, voter4 ] = accounts; - - const name = 'OZ-Governor'; - // const version = '1'; - const tokenName = 'MockToken'; - const tokenSymbol = 'MTKN'; - const tokenSupply = web3.utils.toWei('100'); - - beforeEach(async function () { - this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); - this.mock = await Governor.new(name, this.token.address); - this.receiver = await CallReceiver.new(); - await this.token.mint(owner, tokenSupply); - await this.token.delegate(voter1, { from: voter1 }); - await this.token.delegate(voter2, { from: voter2 }); - await this.token.delegate(voter3, { from: voter3 }); - await this.token.delegate(voter4, { from: voter4 }); - }); - - it('deployment check', async function () { - expect(await this.mock.name()).to.be.equal(name); - expect(await this.mock.token()).to.be.equal(this.token.address); - expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); - expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); - }); - - describe('voting with comp token', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For }, - { voter: voter2, weight: web3.utils.toWei('10'), support: Enums.VoteType.For }, - { voter: voter3, weight: web3.utils.toWei('5'), support: Enums.VoteType.Against }, - { voter: voter4, weight: web3.utils.toWei('2'), support: Enums.VoteType.Abstain }, - ], - }; - }); - afterEach(async function () { - expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false); - expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(true); - expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(true); - expect(await this.mock.hasVoted(this.id, voter3)).to.be.equal(true); - expect(await this.mock.hasVoted(this.id, voter4)).to.be.equal(true); - - this.receipts.castVote.filter(Boolean).forEach(vote => { - const { voter } = vote.logs.find(Boolean).args; - expectEvent( - vote, - 'VoteCast', - this.settings.voters.find(({ address }) => address === voter), - ); - }); - await this.mock.proposalVotes(this.id).then(result => { - for (const [key, value] of Object.entries(Enums.VoteType)) { - expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( - Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( - (acc, { weight }) => acc.add(new BN(weight)), - new BN('0'), - ), - ); - } - }); - }); - runGovernorWorkflow(); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorERC721.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorERC721.test.js deleted file mode 100644 index 3f89c02b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorERC721.test.js +++ /dev/null @@ -1,118 +0,0 @@ -const { expectEvent } = require('@openzeppelin/test-helpers'); -const { BN } = require('bn.js'); -const Enums = require('../../helpers/enums'); - -const { - runGovernorWorkflow, -} = require('./../GovernorWorkflow.behavior'); - -const Token = artifacts.require('ERC721VotesMock'); -const Governor = artifacts.require('GovernorVoteMocks'); -const CallReceiver = artifacts.require('CallReceiverMock'); - -contract('GovernorERC721Mock', function (accounts) { - const [ owner, voter1, voter2, voter3, voter4 ] = accounts; - - const name = 'OZ-Governor'; - const tokenName = 'MockNFToken'; - const tokenSymbol = 'MTKN'; - const NFT0 = web3.utils.toWei('100'); - const NFT1 = web3.utils.toWei('10'); - const NFT2 = web3.utils.toWei('20'); - const NFT3 = web3.utils.toWei('30'); - const NFT4 = web3.utils.toWei('40'); - - // Must be the same as in contract - const ProposalState = { - Pending: new BN('0'), - Active: new BN('1'), - Canceled: new BN('2'), - Defeated: new BN('3'), - Succeeded: new BN('4'), - Queued: new BN('5'), - Expired: new BN('6'), - Executed: new BN('7'), - }; - - beforeEach(async function () { - this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); - this.mock = await Governor.new(name, this.token.address); - this.receiver = await CallReceiver.new(); - await this.token.mint(owner, NFT0); - await this.token.mint(owner, NFT1); - await this.token.mint(owner, NFT2); - await this.token.mint(owner, NFT3); - await this.token.mint(owner, NFT4); - - await this.token.delegate(voter1, { from: voter1 }); - await this.token.delegate(voter2, { from: voter2 }); - await this.token.delegate(voter3, { from: voter3 }); - await this.token.delegate(voter4, { from: voter4 }); - }); - - it('deployment check', async function () { - expect(await this.mock.name()).to.be.equal(name); - expect(await this.mock.token()).to.be.equal(this.token.address); - expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); - expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); - }); - - describe('voting with ERC721 token', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, nfts: [NFT0], support: Enums.VoteType.For }, - { voter: voter2, nfts: [NFT1, NFT2], support: Enums.VoteType.For }, - { voter: voter3, nfts: [NFT3], support: Enums.VoteType.Against }, - { voter: voter4, nfts: [NFT4], support: Enums.VoteType.Abstain }, - ], - }; - }); - - afterEach(async function () { - expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false); - - for (const vote of this.receipts.castVote.filter(Boolean)) { - const { voter } = vote.logs.find(Boolean).args; - - expect(await this.mock.hasVoted(this.id, voter)).to.be.equal(true); - - expectEvent( - vote, - 'VoteCast', - this.settings.voters.find(({ address }) => address === voter), - ); - - if (voter === voter2) { - expect(await this.token.getVotes(voter, vote.blockNumber)).to.be.bignumber.equal('2'); - } else { - expect(await this.token.getVotes(voter, vote.blockNumber)).to.be.bignumber.equal('1'); - } - } - - await this.mock.proposalVotes(this.id).then(result => { - for (const [key, value] of Object.entries(Enums.VoteType)) { - expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( - Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( - (acc, { nfts }) => acc.add(new BN(nfts.length)), - new BN('0'), - ), - ); - } - }); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(ProposalState.Executed); - }); - - runGovernorWorkflow(); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorPreventLateQuorum.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorPreventLateQuorum.test.js deleted file mode 100644 index e4ae5c17..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorPreventLateQuorum.test.js +++ /dev/null @@ -1,247 +0,0 @@ -const { BN, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); -const Enums = require('../../helpers/enums'); - -const { - runGovernorWorkflow, -} = require('../GovernorWorkflow.behavior'); - -const Token = artifacts.require('ERC20VotesCompMock'); -const Governor = artifacts.require('GovernorPreventLateQuorumMock'); -const CallReceiver = artifacts.require('CallReceiverMock'); - -contract('GovernorPreventLateQuorum', function (accounts) { - const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts; - - const name = 'OZ-Governor'; - // const version = '1'; - const tokenName = 'MockToken'; - const tokenSymbol = 'MTKN'; - const tokenSupply = web3.utils.toWei('100'); - const votingDelay = new BN(4); - const votingPeriod = new BN(16); - const lateQuorumVoteExtension = new BN(8); - const quorum = web3.utils.toWei('1'); - - beforeEach(async function () { - this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); - this.mock = await Governor.new( - name, - this.token.address, - votingDelay, - votingPeriod, - quorum, - lateQuorumVoteExtension, - ); - this.receiver = await CallReceiver.new(); - await this.token.mint(owner, tokenSupply); - await this.token.delegate(voter1, { from: voter1 }); - await this.token.delegate(voter2, { from: voter2 }); - await this.token.delegate(voter3, { from: voter3 }); - await this.token.delegate(voter4, { from: voter4 }); - }); - - it('deployment check', async function () { - expect(await this.mock.name()).to.be.equal(name); - expect(await this.mock.token()).to.be.equal(this.token.address); - expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay); - expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod); - expect(await this.mock.quorum(0)).to.be.bignumber.equal(quorum); - expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal(lateQuorumVoteExtension); - }); - - describe('nominal is unaffected', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ 0 ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - proposer, - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For, reason: 'This is nice' }, - { voter: voter2, weight: web3.utils.toWei('7'), support: Enums.VoteType.For }, - { voter: voter3, weight: web3.utils.toWei('5'), support: Enums.VoteType.Against }, - { voter: voter4, weight: web3.utils.toWei('2'), support: Enums.VoteType.Abstain }, - ], - }; - }); - - afterEach(async function () { - expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false); - expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(true); - expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(true); - - await this.mock.proposalVotes(this.id).then(result => { - for (const [key, value] of Object.entries(Enums.VoteType)) { - expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( - Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( - (acc, { weight }) => acc.add(new BN(weight)), - new BN('0'), - ), - ); - } - }); - - const startBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay); - const endBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay).add(votingPeriod); - expect(await this.mock.proposalSnapshot(this.id)).to.be.bignumber.equal(startBlock); - expect(await this.mock.proposalDeadline(this.id)).to.be.bignumber.equal(endBlock); - - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { - proposalId: this.id, - proposer, - targets: this.settings.proposal[0], - // values: this.settings.proposal[1].map(value => new BN(value)), - signatures: this.settings.proposal[2].map(() => ''), - calldatas: this.settings.proposal[2], - startBlock, - endBlock, - description: this.settings.proposal[3], - }, - ); - - this.receipts.castVote.filter(Boolean).forEach(vote => { - const { voter } = vote.logs.find(Boolean).args; - expectEvent( - vote, - 'VoteCast', - this.settings.voters.find(({ address }) => address === voter), - ); - expectEvent.notEmitted( - vote, - 'ProposalExtended', - ); - }); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - }); - runGovernorWorkflow(); - }); - - describe('Delay is extended to prevent last minute take-over', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ 0 ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - proposer, - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('0.2'), support: Enums.VoteType.Against }, - { voter: voter2, weight: web3.utils.toWei('1.0') }, // do not actually vote, only getting tokens - { voter: voter3, weight: web3.utils.toWei('0.9') }, // do not actually vote, only getting tokens - ], - steps: { - wait: { enable: false }, - execute: { enable: false }, - }, - }; - }); - - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active); - - const startBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay); - const endBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay).add(votingPeriod); - expect(await this.mock.proposalSnapshot(this.id)).to.be.bignumber.equal(startBlock); - expect(await this.mock.proposalDeadline(this.id)).to.be.bignumber.equal(endBlock); - - // wait until the vote is almost over - await time.advanceBlockTo(endBlock.subn(1)); - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active); - - // try to overtake the vote at the last minute - const tx = await this.mock.castVote(this.id, Enums.VoteType.For, { from: voter2 }); - - // vote duration is extended - const extendedBlock = new BN(tx.receipt.blockNumber).add(lateQuorumVoteExtension); - expect(await this.mock.proposalDeadline(this.id)).to.be.bignumber.equal(extendedBlock); - - expectEvent( - tx, - 'ProposalExtended', - { proposalId: this.id, extendedDeadline: extendedBlock }, - ); - - // vote is still active after expected end - await time.advanceBlockTo(endBlock.addn(1)); - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active); - - // Still possible to vote - await this.mock.castVote(this.id, Enums.VoteType.Against, { from: voter3 }); - - // proposal fails - await time.advanceBlockTo(extendedBlock.addn(1)); - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated); - }); - runGovernorWorkflow(); - }); - - describe('setLateQuorumVoteExtension', function () { - beforeEach(async function () { - this.newVoteExtension = new BN(0); // disable voting delay extension - }); - - it('protected', async function () { - await expectRevert( - this.mock.setLateQuorumVoteExtension(this.newVoteExtension), - 'Governor: onlyGovernance', - ); - }); - - describe('using workflow', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.mock.address ], - [ web3.utils.toWei('0') ], - [ this.mock.contract.methods.setLateQuorumVoteExtension(this.newVoteExtension).encodeABI() ], - '', - ], - proposer, - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('1.0'), support: Enums.VoteType.For }, - ], - }; - }); - afterEach(async function () { - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'LateQuorumVoteExtensionSet', - { oldVoteExtension: lateQuorumVoteExtension, newVoteExtension: this.newVoteExtension }, - ); - expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal(this.newVoteExtension); - }); - runGovernorWorkflow(); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorTimelockCompound.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorTimelockCompound.test.js deleted file mode 100644 index bc4f15c9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorTimelockCompound.test.js +++ /dev/null @@ -1,487 +0,0 @@ -const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const Enums = require('../../helpers/enums'); -const RLP = require('rlp'); - -const { - runGovernorWorkflow, -} = require('../GovernorWorkflow.behavior'); - -const { - shouldSupportInterfaces, -} = require('../../utils/introspection/SupportsInterface.behavior'); - -const Token = artifacts.require('ERC20VotesMock'); -const Timelock = artifacts.require('CompTimelock'); -const Governor = artifacts.require('GovernorTimelockCompoundMock'); -const CallReceiver = artifacts.require('CallReceiverMock'); - -function makeContractAddress (creator, nonce) { - return web3.utils.toChecksumAddress(web3.utils.sha3(RLP.encode([creator, nonce])).slice(12).substring(14)); -} - -contract('GovernorTimelockCompound', function (accounts) { - const [ admin, voter, other ] = accounts; - - const name = 'OZ-Governor'; - // const version = '1'; - const tokenName = 'MockToken'; - const tokenSymbol = 'MTKN'; - const tokenSupply = web3.utils.toWei('100'); - - beforeEach(async function () { - const [ deployer ] = await web3.eth.getAccounts(); - - this.token = await Token.new(tokenName, tokenSymbol); - - // Need to predict governance address to set it as timelock admin with a delayed transfer - const nonce = await web3.eth.getTransactionCount(deployer); - const predictGovernor = makeContractAddress(deployer, nonce + 1); - - this.timelock = await Timelock.new(predictGovernor, 2 * 86400); - this.mock = await Governor.new(name, this.token.address, 4, 16, this.timelock.address, 0); - this.receiver = await CallReceiver.new(); - await this.token.mint(voter, tokenSupply); - await this.token.delegate(voter, { from: voter }); - }); - - shouldSupportInterfaces([ - 'ERC165', - 'Governor', - 'GovernorTimelock', - ]); - - it('doesn\'t accept ether transfers', async function () { - await expectRevert.unspecified(web3.eth.sendTransaction({ from: voter, to: this.mock.address, value: 1 })); - }); - - it('post deployment check', async function () { - expect(await this.mock.name()).to.be.equal(name); - expect(await this.mock.token()).to.be.equal(this.token.address); - expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); - expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); - - expect(await this.mock.timelock()).to.be.equal(this.timelock.address); - expect(await this.timelock.admin()).to.be.equal(this.mock.address); - }); - - describe('nominal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - }); - afterEach(async function () { - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.queue, - 'ProposalQueued', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.queue.transactionHash, - this.timelock, - 'QueueTransaction', - { eta: this.eta }, - ); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.timelock, - 'ExecuteTransaction', - { eta: this.eta }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - }); - runGovernorWorkflow(); - }); - - describe('not queued', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { enable: false }, - execute: { error: 'GovernorTimelockCompound: proposal not yet queued' }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded); - }); - runGovernorWorkflow(); - }); - - describe('to early', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - execute: { error: 'Timelock::executeTransaction: Transaction hasn\'t surpassed time lock' }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued); - }); - runGovernorWorkflow(); - }); - - describe('to late', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 30 * 86400 }, - execute: { error: 'Governor: proposal not successful' }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Expired); - }); - runGovernorWorkflow(); - }); - - describe('deplicated underlying call', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - Array(2).fill(this.token.address), - Array(2).fill(web3.utils.toWei('0')), - Array(2).fill(this.token.contract.methods.approve(this.receiver.address, constants.MAX_UINT256).encodeABI()), - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { - error: 'GovernorTimelockCompound: identical proposal action already queued', - }, - execute: { - error: 'GovernorTimelockCompound: proposal not yet queued', - }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('re-queue / re-execute', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Executed); - - await expectRevert( - this.mock.queue(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - await expectRevert( - this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('cancel before queue prevents scheduling', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { enable: false }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded); - - expectEvent( - await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'ProposalCanceled', - { proposalId: this.id }, - ); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); - - await expectRevert( - this.mock.queue(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('cancel after queue prevents executing', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 7 * 86400 }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued); - - const receipt = await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash); - expectEvent( - receipt, - 'ProposalCanceled', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - receipt.receipt.transactionHash, - this.timelock, - 'CancelTransaction', - ); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); - - await expectRevert( - this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('relay', function () { - beforeEach(async function () { - await this.token.mint(this.mock.address, 1); - this.call = [ - this.token.address, - 0, - this.token.contract.methods.transfer(other, 1).encodeABI(), - ]; - }); - - it('protected', async function () { - await expectRevert( - this.mock.relay(...this.call), - 'Governor: onlyGovernance', - ); - }); - - describe('using workflow', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ - this.mock.address, - ], - [ - web3.utils.toWei('0'), - ], - [ - this.mock.contract.methods.relay(...this.call).encodeABI(), - ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - - expect(await this.token.balanceOf(this.mock.address), 1); - expect(await this.token.balanceOf(other), 0); - }); - afterEach(async function () { - expect(await this.token.balanceOf(this.mock.address), 0); - expect(await this.token.balanceOf(other), 1); - }); - runGovernorWorkflow(); - }); - }); - - describe('updateTimelock', function () { - beforeEach(async function () { - this.newTimelock = await Timelock.new(this.mock.address, 7 * 86400); - }); - - it('protected', async function () { - await expectRevert( - this.mock.updateTimelock(this.newTimelock.address), - 'Governor: onlyGovernance', - ); - }); - - describe('using workflow', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ - this.timelock.address, - this.mock.address, - ], - [ - web3.utils.toWei('0'), - web3.utils.toWei('0'), - ], - [ - this.timelock.contract.methods.setPendingAdmin(admin).encodeABI(), - this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(), - ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - }); - afterEach(async function () { - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'TimelockChange', - { oldTimelock: this.timelock.address, newTimelock: this.newTimelock.address }, - ); - expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address); - }); - runGovernorWorkflow(); - }); - }); - - describe('transfer timelock to new governor', function () { - beforeEach(async function () { - this.newGovernor = await Governor.new(name, this.token.address, 8, 32, this.timelock.address, 0); - }); - - describe('using workflow', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.timelock.address ], - [ web3.utils.toWei('0') ], - [ this.timelock.contract.methods.setPendingAdmin(this.newGovernor.address).encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - }); - afterEach(async function () { - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.timelock, - 'NewPendingAdmin', - { newPendingAdmin: this.newGovernor.address }, - ); - await this.newGovernor.__acceptAdmin(); - expect(await this.timelock.admin()).to.be.bignumber.equal(this.newGovernor.address); - }); - runGovernorWorkflow(); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorTimelockControl.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorTimelockControl.test.js deleted file mode 100644 index 35242740..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorTimelockControl.test.js +++ /dev/null @@ -1,464 +0,0 @@ -const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const Enums = require('../../helpers/enums'); - -const { - runGovernorWorkflow, -} = require('../GovernorWorkflow.behavior'); - -const { - shouldSupportInterfaces, -} = require('../../utils/introspection/SupportsInterface.behavior'); - -const Token = artifacts.require('ERC20VotesMock'); -const Timelock = artifacts.require('TimelockController'); -const Governor = artifacts.require('GovernorTimelockControlMock'); -const CallReceiver = artifacts.require('CallReceiverMock'); - -contract('GovernorTimelockControl', function (accounts) { - const [ admin, voter, other ] = accounts; - - const name = 'OZ-Governor'; - // const version = '1'; - const tokenName = 'MockToken'; - const tokenSymbol = 'MTKN'; - const tokenSupply = web3.utils.toWei('100'); - - beforeEach(async function () { - const [ deployer ] = await web3.eth.getAccounts(); - - this.token = await Token.new(tokenName, tokenSymbol); - this.timelock = await Timelock.new(3600, [], []); - this.mock = await Governor.new(name, this.token.address, 4, 16, this.timelock.address, 0); - this.receiver = await CallReceiver.new(); - // normal setup: governor is proposer, everyone is executor, timelock is its own admin - await this.timelock.grantRole(await this.timelock.PROPOSER_ROLE(), this.mock.address); - await this.timelock.grantRole(await this.timelock.PROPOSER_ROLE(), admin); - await this.timelock.grantRole(await this.timelock.EXECUTOR_ROLE(), constants.ZERO_ADDRESS); - await this.timelock.revokeRole(await this.timelock.TIMELOCK_ADMIN_ROLE(), deployer); - await this.token.mint(voter, tokenSupply); - await this.token.delegate(voter, { from: voter }); - }); - - shouldSupportInterfaces([ - 'ERC165', - 'Governor', - 'GovernorTimelock', - ]); - - it('doesn\'t accept ether transfers', async function () { - await expectRevert.unspecified(web3.eth.sendTransaction({ from: voter, to: this.mock.address, value: 1 })); - }); - - it('post deployment check', async function () { - expect(await this.mock.name()).to.be.equal(name); - expect(await this.mock.token()).to.be.equal(this.token.address); - expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); - expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); - - expect(await this.mock.timelock()).to.be.equal(this.timelock.address); - }); - - describe('nominal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 3600 }, - }, - }; - }); - afterEach(async function () { - const timelockid = await this.timelock.hashOperationBatch( - ...this.settings.proposal.slice(0, 3), - '0x0', - this.descriptionHash, - ); - - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.queue, - 'ProposalQueued', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.queue.transactionHash, - this.timelock, - 'CallScheduled', - { id: timelockid }, - ); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.timelock, - 'CallExecuted', - { id: timelockid }, - ); - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.receiver, - 'MockFunctionCalled', - ); - }); - runGovernorWorkflow(); - }); - - describe('executed by other proposer', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 3600 }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - await this.timelock.executeBatch( - ...this.settings.proposal.slice(0, 3), - '0x0', - this.descriptionHash, - ); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Executed); - - await expectRevert( - this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('not queued', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { enable: false }, - execute: { error: 'TimelockController: operation is not ready' }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded); - }); - runGovernorWorkflow(); - }); - - describe('to early', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - execute: { error: 'TimelockController: operation is not ready' }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued); - }); - runGovernorWorkflow(); - }); - - describe('re-queue / re-execute', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 3600 }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Executed); - - await expectRevert( - this.mock.queue(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - await expectRevert( - this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('cancel before queue prevents scheduling', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { enable: false }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded); - - expectEvent( - await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'ProposalCanceled', - { proposalId: this.id }, - ); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); - - await expectRevert( - this.mock.queue(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('cancel after queue prevents execution', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 3600 }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - const timelockid = await this.timelock.hashOperationBatch( - ...this.settings.proposal.slice(0, 3), - '0x0', - this.descriptionHash, - ); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued); - - const receipt = await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash); - expectEvent( - receipt, - 'ProposalCanceled', - { proposalId: this.id }, - ); - await expectEvent.inTransaction( - receipt.receipt.transactionHash, - this.timelock, - 'Cancelled', - { id: timelockid }, - ); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); - - await expectRevert( - this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), - 'Governor: proposal not successful', - ); - }); - runGovernorWorkflow(); - }); - - describe('relay', function () { - beforeEach(async function () { - await this.token.mint(this.mock.address, 1); - this.call = [ - this.token.address, - 0, - this.token.contract.methods.transfer(other, 1).encodeABI(), - ]; - }); - - it('protected', async function () { - await expectRevert( - this.mock.relay(...this.call), - 'Governor: onlyGovernance', - ); - }); - - describe('using workflow', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ - this.mock.address, - ], - [ - web3.utils.toWei('0'), - ], - [ - this.mock.contract.methods.relay(...this.call).encodeABI(), - ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 7 * 86400 }, - }, - }; - - expect(await this.token.balanceOf(this.mock.address), 1); - expect(await this.token.balanceOf(other), 0); - }); - afterEach(async function () { - expect(await this.token.balanceOf(this.mock.address), 0); - expect(await this.token.balanceOf(other), 1); - }); - runGovernorWorkflow(); - }); - }); - - describe('cancel on timelock is forwarded in state', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 3600 }, - execute: { enable: false }, - }, - }; - }); - afterEach(async function () { - const timelockid = await this.timelock.hashOperationBatch( - ...this.settings.proposal.slice(0, 3), - '0x0', - this.descriptionHash, - ); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued); - - const receipt = await this.timelock.cancel(timelockid, { from: admin }); - expectEvent( - receipt, - 'Cancelled', - { id: timelockid }, - ); - - expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); - }); - runGovernorWorkflow(); - }); - - describe('updateTimelock', function () { - beforeEach(async function () { - this.newTimelock = await Timelock.new(3600, [], []); - }); - - it('protected', async function () { - await expectRevert( - this.mock.updateTimelock(this.newTimelock.address), - 'Governor: onlyGovernance', - ); - }); - - describe('using workflow', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.mock.address ], - [ web3.utils.toWei('0') ], - [ this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI() ], - '', - ], - voters: [ - { voter: voter, support: Enums.VoteType.For }, - ], - steps: { - queue: { delay: 3600 }, - }, - }; - }); - afterEach(async function () { - expectEvent( - this.receipts.propose, - 'ProposalCreated', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'ProposalExecuted', - { proposalId: this.id }, - ); - expectEvent( - this.receipts.execute, - 'TimelockChange', - { oldTimelock: this.timelock.address, newTimelock: this.newTimelock.address }, - ); - expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address); - }); - runGovernorWorkflow(); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorWeightQuorumFraction.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorWeightQuorumFraction.test.js deleted file mode 100644 index 4d3f90da..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/extensions/GovernorWeightQuorumFraction.test.js +++ /dev/null @@ -1,122 +0,0 @@ -const { BN, expectEvent, time } = require('@openzeppelin/test-helpers'); -const Enums = require('../../helpers/enums'); - -const { - runGovernorWorkflow, -} = require('./../GovernorWorkflow.behavior'); - -const Token = artifacts.require('ERC20VotesMock'); -const Governor = artifacts.require('GovernorMock'); -const CallReceiver = artifacts.require('CallReceiverMock'); - -contract('GovernorVotesQuorumFraction', function (accounts) { - const [ owner, voter1, voter2, voter3, voter4 ] = accounts; - - const name = 'OZ-Governor'; - // const version = '1'; - const tokenName = 'MockToken'; - const tokenSymbol = 'MTKN'; - const tokenSupply = new BN(web3.utils.toWei('100')); - const ratio = new BN(8); // percents - const newRatio = new BN(6); // percents - - beforeEach(async function () { - this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); - this.mock = await Governor.new(name, this.token.address, 4, 16, ratio); - this.receiver = await CallReceiver.new(); - await this.token.mint(owner, tokenSupply); - await this.token.delegate(voter1, { from: voter1 }); - await this.token.delegate(voter2, { from: voter2 }); - await this.token.delegate(voter3, { from: voter3 }); - await this.token.delegate(voter4, { from: voter4 }); - }); - - it('deployment check', async function () { - expect(await this.mock.name()).to.be.equal(name); - expect(await this.mock.token()).to.be.equal(this.token.address); - expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); - expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); - expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); - expect(await this.mock.quorumNumerator()).to.be.bignumber.equal(ratio); - expect(await this.mock.quorumDenominator()).to.be.bignumber.equal('100'); - expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))) - .to.be.bignumber.equal(tokenSupply.mul(ratio).divn(100)); - }); - - describe('quroum not reached', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.receiver.address ], - [ web3.utils.toWei('0') ], - [ this.receiver.contract.methods.mockFunction().encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For }, - ], - steps: { - execute: { error: 'Governor: proposal not successful' }, - }, - }; - }); - runGovernorWorkflow(); - }); - - describe('update quorum ratio through proposal', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.mock.address ], - [ web3.utils.toWei('0') ], - [ this.mock.contract.methods.updateQuorumNumerator(newRatio).encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: tokenSupply, support: Enums.VoteType.For }, - ], - }; - }); - afterEach(async function () { - await expectEvent.inTransaction( - this.receipts.execute.transactionHash, - this.mock, - 'QuorumNumeratorUpdated', - { - oldQuorumNumerator: ratio, - newQuorumNumerator: newRatio, - }, - ); - - expect(await this.mock.quorumNumerator()).to.be.bignumber.equal(newRatio); - expect(await this.mock.quorumDenominator()).to.be.bignumber.equal('100'); - expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))) - .to.be.bignumber.equal(tokenSupply.mul(newRatio).divn(100)); - }); - runGovernorWorkflow(); - }); - - describe('update quorum over the maximum', function () { - beforeEach(async function () { - this.settings = { - proposal: [ - [ this.mock.address ], - [ web3.utils.toWei('0') ], - [ this.mock.contract.methods.updateQuorumNumerator(new BN(101)).encodeABI() ], - '', - ], - tokenHolder: owner, - voters: [ - { voter: voter1, weight: tokenSupply, support: Enums.VoteType.For }, - ], - steps: { - execute: { error: 'GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator' }, - }, - }; - }); - runGovernorWorkflow(); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/utils/Votes.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/utils/Votes.behavior.js deleted file mode 100644 index 17b49eaa..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/utils/Votes.behavior.js +++ /dev/null @@ -1,344 +0,0 @@ -const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); - -const { MAX_UINT256, ZERO_ADDRESS } = constants; - -const { fromRpcSig } = require('ethereumjs-util'); -const ethSigUtil = require('eth-sig-util'); -const Wallet = require('ethereumjs-wallet').default; - -const { EIP712Domain, domainSeparator } = require('../../helpers/eip712'); - -const Delegation = [ - { name: 'delegatee', type: 'address' }, - { name: 'nonce', type: 'uint256' }, - { name: 'expiry', type: 'uint256' }, -]; - -const version = '1'; - -function shouldBehaveLikeVotes () { - describe('run votes workflow', function () { - it('initial nonce is 0', async function () { - expect(await this.votes.nonces(this.account1)).to.be.bignumber.equal('0'); - }); - - it('domain separator', async function () { - expect( - await this.votes.DOMAIN_SEPARATOR(), - ).to.equal( - await domainSeparator(this.name, version, this.chainId, this.votes.address), - ); - }); - - describe('delegation with signature', function () { - const delegator = Wallet.generate(); - const delegatorAddress = web3.utils.toChecksumAddress(delegator.getAddressString()); - const nonce = 0; - - const buildData = (chainId, verifyingContract, name, message) => ({ - data: { - primaryType: 'Delegation', - types: { EIP712Domain, Delegation }, - domain: { name, version, chainId, verifyingContract }, - message, - }, - }); - - beforeEach(async function () { - await this.votes.mint(delegatorAddress, this.NFT0); - }); - - it('accept signed delegation', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - expect(await this.votes.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); - expectEvent(receipt, 'DelegateChanged', { - delegator: delegatorAddress, - fromDelegate: ZERO_ADDRESS, - toDelegate: delegatorAddress, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: delegatorAddress, - previousBalance: '0', - newBalance: '1', - }); - - expect(await this.votes.delegates(delegatorAddress)).to.be.equal(delegatorAddress); - - expect(await this.votes.getVotes(delegatorAddress)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastVotes(delegatorAddress, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.votes.getPastVotes(delegatorAddress, receipt.blockNumber)).to.be.bignumber.equal('1'); - }); - - it('rejects reused signature', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - await this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); - - await expectRevert( - this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s), - 'Votes: invalid nonce', - ); - }); - - it('rejects bad delegatee', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - const { logs } = await this.votes.delegateBySig(this.account1Delegatee, nonce, MAX_UINT256, v, r, s); - const { args } = logs.find(({ event }) => event === 'DelegateChanged'); - expect(args.delegator).to.not.be.equal(delegatorAddress); - expect(args.fromDelegate).to.be.equal(ZERO_ADDRESS); - expect(args.toDelegate).to.be.equal(this.account1Delegatee); - }); - - it('rejects bad nonce', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - await expectRevert( - this.votes.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s), - 'Votes: invalid nonce', - ); - }); - - it('rejects expired permit', async function () { - const expiry = (await time.latest()) - time.duration.weeks(1); - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry, - }), - )); - - await expectRevert( - this.votes.delegateBySig(delegatorAddress, nonce, expiry, v, r, s), - 'Votes: signature expired', - ); - }); - }); - - describe('set delegation', function () { - describe('call', function () { - it('delegation with tokens', async function () { - await this.votes.mint(this.account1, this.NFT0); - expect(await this.votes.delegates(this.account1)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.votes.delegate(this.account1, { from: this.account1 }); - expectEvent(receipt, 'DelegateChanged', { - delegator: this.account1, - fromDelegate: ZERO_ADDRESS, - toDelegate: this.account1, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: this.account1, - previousBalance: '0', - newBalance: '1', - }); - - expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1); - - expect(await this.votes.getVotes(this.account1)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastVotes(this.account1, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.votes.getPastVotes(this.account1, receipt.blockNumber)).to.be.bignumber.equal('1'); - }); - - it('delegation without tokens', async function () { - expect(await this.votes.delegates(this.account1)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.votes.delegate(this.account1, { from: this.account1 }); - expectEvent(receipt, 'DelegateChanged', { - delegator: this.account1, - fromDelegate: ZERO_ADDRESS, - toDelegate: this.account1, - }); - expectEvent.notEmitted(receipt, 'DelegateVotesChanged'); - - expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1); - }); - }); - }); - - describe('change delegation', function () { - beforeEach(async function () { - await this.votes.mint(this.account1, this.NFT0); - await this.votes.delegate(this.account1, { from: this.account1 }); - }); - - it('call', async function () { - expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1); - - const { receipt } = await this.votes.delegate(this.account1Delegatee, { from: this.account1 }); - expectEvent(receipt, 'DelegateChanged', { - delegator: this.account1, - fromDelegate: this.account1, - toDelegate: this.account1Delegatee, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: this.account1, - previousBalance: '1', - newBalance: '0', - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: this.account1Delegatee, - previousBalance: '0', - newBalance: '1', - }); - const prevBlock = receipt.blockNumber - 1; - expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1Delegatee); - - expect(await this.votes.getVotes(this.account1)).to.be.bignumber.equal('0'); - expect(await this.votes.getVotes(this.account1Delegatee)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastVotes(this.account1, receipt.blockNumber - 1)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastVotes(this.account1Delegatee, prevBlock)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.votes.getPastVotes(this.account1, receipt.blockNumber)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastVotes(this.account1Delegatee, receipt.blockNumber)).to.be.bignumber.equal('1'); - }); - }); - - describe('getPastTotalSupply', function () { - beforeEach(async function () { - await this.votes.delegate(this.account1, { from: this.account1 }); - }); - - it('reverts if block number >= current block', async function () { - await expectRevert( - this.votes.getPastTotalSupply(5e10), - 'block not yet mined', - ); - }); - - it('returns 0 if there are no checkpoints', async function () { - expect(await this.votes.getPastTotalSupply(0)).to.be.bignumber.equal('0'); - }); - - it('returns the latest block if >= last checkpoint block', async function () { - const t1 = await this.votes.mint(this.account1, this.NFT0); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); - }); - - it('returns zero if < first checkpoint block', async function () { - await time.advanceBlock(); - const t2 = await this.votes.mint(this.account1, this.NFT1); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.votes.getPastTotalSupply(t2.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); - }); - - it('generally returns the voting balance at the appropriate checkpoint', async function () { - const t1 = await this.votes.mint(this.account1, this.NFT1); - await time.advanceBlock(); - await time.advanceBlock(); - const t2 = await this.votes.burn(this.NFT1); - await time.advanceBlock(); - await time.advanceBlock(); - const t3 = await this.votes.mint(this.account1, this.NFT2); - await time.advanceBlock(); - await time.advanceBlock(); - const t4 = await this.votes.burn(this.NFT2); - await time.advanceBlock(); - await time.advanceBlock(); - const t5 = await this.votes.mint(this.account1, this.NFT3); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastTotalSupply(t5.receipt.blockNumber)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastTotalSupply(t5.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); - }); - }); - - // The following tests are a adaptation of - // https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js. - describe('Compound test suite', function () { - beforeEach(async function () { - await this.votes.mint(this.account1, this.NFT0); - await this.votes.mint(this.account1, this.NFT1); - await this.votes.mint(this.account1, this.NFT2); - await this.votes.mint(this.account1, this.NFT3); - }); - - describe('getPastVotes', function () { - it('reverts if block number >= current block', async function () { - await expectRevert( - this.votes.getPastVotes(this.account2, 5e10), - 'block not yet mined', - ); - }); - - it('returns 0 if there are no checkpoints', async function () { - expect(await this.votes.getPastVotes(this.account2, 0)).to.be.bignumber.equal('0'); - }); - - it('returns the latest block if >= last checkpoint block', async function () { - const t1 = await this.votes.delegate(this.account2, { from: this.account1 }); - await time.advanceBlock(); - await time.advanceBlock(); - const latest = await this.votes.getVotes(this.account2); - const nextBlock = t1.receipt.blockNumber + 1; - expect(await this.votes.getPastVotes(this.account2, t1.receipt.blockNumber)).to.be.bignumber.equal(latest); - expect(await this.votes.getPastVotes(this.account2, nextBlock)).to.be.bignumber.equal(latest); - }); - - it('returns zero if < first checkpoint block', async function () { - await time.advanceBlock(); - const t1 = await this.votes.delegate(this.account2, { from: this.account1 }); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.votes.getPastVotes(this.account2, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - }); - }); - }); - }); -} - -module.exports = { - shouldBehaveLikeVotes, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/utils/Votes.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/utils/Votes.test.js deleted file mode 100644 index 32b7d1dc..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/governance/utils/Votes.test.js +++ /dev/null @@ -1,61 +0,0 @@ -const { expectRevert, BN } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const { - shouldBehaveLikeVotes, -} = require('./Votes.behavior'); - -const Votes = artifacts.require('VotesMock'); - -contract('Votes', function (accounts) { - const [ account1, account2, account3 ] = accounts; - beforeEach(async function () { - this.name = 'My Vote'; - this.votes = await Votes.new(this.name); - }); - - it('starts with zero votes', async function () { - expect(await this.votes.getTotalSupply()).to.be.bignumber.equal('0'); - }); - - describe('performs voting operations', function () { - beforeEach(async function () { - this.tx1 = await this.votes.mint(account1, 1); - this.tx2 = await this.votes.mint(account2, 1); - this.tx3 = await this.votes.mint(account3, 1); - }); - - it('reverts if block number >= current block', async function () { - await expectRevert( - this.votes.getPastTotalSupply(this.tx3.receipt.blockNumber + 1), - 'Votes: block not yet mined', - ); - }); - - it('delegates', async function () { - await this.votes.delegate(account3, account2); - - expect(await this.votes.delegates(account3)).to.be.equal(account2); - }); - - it('returns total amount of votes', async function () { - expect(await this.votes.getTotalSupply()).to.be.bignumber.equal('3'); - }); - }); - - describe('performs voting workflow', function () { - beforeEach(async function () { - this.chainId = await this.votes.getChainId(); - this.account1 = account1; - this.account2 = account2; - this.account1Delegatee = account2; - this.NFT0 = new BN('10000000000000000000000000'); - this.NFT1 = new BN('10'); - this.NFT2 = new BN('20'); - this.NFT3 = new BN('30'); - }); - - shouldBehaveLikeVotes(); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/eip712.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/eip712.js deleted file mode 100644 index 4f8fe7df..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/eip712.js +++ /dev/null @@ -1,21 +0,0 @@ -const ethSigUtil = require('eth-sig-util'); - -const EIP712Domain = [ - { name: 'name', type: 'string' }, - { name: 'version', type: 'string' }, - { name: 'chainId', type: 'uint256' }, - { name: 'verifyingContract', type: 'address' }, -]; - -async function domainSeparator (name, version, chainId, verifyingContract) { - return '0x' + ethSigUtil.TypedDataUtils.hashStruct( - 'EIP712Domain', - { name, version, chainId, verifyingContract }, - { EIP712Domain }, - ).toString('hex'); -} - -module.exports = { - EIP712Domain, - domainSeparator, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/enums.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/enums.js deleted file mode 100644 index de5cdc57..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/enums.js +++ /dev/null @@ -1,24 +0,0 @@ -const { BN } = require('@openzeppelin/test-helpers'); - -function Enum (...options) { - return Object.fromEntries(options.map((key, i) => [ key, new BN(i) ])); -} - -module.exports = { - Enum, - ProposalState: Enum( - 'Pending', - 'Active', - 'Canceled', - 'Defeated', - 'Succeeded', - 'Queued', - 'Expired', - 'Executed', - ), - VoteType: Enum( - 'Against', - 'For', - 'Abstain', - ), -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/erc1967.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/erc1967.js deleted file mode 100644 index aab0e228..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/erc1967.js +++ /dev/null @@ -1,24 +0,0 @@ -const ImplementationLabel = 'eip1967.proxy.implementation'; -const AdminLabel = 'eip1967.proxy.admin'; -const BeaconLabel = 'eip1967.proxy.beacon'; - -function labelToSlot (label) { - return '0x' + web3.utils.toBN(web3.utils.keccak256(label)).subn(1).toString(16); -} - -function getSlot (address, slot) { - return web3.eth.getStorageAt( - web3.utils.isAddress(address) ? address : address.address, - web3.utils.isHex(slot) ? slot : labelToSlot(slot), - ); -} - -module.exports = { - ImplementationLabel, - AdminLabel, - BeaconLabel, - ImplementationSlot: labelToSlot(ImplementationLabel), - AdminSlot: labelToSlot(AdminLabel), - BeaconSlot: labelToSlot(BeaconLabel), - getSlot, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/sign.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/sign.js deleted file mode 100644 index 4c14d1f1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/helpers/sign.js +++ /dev/null @@ -1,47 +0,0 @@ -function toEthSignedMessageHash (messageHex) { - const messageBuffer = Buffer.from(messageHex.substring(2), 'hex'); - const prefix = Buffer.from(`\u0019Ethereum Signed Message:\n${messageBuffer.length}`); - return web3.utils.sha3(Buffer.concat([prefix, messageBuffer])); -} - -/** - * Create a signer between a contract and a signer for a voucher of method, args, and redeemer - * Note that `method` is the web3 method, not the truffle-contract method - * @param contract TruffleContract - * @param signer address - * @param redeemer address - * @param methodName string - * @param methodArgs any[] - */ -const getSignFor = (contract, signer) => (redeemer, methodName, methodArgs = []) => { - const parts = [ - contract.address, - redeemer, - ]; - - const REAL_SIGNATURE_SIZE = 2 * 65; // 65 bytes in hexadecimal string length - const PADDED_SIGNATURE_SIZE = 2 * 96; // 96 bytes in hexadecimal string length - const DUMMY_SIGNATURE = `0x${web3.utils.padLeft('', REAL_SIGNATURE_SIZE)}`; - - // if we have a method, add it to the parts that we're signing - if (methodName) { - if (methodArgs.length > 0) { - parts.push( - contract.contract.methods[methodName](...methodArgs.concat([DUMMY_SIGNATURE])).encodeABI() - .slice(0, -1 * PADDED_SIGNATURE_SIZE), - ); - } else { - const abi = contract.abi.find(abi => abi.name === methodName); - parts.push(abi.signature); - } - } - - // return the signature of the "Ethereum Signed Message" hash of the hash of `parts` - const messageHex = web3.utils.soliditySha3(...parts); - return web3.eth.sign(messageHex, signer); -}; - -module.exports = { - toEthSignedMessageHash, - getSignFor, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/metatx/ERC2771Context.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/metatx/ERC2771Context.test.js deleted file mode 100644 index 8db92ab8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/metatx/ERC2771Context.test.js +++ /dev/null @@ -1,109 +0,0 @@ -const ethSigUtil = require('eth-sig-util'); -const Wallet = require('ethereumjs-wallet').default; -const { EIP712Domain } = require('../helpers/eip712'); - -const { expectEvent } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const ERC2771ContextMock = artifacts.require('ERC2771ContextMock'); -const MinimalForwarder = artifacts.require('MinimalForwarder'); -const ContextMockCaller = artifacts.require('ContextMockCaller'); - -const { shouldBehaveLikeRegularContext } = require('../utils/Context.behavior'); - -const name = 'MinimalForwarder'; -const version = '0.0.1'; - -contract('ERC2771Context', function (accounts) { - beforeEach(async function () { - this.forwarder = await MinimalForwarder.new(); - this.recipient = await ERC2771ContextMock.new(this.forwarder.address); - - this.domain = { - name, - version, - chainId: await web3.eth.getChainId(), - verifyingContract: this.forwarder.address, - }; - this.types = { - EIP712Domain, - ForwardRequest: [ - { name: 'from', type: 'address' }, - { name: 'to', type: 'address' }, - { name: 'value', type: 'uint256' }, - { name: 'gas', type: 'uint256' }, - { name: 'nonce', type: 'uint256' }, - { name: 'data', type: 'bytes' }, - ], - }; - }); - - it('recognize trusted forwarder', async function () { - expect(await this.recipient.isTrustedForwarder(this.forwarder.address)); - }); - - context('when called directly', function () { - beforeEach(async function () { - this.context = this.recipient; // The Context behavior expects the contract in this.context - this.caller = await ContextMockCaller.new(); - }); - - shouldBehaveLikeRegularContext(...accounts); - }); - - context('when receiving a relayed call', function () { - beforeEach(async function () { - this.wallet = Wallet.generate(); - this.sender = web3.utils.toChecksumAddress(this.wallet.getAddressString()); - this.data = { - types: this.types, - domain: this.domain, - primaryType: 'ForwardRequest', - }; - }); - - describe('msgSender', function () { - it('returns the relayed transaction original sender', async function () { - const data = this.recipient.contract.methods.msgSender().encodeABI(); - - const req = { - from: this.sender, - to: this.recipient.address, - value: '0', - gas: '100000', - nonce: (await this.forwarder.getNonce(this.sender)).toString(), - data, - }; - - const sign = ethSigUtil.signTypedMessage(this.wallet.getPrivateKey(), { data: { ...this.data, message: req } }); - expect(await this.forwarder.verify(req, sign)).to.equal(true); - - const { tx } = await this.forwarder.execute(req, sign); - await expectEvent.inTransaction(tx, ERC2771ContextMock, 'Sender', { sender: this.sender }); - }); - }); - - describe('msgData', function () { - it('returns the relayed transaction original data', async function () { - const integerValue = '42'; - const stringValue = 'OpenZeppelin'; - const data = this.recipient.contract.methods.msgData(integerValue, stringValue).encodeABI(); - - const req = { - from: this.sender, - to: this.recipient.address, - value: '0', - gas: '100000', - nonce: (await this.forwarder.getNonce(this.sender)).toString(), - data, - }; - - const sign = ethSigUtil.signTypedMessage(this.wallet.getPrivateKey(), { data: { ...this.data, message: req } }); - expect(await this.forwarder.verify(req, sign)).to.equal(true); - - const { tx } = await this.forwarder.execute(req, sign); - await expectEvent.inTransaction(tx, ERC2771ContextMock, 'Data', { data, integerValue, stringValue }); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/metatx/MinimalForwarder.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/metatx/MinimalForwarder.test.js deleted file mode 100644 index b8984e43..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/metatx/MinimalForwarder.test.js +++ /dev/null @@ -1,184 +0,0 @@ -const ethSigUtil = require('eth-sig-util'); -const Wallet = require('ethereumjs-wallet').default; -const { EIP712Domain } = require('../helpers/eip712'); - -const { expectRevert, constants } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const MinimalForwarder = artifacts.require('MinimalForwarder'); -const CallReceiverMock = artifacts.require('CallReceiverMock'); - -const name = 'MinimalForwarder'; -const version = '0.0.1'; - -contract('MinimalForwarder', function (accounts) { - beforeEach(async function () { - this.forwarder = await MinimalForwarder.new(); - this.domain = { - name, - version, - chainId: await web3.eth.getChainId(), - verifyingContract: this.forwarder.address, - }; - this.types = { - EIP712Domain, - ForwardRequest: [ - { name: 'from', type: 'address' }, - { name: 'to', type: 'address' }, - { name: 'value', type: 'uint256' }, - { name: 'gas', type: 'uint256' }, - { name: 'nonce', type: 'uint256' }, - { name: 'data', type: 'bytes' }, - ], - }; - }); - - context('with message', function () { - beforeEach(async function () { - this.wallet = Wallet.generate(); - this.sender = web3.utils.toChecksumAddress(this.wallet.getAddressString()); - this.req = { - from: this.sender, - to: constants.ZERO_ADDRESS, - value: '0', - gas: '100000', - nonce: Number(await this.forwarder.getNonce(this.sender)), - data: '0x', - }; - this.sign = () => ethSigUtil.signTypedMessage( - this.wallet.getPrivateKey(), - { - data: { - types: this.types, - domain: this.domain, - primaryType: 'ForwardRequest', - message: this.req, - }, - }, - ); - }); - - context('verify', function () { - context('valid signature', function () { - beforeEach(async function () { - expect(await this.forwarder.getNonce(this.req.from)) - .to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); - }); - - it('success', async function () { - expect(await this.forwarder.verify(this.req, this.sign())).to.be.equal(true); - }); - - afterEach(async function () { - expect(await this.forwarder.getNonce(this.req.from)) - .to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); - }); - }); - - context('invalid signature', function () { - it('tampered from', async function () { - expect(await this.forwarder.verify({ ...this.req, from: accounts[0] }, this.sign())) - .to.be.equal(false); - }); - it('tampered to', async function () { - expect(await this.forwarder.verify({ ...this.req, to: accounts[0] }, this.sign())) - .to.be.equal(false); - }); - it('tampered value', async function () { - expect(await this.forwarder.verify({ ...this.req, value: web3.utils.toWei('1') }, this.sign())) - .to.be.equal(false); - }); - it('tampered nonce', async function () { - expect(await this.forwarder.verify({ ...this.req, nonce: this.req.nonce + 1 }, this.sign())) - .to.be.equal(false); - }); - it('tampered data', async function () { - expect(await this.forwarder.verify({ ...this.req, data: '0x1742' }, this.sign())) - .to.be.equal(false); - }); - it('tampered signature', async function () { - const tamperedsign = web3.utils.hexToBytes(this.sign()); - tamperedsign[42] ^= 0xff; - expect(await this.forwarder.verify(this.req, web3.utils.bytesToHex(tamperedsign))) - .to.be.equal(false); - }); - }); - }); - - context('execute', function () { - context('valid signature', function () { - beforeEach(async function () { - expect(await this.forwarder.getNonce(this.req.from)) - .to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); - }); - - it('success', async function () { - await this.forwarder.execute(this.req, this.sign()); // expect to not revert - }); - - afterEach(async function () { - expect(await this.forwarder.getNonce(this.req.from)) - .to.be.bignumber.equal(web3.utils.toBN(this.req.nonce + 1)); - }); - }); - - context('invalid signature', function () { - it('tampered from', async function () { - await expectRevert( - this.forwarder.execute({ ...this.req, from: accounts[0] }, this.sign()), - 'MinimalForwarder: signature does not match request', - ); - }); - it('tampered to', async function () { - await expectRevert( - this.forwarder.execute({ ...this.req, to: accounts[0] }, this.sign()), - 'MinimalForwarder: signature does not match request', - ); - }); - it('tampered value', async function () { - await expectRevert( - this.forwarder.execute({ ...this.req, value: web3.utils.toWei('1') }, this.sign()), - 'MinimalForwarder: signature does not match request', - ); - }); - it('tampered nonce', async function () { - await expectRevert( - this.forwarder.execute({ ...this.req, nonce: this.req.nonce + 1 }, this.sign()), - 'MinimalForwarder: signature does not match request', - ); - }); - it('tampered data', async function () { - await expectRevert( - this.forwarder.execute({ ...this.req, data: '0x1742' }, this.sign()), - 'MinimalForwarder: signature does not match request', - ); - }); - it('tampered signature', async function () { - const tamperedsign = web3.utils.hexToBytes(this.sign()); - tamperedsign[42] ^= 0xff; - await expectRevert( - this.forwarder.execute(this.req, web3.utils.bytesToHex(tamperedsign)), - 'MinimalForwarder: signature does not match request', - ); - }); - }); - - it('bubble out of gas', async function () { - const receiver = await CallReceiverMock.new(); - const gasAvailable = 100000; - this.req.to = receiver.address; - this.req.data = receiver.contract.methods.mockFunctionOutOfGas().encodeABI(); - this.req.gas = 1000000; - - await expectRevert.assertion( - this.forwarder.execute(this.req, this.sign(), { gas: gasAvailable }), - ); - - const { transactions } = await web3.eth.getBlock('latest'); - const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]); - - expect(gasUsed).to.be.equal(gasAvailable); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/migrate-imports.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/migrate-imports.test.js deleted file mode 100644 index 639767c2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/migrate-imports.test.js +++ /dev/null @@ -1,29 +0,0 @@ -const path = require('path'); -const { promises: fs, constants: { F_OK } } = require('fs'); -const { expect } = require('chai'); - -const { pathUpdates, updateImportPaths, getUpgradeablePath } = require('../scripts/migrate-imports.js'); - -describe('migrate-imports.js', function () { - it('every new path exists', async function () { - for (const p of Object.values(pathUpdates)) { - try { - await fs.access(path.join('contracts', p), F_OK); - } catch (e) { - await fs.access(path.join('contracts', getUpgradeablePath(p)), F_OK); - } - } - }); - - it('replaces import paths in a file', async function () { - const source = ` -import '@openzeppelin/contracts/math/Math.sol'; -import '@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol'; - `; - const expected = ` -import '@openzeppelin/contracts/utils/math/Math.sol'; -import '@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol'; - `; - expect(updateImportPaths(source)).to.equal(expected); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Clones.behaviour.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Clones.behaviour.js deleted file mode 100644 index 81c5ee35..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Clones.behaviour.js +++ /dev/null @@ -1,150 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const DummyImplementation = artifacts.require('DummyImplementation'); - -module.exports = function shouldBehaveLikeClone (createClone) { - before('deploy implementation', async function () { - this.implementation = web3.utils.toChecksumAddress((await DummyImplementation.new()).address); - }); - - const assertProxyInitialization = function ({ value, balance }) { - it('initializes the proxy', async function () { - const dummy = new DummyImplementation(this.proxy); - expect(await dummy.value()).to.be.bignumber.equal(value.toString()); - }); - - it('has expected balance', async function () { - expect(await web3.eth.getBalance(this.proxy)).to.be.bignumber.equal(balance.toString()); - }); - }; - - describe('initialization without parameters', function () { - describe('non payable', function () { - const expectedInitializedValue = 10; - const initializeData = new DummyImplementation('').contract.methods['initializeNonPayable()']().encodeABI(); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: 0, - }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - it('reverts', async function () { - await expectRevert.unspecified( - createClone(this.implementation, initializeData, { value }), - ); - }); - }); - }); - - describe('payable', function () { - const expectedInitializedValue = 100; - const initializeData = new DummyImplementation('').contract.methods['initializePayable()']().encodeABI(); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: 0, - }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData, { value }) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: value, - }); - }); - }); - }); - - describe('initialization with parameters', function () { - describe('non payable', function () { - const expectedInitializedValue = 10; - const initializeData = new DummyImplementation('').contract - .methods.initializeNonPayableWithValue(expectedInitializedValue).encodeABI(); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: 0, - }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - it('reverts', async function () { - await expectRevert.unspecified( - createClone(this.implementation, initializeData, { value }), - ); - }); - }); - }); - - describe('payable', function () { - const expectedInitializedValue = 42; - const initializeData = new DummyImplementation('').contract - .methods.initializePayableWithValue(expectedInitializedValue).encodeABI(); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: 0, - }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData, { value }) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: value, - }); - }); - }); - }); -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Clones.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Clones.test.js deleted file mode 100644 index 0f6a5de9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Clones.test.js +++ /dev/null @@ -1,54 +0,0 @@ -const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); - -const shouldBehaveLikeClone = require('./Clones.behaviour'); - -const ClonesMock = artifacts.require('ClonesMock'); - -contract('Clones', function (accounts) { - describe('clone', function () { - shouldBehaveLikeClone(async (implementation, initData, opts = {}) => { - const factory = await ClonesMock.new(); - const receipt = await factory.clone(implementation, initData, { value: opts.value }); - const address = receipt.logs.find(({ event }) => event === 'NewInstance').args.instance; - return { address }; - }); - }); - - describe('cloneDeterministic', function () { - shouldBehaveLikeClone(async (implementation, initData, opts = {}) => { - const salt = web3.utils.randomHex(32); - const factory = await ClonesMock.new(); - const receipt = await factory.cloneDeterministic(implementation, salt, initData, { value: opts.value }); - const address = receipt.logs.find(({ event }) => event === 'NewInstance').args.instance; - return { address }; - }); - - it('address already used', async function () { - const implementation = web3.utils.randomHex(20); - const salt = web3.utils.randomHex(32); - const factory = await ClonesMock.new(); - // deploy once - expectEvent( - await factory.cloneDeterministic(implementation, salt, '0x'), - 'NewInstance', - ); - // deploy twice - await expectRevert( - factory.cloneDeterministic(implementation, salt, '0x'), - 'ERC1167: create2 failed', - ); - }); - - it('address prediction', async function () { - const implementation = web3.utils.randomHex(20); - const salt = web3.utils.randomHex(32); - const factory = await ClonesMock.new(); - const predicted = await factory.predictDeterministicAddress(implementation, salt); - expectEvent( - await factory.cloneDeterministic(implementation, salt, '0x'), - 'NewInstance', - { instance: predicted }, - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/ERC1967/ERC1967Proxy.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/ERC1967/ERC1967Proxy.test.js deleted file mode 100644 index 22df960f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/ERC1967/ERC1967Proxy.test.js +++ /dev/null @@ -1,13 +0,0 @@ -const shouldBehaveLikeProxy = require('../Proxy.behaviour'); - -const ERC1967Proxy = artifacts.require('ERC1967Proxy'); - -contract('ERC1967Proxy', function (accounts) { - const [proxyAdminOwner] = accounts; - - const createProxy = async function (implementation, _admin, initData, opts) { - return ERC1967Proxy.new(implementation, initData, opts); - }; - - shouldBehaveLikeProxy(createProxy, undefined, proxyAdminOwner); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Proxy.behaviour.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Proxy.behaviour.js deleted file mode 100644 index 435792f2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/Proxy.behaviour.js +++ /dev/null @@ -1,224 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); -const { getSlot, ImplementationSlot } = require('../helpers/erc1967'); - -const { expect } = require('chai'); - -const DummyImplementation = artifacts.require('DummyImplementation'); - -module.exports = function shouldBehaveLikeProxy (createProxy, proxyAdminAddress, proxyCreator) { - it('cannot be initialized with a non-contract address', async function () { - const nonContractAddress = proxyCreator; - const initializeData = Buffer.from(''); - await expectRevert.unspecified( - createProxy(nonContractAddress, proxyAdminAddress, initializeData, { - from: proxyCreator, - }), - ); - }); - - before('deploy implementation', async function () { - this.implementation = web3.utils.toChecksumAddress((await DummyImplementation.new()).address); - }); - - const assertProxyInitialization = function ({ value, balance }) { - it('sets the implementation address', async function () { - const implementationSlot = await getSlot(this.proxy, ImplementationSlot); - const implementationAddress = web3.utils.toChecksumAddress(implementationSlot.substr(-40)); - expect(implementationAddress).to.be.equal(this.implementation); - }); - - it('initializes the proxy', async function () { - const dummy = new DummyImplementation(this.proxy); - expect(await dummy.value()).to.be.bignumber.equal(value.toString()); - }); - - it('has expected balance', async function () { - expect(await web3.eth.getBalance(this.proxy)).to.be.bignumber.equal(balance.toString()); - }); - }; - - describe('without initialization', function () { - const initializeData = Buffer.from(''); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createProxy(this.implementation, proxyAdminAddress, initializeData, { - from: proxyCreator, - }) - ).address; - }); - - assertProxyInitialization({ value: 0, balance: 0 }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - beforeEach('creating proxy', async function () { - this.proxy = ( - await createProxy(this.implementation, proxyAdminAddress, initializeData, { - from: proxyCreator, - value, - }) - ).address; - }); - - assertProxyInitialization({ value: 0, balance: value }); - }); - }); - - describe('initialization without parameters', function () { - describe('non payable', function () { - const expectedInitializedValue = 10; - const initializeData = new DummyImplementation('').contract.methods['initializeNonPayable()']().encodeABI(); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createProxy(this.implementation, proxyAdminAddress, initializeData, { - from: proxyCreator, - }) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: 0, - }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - it('reverts', async function () { - await expectRevert.unspecified( - createProxy(this.implementation, proxyAdminAddress, initializeData, { from: proxyCreator, value }), - ); - }); - }); - }); - - describe('payable', function () { - const expectedInitializedValue = 100; - const initializeData = new DummyImplementation('').contract.methods['initializePayable()']().encodeABI(); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createProxy(this.implementation, proxyAdminAddress, initializeData, { - from: proxyCreator, - }) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: 0, - }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - beforeEach('creating proxy', async function () { - this.proxy = ( - await createProxy(this.implementation, proxyAdminAddress, initializeData, { - from: proxyCreator, - value, - }) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: value, - }); - }); - }); - }); - - describe('initialization with parameters', function () { - describe('non payable', function () { - const expectedInitializedValue = 10; - const initializeData = new DummyImplementation('').contract - .methods.initializeNonPayableWithValue(expectedInitializedValue).encodeABI(); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createProxy(this.implementation, proxyAdminAddress, initializeData, { - from: proxyCreator, - }) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: 0, - }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - it('reverts', async function () { - await expectRevert.unspecified( - createProxy(this.implementation, proxyAdminAddress, initializeData, { from: proxyCreator, value }), - ); - }); - }); - }); - - describe('payable', function () { - const expectedInitializedValue = 42; - const initializeData = new DummyImplementation('').contract - .methods.initializePayableWithValue(expectedInitializedValue).encodeABI(); - - describe('when not sending balance', function () { - beforeEach('creating proxy', async function () { - this.proxy = ( - await createProxy(this.implementation, proxyAdminAddress, initializeData, { - from: proxyCreator, - }) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: 0, - }); - }); - - describe('when sending some balance', function () { - const value = 10e5; - - beforeEach('creating proxy', async function () { - this.proxy = ( - await createProxy(this.implementation, proxyAdminAddress, initializeData, { - from: proxyCreator, - value, - }) - ).address; - }); - - assertProxyInitialization({ - value: expectedInitializedValue, - balance: value, - }); - }); - }); - - describe('reverting initialization', function () { - const initializeData = new DummyImplementation('').contract - .methods.reverts().encodeABI(); - - it('reverts', async function () { - await expectRevert( - createProxy(this.implementation, proxyAdminAddress, initializeData, { from: proxyCreator }), - 'DummyImplementation reverted', - ); - }); - }); - }); -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/beacon/BeaconProxy.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/beacon/BeaconProxy.test.js deleted file mode 100644 index 0a4a8d0c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/beacon/BeaconProxy.test.js +++ /dev/null @@ -1,156 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); -const { getSlot, BeaconSlot } = require('../../helpers/erc1967'); - -const { expect } = require('chai'); - -const UpgradeableBeacon = artifacts.require('UpgradeableBeacon'); -const BeaconProxy = artifacts.require('BeaconProxy'); -const DummyImplementation = artifacts.require('DummyImplementation'); -const DummyImplementationV2 = artifacts.require('DummyImplementationV2'); -const BadBeaconNoImpl = artifacts.require('BadBeaconNoImpl'); -const BadBeaconNotContract = artifacts.require('BadBeaconNotContract'); - -contract('BeaconProxy', function (accounts) { - const [anotherAccount] = accounts; - - describe('bad beacon is not accepted', async function () { - it('non-contract beacon', async function () { - await expectRevert( - BeaconProxy.new(anotherAccount, '0x'), - 'ERC1967: new beacon is not a contract', - ); - }); - - it('non-compliant beacon', async function () { - const beacon = await BadBeaconNoImpl.new(); - await expectRevert.unspecified( - BeaconProxy.new(beacon.address, '0x'), - ); - }); - - it('non-contract implementation', async function () { - const beacon = await BadBeaconNotContract.new(); - await expectRevert( - BeaconProxy.new(beacon.address, '0x'), - 'ERC1967: beacon implementation is not a contract', - ); - }); - }); - - before('deploy implementation', async function () { - this.implementationV0 = await DummyImplementation.new(); - this.implementationV1 = await DummyImplementationV2.new(); - }); - - describe('initialization', function () { - before(function () { - this.assertInitialized = async ({ value, balance }) => { - const beaconSlot = await getSlot(this.proxy, BeaconSlot); - const beaconAddress = web3.utils.toChecksumAddress(beaconSlot.substr(-40)); - expect(beaconAddress).to.equal(this.beacon.address); - - const dummy = new DummyImplementation(this.proxy.address); - expect(await dummy.value()).to.bignumber.eq(value); - - expect(await web3.eth.getBalance(this.proxy.address)).to.bignumber.eq(balance); - }; - }); - - beforeEach('deploy beacon', async function () { - this.beacon = await UpgradeableBeacon.new(this.implementationV0.address); - }); - - it('no initialization', async function () { - const data = Buffer.from(''); - const balance = '10'; - this.proxy = await BeaconProxy.new(this.beacon.address, data, { value: balance }); - await this.assertInitialized({ value: '0', balance }); - }); - - it('non-payable initialization', async function () { - const value = '55'; - const data = this.implementationV0.contract.methods - .initializeNonPayableWithValue(value) - .encodeABI(); - this.proxy = await BeaconProxy.new(this.beacon.address, data); - await this.assertInitialized({ value, balance: '0' }); - }); - - it('payable initialization', async function () { - const value = '55'; - const data = this.implementationV0.contract.methods - .initializePayableWithValue(value) - .encodeABI(); - const balance = '100'; - this.proxy = await BeaconProxy.new(this.beacon.address, data, { value: balance }); - await this.assertInitialized({ value, balance }); - }); - - it('reverting initialization', async function () { - const data = this.implementationV0.contract.methods.reverts().encodeABI(); - await expectRevert( - BeaconProxy.new(this.beacon.address, data), - 'DummyImplementation reverted', - ); - }); - }); - - it('upgrade a proxy by upgrading its beacon', async function () { - const beacon = await UpgradeableBeacon.new(this.implementationV0.address); - - const value = '10'; - const data = this.implementationV0.contract.methods - .initializeNonPayableWithValue(value) - .encodeABI(); - const proxy = await BeaconProxy.new(beacon.address, data); - - const dummy = new DummyImplementation(proxy.address); - - // test initial values - expect(await dummy.value()).to.bignumber.eq(value); - - // test initial version - expect(await dummy.version()).to.eq('V1'); - - // upgrade beacon - await beacon.upgradeTo(this.implementationV1.address); - - // test upgraded version - expect(await dummy.version()).to.eq('V2'); - }); - - it('upgrade 2 proxies by upgrading shared beacon', async function () { - const value1 = '10'; - const value2 = '42'; - - const beacon = await UpgradeableBeacon.new(this.implementationV0.address); - - const proxy1InitializeData = this.implementationV0.contract.methods - .initializeNonPayableWithValue(value1) - .encodeABI(); - const proxy1 = await BeaconProxy.new(beacon.address, proxy1InitializeData); - - const proxy2InitializeData = this.implementationV0.contract.methods - .initializeNonPayableWithValue(value2) - .encodeABI(); - const proxy2 = await BeaconProxy.new(beacon.address, proxy2InitializeData); - - const dummy1 = new DummyImplementation(proxy1.address); - const dummy2 = new DummyImplementation(proxy2.address); - - // test initial values - expect(await dummy1.value()).to.bignumber.eq(value1); - expect(await dummy2.value()).to.bignumber.eq(value2); - - // test initial version - expect(await dummy1.version()).to.eq('V1'); - expect(await dummy2.version()).to.eq('V1'); - - // upgrade beacon - await beacon.upgradeTo(this.implementationV1.address); - - // test upgraded version - expect(await dummy1.version()).to.eq('V2'); - expect(await dummy2.version()).to.eq('V2'); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/beacon/UpgradeableBeacon.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/beacon/UpgradeableBeacon.test.js deleted file mode 100644 index 0c49906d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/beacon/UpgradeableBeacon.test.js +++ /dev/null @@ -1,50 +0,0 @@ -const { expectRevert, expectEvent } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const UpgradeableBeacon = artifacts.require('UpgradeableBeacon'); -const Implementation1 = artifacts.require('Implementation1'); -const Implementation2 = artifacts.require('Implementation2'); - -contract('UpgradeableBeacon', function (accounts) { - const [owner, other] = accounts; - - it('cannot be created with non-contract implementation', async function () { - await expectRevert( - UpgradeableBeacon.new(accounts[0]), - 'UpgradeableBeacon: implementation is not a contract', - ); - }); - - context('once deployed', async function () { - beforeEach('deploying beacon', async function () { - this.v1 = await Implementation1.new(); - this.beacon = await UpgradeableBeacon.new(this.v1.address, { from: owner }); - }); - - it('returns implementation', async function () { - expect(await this.beacon.implementation()).to.equal(this.v1.address); - }); - - it('can be upgraded by the owner', async function () { - const v2 = await Implementation2.new(); - const receipt = await this.beacon.upgradeTo(v2.address, { from: owner }); - expectEvent(receipt, 'Upgraded', { implementation: v2.address }); - expect(await this.beacon.implementation()).to.equal(v2.address); - }); - - it('cannot be upgraded to a non-contract', async function () { - await expectRevert( - this.beacon.upgradeTo(other, { from: owner }), - 'UpgradeableBeacon: implementation is not a contract', - ); - }); - - it('cannot be upgraded by other account', async function () { - const v2 = await Implementation2.new(); - await expectRevert( - this.beacon.upgradeTo(v2.address, { from: other }), - 'Ownable: caller is not the owner', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/ProxyAdmin.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/ProxyAdmin.test.js deleted file mode 100644 index 07adba6a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/ProxyAdmin.test.js +++ /dev/null @@ -1,125 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ImplV1 = artifacts.require('DummyImplementation'); -const ImplV2 = artifacts.require('DummyImplementationV2'); -const ProxyAdmin = artifacts.require('ProxyAdmin'); -const TransparentUpgradeableProxy = artifacts.require('TransparentUpgradeableProxy'); - -contract('ProxyAdmin', function (accounts) { - const [proxyAdminOwner, newAdmin, anotherAccount] = accounts; - - before('set implementations', async function () { - this.implementationV1 = await ImplV1.new(); - this.implementationV2 = await ImplV2.new(); - }); - - beforeEach(async function () { - const initializeData = Buffer.from(''); - this.proxyAdmin = await ProxyAdmin.new({ from: proxyAdminOwner }); - this.proxy = await TransparentUpgradeableProxy.new( - this.implementationV1.address, - this.proxyAdmin.address, - initializeData, - { from: proxyAdminOwner }, - ); - }); - - it('has an owner', async function () { - expect(await this.proxyAdmin.owner()).to.equal(proxyAdminOwner); - }); - - describe('#getProxyAdmin', function () { - it('returns proxyAdmin as admin of the proxy', async function () { - const admin = await this.proxyAdmin.getProxyAdmin(this.proxy.address); - expect(admin).to.be.equal(this.proxyAdmin.address); - }); - - it('call to invalid proxy', async function () { - await expectRevert.unspecified(this.proxyAdmin.getProxyAdmin(this.implementationV1.address)); - }); - }); - - describe('#changeProxyAdmin', function () { - it('fails to change proxy admin if its not the proxy owner', async function () { - await expectRevert( - this.proxyAdmin.changeProxyAdmin(this.proxy.address, newAdmin, { from: anotherAccount }), - 'caller is not the owner', - ); - }); - - it('changes proxy admin', async function () { - await this.proxyAdmin.changeProxyAdmin(this.proxy.address, newAdmin, { from: proxyAdminOwner }); - expect(await this.proxy.admin.call({ from: newAdmin })).to.eq(newAdmin); - }); - }); - - describe('#getProxyImplementation', function () { - it('returns proxy implementation address', async function () { - const implementationAddress = await this.proxyAdmin.getProxyImplementation(this.proxy.address); - expect(implementationAddress).to.be.equal(this.implementationV1.address); - }); - - it('call to invalid proxy', async function () { - await expectRevert.unspecified(this.proxyAdmin.getProxyImplementation(this.implementationV1.address)); - }); - }); - - describe('#upgrade', function () { - context('with unauthorized account', function () { - it('fails to upgrade', async function () { - await expectRevert( - this.proxyAdmin.upgrade(this.proxy.address, this.implementationV2.address, { from: anotherAccount }), - 'caller is not the owner', - ); - }); - }); - - context('with authorized account', function () { - it('upgrades implementation', async function () { - await this.proxyAdmin.upgrade(this.proxy.address, this.implementationV2.address, { from: proxyAdminOwner }); - const implementationAddress = await this.proxyAdmin.getProxyImplementation(this.proxy.address); - expect(implementationAddress).to.be.equal(this.implementationV2.address); - }); - }); - }); - - describe('#upgradeAndCall', function () { - context('with unauthorized account', function () { - it('fails to upgrade', async function () { - const callData = new ImplV1('').contract.methods.initializeNonPayableWithValue(1337).encodeABI(); - await expectRevert( - this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, - { from: anotherAccount }, - ), - 'caller is not the owner', - ); - }); - }); - - context('with authorized account', function () { - context('with invalid callData', function () { - it('fails to upgrade', async function () { - const callData = '0x12345678'; - await expectRevert.unspecified( - this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, - { from: proxyAdminOwner }, - ), - ); - }); - }); - - context('with valid callData', function () { - it('upgrades implementation', async function () { - const callData = new ImplV1('').contract.methods.initializeNonPayableWithValue(1337).encodeABI(); - await this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, - { from: proxyAdminOwner }, - ); - const implementationAddress = await this.proxyAdmin.getProxyImplementation(this.proxy.address); - expect(implementationAddress).to.be.equal(this.implementationV2.address); - }); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/TransparentUpgradeableProxy.behaviour.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/TransparentUpgradeableProxy.behaviour.js deleted file mode 100644 index 33fef6f4..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/TransparentUpgradeableProxy.behaviour.js +++ /dev/null @@ -1,431 +0,0 @@ -const { BN, expectRevert, expectEvent, constants } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; -const { getSlot, ImplementationSlot, AdminSlot } = require('../../helpers/erc1967'); - -const { expect } = require('chai'); - -const Proxy = artifacts.require('Proxy'); -const Implementation1 = artifacts.require('Implementation1'); -const Implementation2 = artifacts.require('Implementation2'); -const Implementation3 = artifacts.require('Implementation3'); -const Implementation4 = artifacts.require('Implementation4'); -const MigratableMockV1 = artifacts.require('MigratableMockV1'); -const MigratableMockV2 = artifacts.require('MigratableMockV2'); -const MigratableMockV3 = artifacts.require('MigratableMockV3'); -const InitializableMock = artifacts.require('InitializableMock'); -const DummyImplementation = artifacts.require('DummyImplementation'); -const ClashingImplementation = artifacts.require('ClashingImplementation'); - -module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createProxy, accounts) { - const [proxyAdminAddress, proxyAdminOwner, anotherAccount] = accounts; - - before(async function () { - this.implementationV0 = (await DummyImplementation.new()).address; - this.implementationV1 = (await DummyImplementation.new()).address; - }); - - beforeEach(async function () { - const initializeData = Buffer.from(''); - this.proxy = await createProxy(this.implementationV0, proxyAdminAddress, initializeData, { - from: proxyAdminOwner, - }); - this.proxyAddress = this.proxy.address; - }); - - describe('implementation', function () { - it('returns the current implementation address', async function () { - const implementation = await this.proxy.implementation.call({ from: proxyAdminAddress }); - - expect(implementation).to.be.equal(this.implementationV0); - }); - - it('delegates to the implementation', async function () { - const dummy = new DummyImplementation(this.proxyAddress); - const value = await dummy.get(); - - expect(value).to.equal(true); - }); - }); - - describe('upgradeTo', function () { - describe('when the sender is the admin', function () { - const from = proxyAdminAddress; - - describe('when the given implementation is different from the current one', function () { - it('upgrades to the requested implementation', async function () { - await this.proxy.upgradeTo(this.implementationV1, { from }); - - const implementation = await this.proxy.implementation.call({ from: proxyAdminAddress }); - expect(implementation).to.be.equal(this.implementationV1); - }); - - it('emits an event', async function () { - expectEvent( - await this.proxy.upgradeTo(this.implementationV1, { from }), - 'Upgraded', { - implementation: this.implementationV1, - }, - ); - }); - }); - - describe('when the given implementation is the zero address', function () { - it('reverts', async function () { - await expectRevert( - this.proxy.upgradeTo(ZERO_ADDRESS, { from }), - 'ERC1967: new implementation is not a contract', - ); - }); - }); - }); - - describe('when the sender is not the admin', function () { - const from = anotherAccount; - - it('reverts', async function () { - await expectRevert.unspecified( - this.proxy.upgradeTo(this.implementationV1, { from }), - ); - }); - }); - }); - - describe('upgradeToAndCall', function () { - describe('without migrations', function () { - beforeEach(async function () { - this.behavior = await InitializableMock.new(); - }); - - describe('when the call does not fail', function () { - const initializeData = new InitializableMock('').contract.methods['initializeWithX(uint256)'](42).encodeABI(); - - describe('when the sender is the admin', function () { - const from = proxyAdminAddress; - const value = 1e5; - - beforeEach(async function () { - this.receipt = await this.proxy.upgradeToAndCall(this.behavior.address, initializeData, { from, value }); - }); - - it('upgrades to the requested implementation', async function () { - const implementation = await this.proxy.implementation.call({ from: proxyAdminAddress }); - expect(implementation).to.be.equal(this.behavior.address); - }); - - it('emits an event', function () { - expectEvent(this.receipt, 'Upgraded', { implementation: this.behavior.address }); - }); - - it('calls the initializer function', async function () { - const migratable = new InitializableMock(this.proxyAddress); - const x = await migratable.x(); - expect(x).to.be.bignumber.equal('42'); - }); - - it('sends given value to the proxy', async function () { - const balance = await web3.eth.getBalance(this.proxyAddress); - expect(balance.toString()).to.be.bignumber.equal(value.toString()); - }); - - it.skip('uses the storage of the proxy', async function () { - // storage layout should look as follows: - // - 0: Initializable storage - // - 1-50: Initailizable reserved storage (50 slots) - // - 51: initializerRan - // - 52: x - const storedValue = await Proxy.at(this.proxyAddress).getStorageAt(52); - expect(parseInt(storedValue)).to.eq(42); - }); - }); - - describe('when the sender is not the admin', function () { - it('reverts', async function () { - await expectRevert.unspecified( - this.proxy.upgradeToAndCall(this.behavior.address, initializeData, { from: anotherAccount }), - ); - }); - }); - }); - - describe('when the call does fail', function () { - const initializeData = new InitializableMock('').contract.methods.fail().encodeABI(); - - it('reverts', async function () { - await expectRevert.unspecified( - this.proxy.upgradeToAndCall(this.behavior.address, initializeData, { from: proxyAdminAddress }), - ); - }); - }); - }); - - describe('with migrations', function () { - describe('when the sender is the admin', function () { - const from = proxyAdminAddress; - const value = 1e5; - - describe('when upgrading to V1', function () { - const v1MigrationData = new MigratableMockV1('').contract.methods.initialize(42).encodeABI(); - - beforeEach(async function () { - this.behaviorV1 = await MigratableMockV1.new(); - this.balancePreviousV1 = new BN(await web3.eth.getBalance(this.proxyAddress)); - this.receipt = await this.proxy.upgradeToAndCall(this.behaviorV1.address, v1MigrationData, { from, value }); - }); - - it('upgrades to the requested version and emits an event', async function () { - const implementation = await this.proxy.implementation.call({ from: proxyAdminAddress }); - expect(implementation).to.be.equal(this.behaviorV1.address); - expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV1.address }); - }); - - it('calls the \'initialize\' function and sends given value to the proxy', async function () { - const migratable = new MigratableMockV1(this.proxyAddress); - - const x = await migratable.x(); - expect(x).to.be.bignumber.equal('42'); - - const balance = await web3.eth.getBalance(this.proxyAddress); - expect(new BN(balance)).to.be.bignumber.equal(this.balancePreviousV1.addn(value)); - }); - - describe('when upgrading to V2', function () { - const v2MigrationData = new MigratableMockV2('').contract.methods.migrate(10, 42).encodeABI(); - - beforeEach(async function () { - this.behaviorV2 = await MigratableMockV2.new(); - this.balancePreviousV2 = new BN(await web3.eth.getBalance(this.proxyAddress)); - this.receipt = - await this.proxy.upgradeToAndCall(this.behaviorV2.address, v2MigrationData, { from, value }); - }); - - it('upgrades to the requested version and emits an event', async function () { - const implementation = await this.proxy.implementation.call({ from: proxyAdminAddress }); - expect(implementation).to.be.equal(this.behaviorV2.address); - expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV2.address }); - }); - - it('calls the \'migrate\' function and sends given value to the proxy', async function () { - const migratable = new MigratableMockV2(this.proxyAddress); - - const x = await migratable.x(); - expect(x).to.be.bignumber.equal('10'); - - const y = await migratable.y(); - expect(y).to.be.bignumber.equal('42'); - - const balance = new BN(await web3.eth.getBalance(this.proxyAddress)); - expect(balance).to.be.bignumber.equal(this.balancePreviousV2.addn(value)); - }); - - describe('when upgrading to V3', function () { - const v3MigrationData = new MigratableMockV3('').contract.methods['migrate()']().encodeABI(); - - beforeEach(async function () { - this.behaviorV3 = await MigratableMockV3.new(); - this.balancePreviousV3 = new BN(await web3.eth.getBalance(this.proxyAddress)); - this.receipt = - await this.proxy.upgradeToAndCall(this.behaviorV3.address, v3MigrationData, { from, value }); - }); - - it('upgrades to the requested version and emits an event', async function () { - const implementation = await this.proxy.implementation.call({ from: proxyAdminAddress }); - expect(implementation).to.be.equal(this.behaviorV3.address); - expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV3.address }); - }); - - it('calls the \'migrate\' function and sends given value to the proxy', async function () { - const migratable = new MigratableMockV3(this.proxyAddress); - - const x = await migratable.x(); - expect(x).to.be.bignumber.equal('42'); - - const y = await migratable.y(); - expect(y).to.be.bignumber.equal('10'); - - const balance = new BN(await web3.eth.getBalance(this.proxyAddress)); - expect(balance).to.be.bignumber.equal(this.balancePreviousV3.addn(value)); - }); - }); - }); - }); - }); - - describe('when the sender is not the admin', function () { - const from = anotherAccount; - - it('reverts', async function () { - const behaviorV1 = await MigratableMockV1.new(); - const v1MigrationData = new MigratableMockV1('').contract.methods.initialize(42).encodeABI(); - await expectRevert.unspecified( - this.proxy.upgradeToAndCall(behaviorV1.address, v1MigrationData, { from }), - ); - }); - }); - }); - }); - - describe('changeAdmin', function () { - describe('when the new proposed admin is not the zero address', function () { - const newAdmin = anotherAccount; - - describe('when the sender is the admin', function () { - beforeEach('transferring', async function () { - this.receipt = await this.proxy.changeAdmin(newAdmin, { from: proxyAdminAddress }); - }); - - it('assigns new proxy admin', async function () { - const newProxyAdmin = await this.proxy.admin.call({ from: newAdmin }); - expect(newProxyAdmin).to.be.equal(anotherAccount); - }); - - it('emits an event', function () { - expectEvent(this.receipt, 'AdminChanged', { - previousAdmin: proxyAdminAddress, - newAdmin: newAdmin, - }); - }); - }); - - describe('when the sender is not the admin', function () { - it('reverts', async function () { - await expectRevert.unspecified(this.proxy.changeAdmin(newAdmin, { from: anotherAccount })); - }); - }); - }); - - describe('when the new proposed admin is the zero address', function () { - it('reverts', async function () { - await expectRevert( - this.proxy.changeAdmin(ZERO_ADDRESS, { from: proxyAdminAddress }), - 'ERC1967: new admin is the zero address', - ); - }); - }); - }); - - describe('storage', function () { - it('should store the implementation address in specified location', async function () { - const implementationSlot = await getSlot(this.proxy, ImplementationSlot); - const implementationAddress = web3.utils.toChecksumAddress(implementationSlot.substr(-40)); - expect(implementationAddress).to.be.equal(this.implementationV0); - }); - - it('should store the admin proxy in specified location', async function () { - const proxyAdminSlot = await getSlot(this.proxy, AdminSlot); - const proxyAdminAddress = web3.utils.toChecksumAddress(proxyAdminSlot.substr(-40)); - expect(proxyAdminAddress).to.be.equal(proxyAdminAddress); - }); - }); - - describe('transparent proxy', function () { - beforeEach('creating proxy', async function () { - const initializeData = Buffer.from(''); - this.impl = await ClashingImplementation.new(); - this.proxy = await createProxy(this.impl.address, proxyAdminAddress, initializeData, { from: proxyAdminOwner }); - - this.clashing = new ClashingImplementation(this.proxy.address); - }); - - it('proxy admin cannot call delegated functions', async function () { - await expectRevert( - this.clashing.delegatedFunction({ from: proxyAdminAddress }), - 'TransparentUpgradeableProxy: admin cannot fallback to proxy target', - ); - }); - - context('when function names clash', function () { - it('when sender is proxy admin should run the proxy function', async function () { - const value = await this.proxy.admin.call({ from: proxyAdminAddress }); - expect(value).to.be.equal(proxyAdminAddress); - }); - - it('when sender is other should delegate to implementation', async function () { - const value = await this.proxy.admin.call({ from: anotherAccount }); - expect(value).to.be.equal('0x0000000000000000000000000000000011111142'); - }); - }); - }); - - describe('regression', () => { - const initializeData = Buffer.from(''); - - it('should add new function', async () => { - const instance1 = await Implementation1.new(); - const proxy = await createProxy(instance1.address, proxyAdminAddress, initializeData, { from: proxyAdminOwner }); - - const proxyInstance1 = new Implementation1(proxy.address); - await proxyInstance1.setValue(42); - - const instance2 = await Implementation2.new(); - await proxy.upgradeTo(instance2.address, { from: proxyAdminAddress }); - - const proxyInstance2 = new Implementation2(proxy.address); - const res = await proxyInstance2.getValue(); - expect(res.toString()).to.eq('42'); - }); - - it('should remove function', async () => { - const instance2 = await Implementation2.new(); - const proxy = await createProxy(instance2.address, proxyAdminAddress, initializeData, { from: proxyAdminOwner }); - - const proxyInstance2 = new Implementation2(proxy.address); - await proxyInstance2.setValue(42); - const res = await proxyInstance2.getValue(); - expect(res.toString()).to.eq('42'); - - const instance1 = await Implementation1.new(); - await proxy.upgradeTo(instance1.address, { from: proxyAdminAddress }); - - const proxyInstance1 = new Implementation2(proxy.address); - await expectRevert.unspecified(proxyInstance1.getValue()); - }); - - it('should change function signature', async () => { - const instance1 = await Implementation1.new(); - const proxy = await createProxy(instance1.address, proxyAdminAddress, initializeData, { from: proxyAdminOwner }); - - const proxyInstance1 = new Implementation1(proxy.address); - await proxyInstance1.setValue(42); - - const instance3 = await Implementation3.new(); - await proxy.upgradeTo(instance3.address, { from: proxyAdminAddress }); - const proxyInstance3 = new Implementation3(proxy.address); - - const res = await proxyInstance3.getValue(8); - expect(res.toString()).to.eq('50'); - }); - - it('should add fallback function', async () => { - const initializeData = Buffer.from(''); - const instance1 = await Implementation1.new(); - const proxy = await createProxy(instance1.address, proxyAdminAddress, initializeData, { from: proxyAdminOwner }); - - const instance4 = await Implementation4.new(); - await proxy.upgradeTo(instance4.address, { from: proxyAdminAddress }); - const proxyInstance4 = new Implementation4(proxy.address); - - const data = '0x'; - await web3.eth.sendTransaction({ to: proxy.address, from: anotherAccount, data }); - - const res = await proxyInstance4.getValue(); - expect(res.toString()).to.eq('1'); - }); - - it('should remove fallback function', async () => { - const instance4 = await Implementation4.new(); - const proxy = await createProxy(instance4.address, proxyAdminAddress, initializeData, { from: proxyAdminOwner }); - - const instance2 = await Implementation2.new(); - await proxy.upgradeTo(instance2.address, { from: proxyAdminAddress }); - - const data = '0x'; - await expectRevert.unspecified( - web3.eth.sendTransaction({ to: proxy.address, from: anotherAccount, data }), - ); - - const proxyInstance2 = new Implementation2(proxy.address); - const res = await proxyInstance2.getValue(); - expect(res.toString()).to.eq('0'); - }); - }); -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/TransparentUpgradeableProxy.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/TransparentUpgradeableProxy.test.js deleted file mode 100644 index 86dd55d3..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/transparent/TransparentUpgradeableProxy.test.js +++ /dev/null @@ -1,15 +0,0 @@ -const shouldBehaveLikeProxy = require('../Proxy.behaviour'); -const shouldBehaveLikeTransparentUpgradeableProxy = require('./TransparentUpgradeableProxy.behaviour'); - -const TransparentUpgradeableProxy = artifacts.require('TransparentUpgradeableProxy'); - -contract('TransparentUpgradeableProxy', function (accounts) { - const [proxyAdminAddress, proxyAdminOwner] = accounts; - - const createProxy = async function (logic, admin, initData, opts) { - return TransparentUpgradeableProxy.new(logic, admin, initData, opts); - }; - - shouldBehaveLikeProxy(createProxy, proxyAdminAddress, proxyAdminOwner); - shouldBehaveLikeTransparentUpgradeableProxy(createProxy, accounts); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/utils/Initializable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/utils/Initializable.test.js deleted file mode 100644 index 04884a1d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/utils/Initializable.test.js +++ /dev/null @@ -1,90 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); -const { assert } = require('chai'); - -const InitializableMock = artifacts.require('InitializableMock'); -const ConstructorInitializableMock = artifacts.require('ConstructorInitializableMock'); -const SampleChild = artifacts.require('SampleChild'); - -contract('Initializable', function (accounts) { - describe('basic testing without inheritance', function () { - beforeEach('deploying', async function () { - this.contract = await InitializableMock.new(); - }); - - context('before initialize', function () { - it('initializer has not run', async function () { - assert.isFalse(await this.contract.initializerRan()); - }); - }); - - context('after initialize', function () { - beforeEach('initializing', async function () { - await this.contract.initialize(); - }); - - it('initializer has run', async function () { - assert.isTrue(await this.contract.initializerRan()); - }); - - it('initializer does not run again', async function () { - await expectRevert(this.contract.initialize(), 'Initializable: contract is already initialized'); - }); - }); - - context('nested under an initializer', function () { - it('initializer modifier reverts', async function () { - await expectRevert(this.contract.initializerNested(), 'Initializable: contract is already initialized'); - }); - - it('onlyInitializing modifier succeeds', async function () { - await this.contract.onlyInitializingNested(); - assert.isTrue(await this.contract.onlyInitializingRan()); - }); - }); - - it('cannot call onlyInitializable function outside the scope of an initializable function', async function () { - await expectRevert(this.contract.initializeOnlyInitializing(), 'Initializable: contract is not initializing'); - }); - }); - - it('nested initializer can run during construction', async function () { - const contract2 = await ConstructorInitializableMock.new(); - assert.isTrue(await contract2.initializerRan()); - assert.isTrue(await contract2.onlyInitializingRan()); - }); - - describe('complex testing with inheritance', function () { - const mother = 12; - const gramps = '56'; - const father = 34; - const child = 78; - - beforeEach('deploying', async function () { - this.contract = await SampleChild.new(); - }); - - beforeEach('initializing', async function () { - await this.contract.initialize(mother, gramps, father, child); - }); - - it('initializes human', async function () { - assert.equal(await this.contract.isHuman(), true); - }); - - it('initializes mother', async function () { - assert.equal(await this.contract.mother(), mother); - }); - - it('initializes gramps', async function () { - assert.equal(await this.contract.gramps(), gramps); - }); - - it('initializes father', async function () { - assert.equal(await this.contract.father(), father); - }); - - it('initializes child', async function () { - assert.equal(await this.contract.child(), child); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/utils/UUPSUpgradeable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/utils/UUPSUpgradeable.test.js deleted file mode 100644 index 466081d2..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/proxy/utils/UUPSUpgradeable.test.js +++ /dev/null @@ -1,85 +0,0 @@ -const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { web3 } = require('@openzeppelin/test-helpers/src/setup'); -const { getSlot, ImplementationSlot } = require('../../helpers/erc1967'); - -const ERC1967Proxy = artifacts.require('ERC1967Proxy'); -const UUPSUpgradeableMock = artifacts.require('UUPSUpgradeableMock'); -const UUPSUpgradeableUnsafeMock = artifacts.require('UUPSUpgradeableUnsafeMock'); -const UUPSUpgradeableLegacyMock = artifacts.require('UUPSUpgradeableLegacyMock'); -const CountersImpl = artifacts.require('CountersImpl'); - -contract('UUPSUpgradeable', function (accounts) { - before(async function () { - this.implInitial = await UUPSUpgradeableMock.new(); - this.implUpgradeOk = await UUPSUpgradeableMock.new(); - this.implUpgradeUnsafe = await UUPSUpgradeableUnsafeMock.new(); - this.implUpgradeNonUUPS = await CountersImpl.new(); - }); - - beforeEach(async function () { - const { address } = await ERC1967Proxy.new(this.implInitial.address, '0x'); - this.instance = await UUPSUpgradeableMock.at(address); - }); - - it('upgrade to upgradeable implementation', async function () { - const { receipt } = await this.instance.upgradeTo(this.implUpgradeOk.address); - expect(receipt.logs.filter(({ event }) => event === 'Upgraded').length).to.be.equal(1); - expectEvent(receipt, 'Upgraded', { implementation: this.implUpgradeOk.address }); - }); - - it('upgrade to upgradeable implementation with call', async function () { - expect(await this.instance.current()).to.be.bignumber.equal('0'); - - const { receipt } = await this.instance.upgradeToAndCall( - this.implUpgradeOk.address, - this.implUpgradeOk.contract.methods.increment().encodeABI(), - ); - expect(receipt.logs.filter(({ event }) => event === 'Upgraded').length).to.be.equal(1); - expectEvent(receipt, 'Upgraded', { implementation: this.implUpgradeOk.address }); - - expect(await this.instance.current()).to.be.bignumber.equal('1'); - }); - - it('upgrade to and unsafe upgradeable implementation', async function () { - const { receipt } = await this.instance.upgradeTo(this.implUpgradeUnsafe.address); - expectEvent(receipt, 'Upgraded', { implementation: this.implUpgradeUnsafe.address }); - }); - - // delegate to a non existing upgradeTo function causes a low level revert - it('reject upgrade to non uups implementation', async function () { - await expectRevert( - this.instance.upgradeTo(this.implUpgradeNonUUPS.address), - 'ERC1967Upgrade: new implementation is not UUPS', - ); - }); - - it('reject proxy address as implementation', async function () { - const { address } = await ERC1967Proxy.new(this.implInitial.address, '0x'); - const otherInstance = await UUPSUpgradeableMock.at(address); - - await expectRevert( - this.instance.upgradeTo(otherInstance.address), - 'ERC1967Upgrade: new implementation is not UUPS', - ); - }); - - it('can upgrade from legacy implementations', async function () { - const legacyImpl = await UUPSUpgradeableLegacyMock.new(); - const legacyInstance = await ERC1967Proxy.new(legacyImpl.address, '0x') - .then(({ address }) => UUPSUpgradeableLegacyMock.at(address)); - - const receipt = await legacyInstance.upgradeTo(this.implInitial.address); - - const UpgradedEvents = receipt.logs.filter(({ address, event }) => - address === legacyInstance.address && - event === 'Upgraded', - ); - expect(UpgradedEvents.length).to.be.equal(1); - - expectEvent(receipt, 'Upgraded', { implementation: this.implInitial.address }); - - const implementationSlot = await getSlot(legacyInstance, ImplementationSlot); - const implementationAddress = web3.utils.toChecksumAddress(implementationSlot.substr(-40)); - expect(implementationAddress).to.be.equal(this.implInitial.address); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/Pausable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/Pausable.test.js deleted file mode 100644 index 14681594..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/Pausable.test.js +++ /dev/null @@ -1,89 +0,0 @@ -const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const PausableMock = artifacts.require('PausableMock'); - -contract('Pausable', function (accounts) { - const [ pauser ] = accounts; - - beforeEach(async function () { - this.pausable = await PausableMock.new(); - }); - - context('when unpaused', function () { - beforeEach(async function () { - expect(await this.pausable.paused()).to.equal(false); - }); - - it('can perform normal process in non-pause', async function () { - expect(await this.pausable.count()).to.be.bignumber.equal('0'); - - await this.pausable.normalProcess(); - expect(await this.pausable.count()).to.be.bignumber.equal('1'); - }); - - it('cannot take drastic measure in non-pause', async function () { - await expectRevert(this.pausable.drasticMeasure(), - 'Pausable: not paused', - ); - expect(await this.pausable.drasticMeasureTaken()).to.equal(false); - }); - - context('when paused', function () { - beforeEach(async function () { - ({ logs: this.logs } = await this.pausable.pause({ from: pauser })); - }); - - it('emits a Paused event', function () { - expectEvent.inLogs(this.logs, 'Paused', { account: pauser }); - }); - - it('cannot perform normal process in pause', async function () { - await expectRevert(this.pausable.normalProcess(), 'Pausable: paused'); - }); - - it('can take a drastic measure in a pause', async function () { - await this.pausable.drasticMeasure(); - expect(await this.pausable.drasticMeasureTaken()).to.equal(true); - }); - - it('reverts when re-pausing', async function () { - await expectRevert(this.pausable.pause(), 'Pausable: paused'); - }); - - describe('unpausing', function () { - it('is unpausable by the pauser', async function () { - await this.pausable.unpause(); - expect(await this.pausable.paused()).to.equal(false); - }); - - context('when unpaused', function () { - beforeEach(async function () { - ({ logs: this.logs } = await this.pausable.unpause({ from: pauser })); - }); - - it('emits an Unpaused event', function () { - expectEvent.inLogs(this.logs, 'Unpaused', { account: pauser }); - }); - - it('should resume allowing normal process', async function () { - expect(await this.pausable.count()).to.be.bignumber.equal('0'); - await this.pausable.normalProcess(); - expect(await this.pausable.count()).to.be.bignumber.equal('1'); - }); - - it('should prevent drastic measure', async function () { - await expectRevert(this.pausable.drasticMeasure(), - 'Pausable: not paused', - ); - }); - - it('reverts when re-unpausing', async function () { - await expectRevert(this.pausable.unpause(), 'Pausable: not paused'); - }); - }); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/PullPayment.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/PullPayment.test.js deleted file mode 100644 index 1552ed99..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/PullPayment.test.js +++ /dev/null @@ -1,51 +0,0 @@ -const { balance, ether } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const PullPaymentMock = artifacts.require('PullPaymentMock'); - -contract('PullPayment', function (accounts) { - const [ payer, payee1, payee2 ] = accounts; - - const amount = ether('17'); - - beforeEach(async function () { - this.contract = await PullPaymentMock.new({ value: amount }); - }); - - describe('payments', function () { - it('can record an async payment correctly', async function () { - await this.contract.callTransfer(payee1, 100, { from: payer }); - expect(await this.contract.payments(payee1)).to.be.bignumber.equal('100'); - }); - - it('can add multiple balances on one account', async function () { - await this.contract.callTransfer(payee1, 200, { from: payer }); - await this.contract.callTransfer(payee1, 300, { from: payer }); - expect(await this.contract.payments(payee1)).to.be.bignumber.equal('500'); - }); - - it('can add balances on multiple accounts', async function () { - await this.contract.callTransfer(payee1, 200, { from: payer }); - await this.contract.callTransfer(payee2, 300, { from: payer }); - - expect(await this.contract.payments(payee1)).to.be.bignumber.equal('200'); - - expect(await this.contract.payments(payee2)).to.be.bignumber.equal('300'); - }); - }); - - describe('withdrawPayments', function () { - it('can withdraw payment', async function () { - const balanceTracker = await balance.tracker(payee1); - - await this.contract.callTransfer(payee1, amount, { from: payer }); - expect(await this.contract.payments(payee1)).to.be.bignumber.equal(amount); - - await this.contract.withdrawPayments(payee1); - - expect(await balanceTracker.delta()).to.be.bignumber.equal(amount); - expect(await this.contract.payments(payee1)).to.be.bignumber.equal('0'); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/ReentrancyGuard.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/ReentrancyGuard.test.js deleted file mode 100644 index c0116d54..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/security/ReentrancyGuard.test.js +++ /dev/null @@ -1,40 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ReentrancyMock = artifacts.require('ReentrancyMock'); -const ReentrancyAttack = artifacts.require('ReentrancyAttack'); - -contract('ReentrancyGuard', function (accounts) { - beforeEach(async function () { - this.reentrancyMock = await ReentrancyMock.new(); - expect(await this.reentrancyMock.counter()).to.be.bignumber.equal('0'); - }); - - it('nonReentrant function can be called', async function () { - expect(await this.reentrancyMock.counter()).to.be.bignumber.equal('0'); - await this.reentrancyMock.callback(); - expect(await this.reentrancyMock.counter()).to.be.bignumber.equal('1'); - }); - - it('does not allow remote callback', async function () { - const attacker = await ReentrancyAttack.new(); - await expectRevert( - this.reentrancyMock.countAndCall(attacker.address), 'ReentrancyAttack: failed call'); - }); - - // The following are more side-effects than intended behavior: - // I put them here as documentation, and to monitor any changes - // in the side-effects. - it('does not allow local recursion', async function () { - await expectRevert( - this.reentrancyMock.countLocalRecursive(10), 'ReentrancyGuard: reentrant call', - ); - }); - - it('does not allow indirect local recursion', async function () { - await expectRevert( - this.reentrancyMock.countThisRecursive(10), 'ReentrancyMock: failed call', - ); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/ERC1155.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/ERC1155.behavior.js deleted file mode 100644 index 13b08ac6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/ERC1155.behavior.js +++ /dev/null @@ -1,774 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsInterface.behavior'); - -const ERC1155ReceiverMock = artifacts.require('ERC1155ReceiverMock'); - -function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, multiTokenHolder, recipient, proxy]) { - const firstTokenId = new BN(1); - const secondTokenId = new BN(2); - const unknownTokenId = new BN(3); - - const firstAmount = new BN(1000); - const secondAmount = new BN(2000); - - const RECEIVER_SINGLE_MAGIC_VALUE = '0xf23a6e61'; - const RECEIVER_BATCH_MAGIC_VALUE = '0xbc197c81'; - - describe('like an ERC1155', function () { - describe('balanceOf', function () { - it('reverts when queried about the zero address', async function () { - await expectRevert( - this.token.balanceOf(ZERO_ADDRESS, firstTokenId), - 'ERC1155: balance query for the zero address', - ); - }); - - context('when accounts don\'t own tokens', function () { - it('returns zero for given addresses', async function () { - expect(await this.token.balanceOf( - firstTokenHolder, - firstTokenId, - )).to.be.bignumber.equal('0'); - - expect(await this.token.balanceOf( - secondTokenHolder, - secondTokenId, - )).to.be.bignumber.equal('0'); - - expect(await this.token.balanceOf( - firstTokenHolder, - unknownTokenId, - )).to.be.bignumber.equal('0'); - }); - }); - - context('when accounts own some tokens', function () { - beforeEach(async function () { - await this.token.mint(firstTokenHolder, firstTokenId, firstAmount, '0x', { - from: minter, - }); - await this.token.mint( - secondTokenHolder, - secondTokenId, - secondAmount, - '0x', - { - from: minter, - }, - ); - }); - - it('returns the amount of tokens owned by the given addresses', async function () { - expect(await this.token.balanceOf( - firstTokenHolder, - firstTokenId, - )).to.be.bignumber.equal(firstAmount); - - expect(await this.token.balanceOf( - secondTokenHolder, - secondTokenId, - )).to.be.bignumber.equal(secondAmount); - - expect(await this.token.balanceOf( - firstTokenHolder, - unknownTokenId, - )).to.be.bignumber.equal('0'); - }); - }); - }); - - describe('balanceOfBatch', function () { - it('reverts when input arrays don\'t match up', async function () { - await expectRevert( - this.token.balanceOfBatch( - [firstTokenHolder, secondTokenHolder, firstTokenHolder, secondTokenHolder], - [firstTokenId, secondTokenId, unknownTokenId], - ), - 'ERC1155: accounts and ids length mismatch', - ); - - await expectRevert( - this.token.balanceOfBatch( - [firstTokenHolder, secondTokenHolder], - [firstTokenId, secondTokenId, unknownTokenId], - ), - 'ERC1155: accounts and ids length mismatch', - ); - }); - - it('reverts when one of the addresses is the zero address', async function () { - await expectRevert( - this.token.balanceOfBatch( - [firstTokenHolder, secondTokenHolder, ZERO_ADDRESS], - [firstTokenId, secondTokenId, unknownTokenId], - ), - 'ERC1155: balance query for the zero address', - ); - }); - - context('when accounts don\'t own tokens', function () { - it('returns zeros for each account', async function () { - const result = await this.token.balanceOfBatch( - [firstTokenHolder, secondTokenHolder, firstTokenHolder], - [firstTokenId, secondTokenId, unknownTokenId], - ); - expect(result).to.be.an('array'); - expect(result[0]).to.be.a.bignumber.equal('0'); - expect(result[1]).to.be.a.bignumber.equal('0'); - expect(result[2]).to.be.a.bignumber.equal('0'); - }); - }); - - context('when accounts own some tokens', function () { - beforeEach(async function () { - await this.token.mint(firstTokenHolder, firstTokenId, firstAmount, '0x', { - from: minter, - }); - await this.token.mint( - secondTokenHolder, - secondTokenId, - secondAmount, - '0x', - { - from: minter, - }, - ); - }); - - it('returns amounts owned by each account in order passed', async function () { - const result = await this.token.balanceOfBatch( - [secondTokenHolder, firstTokenHolder, firstTokenHolder], - [secondTokenId, firstTokenId, unknownTokenId], - ); - expect(result).to.be.an('array'); - expect(result[0]).to.be.a.bignumber.equal(secondAmount); - expect(result[1]).to.be.a.bignumber.equal(firstAmount); - expect(result[2]).to.be.a.bignumber.equal('0'); - }); - - it('returns multiple times the balance of the same address when asked', async function () { - const result = await this.token.balanceOfBatch( - [firstTokenHolder, secondTokenHolder, firstTokenHolder], - [firstTokenId, secondTokenId, firstTokenId], - ); - expect(result).to.be.an('array'); - expect(result[0]).to.be.a.bignumber.equal(result[2]); - expect(result[0]).to.be.a.bignumber.equal(firstAmount); - expect(result[1]).to.be.a.bignumber.equal(secondAmount); - expect(result[2]).to.be.a.bignumber.equal(firstAmount); - }); - }); - }); - - describe('setApprovalForAll', function () { - let logs; - beforeEach(async function () { - ({ logs } = await this.token.setApprovalForAll(proxy, true, { from: multiTokenHolder })); - }); - - it('sets approval status which can be queried via isApprovedForAll', async function () { - expect(await this.token.isApprovedForAll(multiTokenHolder, proxy)).to.be.equal(true); - }); - - it('emits an ApprovalForAll log', function () { - expectEvent.inLogs(logs, 'ApprovalForAll', { account: multiTokenHolder, operator: proxy, approved: true }); - }); - - it('can unset approval for an operator', async function () { - await this.token.setApprovalForAll(proxy, false, { from: multiTokenHolder }); - expect(await this.token.isApprovedForAll(multiTokenHolder, proxy)).to.be.equal(false); - }); - - it('reverts if attempting to approve self as an operator', async function () { - await expectRevert( - this.token.setApprovalForAll(multiTokenHolder, true, { from: multiTokenHolder }), - 'ERC1155: setting approval status for self', - ); - }); - }); - - describe('safeTransferFrom', function () { - beforeEach(async function () { - await this.token.mint(multiTokenHolder, firstTokenId, firstAmount, '0x', { - from: minter, - }); - await this.token.mint( - multiTokenHolder, - secondTokenId, - secondAmount, - '0x', - { - from: minter, - }, - ); - }); - - it('reverts when transferring more than balance', async function () { - await expectRevert( - this.token.safeTransferFrom( - multiTokenHolder, - recipient, - firstTokenId, - firstAmount.addn(1), - '0x', - { from: multiTokenHolder }, - ), - 'ERC1155: insufficient balance for transfer', - ); - }); - - it('reverts when transferring to zero address', async function () { - await expectRevert( - this.token.safeTransferFrom( - multiTokenHolder, - ZERO_ADDRESS, - firstTokenId, - firstAmount, - '0x', - { from: multiTokenHolder }, - ), - 'ERC1155: transfer to the zero address', - ); - }); - - function transferWasSuccessful ({ operator, from, id, value }) { - it('debits transferred balance from sender', async function () { - const newBalance = await this.token.balanceOf(from, id); - expect(newBalance).to.be.a.bignumber.equal('0'); - }); - - it('credits transferred balance to receiver', async function () { - const newBalance = await this.token.balanceOf(this.toWhom, id); - expect(newBalance).to.be.a.bignumber.equal(value); - }); - - it('emits a TransferSingle log', function () { - expectEvent.inLogs(this.transferLogs, 'TransferSingle', { - operator, - from, - to: this.toWhom, - id, - value, - }); - }); - } - - context('when called by the multiTokenHolder', async function () { - beforeEach(async function () { - this.toWhom = recipient; - ({ logs: this.transferLogs } = - await this.token.safeTransferFrom(multiTokenHolder, recipient, firstTokenId, firstAmount, '0x', { - from: multiTokenHolder, - })); - }); - - transferWasSuccessful.call(this, { - operator: multiTokenHolder, - from: multiTokenHolder, - id: firstTokenId, - value: firstAmount, - }); - - it('preserves existing balances which are not transferred by multiTokenHolder', async function () { - const balance1 = await this.token.balanceOf(multiTokenHolder, secondTokenId); - expect(balance1).to.be.a.bignumber.equal(secondAmount); - - const balance2 = await this.token.balanceOf(recipient, secondTokenId); - expect(balance2).to.be.a.bignumber.equal('0'); - }); - }); - - context('when called by an operator on behalf of the multiTokenHolder', function () { - context('when operator is not approved by multiTokenHolder', function () { - beforeEach(async function () { - await this.token.setApprovalForAll(proxy, false, { from: multiTokenHolder }); - }); - - it('reverts', async function () { - await expectRevert( - this.token.safeTransferFrom(multiTokenHolder, recipient, firstTokenId, firstAmount, '0x', { - from: proxy, - }), - 'ERC1155: caller is not owner nor approved', - ); - }); - }); - - context('when operator is approved by multiTokenHolder', function () { - beforeEach(async function () { - this.toWhom = recipient; - await this.token.setApprovalForAll(proxy, true, { from: multiTokenHolder }); - ({ logs: this.transferLogs } = - await this.token.safeTransferFrom(multiTokenHolder, recipient, firstTokenId, firstAmount, '0x', { - from: proxy, - })); - }); - - transferWasSuccessful.call(this, { - operator: proxy, - from: multiTokenHolder, - id: firstTokenId, - value: firstAmount, - }); - - it('preserves operator\'s balances not involved in the transfer', async function () { - const balance1 = await this.token.balanceOf(proxy, firstTokenId); - expect(balance1).to.be.a.bignumber.equal('0'); - - const balance2 = await this.token.balanceOf(proxy, secondTokenId); - expect(balance2).to.be.a.bignumber.equal('0'); - }); - }); - }); - - context('when sending to a valid receiver', function () { - beforeEach(async function () { - this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, false, - RECEIVER_BATCH_MAGIC_VALUE, false, - ); - }); - - context('without data', function () { - beforeEach(async function () { - this.toWhom = this.receiver.address; - this.transferReceipt = await this.token.safeTransferFrom( - multiTokenHolder, - this.receiver.address, - firstTokenId, - firstAmount, - '0x', - { from: multiTokenHolder }, - ); - ({ logs: this.transferLogs } = this.transferReceipt); - }); - - transferWasSuccessful.call(this, { - operator: multiTokenHolder, - from: multiTokenHolder, - id: firstTokenId, - value: firstAmount, - }); - - it('calls onERC1155Received', async function () { - await expectEvent.inTransaction(this.transferReceipt.tx, ERC1155ReceiverMock, 'Received', { - operator: multiTokenHolder, - from: multiTokenHolder, - id: firstTokenId, - value: firstAmount, - data: null, - }); - }); - }); - - context('with data', function () { - const data = '0xf00dd00d'; - beforeEach(async function () { - this.toWhom = this.receiver.address; - this.transferReceipt = await this.token.safeTransferFrom( - multiTokenHolder, - this.receiver.address, - firstTokenId, - firstAmount, - data, - { from: multiTokenHolder }, - ); - ({ logs: this.transferLogs } = this.transferReceipt); - }); - - transferWasSuccessful.call(this, { - operator: multiTokenHolder, - from: multiTokenHolder, - id: firstTokenId, - value: firstAmount, - }); - - it('calls onERC1155Received', async function () { - await expectEvent.inTransaction(this.transferReceipt.tx, ERC1155ReceiverMock, 'Received', { - operator: multiTokenHolder, - from: multiTokenHolder, - id: firstTokenId, - value: firstAmount, - data, - }); - }); - }); - }); - - context('to a receiver contract returning unexpected value', function () { - beforeEach(async function () { - this.receiver = await ERC1155ReceiverMock.new( - '0x00c0ffee', false, - RECEIVER_BATCH_MAGIC_VALUE, false, - ); - }); - - it('reverts', async function () { - await expectRevert( - this.token.safeTransferFrom(multiTokenHolder, this.receiver.address, firstTokenId, firstAmount, '0x', { - from: multiTokenHolder, - }), - 'ERC1155: ERC1155Receiver rejected tokens', - ); - }); - }); - - context('to a receiver contract that reverts', function () { - beforeEach(async function () { - this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, true, - RECEIVER_BATCH_MAGIC_VALUE, false, - ); - }); - - it('reverts', async function () { - await expectRevert( - this.token.safeTransferFrom(multiTokenHolder, this.receiver.address, firstTokenId, firstAmount, '0x', { - from: multiTokenHolder, - }), - 'ERC1155ReceiverMock: reverting on receive', - ); - }); - }); - - context('to a contract that does not implement the required function', function () { - it('reverts', async function () { - const invalidReceiver = this.token; - await expectRevert.unspecified( - this.token.safeTransferFrom(multiTokenHolder, invalidReceiver.address, firstTokenId, firstAmount, '0x', { - from: multiTokenHolder, - }), - ); - }); - }); - }); - - describe('safeBatchTransferFrom', function () { - beforeEach(async function () { - await this.token.mint(multiTokenHolder, firstTokenId, firstAmount, '0x', { - from: minter, - }); - await this.token.mint( - multiTokenHolder, - secondTokenId, - secondAmount, - '0x', - { - from: minter, - }, - ); - }); - - it('reverts when transferring amount more than any of balances', async function () { - await expectRevert( - this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount.addn(1)], - '0x', { from: multiTokenHolder }, - ), - 'ERC1155: insufficient balance for transfer', - ); - }); - - it('reverts when ids array length doesn\'t match amounts array length', async function () { - await expectRevert( - this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, - [firstTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - ), - 'ERC1155: ids and amounts length mismatch', - ); - - await expectRevert( - this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, - [firstTokenId, secondTokenId], - [firstAmount], - '0x', { from: multiTokenHolder }, - ), - 'ERC1155: ids and amounts length mismatch', - ); - }); - - it('reverts when transferring to zero address', async function () { - await expectRevert( - this.token.safeBatchTransferFrom( - multiTokenHolder, ZERO_ADDRESS, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - ), - 'ERC1155: transfer to the zero address', - ); - }); - - function batchTransferWasSuccessful ({ operator, from, ids, values }) { - it('debits transferred balances from sender', async function () { - const newBalances = await this.token.balanceOfBatch(new Array(ids.length).fill(from), ids); - for (const newBalance of newBalances) { - expect(newBalance).to.be.a.bignumber.equal('0'); - } - }); - - it('credits transferred balances to receiver', async function () { - const newBalances = await this.token.balanceOfBatch(new Array(ids.length).fill(this.toWhom), ids); - for (let i = 0; i < newBalances.length; i++) { - expect(newBalances[i]).to.be.a.bignumber.equal(values[i]); - } - }); - - it('emits a TransferBatch log', function () { - expectEvent.inLogs(this.transferLogs, 'TransferBatch', { - operator, - from, - to: this.toWhom, - // ids, - // values, - }); - }); - } - - context('when called by the multiTokenHolder', async function () { - beforeEach(async function () { - this.toWhom = recipient; - ({ logs: this.transferLogs } = - await this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - )); - }); - - batchTransferWasSuccessful.call(this, { - operator: multiTokenHolder, - from: multiTokenHolder, - ids: [firstTokenId, secondTokenId], - values: [firstAmount, secondAmount], - }); - }); - - context('when called by an operator on behalf of the multiTokenHolder', function () { - context('when operator is not approved by multiTokenHolder', function () { - beforeEach(async function () { - await this.token.setApprovalForAll(proxy, false, { from: multiTokenHolder }); - }); - - it('reverts', async function () { - await expectRevert( - this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: proxy }, - ), - 'ERC1155: transfer caller is not owner nor approved', - ); - }); - }); - - context('when operator is approved by multiTokenHolder', function () { - beforeEach(async function () { - this.toWhom = recipient; - await this.token.setApprovalForAll(proxy, true, { from: multiTokenHolder }); - ({ logs: this.transferLogs } = - await this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: proxy }, - )); - }); - - batchTransferWasSuccessful.call(this, { - operator: proxy, - from: multiTokenHolder, - ids: [firstTokenId, secondTokenId], - values: [firstAmount, secondAmount], - }); - - it('preserves operator\'s balances not involved in the transfer', async function () { - const balance1 = await this.token.balanceOf(proxy, firstTokenId); - expect(balance1).to.be.a.bignumber.equal('0'); - const balance2 = await this.token.balanceOf(proxy, secondTokenId); - expect(balance2).to.be.a.bignumber.equal('0'); - }); - }); - }); - - context('when sending to a valid receiver', function () { - beforeEach(async function () { - this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, false, - RECEIVER_BATCH_MAGIC_VALUE, false, - ); - }); - - context('without data', function () { - beforeEach(async function () { - this.toWhom = this.receiver.address; - this.transferReceipt = await this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - ); - ({ logs: this.transferLogs } = this.transferReceipt); - }); - - batchTransferWasSuccessful.call(this, { - operator: multiTokenHolder, - from: multiTokenHolder, - ids: [firstTokenId, secondTokenId], - values: [firstAmount, secondAmount], - }); - - it('calls onERC1155BatchReceived', async function () { - await expectEvent.inTransaction(this.transferReceipt.tx, ERC1155ReceiverMock, 'BatchReceived', { - operator: multiTokenHolder, - from: multiTokenHolder, - // ids: [firstTokenId, secondTokenId], - // values: [firstAmount, secondAmount], - data: null, - }); - }); - }); - - context('with data', function () { - const data = '0xf00dd00d'; - beforeEach(async function () { - this.toWhom = this.receiver.address; - this.transferReceipt = await this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - data, { from: multiTokenHolder }, - ); - ({ logs: this.transferLogs } = this.transferReceipt); - }); - - batchTransferWasSuccessful.call(this, { - operator: multiTokenHolder, - from: multiTokenHolder, - ids: [firstTokenId, secondTokenId], - values: [firstAmount, secondAmount], - }); - - it('calls onERC1155Received', async function () { - await expectEvent.inTransaction(this.transferReceipt.tx, ERC1155ReceiverMock, 'BatchReceived', { - operator: multiTokenHolder, - from: multiTokenHolder, - // ids: [firstTokenId, secondTokenId], - // values: [firstAmount, secondAmount], - data, - }); - }); - }); - }); - - context('to a receiver contract returning unexpected value', function () { - beforeEach(async function () { - this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, false, - RECEIVER_SINGLE_MAGIC_VALUE, false, - ); - }); - - it('reverts', async function () { - await expectRevert( - this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - ), - 'ERC1155: ERC1155Receiver rejected tokens', - ); - }); - }); - - context('to a receiver contract that reverts', function () { - beforeEach(async function () { - this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, false, - RECEIVER_BATCH_MAGIC_VALUE, true, - ); - }); - - it('reverts', async function () { - await expectRevert( - this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - ), - 'ERC1155ReceiverMock: reverting on batch receive', - ); - }); - }); - - context('to a receiver contract that reverts only on single transfers', function () { - beforeEach(async function () { - this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, true, - RECEIVER_BATCH_MAGIC_VALUE, false, - ); - - this.toWhom = this.receiver.address; - this.transferReceipt = await this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - ); - ({ logs: this.transferLogs } = this.transferReceipt); - }); - - batchTransferWasSuccessful.call(this, { - operator: multiTokenHolder, - from: multiTokenHolder, - ids: [firstTokenId, secondTokenId], - values: [firstAmount, secondAmount], - }); - - it('calls onERC1155BatchReceived', async function () { - await expectEvent.inTransaction(this.transferReceipt.tx, ERC1155ReceiverMock, 'BatchReceived', { - operator: multiTokenHolder, - from: multiTokenHolder, - // ids: [firstTokenId, secondTokenId], - // values: [firstAmount, secondAmount], - data: null, - }); - }); - }); - - context('to a contract that does not implement the required function', function () { - it('reverts', async function () { - const invalidReceiver = this.token; - await expectRevert.unspecified( - this.token.safeBatchTransferFrom( - multiTokenHolder, invalidReceiver.address, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - ), - ); - }); - }); - }); - - shouldSupportInterfaces(['ERC165', 'ERC1155']); - }); -} - -module.exports = { - shouldBehaveLikeERC1155, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/ERC1155.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/ERC1155.test.js deleted file mode 100644 index dffe054b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/ERC1155.test.js +++ /dev/null @@ -1,264 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const { shouldBehaveLikeERC1155 } = require('./ERC1155.behavior'); -const ERC1155Mock = artifacts.require('ERC1155Mock'); - -contract('ERC1155', function (accounts) { - const [operator, tokenHolder, tokenBatchHolder, ...otherAccounts] = accounts; - - const initialURI = 'https://token-cdn-domain/{id}.json'; - - beforeEach(async function () { - this.token = await ERC1155Mock.new(initialURI); - }); - - shouldBehaveLikeERC1155(otherAccounts); - - describe('internal functions', function () { - const tokenId = new BN(1990); - const mintAmount = new BN(9001); - const burnAmount = new BN(3000); - - const tokenBatchIds = [new BN(2000), new BN(2010), new BN(2020)]; - const mintAmounts = [new BN(5000), new BN(10000), new BN(42195)]; - const burnAmounts = [new BN(5000), new BN(9001), new BN(195)]; - - const data = '0x12345678'; - - describe('_mint', function () { - it('reverts with a zero destination address', async function () { - await expectRevert( - this.token.mint(ZERO_ADDRESS, tokenId, mintAmount, data), - 'ERC1155: mint to the zero address', - ); - }); - - context('with minted tokens', function () { - beforeEach(async function () { - ({ logs: this.logs } = await this.token.mint(tokenHolder, tokenId, mintAmount, data, { from: operator })); - }); - - it('emits a TransferSingle event', function () { - expectEvent.inLogs(this.logs, 'TransferSingle', { - operator, - from: ZERO_ADDRESS, - to: tokenHolder, - id: tokenId, - value: mintAmount, - }); - }); - - it('credits the minted amount of tokens', async function () { - expect(await this.token.balanceOf(tokenHolder, tokenId)).to.be.bignumber.equal(mintAmount); - }); - }); - }); - - describe('_mintBatch', function () { - it('reverts with a zero destination address', async function () { - await expectRevert( - this.token.mintBatch(ZERO_ADDRESS, tokenBatchIds, mintAmounts, data), - 'ERC1155: mint to the zero address', - ); - }); - - it('reverts if length of inputs do not match', async function () { - await expectRevert( - this.token.mintBatch(tokenBatchHolder, tokenBatchIds, mintAmounts.slice(1), data), - 'ERC1155: ids and amounts length mismatch', - ); - - await expectRevert( - this.token.mintBatch(tokenBatchHolder, tokenBatchIds.slice(1), mintAmounts, data), - 'ERC1155: ids and amounts length mismatch', - ); - }); - - context('with minted batch of tokens', function () { - beforeEach(async function () { - ({ logs: this.logs } = await this.token.mintBatch( - tokenBatchHolder, - tokenBatchIds, - mintAmounts, - data, - { from: operator }, - )); - }); - - it('emits a TransferBatch event', function () { - expectEvent.inLogs(this.logs, 'TransferBatch', { - operator, - from: ZERO_ADDRESS, - to: tokenBatchHolder, - }); - }); - - it('credits the minted batch of tokens', async function () { - const holderBatchBalances = await this.token.balanceOfBatch( - new Array(tokenBatchIds.length).fill(tokenBatchHolder), - tokenBatchIds, - ); - - for (let i = 0; i < holderBatchBalances.length; i++) { - expect(holderBatchBalances[i]).to.be.bignumber.equal(mintAmounts[i]); - } - }); - }); - }); - - describe('_burn', function () { - it('reverts when burning the zero account\'s tokens', async function () { - await expectRevert( - this.token.burn(ZERO_ADDRESS, tokenId, mintAmount), - 'ERC1155: burn from the zero address', - ); - }); - - it('reverts when burning a non-existent token id', async function () { - await expectRevert( - this.token.burn(tokenHolder, tokenId, mintAmount), - 'ERC1155: burn amount exceeds balance', - ); - }); - - it('reverts when burning more than available tokens', async function () { - await this.token.mint( - tokenHolder, - tokenId, - mintAmount, - data, - { from: operator }, - ); - - await expectRevert( - this.token.burn(tokenHolder, tokenId, mintAmount.addn(1)), - 'ERC1155: burn amount exceeds balance', - ); - }); - - context('with minted-then-burnt tokens', function () { - beforeEach(async function () { - await this.token.mint(tokenHolder, tokenId, mintAmount, data); - ({ logs: this.logs } = await this.token.burn( - tokenHolder, - tokenId, - burnAmount, - { from: operator }, - )); - }); - - it('emits a TransferSingle event', function () { - expectEvent.inLogs(this.logs, 'TransferSingle', { - operator, - from: tokenHolder, - to: ZERO_ADDRESS, - id: tokenId, - value: burnAmount, - }); - }); - - it('accounts for both minting and burning', async function () { - expect(await this.token.balanceOf( - tokenHolder, - tokenId, - )).to.be.bignumber.equal(mintAmount.sub(burnAmount)); - }); - }); - }); - - describe('_burnBatch', function () { - it('reverts when burning the zero account\'s tokens', async function () { - await expectRevert( - this.token.burnBatch(ZERO_ADDRESS, tokenBatchIds, burnAmounts), - 'ERC1155: burn from the zero address', - ); - }); - - it('reverts if length of inputs do not match', async function () { - await expectRevert( - this.token.burnBatch(tokenBatchHolder, tokenBatchIds, burnAmounts.slice(1)), - 'ERC1155: ids and amounts length mismatch', - ); - - await expectRevert( - this.token.burnBatch(tokenBatchHolder, tokenBatchIds.slice(1), burnAmounts), - 'ERC1155: ids and amounts length mismatch', - ); - }); - - it('reverts when burning a non-existent token id', async function () { - await expectRevert( - this.token.burnBatch(tokenBatchHolder, tokenBatchIds, burnAmounts), - 'ERC1155: burn amount exceeds balance', - ); - }); - - context('with minted-then-burnt tokens', function () { - beforeEach(async function () { - await this.token.mintBatch(tokenBatchHolder, tokenBatchIds, mintAmounts, data); - ({ logs: this.logs } = await this.token.burnBatch( - tokenBatchHolder, - tokenBatchIds, - burnAmounts, - { from: operator }, - )); - }); - - it('emits a TransferBatch event', function () { - expectEvent.inLogs(this.logs, 'TransferBatch', { - operator, - from: tokenBatchHolder, - to: ZERO_ADDRESS, - // ids: tokenBatchIds, - // values: burnAmounts, - }); - }); - - it('accounts for both minting and burning', async function () { - const holderBatchBalances = await this.token.balanceOfBatch( - new Array(tokenBatchIds.length).fill(tokenBatchHolder), - tokenBatchIds, - ); - - for (let i = 0; i < holderBatchBalances.length; i++) { - expect(holderBatchBalances[i]).to.be.bignumber.equal(mintAmounts[i].sub(burnAmounts[i])); - } - }); - }); - }); - }); - - describe('ERC1155MetadataURI', function () { - const firstTokenID = new BN('42'); - const secondTokenID = new BN('1337'); - - it('emits no URI event in constructor', async function () { - await expectEvent.notEmitted.inConstruction(this.token, 'URI'); - }); - - it('sets the initial URI for all token types', async function () { - expect(await this.token.uri(firstTokenID)).to.be.equal(initialURI); - expect(await this.token.uri(secondTokenID)).to.be.equal(initialURI); - }); - - describe('_setURI', function () { - const newURI = 'https://token-cdn-domain/{locale}/{id}.json'; - - it('emits no URI event', async function () { - const receipt = await this.token.setURI(newURI); - - expectEvent.notEmitted(receipt, 'URI'); - }); - - it('sets the new URI for all token types', async function () { - await this.token.setURI(newURI); - - expect(await this.token.uri(firstTokenID)).to.be.equal(newURI); - expect(await this.token.uri(secondTokenID)).to.be.equal(newURI); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Burnable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Burnable.test.js deleted file mode 100644 index b17f8d07..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Burnable.test.js +++ /dev/null @@ -1,67 +0,0 @@ -const { BN, expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC1155BurnableMock = artifacts.require('ERC1155BurnableMock'); - -contract('ERC1155Burnable', function (accounts) { - const [ holder, operator, other ] = accounts; - - const uri = 'https://token.com'; - - const tokenIds = [new BN('42'), new BN('1137')]; - const amounts = [new BN('3000'), new BN('9902')]; - - beforeEach(async function () { - this.token = await ERC1155BurnableMock.new(uri); - - await this.token.mint(holder, tokenIds[0], amounts[0], '0x'); - await this.token.mint(holder, tokenIds[1], amounts[1], '0x'); - }); - - describe('burn', function () { - it('holder can burn their tokens', async function () { - await this.token.burn(holder, tokenIds[0], amounts[0].subn(1), { from: holder }); - - expect(await this.token.balanceOf(holder, tokenIds[0])).to.be.bignumber.equal('1'); - }); - - it('approved operators can burn the holder\'s tokens', async function () { - await this.token.setApprovalForAll(operator, true, { from: holder }); - await this.token.burn(holder, tokenIds[0], amounts[0].subn(1), { from: operator }); - - expect(await this.token.balanceOf(holder, tokenIds[0])).to.be.bignumber.equal('1'); - }); - - it('unapproved accounts cannot burn the holder\'s tokens', async function () { - await expectRevert( - this.token.burn(holder, tokenIds[0], amounts[0].subn(1), { from: other }), - 'ERC1155: caller is not owner nor approved', - ); - }); - }); - - describe('burnBatch', function () { - it('holder can burn their tokens', async function () { - await this.token.burnBatch(holder, tokenIds, [ amounts[0].subn(1), amounts[1].subn(2) ], { from: holder }); - - expect(await this.token.balanceOf(holder, tokenIds[0])).to.be.bignumber.equal('1'); - expect(await this.token.balanceOf(holder, tokenIds[1])).to.be.bignumber.equal('2'); - }); - - it('approved operators can burn the holder\'s tokens', async function () { - await this.token.setApprovalForAll(operator, true, { from: holder }); - await this.token.burnBatch(holder, tokenIds, [ amounts[0].subn(1), amounts[1].subn(2) ], { from: operator }); - - expect(await this.token.balanceOf(holder, tokenIds[0])).to.be.bignumber.equal('1'); - expect(await this.token.balanceOf(holder, tokenIds[1])).to.be.bignumber.equal('2'); - }); - - it('unapproved accounts cannot burn the holder\'s tokens', async function () { - await expectRevert( - this.token.burnBatch(holder, tokenIds, [ amounts[0].subn(1), amounts[1].subn(2) ], { from: other }), - 'ERC1155: caller is not owner nor approved', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Pausable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Pausable.test.js deleted file mode 100644 index f7c40523..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Pausable.test.js +++ /dev/null @@ -1,108 +0,0 @@ -const { BN, expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC1155PausableMock = artifacts.require('ERC1155PausableMock'); - -contract('ERC1155Pausable', function (accounts) { - const [ holder, operator, receiver, other ] = accounts; - - const uri = 'https://token.com'; - - beforeEach(async function () { - this.token = await ERC1155PausableMock.new(uri); - }); - - context('when token is paused', function () { - const firstTokenId = new BN('37'); - const firstTokenAmount = new BN('42'); - - const secondTokenId = new BN('19842'); - const secondTokenAmount = new BN('23'); - - beforeEach(async function () { - await this.token.setApprovalForAll(operator, true, { from: holder }); - await this.token.mint(holder, firstTokenId, firstTokenAmount, '0x'); - - await this.token.pause(); - }); - - it('reverts when trying to safeTransferFrom from holder', async function () { - await expectRevert( - this.token.safeTransferFrom(holder, receiver, firstTokenId, firstTokenAmount, '0x', { from: holder }), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to safeTransferFrom from operator', async function () { - await expectRevert( - this.token.safeTransferFrom(holder, receiver, firstTokenId, firstTokenAmount, '0x', { from: operator }), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to safeBatchTransferFrom from holder', async function () { - await expectRevert( - this.token.safeBatchTransferFrom(holder, receiver, [firstTokenId], [firstTokenAmount], '0x', { from: holder }), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to safeBatchTransferFrom from operator', async function () { - await expectRevert( - this.token.safeBatchTransferFrom( - holder, receiver, [firstTokenId], [firstTokenAmount], '0x', { from: operator }, - ), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to mint', async function () { - await expectRevert( - this.token.mint(holder, secondTokenId, secondTokenAmount, '0x'), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to mintBatch', async function () { - await expectRevert( - this.token.mintBatch(holder, [secondTokenId], [secondTokenAmount], '0x'), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to burn', async function () { - await expectRevert( - this.token.burn(holder, firstTokenId, firstTokenAmount), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to burnBatch', async function () { - await expectRevert( - this.token.burnBatch(holder, [firstTokenId], [firstTokenAmount]), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - describe('setApprovalForAll', function () { - it('approves an operator', async function () { - await this.token.setApprovalForAll(other, true, { from: holder }); - expect(await this.token.isApprovedForAll(holder, other)).to.equal(true); - }); - }); - - describe('balanceOf', function () { - it('returns the amount of tokens owned by the given address', async function () { - const balance = await this.token.balanceOf(holder, firstTokenId); - expect(balance).to.be.bignumber.equal(firstTokenAmount); - }); - }); - - describe('isApprovedForAll', function () { - it('returns the approval of the operator', async function () { - expect(await this.token.isApprovedForAll(holder, operator)).to.equal(true); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Supply.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Supply.test.js deleted file mode 100644 index 1a632604..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/extensions/ERC1155Supply.test.js +++ /dev/null @@ -1,111 +0,0 @@ -const { BN } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC1155SupplyMock = artifacts.require('ERC1155SupplyMock'); - -contract('ERC1155Supply', function (accounts) { - const [ holder ] = accounts; - - const uri = 'https://token.com'; - - const firstTokenId = new BN('37'); - const firstTokenAmount = new BN('42'); - - const secondTokenId = new BN('19842'); - const secondTokenAmount = new BN('23'); - - beforeEach(async function () { - this.token = await ERC1155SupplyMock.new(uri); - }); - - context('before mint', function () { - it('exist', async function () { - expect(await this.token.exists(firstTokenId)).to.be.equal(false); - }); - - it('totalSupply', async function () { - expect(await this.token.totalSupply(firstTokenId)).to.be.bignumber.equal('0'); - }); - }); - - context('after mint', function () { - context('single', function () { - beforeEach(async function () { - await this.token.mint(holder, firstTokenId, firstTokenAmount, '0x'); - }); - - it('exist', async function () { - expect(await this.token.exists(firstTokenId)).to.be.equal(true); - }); - - it('totalSupply', async function () { - expect(await this.token.totalSupply(firstTokenId)).to.be.bignumber.equal(firstTokenAmount); - }); - }); - - context('batch', function () { - beforeEach(async function () { - await this.token.mintBatch( - holder, - [ firstTokenId, secondTokenId ], - [ firstTokenAmount, secondTokenAmount ], - '0x', - ); - }); - - it('exist', async function () { - expect(await this.token.exists(firstTokenId)).to.be.equal(true); - expect(await this.token.exists(secondTokenId)).to.be.equal(true); - }); - - it('totalSupply', async function () { - expect(await this.token.totalSupply(firstTokenId)).to.be.bignumber.equal(firstTokenAmount); - expect(await this.token.totalSupply(secondTokenId)).to.be.bignumber.equal(secondTokenAmount); - }); - }); - }); - - context('after burn', function () { - context('single', function () { - beforeEach(async function () { - await this.token.mint(holder, firstTokenId, firstTokenAmount, '0x'); - await this.token.burn(holder, firstTokenId, firstTokenAmount); - }); - - it('exist', async function () { - expect(await this.token.exists(firstTokenId)).to.be.equal(false); - }); - - it('totalSupply', async function () { - expect(await this.token.totalSupply(firstTokenId)).to.be.bignumber.equal('0'); - }); - }); - - context('batch', function () { - beforeEach(async function () { - await this.token.mintBatch( - holder, - [ firstTokenId, secondTokenId ], - [ firstTokenAmount, secondTokenAmount ], - '0x', - ); - await this.token.burnBatch( - holder, - [ firstTokenId, secondTokenId ], - [ firstTokenAmount, secondTokenAmount ], - ); - }); - - it('exist', async function () { - expect(await this.token.exists(firstTokenId)).to.be.equal(false); - expect(await this.token.exists(secondTokenId)).to.be.equal(false); - }); - - it('totalSupply', async function () { - expect(await this.token.totalSupply(firstTokenId)).to.be.bignumber.equal('0'); - expect(await this.token.totalSupply(secondTokenId)).to.be.bignumber.equal('0'); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/presets/ERC1155PresetMinterPauser.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/presets/ERC1155PresetMinterPauser.test.js deleted file mode 100644 index a8d83d12..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/presets/ERC1155PresetMinterPauser.test.js +++ /dev/null @@ -1,146 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; -const { shouldSupportInterfaces } = require('../../../utils/introspection/SupportsInterface.behavior'); - -const { expect } = require('chai'); - -const ERC1155PresetMinterPauser = artifacts.require('ERC1155PresetMinterPauser'); - -contract('ERC1155PresetMinterPauser', function (accounts) { - const [ deployer, other ] = accounts; - - const firstTokenId = new BN('845'); - const firstTokenIdAmount = new BN('5000'); - - const secondTokenId = new BN('48324'); - const secondTokenIdAmount = new BN('77875'); - - const DEFAULT_ADMIN_ROLE = '0x0000000000000000000000000000000000000000000000000000000000000000'; - const MINTER_ROLE = web3.utils.soliditySha3('MINTER_ROLE'); - const PAUSER_ROLE = web3.utils.soliditySha3('PAUSER_ROLE'); - - const uri = 'https://token.com'; - - beforeEach(async function () { - this.token = await ERC1155PresetMinterPauser.new(uri, { from: deployer }); - }); - - shouldSupportInterfaces(['ERC1155', 'AccessControl', 'AccessControlEnumerable']); - - it('deployer has the default admin role', async function () { - expect(await this.token.getRoleMemberCount(DEFAULT_ADMIN_ROLE)).to.be.bignumber.equal('1'); - expect(await this.token.getRoleMember(DEFAULT_ADMIN_ROLE, 0)).to.equal(deployer); - }); - - it('deployer has the minter role', async function () { - expect(await this.token.getRoleMemberCount(MINTER_ROLE)).to.be.bignumber.equal('1'); - expect(await this.token.getRoleMember(MINTER_ROLE, 0)).to.equal(deployer); - }); - - it('deployer has the pauser role', async function () { - expect(await this.token.getRoleMemberCount(PAUSER_ROLE)).to.be.bignumber.equal('1'); - expect(await this.token.getRoleMember(PAUSER_ROLE, 0)).to.equal(deployer); - }); - - it('minter and pauser role admin is the default admin', async function () { - expect(await this.token.getRoleAdmin(MINTER_ROLE)).to.equal(DEFAULT_ADMIN_ROLE); - expect(await this.token.getRoleAdmin(PAUSER_ROLE)).to.equal(DEFAULT_ADMIN_ROLE); - }); - - describe('minting', function () { - it('deployer can mint tokens', async function () { - const receipt = await this.token.mint(other, firstTokenId, firstTokenIdAmount, '0x', { from: deployer }); - expectEvent(receipt, 'TransferSingle', - { operator: deployer, from: ZERO_ADDRESS, to: other, value: firstTokenIdAmount, id: firstTokenId }, - ); - - expect(await this.token.balanceOf(other, firstTokenId)).to.be.bignumber.equal(firstTokenIdAmount); - }); - - it('other accounts cannot mint tokens', async function () { - await expectRevert( - this.token.mint(other, firstTokenId, firstTokenIdAmount, '0x', { from: other }), - 'ERC1155PresetMinterPauser: must have minter role to mint', - ); - }); - }); - - describe('batched minting', function () { - it('deployer can batch mint tokens', async function () { - const receipt = await this.token.mintBatch( - other, [firstTokenId, secondTokenId], [firstTokenIdAmount, secondTokenIdAmount], '0x', { from: deployer }, - ); - - expectEvent(receipt, 'TransferBatch', - { operator: deployer, from: ZERO_ADDRESS, to: other }, - ); - - expect(await this.token.balanceOf(other, firstTokenId)).to.be.bignumber.equal(firstTokenIdAmount); - }); - - it('other accounts cannot batch mint tokens', async function () { - await expectRevert( - this.token.mintBatch( - other, [firstTokenId, secondTokenId], [firstTokenIdAmount, secondTokenIdAmount], '0x', { from: other }, - ), - 'ERC1155PresetMinterPauser: must have minter role to mint', - ); - }); - }); - - describe('pausing', function () { - it('deployer can pause', async function () { - const receipt = await this.token.pause({ from: deployer }); - expectEvent(receipt, 'Paused', { account: deployer }); - - expect(await this.token.paused()).to.equal(true); - }); - - it('deployer can unpause', async function () { - await this.token.pause({ from: deployer }); - - const receipt = await this.token.unpause({ from: deployer }); - expectEvent(receipt, 'Unpaused', { account: deployer }); - - expect(await this.token.paused()).to.equal(false); - }); - - it('cannot mint while paused', async function () { - await this.token.pause({ from: deployer }); - - await expectRevert( - this.token.mint(other, firstTokenId, firstTokenIdAmount, '0x', { from: deployer }), - 'ERC1155Pausable: token transfer while paused', - ); - }); - - it('other accounts cannot pause', async function () { - await expectRevert( - this.token.pause({ from: other }), - 'ERC1155PresetMinterPauser: must have pauser role to pause', - ); - }); - - it('other accounts cannot unpause', async function () { - await this.token.pause({ from: deployer }); - - await expectRevert( - this.token.unpause({ from: other }), - 'ERC1155PresetMinterPauser: must have pauser role to unpause', - ); - }); - }); - - describe('burning', function () { - it('holders can burn their tokens', async function () { - await this.token.mint(other, firstTokenId, firstTokenIdAmount, '0x', { from: deployer }); - - const receipt = await this.token.burn(other, firstTokenId, firstTokenIdAmount.subn(1), { from: other }); - expectEvent(receipt, 'TransferSingle', - { operator: other, from: other, to: ZERO_ADDRESS, value: firstTokenIdAmount.subn(1), id: firstTokenId }, - ); - - expect(await this.token.balanceOf(other, firstTokenId)).to.be.bignumber.equal('1'); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/utils/ERC1155Holder.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/utils/ERC1155Holder.test.js deleted file mode 100644 index 41225c23..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC1155/utils/ERC1155Holder.test.js +++ /dev/null @@ -1,62 +0,0 @@ -const { BN } = require('@openzeppelin/test-helpers'); - -const ERC1155Holder = artifacts.require('ERC1155Holder'); -const ERC1155Mock = artifacts.require('ERC1155Mock'); - -const { expect } = require('chai'); - -const { shouldSupportInterfaces } = require('../../../utils/introspection/SupportsInterface.behavior'); - -contract('ERC1155Holder', function (accounts) { - const [creator] = accounts; - const uri = 'https://token-cdn-domain/{id}.json'; - const multiTokenIds = [new BN(1), new BN(2), new BN(3)]; - const multiTokenAmounts = [new BN(1000), new BN(2000), new BN(3000)]; - const transferData = '0x12345678'; - - beforeEach(async function () { - this.multiToken = await ERC1155Mock.new(uri, { from: creator }); - this.holder = await ERC1155Holder.new(); - await this.multiToken.mintBatch(creator, multiTokenIds, multiTokenAmounts, '0x', { from: creator }); - }); - - shouldSupportInterfaces(['ERC165', 'ERC1155Receiver']); - - it('receives ERC1155 tokens from a single ID', async function () { - await this.multiToken.safeTransferFrom( - creator, - this.holder.address, - multiTokenIds[0], - multiTokenAmounts[0], - transferData, - { from: creator }, - ); - - expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[0])) - .to.be.bignumber.equal(multiTokenAmounts[0]); - - for (let i = 1; i < multiTokenIds.length; i++) { - expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[i])).to.be.bignumber.equal(new BN(0)); - } - }); - - it('receives ERC1155 tokens from a multiple IDs', async function () { - for (let i = 0; i < multiTokenIds.length; i++) { - expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[i])).to.be.bignumber.equal(new BN(0)); - }; - - await this.multiToken.safeBatchTransferFrom( - creator, - this.holder.address, - multiTokenIds, - multiTokenAmounts, - transferData, - { from: creator }, - ); - - for (let i = 0; i < multiTokenIds.length; i++) { - expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[i])) - .to.be.bignumber.equal(multiTokenAmounts[i]); - } - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/ERC20.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/ERC20.behavior.js deleted file mode 100644 index 8bc54762..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/ERC20.behavior.js +++ /dev/null @@ -1,333 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { ZERO_ADDRESS, MAX_UINT256 } = constants; - -function shouldBehaveLikeERC20 (errorPrefix, initialSupply, initialHolder, recipient, anotherAccount) { - describe('total supply', function () { - it('returns the total amount of tokens', async function () { - expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply); - }); - }); - - describe('balanceOf', function () { - describe('when the requested account has no tokens', function () { - it('returns zero', async function () { - expect(await this.token.balanceOf(anotherAccount)).to.be.bignumber.equal('0'); - }); - }); - - describe('when the requested account has some tokens', function () { - it('returns the total amount of tokens', async function () { - expect(await this.token.balanceOf(initialHolder)).to.be.bignumber.equal(initialSupply); - }); - }); - }); - - describe('transfer', function () { - shouldBehaveLikeERC20Transfer(errorPrefix, initialHolder, recipient, initialSupply, - function (from, to, value) { - return this.token.transfer(to, value, { from }); - }, - ); - }); - - describe('transfer from', function () { - const spender = recipient; - - describe('when the token owner is not the zero address', function () { - const tokenOwner = initialHolder; - - describe('when the recipient is not the zero address', function () { - const to = anotherAccount; - - describe('when the spender has enough allowance', function () { - beforeEach(async function () { - await this.token.approve(spender, initialSupply, { from: initialHolder }); - }); - - describe('when the token owner has enough balance', function () { - const amount = initialSupply; - - it('transfers the requested amount', async function () { - await this.token.transferFrom(tokenOwner, to, amount, { from: spender }); - - expect(await this.token.balanceOf(tokenOwner)).to.be.bignumber.equal('0'); - - expect(await this.token.balanceOf(to)).to.be.bignumber.equal(amount); - }); - - it('decreases the spender allowance', async function () { - await this.token.transferFrom(tokenOwner, to, amount, { from: spender }); - - expect(await this.token.allowance(tokenOwner, spender)).to.be.bignumber.equal('0'); - }); - - it('emits a transfer event', async function () { - expectEvent( - await this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - 'Transfer', - { from: tokenOwner, to: to, value: amount }, - ); - }); - - it('emits an approval event', async function () { - expectEvent( - await this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - 'Approval', - { owner: tokenOwner, spender: spender, value: await this.token.allowance(tokenOwner, spender) }, - ); - }); - }); - - describe('when the token owner does not have enough balance', function () { - const amount = initialSupply; - - beforeEach('reducing balance', async function () { - await this.token.transfer(to, 1, { from: tokenOwner }); - }); - - it('reverts', async function () { - await expectRevert( - this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - `${errorPrefix}: transfer amount exceeds balance`, - ); - }); - }); - }); - - describe('when the spender does not have enough allowance', function () { - const allowance = initialSupply.subn(1); - - beforeEach(async function () { - await this.token.approve(spender, allowance, { from: tokenOwner }); - }); - - describe('when the token owner has enough balance', function () { - const amount = initialSupply; - - it('reverts', async function () { - await expectRevert( - this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - `${errorPrefix}: insufficient allowance`, - ); - }); - }); - - describe('when the token owner does not have enough balance', function () { - const amount = allowance; - - beforeEach('reducing balance', async function () { - await this.token.transfer(to, 2, { from: tokenOwner }); - }); - - it('reverts', async function () { - await expectRevert( - this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - `${errorPrefix}: transfer amount exceeds balance`, - ); - }); - }); - }); - - describe('when the spender has unlimited allowance', function () { - beforeEach(async function () { - await this.token.approve(spender, MAX_UINT256, { from: initialHolder }); - }); - - it('does not decrease the spender allowance', async function () { - await this.token.transferFrom(tokenOwner, to, 1, { from: spender }); - - expect(await this.token.allowance(tokenOwner, spender)).to.be.bignumber.equal(MAX_UINT256); - }); - - it('does not emit an approval event', async function () { - expectEvent.notEmitted( - await this.token.transferFrom(tokenOwner, to, 1, { from: spender }), - 'Approval', - ); - }); - }); - }); - - describe('when the recipient is the zero address', function () { - const amount = initialSupply; - const to = ZERO_ADDRESS; - - beforeEach(async function () { - await this.token.approve(spender, amount, { from: tokenOwner }); - }); - - it('reverts', async function () { - await expectRevert(this.token.transferFrom( - tokenOwner, to, amount, { from: spender }), `${errorPrefix}: transfer to the zero address`, - ); - }); - }); - }); - - describe('when the token owner is the zero address', function () { - const amount = 0; - const tokenOwner = ZERO_ADDRESS; - const to = recipient; - - it('reverts', async function () { - await expectRevert( - this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - 'from the zero address', - ); - }); - }); - }); - - describe('approve', function () { - shouldBehaveLikeERC20Approve(errorPrefix, initialHolder, recipient, initialSupply, - function (owner, spender, amount) { - return this.token.approve(spender, amount, { from: owner }); - }, - ); - }); -} - -function shouldBehaveLikeERC20Transfer (errorPrefix, from, to, balance, transfer) { - describe('when the recipient is not the zero address', function () { - describe('when the sender does not have enough balance', function () { - const amount = balance.addn(1); - - it('reverts', async function () { - await expectRevert(transfer.call(this, from, to, amount), - `${errorPrefix}: transfer amount exceeds balance`, - ); - }); - }); - - describe('when the sender transfers all balance', function () { - const amount = balance; - - it('transfers the requested amount', async function () { - await transfer.call(this, from, to, amount); - - expect(await this.token.balanceOf(from)).to.be.bignumber.equal('0'); - - expect(await this.token.balanceOf(to)).to.be.bignumber.equal(amount); - }); - - it('emits a transfer event', async function () { - expectEvent( - await transfer.call(this, from, to, amount), - 'Transfer', - { from, to, value: amount }, - ); - }); - }); - - describe('when the sender transfers zero tokens', function () { - const amount = new BN('0'); - - it('transfers the requested amount', async function () { - await transfer.call(this, from, to, amount); - - expect(await this.token.balanceOf(from)).to.be.bignumber.equal(balance); - - expect(await this.token.balanceOf(to)).to.be.bignumber.equal('0'); - }); - - it('emits a transfer event', async function () { - expectEvent( - await transfer.call(this, from, to, amount), - 'Transfer', - { from, to, value: amount }, - ); - }); - }); - }); - - describe('when the recipient is the zero address', function () { - it('reverts', async function () { - await expectRevert(transfer.call(this, from, ZERO_ADDRESS, balance), - `${errorPrefix}: transfer to the zero address`, - ); - }); - }); -} - -function shouldBehaveLikeERC20Approve (errorPrefix, owner, spender, supply, approve) { - describe('when the spender is not the zero address', function () { - describe('when the sender has enough balance', function () { - const amount = supply; - - it('emits an approval event', async function () { - expectEvent( - await approve.call(this, owner, spender, amount), - 'Approval', - { owner: owner, spender: spender, value: amount }, - ); - }); - - describe('when there was no approved amount before', function () { - it('approves the requested amount', async function () { - await approve.call(this, owner, spender, amount); - - expect(await this.token.allowance(owner, spender)).to.be.bignumber.equal(amount); - }); - }); - - describe('when the spender had an approved amount', function () { - beforeEach(async function () { - await approve.call(this, owner, spender, new BN(1)); - }); - - it('approves the requested amount and replaces the previous one', async function () { - await approve.call(this, owner, spender, amount); - - expect(await this.token.allowance(owner, spender)).to.be.bignumber.equal(amount); - }); - }); - }); - - describe('when the sender does not have enough balance', function () { - const amount = supply.addn(1); - - it('emits an approval event', async function () { - expectEvent( - await approve.call(this, owner, spender, amount), - 'Approval', - { owner: owner, spender: spender, value: amount }, - ); - }); - - describe('when there was no approved amount before', function () { - it('approves the requested amount', async function () { - await approve.call(this, owner, spender, amount); - - expect(await this.token.allowance(owner, spender)).to.be.bignumber.equal(amount); - }); - }); - - describe('when the spender had an approved amount', function () { - beforeEach(async function () { - await approve.call(this, owner, spender, new BN(1)); - }); - - it('approves the requested amount and replaces the previous one', async function () { - await approve.call(this, owner, spender, amount); - - expect(await this.token.allowance(owner, spender)).to.be.bignumber.equal(amount); - }); - }); - }); - }); - - describe('when the spender is the zero address', function () { - it('reverts', async function () { - await expectRevert(approve.call(this, owner, ZERO_ADDRESS, supply), - `${errorPrefix}: approve to the zero address`, - ); - }); - }); -} - -module.exports = { - shouldBehaveLikeERC20, - shouldBehaveLikeERC20Transfer, - shouldBehaveLikeERC20Approve, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/ERC20.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/ERC20.test.js deleted file mode 100644 index 992edf93..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/ERC20.test.js +++ /dev/null @@ -1,309 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { ZERO_ADDRESS } = constants; - -const { - shouldBehaveLikeERC20, - shouldBehaveLikeERC20Transfer, - shouldBehaveLikeERC20Approve, -} = require('./ERC20.behavior'); - -const ERC20Mock = artifacts.require('ERC20Mock'); -const ERC20DecimalsMock = artifacts.require('ERC20DecimalsMock'); - -contract('ERC20', function (accounts) { - const [ initialHolder, recipient, anotherAccount ] = accounts; - - const name = 'My Token'; - const symbol = 'MTKN'; - - const initialSupply = new BN(100); - - beforeEach(async function () { - this.token = await ERC20Mock.new(name, symbol, initialHolder, initialSupply); - }); - - it('has a name', async function () { - expect(await this.token.name()).to.equal(name); - }); - - it('has a symbol', async function () { - expect(await this.token.symbol()).to.equal(symbol); - }); - - it('has 18 decimals', async function () { - expect(await this.token.decimals()).to.be.bignumber.equal('18'); - }); - - describe('set decimals', function () { - const decimals = new BN(6); - - it('can set decimals during construction', async function () { - const token = await ERC20DecimalsMock.new(name, symbol, decimals); - expect(await token.decimals()).to.be.bignumber.equal(decimals); - }); - }); - - shouldBehaveLikeERC20('ERC20', initialSupply, initialHolder, recipient, anotherAccount); - - describe('decrease allowance', function () { - describe('when the spender is not the zero address', function () { - const spender = recipient; - - function shouldDecreaseApproval (amount) { - describe('when there was no approved amount before', function () { - it('reverts', async function () { - await expectRevert(this.token.decreaseAllowance( - spender, amount, { from: initialHolder }), 'ERC20: decreased allowance below zero', - ); - }); - }); - - describe('when the spender had an approved amount', function () { - const approvedAmount = amount; - - beforeEach(async function () { - await this.token.approve(spender, approvedAmount, { from: initialHolder }); - }); - - it('emits an approval event', async function () { - expectEvent( - await this.token.decreaseAllowance(spender, approvedAmount, { from: initialHolder }), - 'Approval', - { owner: initialHolder, spender: spender, value: new BN(0) }, - ); - }); - - it('decreases the spender allowance subtracting the requested amount', async function () { - await this.token.decreaseAllowance(spender, approvedAmount.subn(1), { from: initialHolder }); - - expect(await this.token.allowance(initialHolder, spender)).to.be.bignumber.equal('1'); - }); - - it('sets the allowance to zero when all allowance is removed', async function () { - await this.token.decreaseAllowance(spender, approvedAmount, { from: initialHolder }); - expect(await this.token.allowance(initialHolder, spender)).to.be.bignumber.equal('0'); - }); - - it('reverts when more than the full allowance is removed', async function () { - await expectRevert( - this.token.decreaseAllowance(spender, approvedAmount.addn(1), { from: initialHolder }), - 'ERC20: decreased allowance below zero', - ); - }); - }); - } - - describe('when the sender has enough balance', function () { - const amount = initialSupply; - - shouldDecreaseApproval(amount); - }); - - describe('when the sender does not have enough balance', function () { - const amount = initialSupply.addn(1); - - shouldDecreaseApproval(amount); - }); - }); - - describe('when the spender is the zero address', function () { - const amount = initialSupply; - const spender = ZERO_ADDRESS; - - it('reverts', async function () { - await expectRevert(this.token.decreaseAllowance( - spender, amount, { from: initialHolder }), 'ERC20: decreased allowance below zero', - ); - }); - }); - }); - - describe('increase allowance', function () { - const amount = initialSupply; - - describe('when the spender is not the zero address', function () { - const spender = recipient; - - describe('when the sender has enough balance', function () { - it('emits an approval event', async function () { - expectEvent( - await this.token.increaseAllowance(spender, amount, { from: initialHolder }), - 'Approval', - { owner: initialHolder, spender: spender, value: amount }, - ); - }); - - describe('when there was no approved amount before', function () { - it('approves the requested amount', async function () { - await this.token.increaseAllowance(spender, amount, { from: initialHolder }); - - expect(await this.token.allowance(initialHolder, spender)).to.be.bignumber.equal(amount); - }); - }); - - describe('when the spender had an approved amount', function () { - beforeEach(async function () { - await this.token.approve(spender, new BN(1), { from: initialHolder }); - }); - - it('increases the spender allowance adding the requested amount', async function () { - await this.token.increaseAllowance(spender, amount, { from: initialHolder }); - - expect(await this.token.allowance(initialHolder, spender)).to.be.bignumber.equal(amount.addn(1)); - }); - }); - }); - - describe('when the sender does not have enough balance', function () { - const amount = initialSupply.addn(1); - - it('emits an approval event', async function () { - expectEvent( - await this.token.increaseAllowance(spender, amount, { from: initialHolder }), - 'Approval', - { owner: initialHolder, spender: spender, value: amount }, - ); - }); - - describe('when there was no approved amount before', function () { - it('approves the requested amount', async function () { - await this.token.increaseAllowance(spender, amount, { from: initialHolder }); - - expect(await this.token.allowance(initialHolder, spender)).to.be.bignumber.equal(amount); - }); - }); - - describe('when the spender had an approved amount', function () { - beforeEach(async function () { - await this.token.approve(spender, new BN(1), { from: initialHolder }); - }); - - it('increases the spender allowance adding the requested amount', async function () { - await this.token.increaseAllowance(spender, amount, { from: initialHolder }); - - expect(await this.token.allowance(initialHolder, spender)).to.be.bignumber.equal(amount.addn(1)); - }); - }); - }); - }); - - describe('when the spender is the zero address', function () { - const spender = ZERO_ADDRESS; - - it('reverts', async function () { - await expectRevert( - this.token.increaseAllowance(spender, amount, { from: initialHolder }), 'ERC20: approve to the zero address', - ); - }); - }); - }); - - describe('_mint', function () { - const amount = new BN(50); - it('rejects a null account', async function () { - await expectRevert( - this.token.mint(ZERO_ADDRESS, amount), 'ERC20: mint to the zero address', - ); - }); - - describe('for a non zero account', function () { - beforeEach('minting', async function () { - this.receipt = await this.token.mint(recipient, amount); - }); - - it('increments totalSupply', async function () { - const expectedSupply = initialSupply.add(amount); - expect(await this.token.totalSupply()).to.be.bignumber.equal(expectedSupply); - }); - - it('increments recipient balance', async function () { - expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(amount); - }); - - it('emits Transfer event', async function () { - const event = expectEvent( - this.receipt, - 'Transfer', - { from: ZERO_ADDRESS, to: recipient }, - ); - - expect(event.args.value).to.be.bignumber.equal(amount); - }); - }); - }); - - describe('_burn', function () { - it('rejects a null account', async function () { - await expectRevert(this.token.burn(ZERO_ADDRESS, new BN(1)), - 'ERC20: burn from the zero address'); - }); - - describe('for a non zero account', function () { - it('rejects burning more than balance', async function () { - await expectRevert(this.token.burn( - initialHolder, initialSupply.addn(1)), 'ERC20: burn amount exceeds balance', - ); - }); - - const describeBurn = function (description, amount) { - describe(description, function () { - beforeEach('burning', async function () { - this.receipt = await this.token.burn(initialHolder, amount); - }); - - it('decrements totalSupply', async function () { - const expectedSupply = initialSupply.sub(amount); - expect(await this.token.totalSupply()).to.be.bignumber.equal(expectedSupply); - }); - - it('decrements initialHolder balance', async function () { - const expectedBalance = initialSupply.sub(amount); - expect(await this.token.balanceOf(initialHolder)).to.be.bignumber.equal(expectedBalance); - }); - - it('emits Transfer event', async function () { - const event = expectEvent( - this.receipt, - 'Transfer', - { from: initialHolder, to: ZERO_ADDRESS }, - ); - - expect(event.args.value).to.be.bignumber.equal(amount); - }); - }); - }; - - describeBurn('for entire balance', initialSupply); - describeBurn('for less amount than balance', initialSupply.subn(1)); - }); - }); - - describe('_transfer', function () { - shouldBehaveLikeERC20Transfer('ERC20', initialHolder, recipient, initialSupply, function (from, to, amount) { - return this.token.transferInternal(from, to, amount); - }); - - describe('when the sender is the zero address', function () { - it('reverts', async function () { - await expectRevert(this.token.transferInternal(ZERO_ADDRESS, recipient, initialSupply), - 'ERC20: transfer from the zero address', - ); - }); - }); - }); - - describe('_approve', function () { - shouldBehaveLikeERC20Approve('ERC20', initialHolder, recipient, initialSupply, function (owner, spender, amount) { - return this.token.approveInternal(owner, spender, amount); - }); - - describe('when the owner is the zero address', function () { - it('reverts', async function () { - await expectRevert(this.token.approveInternal(ZERO_ADDRESS, recipient, initialSupply), - 'ERC20: approve from the zero address', - ); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Burnable.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Burnable.behavior.js deleted file mode 100644 index 3ba2fc9d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Burnable.behavior.js +++ /dev/null @@ -1,110 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { - describe('burn', function () { - describe('when the given amount is not greater than balance of the sender', function () { - context('for a zero amount', function () { - shouldBurn(new BN(0)); - }); - - context('for a non-zero amount', function () { - shouldBurn(new BN(100)); - }); - - function shouldBurn (amount) { - beforeEach(async function () { - ({ logs: this.logs } = await this.token.burn(amount, { from: owner })); - }); - - it('burns the requested amount', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal(initialBalance.sub(amount)); - }); - - it('emits a transfer event', async function () { - expectEvent.inLogs(this.logs, 'Transfer', { - from: owner, - to: ZERO_ADDRESS, - value: amount, - }); - }); - } - }); - - describe('when the given amount is greater than the balance of the sender', function () { - const amount = initialBalance.addn(1); - - it('reverts', async function () { - await expectRevert(this.token.burn(amount, { from: owner }), - 'ERC20: burn amount exceeds balance', - ); - }); - }); - }); - - describe('burnFrom', function () { - describe('on success', function () { - context('for a zero amount', function () { - shouldBurnFrom(new BN(0)); - }); - - context('for a non-zero amount', function () { - shouldBurnFrom(new BN(100)); - }); - - function shouldBurnFrom (amount) { - const originalAllowance = amount.muln(3); - - beforeEach(async function () { - await this.token.approve(burner, originalAllowance, { from: owner }); - const { logs } = await this.token.burnFrom(owner, amount, { from: burner }); - this.logs = logs; - }); - - it('burns the requested amount', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal(initialBalance.sub(amount)); - }); - - it('decrements allowance', async function () { - expect(await this.token.allowance(owner, burner)).to.be.bignumber.equal(originalAllowance.sub(amount)); - }); - - it('emits a transfer event', async function () { - expectEvent.inLogs(this.logs, 'Transfer', { - from: owner, - to: ZERO_ADDRESS, - value: amount, - }); - }); - } - }); - - describe('when the given amount is greater than the balance of the sender', function () { - const amount = initialBalance.addn(1); - - it('reverts', async function () { - await this.token.approve(burner, amount, { from: owner }); - await expectRevert(this.token.burnFrom(owner, amount, { from: burner }), - 'ERC20: burn amount exceeds balance', - ); - }); - }); - - describe('when the given amount is greater than the allowance', function () { - const allowance = new BN(100); - - it('reverts', async function () { - await this.token.approve(burner, allowance, { from: owner }); - await expectRevert(this.token.burnFrom(owner, allowance.addn(1), { from: burner }), - 'ERC20: insufficient allowance', - ); - }); - }); - }); -} - -module.exports = { - shouldBehaveLikeERC20Burnable, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Burnable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Burnable.test.js deleted file mode 100644 index 8aa4fb66..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Burnable.test.js +++ /dev/null @@ -1,19 +0,0 @@ -const { BN } = require('@openzeppelin/test-helpers'); - -const { shouldBehaveLikeERC20Burnable } = require('./ERC20Burnable.behavior'); -const ERC20BurnableMock = artifacts.require('ERC20BurnableMock'); - -contract('ERC20Burnable', function (accounts) { - const [ owner, ...otherAccounts ] = accounts; - - const initialBalance = new BN(1000); - - const name = 'My Token'; - const symbol = 'MTKN'; - - beforeEach(async function () { - this.token = await ERC20BurnableMock.new(name, symbol, owner, initialBalance, { from: owner }); - }); - - shouldBehaveLikeERC20Burnable(owner, initialBalance, otherAccounts); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Capped.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Capped.behavior.js deleted file mode 100644 index 4692f997..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Capped.behavior.js +++ /dev/null @@ -1,32 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -function shouldBehaveLikeERC20Capped (minter, [other], cap) { - describe('capped token', function () { - const from = minter; - - it('starts with the correct cap', async function () { - expect(await this.token.cap()).to.be.bignumber.equal(cap); - }); - - it('mints when amount is less than cap', async function () { - await this.token.mint(other, cap.subn(1), { from }); - expect(await this.token.totalSupply()).to.be.bignumber.equal(cap.subn(1)); - }); - - it('fails to mint if the amount exceeds the cap', async function () { - await this.token.mint(other, cap.subn(1), { from }); - await expectRevert(this.token.mint(other, 2, { from }), 'ERC20Capped: cap exceeded'); - }); - - it('fails to mint after cap is reached', async function () { - await this.token.mint(other, cap, { from }); - await expectRevert(this.token.mint(other, 1, { from }), 'ERC20Capped: cap exceeded'); - }); - }); -} - -module.exports = { - shouldBehaveLikeERC20Capped, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Capped.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Capped.test.js deleted file mode 100644 index 76532cef..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Capped.test.js +++ /dev/null @@ -1,27 +0,0 @@ -const { BN, ether, expectRevert } = require('@openzeppelin/test-helpers'); -const { shouldBehaveLikeERC20Capped } = require('./ERC20Capped.behavior'); - -const ERC20Capped = artifacts.require('ERC20CappedMock'); - -contract('ERC20Capped', function (accounts) { - const [ minter, ...otherAccounts ] = accounts; - - const cap = ether('1000'); - - const name = 'My Token'; - const symbol = 'MTKN'; - - it('requires a non-zero cap', async function () { - await expectRevert( - ERC20Capped.new(name, symbol, new BN(0), { from: minter }), 'ERC20Capped: cap is 0', - ); - }); - - context('once deployed', async function () { - beforeEach(async function () { - this.token = await ERC20Capped.new(name, symbol, cap, { from: minter }); - }); - - shouldBehaveLikeERC20Capped(minter, otherAccounts, cap); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20FlashMint.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20FlashMint.test.js deleted file mode 100644 index 97af5bb8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20FlashMint.test.js +++ /dev/null @@ -1,90 +0,0 @@ -/* eslint-disable */ - -const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { MAX_UINT256, ZERO_ADDRESS, ZERO_BYTES32 } = constants; - -const ERC20FlashMintMock = artifacts.require('ERC20FlashMintMock'); -const ERC3156FlashBorrowerMock = artifacts.require('ERC3156FlashBorrowerMock'); - -contract('ERC20FlashMint', function (accounts) { - const [ initialHolder, other ] = accounts; - - const name = 'My Token'; - const symbol = 'MTKN'; - - const initialSupply = new BN(100); - const loanAmount = new BN(10000000000000); - - beforeEach(async function () { - this.token = await ERC20FlashMintMock.new(name, symbol, initialHolder, initialSupply); - }); - - describe('maxFlashLoan', function () { - it('token match', async function () { - expect(await this.token.maxFlashLoan(this.token.address)).to.be.bignumber.equal(MAX_UINT256.sub(initialSupply)); - }); - - it('token mismatch', async function () { - expect(await this.token.maxFlashLoan(ZERO_ADDRESS)).to.be.bignumber.equal('0'); - }); - }); - - describe('flashFee', function () { - it('token match', async function () { - expect(await this.token.flashFee(this.token.address, loanAmount)).to.be.bignumber.equal('0'); - }); - - it('token mismatch', async function () { - await expectRevert(this.token.flashFee(ZERO_ADDRESS, loanAmount), 'ERC20FlashMint: wrong token'); - }); - }); - - describe('flashLoan', function () { - it('success', async function () { - const receiver = await ERC3156FlashBorrowerMock.new(true, true); - const { tx } = await this.token.flashLoan(receiver.address, this.token.address, loanAmount, '0x'); - - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: ZERO_ADDRESS, to: receiver.address, value: loanAmount }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: receiver.address, to: ZERO_ADDRESS, value: loanAmount }); - await expectEvent.inTransaction(tx, receiver, 'BalanceOf', { token: this.token.address, account: receiver.address, value: loanAmount }); - await expectEvent.inTransaction(tx, receiver, 'TotalSupply', { token: this.token.address, value: initialSupply.add(loanAmount) }); - - expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply); - expect(await this.token.balanceOf(receiver.address)).to.be.bignumber.equal('0'); - expect(await this.token.allowance(receiver.address, this.token.address)).to.be.bignumber.equal('0'); - }); - - it ('missing return value', async function () { - const receiver = await ERC3156FlashBorrowerMock.new(false, true); - await expectRevert( - this.token.flashLoan(receiver.address, this.token.address, loanAmount, '0x'), - 'ERC20FlashMint: invalid return value', - ); - }); - - it ('missing approval', async function () { - const receiver = await ERC3156FlashBorrowerMock.new(true, false); - await expectRevert( - this.token.flashLoan(receiver.address, this.token.address, loanAmount, '0x'), - 'ERC20FlashMint: allowance does not allow refund', - ); - }); - - it ('unavailable funds', async function () { - const receiver = await ERC3156FlashBorrowerMock.new(true, true); - const data = this.token.contract.methods.transfer(other, 10).encodeABI(); - await expectRevert( - this.token.flashLoan(receiver.address, this.token.address, loanAmount, data), - 'ERC20: burn amount exceeds balance', - ); - }); - - it ('more than maxFlashLoan', async function () { - const receiver = await ERC3156FlashBorrowerMock.new(true, true); - const data = this.token.contract.methods.transfer(other, 10).encodeABI(); - // _mint overflow reverts using a panic code. No reason string. - await expectRevert.unspecified(this.token.flashLoan(receiver.address, this.token.address, MAX_UINT256, data)); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Pausable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Pausable.test.js deleted file mode 100644 index 8670e2fc..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Pausable.test.js +++ /dev/null @@ -1,134 +0,0 @@ -const { BN, expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC20PausableMock = artifacts.require('ERC20PausableMock'); - -contract('ERC20Pausable', function (accounts) { - const [ holder, recipient, anotherAccount ] = accounts; - - const initialSupply = new BN(100); - - const name = 'My Token'; - const symbol = 'MTKN'; - - beforeEach(async function () { - this.token = await ERC20PausableMock.new(name, symbol, holder, initialSupply); - }); - - describe('pausable token', function () { - describe('transfer', function () { - it('allows to transfer when unpaused', async function () { - await this.token.transfer(recipient, initialSupply, { from: holder }); - - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(initialSupply); - }); - - it('allows to transfer when paused and then unpaused', async function () { - await this.token.pause(); - await this.token.unpause(); - - await this.token.transfer(recipient, initialSupply, { from: holder }); - - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(initialSupply); - }); - - it('reverts when trying to transfer when paused', async function () { - await this.token.pause(); - - await expectRevert(this.token.transfer(recipient, initialSupply, { from: holder }), - 'ERC20Pausable: token transfer while paused', - ); - }); - }); - - describe('transfer from', function () { - const allowance = new BN(40); - - beforeEach(async function () { - await this.token.approve(anotherAccount, allowance, { from: holder }); - }); - - it('allows to transfer from when unpaused', async function () { - await this.token.transferFrom(holder, recipient, allowance, { from: anotherAccount }); - - expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(allowance); - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal(initialSupply.sub(allowance)); - }); - - it('allows to transfer when paused and then unpaused', async function () { - await this.token.pause(); - await this.token.unpause(); - - await this.token.transferFrom(holder, recipient, allowance, { from: anotherAccount }); - - expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(allowance); - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal(initialSupply.sub(allowance)); - }); - - it('reverts when trying to transfer from when paused', async function () { - await this.token.pause(); - - await expectRevert(this.token.transferFrom( - holder, recipient, allowance, { from: anotherAccount }), 'ERC20Pausable: token transfer while paused', - ); - }); - }); - - describe('mint', function () { - const amount = new BN('42'); - - it('allows to mint when unpaused', async function () { - await this.token.mint(recipient, amount); - - expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(amount); - }); - - it('allows to mint when paused and then unpaused', async function () { - await this.token.pause(); - await this.token.unpause(); - - await this.token.mint(recipient, amount); - - expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(amount); - }); - - it('reverts when trying to mint when paused', async function () { - await this.token.pause(); - - await expectRevert(this.token.mint(recipient, amount), - 'ERC20Pausable: token transfer while paused', - ); - }); - }); - - describe('burn', function () { - const amount = new BN('42'); - - it('allows to burn when unpaused', async function () { - await this.token.burn(holder, amount); - - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal(initialSupply.sub(amount)); - }); - - it('allows to burn when paused and then unpaused', async function () { - await this.token.pause(); - await this.token.unpause(); - - await this.token.burn(holder, amount); - - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal(initialSupply.sub(amount)); - }); - - it('reverts when trying to burn when paused', async function () { - await this.token.pause(); - - await expectRevert(this.token.burn(holder, amount), - 'ERC20Pausable: token transfer while paused', - ); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Snapshot.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Snapshot.test.js deleted file mode 100644 index b05ca2b9..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Snapshot.test.js +++ /dev/null @@ -1,204 +0,0 @@ -const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const ERC20SnapshotMock = artifacts.require('ERC20SnapshotMock'); - -const { expect } = require('chai'); - -contract('ERC20Snapshot', function (accounts) { - const [ initialHolder, recipient, other ] = accounts; - - const initialSupply = new BN(100); - - const name = 'My Token'; - const symbol = 'MTKN'; - - beforeEach(async function () { - this.token = await ERC20SnapshotMock.new(name, symbol, initialHolder, initialSupply); - }); - - describe('snapshot', function () { - it('emits a snapshot event', async function () { - const { logs } = await this.token.snapshot(); - expectEvent.inLogs(logs, 'Snapshot'); - }); - - it('creates increasing snapshots ids, starting from 1', async function () { - for (const id of ['1', '2', '3', '4', '5']) { - const { logs } = await this.token.snapshot(); - expectEvent.inLogs(logs, 'Snapshot', { id }); - } - }); - }); - - describe('totalSupplyAt', function () { - it('reverts with a snapshot id of 0', async function () { - await expectRevert(this.token.totalSupplyAt(0), 'ERC20Snapshot: id is 0'); - }); - - it('reverts with a not-yet-created snapshot id', async function () { - await expectRevert(this.token.totalSupplyAt(1), 'ERC20Snapshot: nonexistent id'); - }); - - context('with initial snapshot', function () { - beforeEach(async function () { - this.initialSnapshotId = new BN('1'); - - const { logs } = await this.token.snapshot(); - expectEvent.inLogs(logs, 'Snapshot', { id: this.initialSnapshotId }); - }); - - context('with no supply changes after the snapshot', function () { - it('returns the current total supply', async function () { - expect(await this.token.totalSupplyAt(this.initialSnapshotId)).to.be.bignumber.equal(initialSupply); - }); - }); - - context('with supply changes after the snapshot', function () { - beforeEach(async function () { - await this.token.mint(other, new BN('50')); - await this.token.burn(initialHolder, new BN('20')); - }); - - it('returns the total supply before the changes', async function () { - expect(await this.token.totalSupplyAt(this.initialSnapshotId)).to.be.bignumber.equal(initialSupply); - }); - - context('with a second snapshot after supply changes', function () { - beforeEach(async function () { - this.secondSnapshotId = new BN('2'); - - const { logs } = await this.token.snapshot(); - expectEvent.inLogs(logs, 'Snapshot', { id: this.secondSnapshotId }); - }); - - it('snapshots return the supply before and after the changes', async function () { - expect(await this.token.totalSupplyAt(this.initialSnapshotId)).to.be.bignumber.equal(initialSupply); - - expect(await this.token.totalSupplyAt(this.secondSnapshotId)).to.be.bignumber.equal( - await this.token.totalSupply(), - ); - }); - }); - - context('with multiple snapshots after supply changes', function () { - beforeEach(async function () { - this.secondSnapshotIds = ['2', '3', '4']; - - for (const id of this.secondSnapshotIds) { - const { logs } = await this.token.snapshot(); - expectEvent.inLogs(logs, 'Snapshot', { id }); - } - }); - - it('all posterior snapshots return the supply after the changes', async function () { - expect(await this.token.totalSupplyAt(this.initialSnapshotId)).to.be.bignumber.equal(initialSupply); - - const currentSupply = await this.token.totalSupply(); - - for (const id of this.secondSnapshotIds) { - expect(await this.token.totalSupplyAt(id)).to.be.bignumber.equal(currentSupply); - } - }); - }); - }); - }); - }); - - describe('balanceOfAt', function () { - it('reverts with a snapshot id of 0', async function () { - await expectRevert(this.token.balanceOfAt(other, 0), 'ERC20Snapshot: id is 0'); - }); - - it('reverts with a not-yet-created snapshot id', async function () { - await expectRevert(this.token.balanceOfAt(other, 1), 'ERC20Snapshot: nonexistent id'); - }); - - context('with initial snapshot', function () { - beforeEach(async function () { - this.initialSnapshotId = new BN('1'); - - const { logs } = await this.token.snapshot(); - expectEvent.inLogs(logs, 'Snapshot', { id: this.initialSnapshotId }); - }); - - context('with no balance changes after the snapshot', function () { - it('returns the current balance for all accounts', async function () { - expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)) - .to.be.bignumber.equal(initialSupply); - expect(await this.token.balanceOfAt(recipient, this.initialSnapshotId)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOfAt(other, this.initialSnapshotId)).to.be.bignumber.equal('0'); - }); - }); - - context('with balance changes after the snapshot', function () { - beforeEach(async function () { - await this.token.transfer(recipient, new BN('10'), { from: initialHolder }); - await this.token.mint(other, new BN('50')); - await this.token.burn(initialHolder, new BN('20')); - }); - - it('returns the balances before the changes', async function () { - expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)) - .to.be.bignumber.equal(initialSupply); - expect(await this.token.balanceOfAt(recipient, this.initialSnapshotId)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOfAt(other, this.initialSnapshotId)).to.be.bignumber.equal('0'); - }); - - context('with a second snapshot after supply changes', function () { - beforeEach(async function () { - this.secondSnapshotId = new BN('2'); - - const { logs } = await this.token.snapshot(); - expectEvent.inLogs(logs, 'Snapshot', { id: this.secondSnapshotId }); - }); - - it('snapshots return the balances before and after the changes', async function () { - expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)) - .to.be.bignumber.equal(initialSupply); - expect(await this.token.balanceOfAt(recipient, this.initialSnapshotId)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOfAt(other, this.initialSnapshotId)).to.be.bignumber.equal('0'); - - expect(await this.token.balanceOfAt(initialHolder, this.secondSnapshotId)).to.be.bignumber.equal( - await this.token.balanceOf(initialHolder), - ); - expect(await this.token.balanceOfAt(recipient, this.secondSnapshotId)).to.be.bignumber.equal( - await this.token.balanceOf(recipient), - ); - expect(await this.token.balanceOfAt(other, this.secondSnapshotId)).to.be.bignumber.equal( - await this.token.balanceOf(other), - ); - }); - }); - - context('with multiple snapshots after supply changes', function () { - beforeEach(async function () { - this.secondSnapshotIds = ['2', '3', '4']; - - for (const id of this.secondSnapshotIds) { - const { logs } = await this.token.snapshot(); - expectEvent.inLogs(logs, 'Snapshot', { id }); - } - }); - - it('all posterior snapshots return the supply after the changes', async function () { - expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)) - .to.be.bignumber.equal(initialSupply); - expect(await this.token.balanceOfAt(recipient, this.initialSnapshotId)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOfAt(other, this.initialSnapshotId)).to.be.bignumber.equal('0'); - - for (const id of this.secondSnapshotIds) { - expect(await this.token.balanceOfAt(initialHolder, id)).to.be.bignumber.equal( - await this.token.balanceOf(initialHolder), - ); - expect(await this.token.balanceOfAt(recipient, id)).to.be.bignumber.equal( - await this.token.balanceOf(recipient), - ); - expect(await this.token.balanceOfAt(other, id)).to.be.bignumber.equal( - await this.token.balanceOf(other), - ); - } - }); - }); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Votes.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Votes.test.js deleted file mode 100644 index a0ab60ab..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Votes.test.js +++ /dev/null @@ -1,538 +0,0 @@ -/* eslint-disable */ - -const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { MAX_UINT256, ZERO_ADDRESS, ZERO_BYTES32 } = constants; - -const { fromRpcSig } = require('ethereumjs-util'); -const ethSigUtil = require('eth-sig-util'); -const Wallet = require('ethereumjs-wallet').default; - -const { promisify } = require('util'); -const queue = promisify(setImmediate); - -const ERC20VotesMock = artifacts.require('ERC20VotesMock'); - -const { EIP712Domain, domainSeparator } = require('../../../helpers/eip712'); - -const Delegation = [ - { name: 'delegatee', type: 'address' }, - { name: 'nonce', type: 'uint256' }, - { name: 'expiry', type: 'uint256' }, -]; - -async function countPendingTransactions() { - return parseInt( - await network.provider.send('eth_getBlockTransactionCountByNumber', ['pending']) - ); -} - -async function batchInBlock (txs) { - try { - // disable auto-mining - await network.provider.send('evm_setAutomine', [false]); - // send all transactions - const promises = txs.map(fn => fn()); - // wait for node to have all pending transactions - while (txs.length > await countPendingTransactions()) { - await queue(); - } - // mine one block - await network.provider.send('evm_mine'); - // fetch receipts - const receipts = await Promise.all(promises); - // Sanity check, all tx should be in the same block - const minedBlocks = new Set(receipts.map(({ receipt }) => receipt.blockNumber)); - expect(minedBlocks.size).to.equal(1); - - return receipts; - } finally { - // enable auto-mining - await network.provider.send('evm_setAutomine', [true]); - } -} - -contract('ERC20Votes', function (accounts) { - const [ holder, recipient, holderDelegatee, recipientDelegatee, other1, other2 ] = accounts; - - const name = 'My Token'; - const symbol = 'MTKN'; - const version = '1'; - const supply = new BN('10000000000000000000000000'); - - beforeEach(async function () { - this.token = await ERC20VotesMock.new(name, symbol); - - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.token.getChainId(); - }); - - it('initial nonce is 0', async function () { - expect(await this.token.nonces(holder)).to.be.bignumber.equal('0'); - }); - - it('domain separator', async function () { - expect( - await this.token.DOMAIN_SEPARATOR(), - ).to.equal( - await domainSeparator(name, version, this.chainId, this.token.address), - ); - }); - - it('minting restriction', async function () { - const amount = new BN('2').pow(new BN('224')); - await expectRevert( - this.token.mint(holder, amount), - 'ERC20Votes: total supply risks overflowing votes', - ); - }); - - describe('set delegation', function () { - describe('call', function () { - it('delegation with balance', async function () { - await this.token.mint(holder, supply); - expect(await this.token.delegates(holder)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.token.delegate(holder, { from: holder }); - expectEvent(receipt, 'DelegateChanged', { - delegator: holder, - fromDelegate: ZERO_ADDRESS, - toDelegate: holder, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: holder, - previousBalance: '0', - newBalance: supply, - }); - - expect(await this.token.delegates(holder)).to.be.equal(holder); - - expect(await this.token.getVotes(holder)).to.be.bignumber.equal(supply); - expect(await this.token.getPastVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.token.getPastVotes(holder, receipt.blockNumber)).to.be.bignumber.equal(supply); - }); - - it('delegation without balance', async function () { - expect(await this.token.delegates(holder)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.token.delegate(holder, { from: holder }); - expectEvent(receipt, 'DelegateChanged', { - delegator: holder, - fromDelegate: ZERO_ADDRESS, - toDelegate: holder, - }); - expectEvent.notEmitted(receipt, 'DelegateVotesChanged'); - - expect(await this.token.delegates(holder)).to.be.equal(holder); - }); - }); - - describe('with signature', function () { - const delegator = Wallet.generate(); - const delegatorAddress = web3.utils.toChecksumAddress(delegator.getAddressString()); - const nonce = 0; - - const buildData = (chainId, verifyingContract, message) => ({ data: { - primaryType: 'Delegation', - types: { EIP712Domain, Delegation }, - domain: { name, version, chainId, verifyingContract }, - message, - }}); - - beforeEach(async function () { - await this.token.mint(delegatorAddress, supply); - }); - - it('accept signed delegation', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - expect(await this.token.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); - expectEvent(receipt, 'DelegateChanged', { - delegator: delegatorAddress, - fromDelegate: ZERO_ADDRESS, - toDelegate: delegatorAddress, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: delegatorAddress, - previousBalance: '0', - newBalance: supply, - }); - - expect(await this.token.delegates(delegatorAddress)).to.be.equal(delegatorAddress); - - expect(await this.token.getVotes(delegatorAddress)).to.be.bignumber.equal(supply); - expect(await this.token.getPastVotes(delegatorAddress, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.token.getPastVotes(delegatorAddress, receipt.blockNumber)).to.be.bignumber.equal(supply); - }); - - it('rejects reused signature', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - await this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); - - await expectRevert( - this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s), - 'ERC20Votes: invalid nonce', - ); - }); - - it('rejects bad delegatee', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - const { logs } = await this.token.delegateBySig(holderDelegatee, nonce, MAX_UINT256, v, r, s); - const { args } = logs.find(({ event }) => event == 'DelegateChanged'); - expect(args.delegator).to.not.be.equal(delegatorAddress); - expect(args.fromDelegate).to.be.equal(ZERO_ADDRESS); - expect(args.toDelegate).to.be.equal(holderDelegatee); - }); - - it('rejects bad nonce', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - await expectRevert( - this.token.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s), - 'ERC20Votes: invalid nonce', - ); - }); - - it('rejects expired permit', async function () { - const expiry = (await time.latest()) - time.duration.weeks(1); - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry, - }), - )); - - await expectRevert( - this.token.delegateBySig(delegatorAddress, nonce, expiry, v, r, s), - 'ERC20Votes: signature expired', - ); - }); - }); - }); - - describe('change delegation', function () { - beforeEach(async function () { - await this.token.mint(holder, supply); - await this.token.delegate(holder, { from: holder }); - }); - - it('call', async function () { - expect(await this.token.delegates(holder)).to.be.equal(holder); - - const { receipt } = await this.token.delegate(holderDelegatee, { from: holder }); - expectEvent(receipt, 'DelegateChanged', { - delegator: holder, - fromDelegate: holder, - toDelegate: holderDelegatee, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: holder, - previousBalance: supply, - newBalance: '0', - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: holderDelegatee, - previousBalance: '0', - newBalance: supply, - }); - - expect(await this.token.delegates(holder)).to.be.equal(holderDelegatee); - - expect(await this.token.getVotes(holder)).to.be.bignumber.equal('0'); - expect(await this.token.getVotes(holderDelegatee)).to.be.bignumber.equal(supply); - expect(await this.token.getPastVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal(supply); - expect(await this.token.getPastVotes(holderDelegatee, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.token.getPastVotes(holder, receipt.blockNumber)).to.be.bignumber.equal('0'); - expect(await this.token.getPastVotes(holderDelegatee, receipt.blockNumber)).to.be.bignumber.equal(supply); - }); - }); - - describe('transfers', function () { - beforeEach(async function () { - await this.token.mint(holder, supply); - }); - - it('no delegation', async function () { - const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); - expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent.notEmitted(receipt, 'DelegateVotesChanged'); - - this.holderVotes = '0'; - this.recipientVotes = '0'; - }); - - it('sender delegation', async function () { - await this.token.delegate(holder, { from: holder }); - - const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); - expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) }); - - const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); - - this.holderVotes = supply.subn(1); - this.recipientVotes = '0'; - }); - - it('receiver delegation', async function () { - await this.token.delegate(recipient, { from: recipient }); - - const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); - expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' }); - - const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); - - this.holderVotes = '0'; - this.recipientVotes = '1'; - }); - - it('full delegation', async function () { - await this.token.delegate(holder, { from: holder }); - await this.token.delegate(recipient, { from: recipient }); - - const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); - expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' }); - - const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); - - this.holderVotes = supply.subn(1); - this.recipientVotes = '1'; - }); - - afterEach(async function () { - expect(await this.token.getVotes(holder)).to.be.bignumber.equal(this.holderVotes); - expect(await this.token.getVotes(recipient)).to.be.bignumber.equal(this.recipientVotes); - - // need to advance 2 blocks to see the effect of a transfer on "getPastVotes" - const blockNumber = await time.latestBlock(); - await time.advanceBlock(); - expect(await this.token.getPastVotes(holder, blockNumber)).to.be.bignumber.equal(this.holderVotes); - expect(await this.token.getPastVotes(recipient, blockNumber)).to.be.bignumber.equal(this.recipientVotes); - }); - }); - - // The following tests are a adaptation of https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js. - describe('Compound test suite', function () { - beforeEach(async function () { - await this.token.mint(holder, supply); - }); - - describe('balanceOf', function () { - it('grants to initial account', async function () { - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal('10000000000000000000000000'); - }); - }); - - describe('numCheckpoints', function () { - it('returns the number of checkpoints for a delegate', async function () { - await this.token.transfer(recipient, '100', { from: holder }); //give an account a few tokens for readability - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('0'); - - const t1 = await this.token.delegate(other1, { from: recipient }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('1'); - - const t2 = await this.token.transfer(other2, 10, { from: recipient }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('2'); - - const t3 = await this.token.transfer(other2, 10, { from: recipient }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('3'); - - const t4 = await this.token.transfer(recipient, 20, { from: holder }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('4'); - - expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '100' ]); - expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t2.receipt.blockNumber.toString(), '90' ]); - expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ t3.receipt.blockNumber.toString(), '80' ]); - expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); - - await time.advanceBlock(); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('100'); - expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('90'); - expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('80'); - expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('100'); - }); - - it('does not add more than one checkpoint in a block', async function () { - await this.token.transfer(recipient, '100', { from: holder }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('0'); - - const [ t1, t2, t3 ] = await batchInBlock([ - () => this.token.delegate(other1, { from: recipient, gas: 100000 }), - () => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }), - () => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }), - ]); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('1'); - expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '80' ]); - // expectReve(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check - // expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check - - const t4 = await this.token.transfer(recipient, 20, { from: holder }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('2'); - expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); - }); - }); - - describe('getPastVotes', function () { - it('reverts if block number >= current block', async function () { - await expectRevert( - this.token.getPastVotes(other1, 5e10), - 'ERC20Votes: block not yet mined', - ); - }); - - it('returns 0 if there are no checkpoints', async function () { - expect(await this.token.getPastVotes(other1, 0)).to.be.bignumber.equal('0'); - }); - - it('returns the latest block if >= last checkpoint block', async function () { - const t1 = await this.token.delegate(other1, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - - it('returns zero if < first checkpoint block', async function () { - await time.advanceBlock(); - const t1 = await this.token.delegate(other1, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - - it('generally returns the voting balance at the appropriate checkpoint', async function () { - const t1 = await this.token.delegate(other1, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - const t2 = await this.token.transfer(other2, 10, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - const t3 = await this.token.transfer(other2, 10, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - const t4 = await this.token.transfer(holder, 20, { from: other2 }); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - }); - }); - - describe('getPastTotalSupply', function () { - beforeEach(async function () { - await this.token.delegate(holder, { from: holder }); - }); - - it('reverts if block number >= current block', async function () { - await expectRevert( - this.token.getPastTotalSupply(5e10), - 'ERC20Votes: block not yet mined', - ); - }); - - it('returns 0 if there are no checkpoints', async function () { - expect(await this.token.getPastTotalSupply(0)).to.be.bignumber.equal('0'); - }); - - it('returns the latest block if >= last checkpoint block', async function () { - t1 = await this.token.mint(holder, supply); - - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal(supply); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal(supply); - }); - - it('returns zero if < first checkpoint block', async function () { - await time.advanceBlock(); - const t1 = await this.token.mint(holder, supply); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - - it('generally returns the voting balance at the appropriate checkpoint', async function () { - const t1 = await this.token.mint(holder, supply); - await time.advanceBlock(); - await time.advanceBlock(); - const t2 = await this.token.burn(holder, 10); - await time.advanceBlock(); - await time.advanceBlock(); - const t3 = await this.token.burn(holder, 10); - await time.advanceBlock(); - await time.advanceBlock(); - const t4 = await this.token.mint(holder, 20); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20VotesComp.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20VotesComp.test.js deleted file mode 100644 index 0f0c25eb..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20VotesComp.test.js +++ /dev/null @@ -1,529 +0,0 @@ -/* eslint-disable */ - -const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { MAX_UINT256, ZERO_ADDRESS, ZERO_BYTES32 } = constants; - -const { fromRpcSig } = require('ethereumjs-util'); -const ethSigUtil = require('eth-sig-util'); -const Wallet = require('ethereumjs-wallet').default; - -const { promisify } = require('util'); -const queue = promisify(setImmediate); - -const ERC20VotesCompMock = artifacts.require('ERC20VotesCompMock'); - -const { EIP712Domain, domainSeparator } = require('../../../helpers/eip712'); - -const Delegation = [ - { name: 'delegatee', type: 'address' }, - { name: 'nonce', type: 'uint256' }, - { name: 'expiry', type: 'uint256' }, -]; - -async function countPendingTransactions() { - return parseInt( - await network.provider.send('eth_getBlockTransactionCountByNumber', ['pending']) - ); -} - -async function batchInBlock (txs) { - try { - // disable auto-mining - await network.provider.send('evm_setAutomine', [false]); - // send all transactions - const promises = txs.map(fn => fn()); - // wait for node to have all pending transactions - while (txs.length > await countPendingTransactions()) { - await queue(); - } - // mine one block - await network.provider.send('evm_mine'); - // fetch receipts - const receipts = await Promise.all(promises); - // Sanity check, all tx should be in the same block - const minedBlocks = new Set(receipts.map(({ receipt }) => receipt.blockNumber)); - expect(minedBlocks.size).to.equal(1); - - return receipts; - } finally { - // enable auto-mining - await network.provider.send('evm_setAutomine', [true]); - } -} - -contract('ERC20VotesComp', function (accounts) { - const [ holder, recipient, holderDelegatee, recipientDelegatee, other1, other2 ] = accounts; - - const name = 'My Token'; - const symbol = 'MTKN'; - const version = '1'; - const supply = new BN('10000000000000000000000000'); - - beforeEach(async function () { - this.token = await ERC20VotesCompMock.new(name, symbol); - - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.token.getChainId(); - }); - - it('initial nonce is 0', async function () { - expect(await this.token.nonces(holder)).to.be.bignumber.equal('0'); - }); - - it('domain separator', async function () { - expect( - await this.token.DOMAIN_SEPARATOR(), - ).to.equal( - await domainSeparator(name, version, this.chainId, this.token.address), - ); - }); - - it('minting restriction', async function () { - const amount = new BN('2').pow(new BN('96')); - await expectRevert( - this.token.mint(holder, amount), - 'ERC20Votes: total supply risks overflowing votes', - ); - }); - - describe('set delegation', function () { - describe('call', function () { - it('delegation with balance', async function () { - await this.token.mint(holder, supply); - expect(await this.token.delegates(holder)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.token.delegate(holder, { from: holder }); - expectEvent(receipt, 'DelegateChanged', { - delegator: holder, - fromDelegate: ZERO_ADDRESS, - toDelegate: holder, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: holder, - previousBalance: '0', - newBalance: supply, - }); - - expect(await this.token.delegates(holder)).to.be.equal(holder); - - expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal(supply); - expect(await this.token.getPriorVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.token.getPriorVotes(holder, receipt.blockNumber)).to.be.bignumber.equal(supply); - }); - - it('delegation without balance', async function () { - expect(await this.token.delegates(holder)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.token.delegate(holder, { from: holder }); - expectEvent(receipt, 'DelegateChanged', { - delegator: holder, - fromDelegate: ZERO_ADDRESS, - toDelegate: holder, - }); - expectEvent.notEmitted(receipt, 'DelegateVotesChanged'); - - expect(await this.token.delegates(holder)).to.be.equal(holder); - }); - }); - - describe('with signature', function () { - const delegator = Wallet.generate(); - const delegatorAddress = web3.utils.toChecksumAddress(delegator.getAddressString()); - const nonce = 0; - - const buildData = (chainId, verifyingContract, message) => ({ data: { - primaryType: 'Delegation', - types: { EIP712Domain, Delegation }, - domain: { name, version, chainId, verifyingContract }, - message, - }}); - - beforeEach(async function () { - await this.token.mint(delegatorAddress, supply); - }); - - it('accept signed delegation', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - expect(await this.token.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS); - - const { receipt } = await this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); - expectEvent(receipt, 'DelegateChanged', { - delegator: delegatorAddress, - fromDelegate: ZERO_ADDRESS, - toDelegate: delegatorAddress, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: delegatorAddress, - previousBalance: '0', - newBalance: supply, - }); - - expect(await this.token.delegates(delegatorAddress)).to.be.equal(delegatorAddress); - - expect(await this.token.getCurrentVotes(delegatorAddress)).to.be.bignumber.equal(supply); - expect(await this.token.getPriorVotes(delegatorAddress, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.token.getPriorVotes(delegatorAddress, receipt.blockNumber)).to.be.bignumber.equal(supply); - }); - - it('rejects reused signature', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - await this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); - - await expectRevert( - this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s), - 'ERC20Votes: invalid nonce', - ); - }); - - it('rejects bad delegatee', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - - const { logs } = await this.token.delegateBySig(holderDelegatee, nonce, MAX_UINT256, v, r, s); - const { args } = logs.find(({ event }) => event == 'DelegateChanged'); - expect(args.delegator).to.not.be.equal(delegatorAddress); - expect(args.fromDelegate).to.be.equal(ZERO_ADDRESS); - expect(args.toDelegate).to.be.equal(holderDelegatee); - }); - - it('rejects bad nonce', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); - await expectRevert( - this.token.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s), - 'ERC20Votes: invalid nonce', - ); - }); - - it('rejects expired permit', async function () { - const expiry = (await time.latest()) - time.duration.weeks(1); - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry, - }), - )); - - await expectRevert( - this.token.delegateBySig(delegatorAddress, nonce, expiry, v, r, s), - 'ERC20Votes: signature expired', - ); - }); - }); - }); - - describe('change delegation', function () { - beforeEach(async function () { - await this.token.mint(holder, supply); - await this.token.delegate(holder, { from: holder }); - }); - - it('call', async function () { - expect(await this.token.delegates(holder)).to.be.equal(holder); - - const { receipt } = await this.token.delegate(holderDelegatee, { from: holder }); - expectEvent(receipt, 'DelegateChanged', { - delegator: holder, - fromDelegate: holder, - toDelegate: holderDelegatee, - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: holder, - previousBalance: supply, - newBalance: '0', - }); - expectEvent(receipt, 'DelegateVotesChanged', { - delegate: holderDelegatee, - previousBalance: '0', - newBalance: supply, - }); - - expect(await this.token.delegates(holder)).to.be.equal(holderDelegatee); - - expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal('0'); - expect(await this.token.getCurrentVotes(holderDelegatee)).to.be.bignumber.equal(supply); - expect(await this.token.getPriorVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal(supply); - expect(await this.token.getPriorVotes(holderDelegatee, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - await time.advanceBlock(); - expect(await this.token.getPriorVotes(holder, receipt.blockNumber)).to.be.bignumber.equal('0'); - expect(await this.token.getPriorVotes(holderDelegatee, receipt.blockNumber)).to.be.bignumber.equal(supply); - }); - }); - - describe('transfers', function () { - beforeEach(async function () { - await this.token.mint(holder, supply); - }); - - it('no delegation', async function () { - const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); - expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent.notEmitted(receipt, 'DelegateVotesChanged'); - - this.holderVotes = '0'; - this.recipientVotes = '0'; - }); - - it('sender delegation', async function () { - await this.token.delegate(holder, { from: holder }); - - const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); - expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) }); - - this.holderVotes = supply.subn(1); - this.recipientVotes = '0'; - }); - - it('receiver delegation', async function () { - await this.token.delegate(recipient, { from: recipient }); - - const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); - expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' }); - - this.holderVotes = '0'; - this.recipientVotes = '1'; - }); - - it('full delegation', async function () { - await this.token.delegate(holder, { from: holder }); - await this.token.delegate(recipient, { from: recipient }); - - const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); - expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' }); - - this.holderVotes = supply.subn(1); - this.recipientVotes = '1'; - }); - - afterEach(async function () { - expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal(this.holderVotes); - expect(await this.token.getCurrentVotes(recipient)).to.be.bignumber.equal(this.recipientVotes); - - // need to advance 2 blocks to see the effect of a transfer on "getPriorVotes" - const blockNumber = await time.latestBlock(); - await time.advanceBlock(); - expect(await this.token.getPriorVotes(holder, blockNumber)).to.be.bignumber.equal(this.holderVotes); - expect(await this.token.getPriorVotes(recipient, blockNumber)).to.be.bignumber.equal(this.recipientVotes); - }); - }); - - // The following tests are a adaptation of https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js. - describe('Compound test suite', function () { - beforeEach(async function () { - await this.token.mint(holder, supply); - }); - - describe('balanceOf', function () { - it('grants to initial account', async function () { - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal('10000000000000000000000000'); - }); - }); - - describe('numCheckpoints', function () { - it('returns the number of checkpoints for a delegate', async function () { - await this.token.transfer(recipient, '100', { from: holder }); //give an account a few tokens for readability - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('0'); - - const t1 = await this.token.delegate(other1, { from: recipient }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('1'); - - const t2 = await this.token.transfer(other2, 10, { from: recipient }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('2'); - - const t3 = await this.token.transfer(other2, 10, { from: recipient }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('3'); - - const t4 = await this.token.transfer(recipient, 20, { from: holder }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('4'); - - expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '100' ]); - expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t2.receipt.blockNumber.toString(), '90' ]); - expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ t3.receipt.blockNumber.toString(), '80' ]); - expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); - - await time.advanceBlock(); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('100'); - expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('90'); - expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('80'); - expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('100'); - }); - - it('does not add more than one checkpoint in a block', async function () { - await this.token.transfer(recipient, '100', { from: holder }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('0'); - - const [ t1, t2, t3 ] = await batchInBlock([ - () => this.token.delegate(other1, { from: recipient, gas: 100000 }), - () => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }), - () => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }), - ]); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('1'); - expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '80' ]); - // expectReve(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check - // expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check - - const t4 = await this.token.transfer(recipient, 20, { from: holder }); - expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('2'); - expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); - }); - }); - - describe('getPriorVotes', function () { - it('reverts if block number >= current block', async function () { - await expectRevert( - this.token.getPriorVotes(other1, 5e10), - 'ERC20Votes: block not yet mined', - ); - }); - - it('returns 0 if there are no checkpoints', async function () { - expect(await this.token.getPriorVotes(other1, 0)).to.be.bignumber.equal('0'); - }); - - it('returns the latest block if >= last checkpoint block', async function () { - const t1 = await this.token.delegate(other1, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - - it('returns zero if < first checkpoint block', async function () { - await time.advanceBlock(); - const t1 = await this.token.delegate(other1, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - - it('generally returns the voting balance at the appropriate checkpoint', async function () { - const t1 = await this.token.delegate(other1, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - const t2 = await this.token.transfer(other2, 10, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - const t3 = await this.token.transfer(other2, 10, { from: holder }); - await time.advanceBlock(); - await time.advanceBlock(); - const t4 = await this.token.transfer(holder, 20, { from: other2 }); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - }); - }); - - describe('getPastTotalSupply', function () { - beforeEach(async function () { - await this.token.delegate(holder, { from: holder }); - }); - - it('reverts if block number >= current block', async function () { - await expectRevert( - this.token.getPastTotalSupply(5e10), - 'ERC20Votes: block not yet mined', - ); - }); - - it('returns 0 if there are no checkpoints', async function () { - expect(await this.token.getPastTotalSupply(0)).to.be.bignumber.equal('0'); - }); - - it('returns the latest block if >= last checkpoint block', async function () { - t1 = await this.token.mint(holder, supply); - - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal(supply); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal(supply); - }); - - it('returns zero if < first checkpoint block', async function () { - await time.advanceBlock(); - const t1 = await this.token.mint(holder, supply); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - - it('generally returns the voting balance at the appropriate checkpoint', async function () { - const t1 = await this.token.mint(holder, supply); - await time.advanceBlock(); - await time.advanceBlock(); - const t2 = await this.token.burn(holder, 10); - await time.advanceBlock(); - await time.advanceBlock(); - const t3 = await this.token.burn(holder, 10); - await time.advanceBlock(); - await time.advanceBlock(); - const t4 = await this.token.mint(holder, 20); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Wrapper.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Wrapper.test.js deleted file mode 100644 index ec074e1b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/ERC20Wrapper.test.js +++ /dev/null @@ -1,181 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { ZERO_ADDRESS, MAX_UINT256 } = constants; - -const { shouldBehaveLikeERC20 } = require('../ERC20.behavior'); - -const ERC20Mock = artifacts.require('ERC20Mock'); -const ERC20WrapperMock = artifacts.require('ERC20WrapperMock'); - -contract('ERC20', function (accounts) { - const [ initialHolder, recipient, anotherAccount ] = accounts; - - const name = 'My Token'; - const symbol = 'MTKN'; - - const initialSupply = new BN(100); - - beforeEach(async function () { - this.underlying = await ERC20Mock.new(name, symbol, initialHolder, initialSupply); - this.token = await ERC20WrapperMock.new(this.underlying.address, `Wrapped ${name}`, `W${symbol}`); - }); - - afterEach(async function () { - expect(await this.underlying.balanceOf(this.token.address)).to.be.bignumber.equal(await this.token.totalSupply()); - }); - - it('has a name', async function () { - expect(await this.token.name()).to.equal(`Wrapped ${name}`); - }); - - it('has a symbol', async function () { - expect(await this.token.symbol()).to.equal(`W${symbol}`); - }); - - it('has 18 decimals', async function () { - expect(await this.token.decimals()).to.be.bignumber.equal('18'); - }); - - it('has underlying', async function () { - expect(await this.token.underlying()).to.be.bignumber.equal(this.underlying.address); - }); - - describe('deposit', function () { - it('valid', async function () { - await this.underlying.approve(this.token.address, initialSupply, { from: initialHolder }); - const { tx } = await this.token.depositFor(initialHolder, initialSupply, { from: initialHolder }); - await expectEvent.inTransaction(tx, this.underlying, 'Transfer', { - from: initialHolder, - to: this.token.address, - value: initialSupply, - }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { - from: ZERO_ADDRESS, - to: initialHolder, - value: initialSupply, - }); - }); - - it('missing approval', async function () { - await expectRevert( - this.token.depositFor(initialHolder, initialSupply, { from: initialHolder }), - 'ERC20: insufficient allowance', - ); - }); - - it('missing balance', async function () { - await this.underlying.approve(this.token.address, MAX_UINT256, { from: initialHolder }); - await expectRevert( - this.token.depositFor(initialHolder, MAX_UINT256, { from: initialHolder }), - 'ERC20: transfer amount exceeds balance', - ); - }); - - it('to other account', async function () { - await this.underlying.approve(this.token.address, initialSupply, { from: initialHolder }); - const { tx } = await this.token.depositFor(anotherAccount, initialSupply, { from: initialHolder }); - await expectEvent.inTransaction(tx, this.underlying, 'Transfer', { - from: initialHolder, - to: this.token.address, - value: initialSupply, - }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { - from: ZERO_ADDRESS, - to: anotherAccount, - value: initialSupply, - }); - }); - }); - - describe('withdraw', function () { - beforeEach(async function () { - await this.underlying.approve(this.token.address, initialSupply, { from: initialHolder }); - await this.token.depositFor(initialHolder, initialSupply, { from: initialHolder }); - }); - - it('missing balance', async function () { - await expectRevert( - this.token.withdrawTo(initialHolder, MAX_UINT256, { from: initialHolder }), - 'ERC20: burn amount exceeds balance', - ); - }); - - it('valid', async function () { - const value = new BN(42); - - const { tx } = await this.token.withdrawTo(initialHolder, value, { from: initialHolder }); - await expectEvent.inTransaction(tx, this.underlying, 'Transfer', { - from: this.token.address, - to: initialHolder, - value: value, - }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { - from: initialHolder, - to: ZERO_ADDRESS, - value: value, - }); - }); - - it('entire balance', async function () { - const { tx } = await this.token.withdrawTo(initialHolder, initialSupply, { from: initialHolder }); - await expectEvent.inTransaction(tx, this.underlying, 'Transfer', { - from: this.token.address, - to: initialHolder, - value: initialSupply, - }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { - from: initialHolder, - to: ZERO_ADDRESS, - value: initialSupply, - }); - }); - - it('to other account', async function () { - const { tx } = await this.token.withdrawTo(anotherAccount, initialSupply, { from: initialHolder }); - await expectEvent.inTransaction(tx, this.underlying, 'Transfer', { - from: this.token.address, - to: anotherAccount, - value: initialSupply, - }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { - from: initialHolder, - to: ZERO_ADDRESS, - value: initialSupply, - }); - }); - }); - - describe('recover', function () { - it('nothing to recover', async function () { - await this.underlying.approve(this.token.address, initialSupply, { from: initialHolder }); - await this.token.depositFor(initialHolder, initialSupply, { from: initialHolder }); - - const { tx } = await this.token.recover(anotherAccount); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { - from: ZERO_ADDRESS, - to: anotherAccount, - value: '0', - }); - }); - - it('something to recover', async function () { - await this.underlying.transfer(this.token.address, initialSupply, { from: initialHolder }); - - const { tx } = await this.token.recover(anotherAccount); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { - from: ZERO_ADDRESS, - to: anotherAccount, - value: initialSupply, - }); - }); - }); - - describe('erc20 behaviour', function () { - beforeEach(async function () { - await this.underlying.approve(this.token.address, initialSupply, { from: initialHolder }); - await this.token.depositFor(initialHolder, initialSupply, { from: initialHolder }); - }); - - shouldBehaveLikeERC20('ERC20', initialSupply, initialHolder, recipient, anotherAccount); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/draft-ERC20Permit.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/draft-ERC20Permit.test.js deleted file mode 100644 index 9aa64456..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/extensions/draft-ERC20Permit.test.js +++ /dev/null @@ -1,117 +0,0 @@ -/* eslint-disable */ - -const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { MAX_UINT256, ZERO_ADDRESS, ZERO_BYTES32 } = constants; - -const { fromRpcSig } = require('ethereumjs-util'); -const ethSigUtil = require('eth-sig-util'); -const Wallet = require('ethereumjs-wallet').default; - -const ERC20PermitMock = artifacts.require('ERC20PermitMock'); - -const { EIP712Domain, domainSeparator } = require('../../../helpers/eip712'); - -const Permit = [ - { name: 'owner', type: 'address' }, - { name: 'spender', type: 'address' }, - { name: 'value', type: 'uint256' }, - { name: 'nonce', type: 'uint256' }, - { name: 'deadline', type: 'uint256' }, -]; - -contract('ERC20Permit', function (accounts) { - const [ initialHolder, spender, recipient, other ] = accounts; - - const name = 'My Token'; - const symbol = 'MTKN'; - const version = '1'; - - const initialSupply = new BN(100); - - beforeEach(async function () { - this.token = await ERC20PermitMock.new(name, symbol, initialHolder, initialSupply); - - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.token.getChainId(); - }); - - it('initial nonce is 0', async function () { - expect(await this.token.nonces(initialHolder)).to.be.bignumber.equal('0'); - }); - - it('domain separator', async function () { - expect( - await this.token.DOMAIN_SEPARATOR(), - ).to.equal( - await domainSeparator(name, version, this.chainId, this.token.address), - ); - }); - - describe('permit', function () { - const wallet = Wallet.generate(); - - const owner = wallet.getAddressString(); - const value = new BN(42); - const nonce = 0; - const maxDeadline = MAX_UINT256; - - const buildData = (chainId, verifyingContract, deadline = maxDeadline) => ({ - primaryType: 'Permit', - types: { EIP712Domain, Permit }, - domain: { name, version, chainId, verifyingContract }, - message: { owner, spender, value, nonce, deadline }, - }); - - it('accepts owner signature', async function () { - const data = buildData(this.chainId, this.token.address); - const signature = ethSigUtil.signTypedMessage(wallet.getPrivateKey(), { data }); - const { v, r, s } = fromRpcSig(signature); - - const receipt = await this.token.permit(owner, spender, value, maxDeadline, v, r, s); - - expect(await this.token.nonces(owner)).to.be.bignumber.equal('1'); - expect(await this.token.allowance(owner, spender)).to.be.bignumber.equal(value); - }); - - it('rejects reused signature', async function () { - const data = buildData(this.chainId, this.token.address); - const signature = ethSigUtil.signTypedMessage(wallet.getPrivateKey(), { data }); - const { v, r, s } = fromRpcSig(signature); - - await this.token.permit(owner, spender, value, maxDeadline, v, r, s); - - await expectRevert( - this.token.permit(owner, spender, value, maxDeadline, v, r, s), - 'ERC20Permit: invalid signature', - ); - }); - - it('rejects other signature', async function () { - const otherWallet = Wallet.generate(); - const data = buildData(this.chainId, this.token.address); - const signature = ethSigUtil.signTypedMessage(otherWallet.getPrivateKey(), { data }); - const { v, r, s } = fromRpcSig(signature); - - await expectRevert( - this.token.permit(owner, spender, value, maxDeadline, v, r, s), - 'ERC20Permit: invalid signature', - ); - }); - - it('rejects expired permit', async function () { - const deadline = (await time.latest()) - time.duration.weeks(1); - - const data = buildData(this.chainId, this.token.address, deadline); - const signature = ethSigUtil.signTypedMessage(wallet.getPrivateKey(), { data }); - const { v, r, s } = fromRpcSig(signature); - - await expectRevert( - this.token.permit(owner, spender, value, deadline, v, r, s), - 'ERC20Permit: expired deadline', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/presets/ERC20PresetFixedSupply.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/presets/ERC20PresetFixedSupply.test.js deleted file mode 100644 index f1d0b53a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/presets/ERC20PresetFixedSupply.test.js +++ /dev/null @@ -1,42 +0,0 @@ -const { BN, constants, expectEvent } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const ERC20PresetFixedSupply = artifacts.require('ERC20PresetFixedSupply'); - -contract('ERC20PresetFixedSupply', function (accounts) { - const [deployer, owner] = accounts; - - const name = 'PresetFixedSupply'; - const symbol = 'PFS'; - - const initialSupply = new BN('50000'); - const amount = new BN('10000'); - - before(async function () { - this.token = await ERC20PresetFixedSupply.new(name, symbol, initialSupply, owner, { from: deployer }); - }); - - it('deployer has the balance equal to initial supply', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal(initialSupply); - }); - - it('total supply is equal to initial supply', async function () { - expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply); - }); - - describe('burning', function () { - it('holders can burn their tokens', async function () { - const remainingBalance = initialSupply.sub(amount); - const receipt = await this.token.burn(amount, { from: owner }); - expectEvent(receipt, 'Transfer', { from: owner, to: ZERO_ADDRESS, value: amount }); - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal(remainingBalance); - }); - - it('decrements totalSupply', async function () { - const expectedSupply = initialSupply.sub(amount); - expect(await this.token.totalSupply()).to.be.bignumber.equal(expectedSupply); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/presets/ERC20PresetMinterPauser.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/presets/ERC20PresetMinterPauser.test.js deleted file mode 100644 index c143790f..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/presets/ERC20PresetMinterPauser.test.js +++ /dev/null @@ -1,113 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const ERC20PresetMinterPauser = artifacts.require('ERC20PresetMinterPauser'); - -contract('ERC20PresetMinterPauser', function (accounts) { - const [ deployer, other ] = accounts; - - const name = 'MinterPauserToken'; - const symbol = 'DRT'; - - const amount = new BN('5000'); - - const DEFAULT_ADMIN_ROLE = '0x0000000000000000000000000000000000000000000000000000000000000000'; - const MINTER_ROLE = web3.utils.soliditySha3('MINTER_ROLE'); - const PAUSER_ROLE = web3.utils.soliditySha3('PAUSER_ROLE'); - - beforeEach(async function () { - this.token = await ERC20PresetMinterPauser.new(name, symbol, { from: deployer }); - }); - - it('deployer has the default admin role', async function () { - expect(await this.token.getRoleMemberCount(DEFAULT_ADMIN_ROLE)).to.be.bignumber.equal('1'); - expect(await this.token.getRoleMember(DEFAULT_ADMIN_ROLE, 0)).to.equal(deployer); - }); - - it('deployer has the minter role', async function () { - expect(await this.token.getRoleMemberCount(MINTER_ROLE)).to.be.bignumber.equal('1'); - expect(await this.token.getRoleMember(MINTER_ROLE, 0)).to.equal(deployer); - }); - - it('deployer has the pauser role', async function () { - expect(await this.token.getRoleMemberCount(PAUSER_ROLE)).to.be.bignumber.equal('1'); - expect(await this.token.getRoleMember(PAUSER_ROLE, 0)).to.equal(deployer); - }); - - it('minter and pauser role admin is the default admin', async function () { - expect(await this.token.getRoleAdmin(MINTER_ROLE)).to.equal(DEFAULT_ADMIN_ROLE); - expect(await this.token.getRoleAdmin(PAUSER_ROLE)).to.equal(DEFAULT_ADMIN_ROLE); - }); - - describe('minting', function () { - it('deployer can mint tokens', async function () { - const receipt = await this.token.mint(other, amount, { from: deployer }); - expectEvent(receipt, 'Transfer', { from: ZERO_ADDRESS, to: other, value: amount }); - - expect(await this.token.balanceOf(other)).to.be.bignumber.equal(amount); - }); - - it('other accounts cannot mint tokens', async function () { - await expectRevert( - this.token.mint(other, amount, { from: other }), - 'ERC20PresetMinterPauser: must have minter role to mint', - ); - }); - }); - - describe('pausing', function () { - it('deployer can pause', async function () { - const receipt = await this.token.pause({ from: deployer }); - expectEvent(receipt, 'Paused', { account: deployer }); - - expect(await this.token.paused()).to.equal(true); - }); - - it('deployer can unpause', async function () { - await this.token.pause({ from: deployer }); - - const receipt = await this.token.unpause({ from: deployer }); - expectEvent(receipt, 'Unpaused', { account: deployer }); - - expect(await this.token.paused()).to.equal(false); - }); - - it('cannot mint while paused', async function () { - await this.token.pause({ from: deployer }); - - await expectRevert( - this.token.mint(other, amount, { from: deployer }), - 'ERC20Pausable: token transfer while paused', - ); - }); - - it('other accounts cannot pause', async function () { - await expectRevert( - this.token.pause({ from: other }), - 'ERC20PresetMinterPauser: must have pauser role to pause', - ); - }); - - it('other accounts cannot unpause', async function () { - await this.token.pause({ from: deployer }); - - await expectRevert( - this.token.unpause({ from: other }), - 'ERC20PresetMinterPauser: must have pauser role to unpause', - ); - }); - }); - - describe('burning', function () { - it('holders can burn their tokens', async function () { - await this.token.mint(other, amount, { from: deployer }); - - const receipt = await this.token.burn(amount.subn(1), { from: other }); - expectEvent(receipt, 'Transfer', { from: other, to: ZERO_ADDRESS, value: amount.subn(1) }); - - expect(await this.token.balanceOf(other)).to.be.bignumber.equal('1'); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/utils/SafeERC20.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/utils/SafeERC20.test.js deleted file mode 100644 index 0bed7052..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/utils/SafeERC20.test.js +++ /dev/null @@ -1,135 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); - -const ERC20ReturnFalseMock = artifacts.require('ERC20ReturnFalseMock'); -const ERC20ReturnTrueMock = artifacts.require('ERC20ReturnTrueMock'); -const ERC20NoReturnMock = artifacts.require('ERC20NoReturnMock'); -const SafeERC20Wrapper = artifacts.require('SafeERC20Wrapper'); - -contract('SafeERC20', function (accounts) { - const [ hasNoCode ] = accounts; - - describe('with address that has no contract code', function () { - beforeEach(async function () { - this.wrapper = await SafeERC20Wrapper.new(hasNoCode); - }); - - shouldRevertOnAllCalls('Address: call to non-contract'); - }); - - describe('with token that returns false on all calls', function () { - beforeEach(async function () { - this.wrapper = await SafeERC20Wrapper.new((await ERC20ReturnFalseMock.new()).address); - }); - - shouldRevertOnAllCalls('SafeERC20: ERC20 operation did not succeed'); - }); - - describe('with token that returns true on all calls', function () { - beforeEach(async function () { - this.wrapper = await SafeERC20Wrapper.new((await ERC20ReturnTrueMock.new()).address); - }); - - shouldOnlyRevertOnErrors(); - }); - - describe('with token that returns no boolean values', function () { - beforeEach(async function () { - this.wrapper = await SafeERC20Wrapper.new((await ERC20NoReturnMock.new()).address); - }); - - shouldOnlyRevertOnErrors(); - }); -}); - -function shouldRevertOnAllCalls (reason) { - it('reverts on transfer', async function () { - await expectRevert(this.wrapper.transfer(), reason); - }); - - it('reverts on transferFrom', async function () { - await expectRevert(this.wrapper.transferFrom(), reason); - }); - - it('reverts on approve', async function () { - await expectRevert(this.wrapper.approve(0), reason); - }); - - it('reverts on increaseAllowance', async function () { - // [TODO] make sure it's reverting for the right reason - await expectRevert.unspecified(this.wrapper.increaseAllowance(0)); - }); - - it('reverts on decreaseAllowance', async function () { - // [TODO] make sure it's reverting for the right reason - await expectRevert.unspecified(this.wrapper.decreaseAllowance(0)); - }); -} - -function shouldOnlyRevertOnErrors () { - it('doesn\'t revert on transfer', async function () { - await this.wrapper.transfer(); - }); - - it('doesn\'t revert on transferFrom', async function () { - await this.wrapper.transferFrom(); - }); - - describe('approvals', function () { - context('with zero allowance', function () { - beforeEach(async function () { - await this.wrapper.setAllowance(0); - }); - - it('doesn\'t revert when approving a non-zero allowance', async function () { - await this.wrapper.approve(100); - }); - - it('doesn\'t revert when approving a zero allowance', async function () { - await this.wrapper.approve(0); - }); - - it('doesn\'t revert when increasing the allowance', async function () { - await this.wrapper.increaseAllowance(10); - }); - - it('reverts when decreasing the allowance', async function () { - await expectRevert( - this.wrapper.decreaseAllowance(10), - 'SafeERC20: decreased allowance below zero', - ); - }); - }); - - context('with non-zero allowance', function () { - beforeEach(async function () { - await this.wrapper.setAllowance(100); - }); - - it('reverts when approving a non-zero allowance', async function () { - await expectRevert( - this.wrapper.approve(20), - 'SafeERC20: approve from non-zero to non-zero allowance', - ); - }); - - it('doesn\'t revert when approving a zero allowance', async function () { - await this.wrapper.approve(0); - }); - - it('doesn\'t revert when increasing the allowance', async function () { - await this.wrapper.increaseAllowance(10); - }); - - it('doesn\'t revert when decreasing the allowance to a positive value', async function () { - await this.wrapper.decreaseAllowance(50); - }); - - it('reverts when decreasing the allowance to a negative value', async function () { - await expectRevert( - this.wrapper.decreaseAllowance(200), - 'SafeERC20: decreased allowance below zero', - ); - }); - }); - }); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/utils/TokenTimelock.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/utils/TokenTimelock.test.js deleted file mode 100644 index e546b341..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC20/utils/TokenTimelock.test.js +++ /dev/null @@ -1,71 +0,0 @@ -const { BN, expectRevert, time } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC20Mock = artifacts.require('ERC20Mock'); -const TokenTimelock = artifacts.require('TokenTimelock'); - -contract('TokenTimelock', function (accounts) { - const [ beneficiary ] = accounts; - - const name = 'My Token'; - const symbol = 'MTKN'; - - const amount = new BN(100); - - context('with token', function () { - beforeEach(async function () { - this.token = await ERC20Mock.new(name, symbol, beneficiary, 0); // We're not using the preminted tokens - }); - - it('rejects a release time in the past', async function () { - const pastReleaseTime = (await time.latest()).sub(time.duration.years(1)); - await expectRevert( - TokenTimelock.new(this.token.address, beneficiary, pastReleaseTime), - 'TokenTimelock: release time is before current time', - ); - }); - - context('once deployed', function () { - beforeEach(async function () { - this.releaseTime = (await time.latest()).add(time.duration.years(1)); - this.timelock = await TokenTimelock.new(this.token.address, beneficiary, this.releaseTime); - await this.token.mint(this.timelock.address, amount); - }); - - it('can get state', async function () { - expect(await this.timelock.token()).to.equal(this.token.address); - expect(await this.timelock.beneficiary()).to.equal(beneficiary); - expect(await this.timelock.releaseTime()).to.be.bignumber.equal(this.releaseTime); - }); - - it('cannot be released before time limit', async function () { - await expectRevert(this.timelock.release(), 'TokenTimelock: current time is before release time'); - }); - - it('cannot be released just before time limit', async function () { - await time.increaseTo(this.releaseTime.sub(time.duration.seconds(3))); - await expectRevert(this.timelock.release(), 'TokenTimelock: current time is before release time'); - }); - - it('can be released just after limit', async function () { - await time.increaseTo(this.releaseTime.add(time.duration.seconds(1))); - await this.timelock.release(); - expect(await this.token.balanceOf(beneficiary)).to.be.bignumber.equal(amount); - }); - - it('can be released after time limit', async function () { - await time.increaseTo(this.releaseTime.add(time.duration.years(1))); - await this.timelock.release(); - expect(await this.token.balanceOf(beneficiary)).to.be.bignumber.equal(amount); - }); - - it('cannot be released twice', async function () { - await time.increaseTo(this.releaseTime.add(time.duration.years(1))); - await this.timelock.release(); - await expectRevert(this.timelock.release(), 'TokenTimelock: no tokens to release'); - expect(await this.token.balanceOf(beneficiary)).to.be.bignumber.equal(amount); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721.behavior.js deleted file mode 100644 index 67fa98a4..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721.behavior.js +++ /dev/null @@ -1,945 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { ZERO_ADDRESS } = constants; - -const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsInterface.behavior'); - -const ERC721ReceiverMock = artifacts.require('ERC721ReceiverMock'); - -const Error = [ 'None', 'RevertWithMessage', 'RevertWithoutMessage', 'Panic' ] - .reduce((acc, entry, idx) => Object.assign({ [entry]: idx }, acc), {}); - -const firstTokenId = new BN('5042'); -const secondTokenId = new BN('79217'); -const nonExistentTokenId = new BN('13'); -const fourthTokenId = new BN(4); -const baseURI = 'https://api.example.com/v1/'; - -const RECEIVER_MAGIC_VALUE = '0x150b7a02'; - -function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, anotherApproved, operator, other) { - shouldSupportInterfaces([ - 'ERC165', - 'ERC721', - ]); - - context('with minted tokens', function () { - beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); - this.toWhom = other; // default to other for toWhom in context-dependent tests - }); - - describe('balanceOf', function () { - context('when the given address owns some tokens', function () { - it('returns the amount of tokens owned by the given address', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('2'); - }); - }); - - context('when the given address does not own any tokens', function () { - it('returns 0', async function () { - expect(await this.token.balanceOf(other)).to.be.bignumber.equal('0'); - }); - }); - - context('when querying the zero address', function () { - it('throws', async function () { - await expectRevert( - this.token.balanceOf(ZERO_ADDRESS), 'ERC721: balance query for the zero address', - ); - }); - }); - }); - - describe('ownerOf', function () { - context('when the given token ID was tracked by this token', function () { - const tokenId = firstTokenId; - - it('returns the owner of the given token ID', async function () { - expect(await this.token.ownerOf(tokenId)).to.be.equal(owner); - }); - }); - - context('when the given token ID was not tracked by this token', function () { - const tokenId = nonExistentTokenId; - - it('reverts', async function () { - await expectRevert( - this.token.ownerOf(tokenId), 'ERC721: owner query for nonexistent token', - ); - }); - }); - }); - - describe('transfers', function () { - const tokenId = firstTokenId; - const data = '0x42'; - - let logs = null; - - beforeEach(async function () { - await this.token.approve(approved, tokenId, { from: owner }); - await this.token.setApprovalForAll(operator, true, { from: owner }); - }); - - const transferWasSuccessful = function ({ owner, tokenId, approved }) { - it('transfers the ownership of the given token ID to the given address', async function () { - expect(await this.token.ownerOf(tokenId)).to.be.equal(this.toWhom); - }); - - it('emits a Transfer event', async function () { - expectEvent.inLogs(logs, 'Transfer', { from: owner, to: this.toWhom, tokenId: tokenId }); - }); - - it('clears the approval for the token ID', async function () { - expect(await this.token.getApproved(tokenId)).to.be.equal(ZERO_ADDRESS); - }); - - it('emits an Approval event', async function () { - expectEvent.inLogs(logs, 'Approval', { owner, approved: ZERO_ADDRESS, tokenId: tokenId }); - }); - - it('adjusts owners balances', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('1'); - }); - - it('adjusts owners tokens by index', async function () { - if (!this.token.tokenOfOwnerByIndex) return; - - expect(await this.token.tokenOfOwnerByIndex(this.toWhom, 0)).to.be.bignumber.equal(tokenId); - - expect(await this.token.tokenOfOwnerByIndex(owner, 0)).to.be.bignumber.not.equal(tokenId); - }); - }; - - const shouldTransferTokensByUsers = function (transferFunction) { - context('when called by the owner', function () { - beforeEach(async function () { - ({ logs } = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: owner })); - }); - transferWasSuccessful({ owner, tokenId, approved }); - }); - - context('when called by the approved individual', function () { - beforeEach(async function () { - ({ logs } = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: approved })); - }); - transferWasSuccessful({ owner, tokenId, approved }); - }); - - context('when called by the operator', function () { - beforeEach(async function () { - ({ logs } = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: operator })); - }); - transferWasSuccessful({ owner, tokenId, approved }); - }); - - context('when called by the owner without an approved user', function () { - beforeEach(async function () { - await this.token.approve(ZERO_ADDRESS, tokenId, { from: owner }); - ({ logs } = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: operator })); - }); - transferWasSuccessful({ owner, tokenId, approved: null }); - }); - - context('when sent to the owner', function () { - beforeEach(async function () { - ({ logs } = await transferFunction.call(this, owner, owner, tokenId, { from: owner })); - }); - - it('keeps ownership of the token', async function () { - expect(await this.token.ownerOf(tokenId)).to.be.equal(owner); - }); - - it('clears the approval for the token ID', async function () { - expect(await this.token.getApproved(tokenId)).to.be.equal(ZERO_ADDRESS); - }); - - it('emits only a transfer event', async function () { - expectEvent.inLogs(logs, 'Transfer', { - from: owner, - to: owner, - tokenId: tokenId, - }); - }); - - it('keeps the owner balance', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('2'); - }); - - it('keeps same tokens by index', async function () { - if (!this.token.tokenOfOwnerByIndex) return; - const tokensListed = await Promise.all( - [0, 1].map(i => this.token.tokenOfOwnerByIndex(owner, i)), - ); - expect(tokensListed.map(t => t.toNumber())).to.have.members( - [firstTokenId.toNumber(), secondTokenId.toNumber()], - ); - }); - }); - - context('when the address of the previous owner is incorrect', function () { - it('reverts', async function () { - await expectRevert( - transferFunction.call(this, other, other, tokenId, { from: owner }), - 'ERC721: transfer from incorrect owner', - ); - }); - }); - - context('when the sender is not authorized for the token id', function () { - it('reverts', async function () { - await expectRevert( - transferFunction.call(this, owner, other, tokenId, { from: other }), - 'ERC721: transfer caller is not owner nor approved', - ); - }); - }); - - context('when the given token ID does not exist', function () { - it('reverts', async function () { - await expectRevert( - transferFunction.call(this, owner, other, nonExistentTokenId, { from: owner }), - 'ERC721: operator query for nonexistent token', - ); - }); - }); - - context('when the address to transfer the token to is the zero address', function () { - it('reverts', async function () { - await expectRevert( - transferFunction.call(this, owner, ZERO_ADDRESS, tokenId, { from: owner }), - 'ERC721: transfer to the zero address', - ); - }); - }); - }; - - describe('via transferFrom', function () { - shouldTransferTokensByUsers(function (from, to, tokenId, opts) { - return this.token.transferFrom(from, to, tokenId, opts); - }); - }); - - describe('via safeTransferFrom', function () { - const safeTransferFromWithData = function (from, to, tokenId, opts) { - return this.token.methods['safeTransferFrom(address,address,uint256,bytes)'](from, to, tokenId, data, opts); - }; - - const safeTransferFromWithoutData = function (from, to, tokenId, opts) { - return this.token.methods['safeTransferFrom(address,address,uint256)'](from, to, tokenId, opts); - }; - - const shouldTransferSafely = function (transferFun, data) { - describe('to a user account', function () { - shouldTransferTokensByUsers(transferFun); - }); - - describe('to a valid receiver contract', function () { - beforeEach(async function () { - this.receiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.None); - this.toWhom = this.receiver.address; - }); - - shouldTransferTokensByUsers(transferFun); - - it('calls onERC721Received', async function () { - const receipt = await transferFun.call(this, owner, this.receiver.address, tokenId, { from: owner }); - - await expectEvent.inTransaction(receipt.tx, ERC721ReceiverMock, 'Received', { - operator: owner, - from: owner, - tokenId: tokenId, - data: data, - }); - }); - - it('calls onERC721Received from approved', async function () { - const receipt = await transferFun.call(this, owner, this.receiver.address, tokenId, { from: approved }); - - await expectEvent.inTransaction(receipt.tx, ERC721ReceiverMock, 'Received', { - operator: approved, - from: owner, - tokenId: tokenId, - data: data, - }); - }); - - describe('with an invalid token id', function () { - it('reverts', async function () { - await expectRevert( - transferFun.call( - this, - owner, - this.receiver.address, - nonExistentTokenId, - { from: owner }, - ), - 'ERC721: operator query for nonexistent token', - ); - }); - }); - }); - }; - - describe('with data', function () { - shouldTransferSafely(safeTransferFromWithData, data); - }); - - describe('without data', function () { - shouldTransferSafely(safeTransferFromWithoutData, null); - }); - - describe('to a receiver contract returning unexpected value', function () { - it('reverts', async function () { - const invalidReceiver = await ERC721ReceiverMock.new('0x42', Error.None); - await expectRevert( - this.token.safeTransferFrom(owner, invalidReceiver.address, tokenId, { from: owner }), - 'ERC721: transfer to non ERC721Receiver implementer', - ); - }); - }); - - describe('to a receiver contract that reverts with message', function () { - it('reverts', async function () { - const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.RevertWithMessage); - await expectRevert( - this.token.safeTransferFrom(owner, revertingReceiver.address, tokenId, { from: owner }), - 'ERC721ReceiverMock: reverting', - ); - }); - }); - - describe('to a receiver contract that reverts without message', function () { - it('reverts', async function () { - const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.RevertWithoutMessage); - await expectRevert( - this.token.safeTransferFrom(owner, revertingReceiver.address, tokenId, { from: owner }), - 'ERC721: transfer to non ERC721Receiver implementer', - ); - }); - }); - - describe('to a receiver contract that panics', function () { - it('reverts', async function () { - const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.Panic); - await expectRevert.unspecified( - this.token.safeTransferFrom(owner, revertingReceiver.address, tokenId, { from: owner }), - ); - }); - }); - - describe('to a contract that does not implement the required function', function () { - it('reverts', async function () { - const nonReceiver = this.token; - await expectRevert( - this.token.safeTransferFrom(owner, nonReceiver.address, tokenId, { from: owner }), - 'ERC721: transfer to non ERC721Receiver implementer', - ); - }); - }); - }); - }); - - describe('safe mint', function () { - const tokenId = fourthTokenId; - const data = '0x42'; - - describe('via safeMint', function () { // regular minting is tested in ERC721Mintable.test.js and others - it('calls onERC721Received — with data', async function () { - this.receiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.None); - const receipt = await this.token.safeMint(this.receiver.address, tokenId, data); - - await expectEvent.inTransaction(receipt.tx, ERC721ReceiverMock, 'Received', { - from: ZERO_ADDRESS, - tokenId: tokenId, - data: data, - }); - }); - - it('calls onERC721Received — without data', async function () { - this.receiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.None); - const receipt = await this.token.safeMint(this.receiver.address, tokenId); - - await expectEvent.inTransaction(receipt.tx, ERC721ReceiverMock, 'Received', { - from: ZERO_ADDRESS, - tokenId: tokenId, - }); - }); - - context('to a receiver contract returning unexpected value', function () { - it('reverts', async function () { - const invalidReceiver = await ERC721ReceiverMock.new('0x42', Error.None); - await expectRevert( - this.token.safeMint(invalidReceiver.address, tokenId), - 'ERC721: transfer to non ERC721Receiver implementer', - ); - }); - }); - - context('to a receiver contract that reverts with message', function () { - it('reverts', async function () { - const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.RevertWithMessage); - await expectRevert( - this.token.safeMint(revertingReceiver.address, tokenId), - 'ERC721ReceiverMock: reverting', - ); - }); - }); - - context('to a receiver contract that reverts without message', function () { - it('reverts', async function () { - const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.RevertWithoutMessage); - await expectRevert( - this.token.safeMint(revertingReceiver.address, tokenId), - 'ERC721: transfer to non ERC721Receiver implementer', - ); - }); - }); - - context('to a receiver contract that panics', function () { - it('reverts', async function () { - const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.Panic); - await expectRevert.unspecified( - this.token.safeMint(revertingReceiver.address, tokenId), - ); - }); - }); - - context('to a contract that does not implement the required function', function () { - it('reverts', async function () { - const nonReceiver = this.token; - await expectRevert( - this.token.safeMint(nonReceiver.address, tokenId), - 'ERC721: transfer to non ERC721Receiver implementer', - ); - }); - }); - }); - }); - - describe('approve', function () { - const tokenId = firstTokenId; - - let logs = null; - - const itClearsApproval = function () { - it('clears approval for the token', async function () { - expect(await this.token.getApproved(tokenId)).to.be.equal(ZERO_ADDRESS); - }); - }; - - const itApproves = function (address) { - it('sets the approval for the target address', async function () { - expect(await this.token.getApproved(tokenId)).to.be.equal(address); - }); - }; - - const itEmitsApprovalEvent = function (address) { - it('emits an approval event', async function () { - expectEvent.inLogs(logs, 'Approval', { - owner: owner, - approved: address, - tokenId: tokenId, - }); - }); - }; - - context('when clearing approval', function () { - context('when there was no prior approval', function () { - beforeEach(async function () { - ({ logs } = await this.token.approve(ZERO_ADDRESS, tokenId, { from: owner })); - }); - - itClearsApproval(); - itEmitsApprovalEvent(ZERO_ADDRESS); - }); - - context('when there was a prior approval', function () { - beforeEach(async function () { - await this.token.approve(approved, tokenId, { from: owner }); - ({ logs } = await this.token.approve(ZERO_ADDRESS, tokenId, { from: owner })); - }); - - itClearsApproval(); - itEmitsApprovalEvent(ZERO_ADDRESS); - }); - }); - - context('when approving a non-zero address', function () { - context('when there was no prior approval', function () { - beforeEach(async function () { - ({ logs } = await this.token.approve(approved, tokenId, { from: owner })); - }); - - itApproves(approved); - itEmitsApprovalEvent(approved); - }); - - context('when there was a prior approval to the same address', function () { - beforeEach(async function () { - await this.token.approve(approved, tokenId, { from: owner }); - ({ logs } = await this.token.approve(approved, tokenId, { from: owner })); - }); - - itApproves(approved); - itEmitsApprovalEvent(approved); - }); - - context('when there was a prior approval to a different address', function () { - beforeEach(async function () { - await this.token.approve(anotherApproved, tokenId, { from: owner }); - ({ logs } = await this.token.approve(anotherApproved, tokenId, { from: owner })); - }); - - itApproves(anotherApproved); - itEmitsApprovalEvent(anotherApproved); - }); - }); - - context('when the address that receives the approval is the owner', function () { - it('reverts', async function () { - await expectRevert( - this.token.approve(owner, tokenId, { from: owner }), 'ERC721: approval to current owner', - ); - }); - }); - - context('when the sender does not own the given token ID', function () { - it('reverts', async function () { - await expectRevert(this.token.approve(approved, tokenId, { from: other }), - 'ERC721: approve caller is not owner nor approved'); - }); - }); - - context('when the sender is approved for the given token ID', function () { - it('reverts', async function () { - await this.token.approve(approved, tokenId, { from: owner }); - await expectRevert(this.token.approve(anotherApproved, tokenId, { from: approved }), - 'ERC721: approve caller is not owner nor approved for all'); - }); - }); - - context('when the sender is an operator', function () { - beforeEach(async function () { - await this.token.setApprovalForAll(operator, true, { from: owner }); - ({ logs } = await this.token.approve(approved, tokenId, { from: operator })); - }); - - itApproves(approved); - itEmitsApprovalEvent(approved); - }); - - context('when the given token ID does not exist', function () { - it('reverts', async function () { - await expectRevert(this.token.approve(approved, nonExistentTokenId, { from: operator }), - 'ERC721: owner query for nonexistent token'); - }); - }); - }); - - describe('setApprovalForAll', function () { - context('when the operator willing to approve is not the owner', function () { - context('when there is no operator approval set by the sender', function () { - it('approves the operator', async function () { - await this.token.setApprovalForAll(operator, true, { from: owner }); - - expect(await this.token.isApprovedForAll(owner, operator)).to.equal(true); - }); - - it('emits an approval event', async function () { - const { logs } = await this.token.setApprovalForAll(operator, true, { from: owner }); - - expectEvent.inLogs(logs, 'ApprovalForAll', { - owner: owner, - operator: operator, - approved: true, - }); - }); - }); - - context('when the operator was set as not approved', function () { - beforeEach(async function () { - await this.token.setApprovalForAll(operator, false, { from: owner }); - }); - - it('approves the operator', async function () { - await this.token.setApprovalForAll(operator, true, { from: owner }); - - expect(await this.token.isApprovedForAll(owner, operator)).to.equal(true); - }); - - it('emits an approval event', async function () { - const { logs } = await this.token.setApprovalForAll(operator, true, { from: owner }); - - expectEvent.inLogs(logs, 'ApprovalForAll', { - owner: owner, - operator: operator, - approved: true, - }); - }); - - it('can unset the operator approval', async function () { - await this.token.setApprovalForAll(operator, false, { from: owner }); - - expect(await this.token.isApprovedForAll(owner, operator)).to.equal(false); - }); - }); - - context('when the operator was already approved', function () { - beforeEach(async function () { - await this.token.setApprovalForAll(operator, true, { from: owner }); - }); - - it('keeps the approval to the given address', async function () { - await this.token.setApprovalForAll(operator, true, { from: owner }); - - expect(await this.token.isApprovedForAll(owner, operator)).to.equal(true); - }); - - it('emits an approval event', async function () { - const { logs } = await this.token.setApprovalForAll(operator, true, { from: owner }); - - expectEvent.inLogs(logs, 'ApprovalForAll', { - owner: owner, - operator: operator, - approved: true, - }); - }); - }); - }); - - context('when the operator is the owner', function () { - it('reverts', async function () { - await expectRevert(this.token.setApprovalForAll(owner, true, { from: owner }), - 'ERC721: approve to caller'); - }); - }); - }); - - describe('getApproved', async function () { - context('when token is not minted', async function () { - it('reverts', async function () { - await expectRevert( - this.token.getApproved(nonExistentTokenId), - 'ERC721: approved query for nonexistent token', - ); - }); - }); - - context('when token has been minted ', async function () { - it('should return the zero address', async function () { - expect(await this.token.getApproved(firstTokenId)).to.be.equal( - ZERO_ADDRESS, - ); - }); - - context('when account has been approved', async function () { - beforeEach(async function () { - await this.token.approve(approved, firstTokenId, { from: owner }); - }); - - it('returns approved account', async function () { - expect(await this.token.getApproved(firstTokenId)).to.be.equal(approved); - }); - }); - }); - }); - }); - - describe('_mint(address, uint256)', function () { - it('reverts with a null destination address', async function () { - await expectRevert( - this.token.mint(ZERO_ADDRESS, firstTokenId), 'ERC721: mint to the zero address', - ); - }); - - context('with minted token', async function () { - beforeEach(async function () { - ({ logs: this.logs } = await this.token.mint(owner, firstTokenId)); - }); - - it('emits a Transfer event', function () { - expectEvent.inLogs(this.logs, 'Transfer', { from: ZERO_ADDRESS, to: owner, tokenId: firstTokenId }); - }); - - it('creates the token', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('1'); - expect(await this.token.ownerOf(firstTokenId)).to.equal(owner); - }); - - it('reverts when adding a token id that already exists', async function () { - await expectRevert(this.token.mint(owner, firstTokenId), 'ERC721: token already minted'); - }); - }); - }); - - describe('_burn', function () { - it('reverts when burning a non-existent token id', async function () { - await expectRevert( - this.token.burn(nonExistentTokenId), 'ERC721: owner query for nonexistent token', - ); - }); - - context('with minted tokens', function () { - beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); - }); - - context('with burnt token', function () { - beforeEach(async function () { - ({ logs: this.logs } = await this.token.burn(firstTokenId)); - }); - - it('emits a Transfer event', function () { - expectEvent.inLogs(this.logs, 'Transfer', { from: owner, to: ZERO_ADDRESS, tokenId: firstTokenId }); - }); - - it('emits an Approval event', function () { - expectEvent.inLogs(this.logs, 'Approval', { owner, approved: ZERO_ADDRESS, tokenId: firstTokenId }); - }); - - it('deletes the token', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('1'); - await expectRevert( - this.token.ownerOf(firstTokenId), 'ERC721: owner query for nonexistent token', - ); - }); - - it('reverts when burning a token id that has been deleted', async function () { - await expectRevert( - this.token.burn(firstTokenId), 'ERC721: owner query for nonexistent token', - ); - }); - }); - }); - }); -} - -function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approved, anotherApproved, operator, other) { - shouldSupportInterfaces([ - 'ERC721Enumerable', - ]); - - context('with minted tokens', function () { - beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); - this.toWhom = other; // default to other for toWhom in context-dependent tests - }); - - describe('totalSupply', function () { - it('returns total token supply', async function () { - expect(await this.token.totalSupply()).to.be.bignumber.equal('2'); - }); - }); - - describe('tokenOfOwnerByIndex', function () { - describe('when the given index is lower than the amount of tokens owned by the given address', function () { - it('returns the token ID placed at the given index', async function () { - expect(await this.token.tokenOfOwnerByIndex(owner, 0)).to.be.bignumber.equal(firstTokenId); - }); - }); - - describe('when the index is greater than or equal to the total tokens owned by the given address', function () { - it('reverts', async function () { - await expectRevert( - this.token.tokenOfOwnerByIndex(owner, 2), 'ERC721Enumerable: owner index out of bounds', - ); - }); - }); - - describe('when the given address does not own any token', function () { - it('reverts', async function () { - await expectRevert( - this.token.tokenOfOwnerByIndex(other, 0), 'ERC721Enumerable: owner index out of bounds', - ); - }); - }); - - describe('after transferring all tokens to another user', function () { - beforeEach(async function () { - await this.token.transferFrom(owner, other, firstTokenId, { from: owner }); - await this.token.transferFrom(owner, other, secondTokenId, { from: owner }); - }); - - it('returns correct token IDs for target', async function () { - expect(await this.token.balanceOf(other)).to.be.bignumber.equal('2'); - const tokensListed = await Promise.all( - [0, 1].map(i => this.token.tokenOfOwnerByIndex(other, i)), - ); - expect(tokensListed.map(t => t.toNumber())).to.have.members([firstTokenId.toNumber(), - secondTokenId.toNumber()]); - }); - - it('returns empty collection for original owner', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('0'); - await expectRevert( - this.token.tokenOfOwnerByIndex(owner, 0), 'ERC721Enumerable: owner index out of bounds', - ); - }); - }); - }); - - describe('tokenByIndex', function () { - it('returns all tokens', async function () { - const tokensListed = await Promise.all( - [0, 1].map(i => this.token.tokenByIndex(i)), - ); - expect(tokensListed.map(t => t.toNumber())).to.have.members([firstTokenId.toNumber(), - secondTokenId.toNumber()]); - }); - - it('reverts if index is greater than supply', async function () { - await expectRevert( - this.token.tokenByIndex(2), 'ERC721Enumerable: global index out of bounds', - ); - }); - - [firstTokenId, secondTokenId].forEach(function (tokenId) { - it(`returns all tokens after burning token ${tokenId} and minting new tokens`, async function () { - const newTokenId = new BN(300); - const anotherNewTokenId = new BN(400); - - await this.token.burn(tokenId); - await this.token.mint(newOwner, newTokenId); - await this.token.mint(newOwner, anotherNewTokenId); - - expect(await this.token.totalSupply()).to.be.bignumber.equal('3'); - - const tokensListed = await Promise.all( - [0, 1, 2].map(i => this.token.tokenByIndex(i)), - ); - const expectedTokens = [firstTokenId, secondTokenId, newTokenId, anotherNewTokenId].filter( - x => (x !== tokenId), - ); - expect(tokensListed.map(t => t.toNumber())).to.have.members(expectedTokens.map(t => t.toNumber())); - }); - }); - }); - }); - - describe('_mint(address, uint256)', function () { - it('reverts with a null destination address', async function () { - await expectRevert( - this.token.mint(ZERO_ADDRESS, firstTokenId), 'ERC721: mint to the zero address', - ); - }); - - context('with minted token', async function () { - beforeEach(async function () { - ({ logs: this.logs } = await this.token.mint(owner, firstTokenId)); - }); - - it('adjusts owner tokens by index', async function () { - expect(await this.token.tokenOfOwnerByIndex(owner, 0)).to.be.bignumber.equal(firstTokenId); - }); - - it('adjusts all tokens list', async function () { - expect(await this.token.tokenByIndex(0)).to.be.bignumber.equal(firstTokenId); - }); - }); - }); - - describe('_burn', function () { - it('reverts when burning a non-existent token id', async function () { - await expectRevert( - this.token.burn(firstTokenId), 'ERC721: owner query for nonexistent token', - ); - }); - - context('with minted tokens', function () { - beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); - }); - - context('with burnt token', function () { - beforeEach(async function () { - ({ logs: this.logs } = await this.token.burn(firstTokenId)); - }); - - it('removes that token from the token list of the owner', async function () { - expect(await this.token.tokenOfOwnerByIndex(owner, 0)).to.be.bignumber.equal(secondTokenId); - }); - - it('adjusts all tokens list', async function () { - expect(await this.token.tokenByIndex(0)).to.be.bignumber.equal(secondTokenId); - }); - - it('burns all tokens', async function () { - await this.token.burn(secondTokenId, { from: owner }); - expect(await this.token.totalSupply()).to.be.bignumber.equal('0'); - await expectRevert( - this.token.tokenByIndex(0), 'ERC721Enumerable: global index out of bounds', - ); - }); - }); - }); - }); -} - -function shouldBehaveLikeERC721Metadata (errorPrefix, name, symbol, owner) { - shouldSupportInterfaces([ - 'ERC721Metadata', - ]); - - describe('metadata', function () { - it('has a name', async function () { - expect(await this.token.name()).to.be.equal(name); - }); - - it('has a symbol', async function () { - expect(await this.token.symbol()).to.be.equal(symbol); - }); - - describe('token URI', function () { - beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - }); - - it('return empty string by default', async function () { - expect(await this.token.tokenURI(firstTokenId)).to.be.equal(''); - }); - - it('reverts when queried for non existent token id', async function () { - await expectRevert( - this.token.tokenURI(nonExistentTokenId), 'ERC721Metadata: URI query for nonexistent token', - ); - }); - - describe('base URI', function () { - beforeEach(function () { - if (this.token.setBaseURI === undefined) { - this.skip(); - } - }); - - it('base URI can be set', async function () { - await this.token.setBaseURI(baseURI); - expect(await this.token.baseURI()).to.equal(baseURI); - }); - - it('base URI is added as a prefix to the token URI', async function () { - await this.token.setBaseURI(baseURI); - expect(await this.token.tokenURI(firstTokenId)).to.be.equal(baseURI + firstTokenId.toString()); - }); - - it('token URI can be changed by changing the base URI', async function () { - await this.token.setBaseURI(baseURI); - const newBaseURI = 'https://api.example.com/v2/'; - await this.token.setBaseURI(newBaseURI); - expect(await this.token.tokenURI(firstTokenId)).to.be.equal(newBaseURI + firstTokenId.toString()); - }); - }); - }); - }); -} - -module.exports = { - shouldBehaveLikeERC721, - shouldBehaveLikeERC721Enumerable, - shouldBehaveLikeERC721Metadata, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721.test.js deleted file mode 100644 index 1abbd662..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721.test.js +++ /dev/null @@ -1,18 +0,0 @@ -const { - shouldBehaveLikeERC721, - shouldBehaveLikeERC721Metadata, -} = require('./ERC721.behavior'); - -const ERC721Mock = artifacts.require('ERC721Mock'); - -contract('ERC721', function (accounts) { - const name = 'Non Fungible Token'; - const symbol = 'NFT'; - - beforeEach(async function () { - this.token = await ERC721Mock.new(name, symbol); - }); - - shouldBehaveLikeERC721('ERC721', ...accounts); - shouldBehaveLikeERC721Metadata('ERC721', name, symbol, ...accounts); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721Enumerable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721Enumerable.test.js deleted file mode 100644 index 2c136216..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/ERC721Enumerable.test.js +++ /dev/null @@ -1,20 +0,0 @@ -const { - shouldBehaveLikeERC721, - shouldBehaveLikeERC721Metadata, - shouldBehaveLikeERC721Enumerable, -} = require('./ERC721.behavior'); - -const ERC721Mock = artifacts.require('ERC721EnumerableMock'); - -contract('ERC721Enumerable', function (accounts) { - const name = 'Non Fungible Token'; - const symbol = 'NFT'; - - beforeEach(async function () { - this.token = await ERC721Mock.new(name, symbol); - }); - - shouldBehaveLikeERC721('ERC721', ...accounts); - shouldBehaveLikeERC721Metadata('ERC721', name, symbol, ...accounts); - shouldBehaveLikeERC721Enumerable('ERC721', ...accounts); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Burnable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Burnable.test.js deleted file mode 100644 index 3ffca104..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Burnable.test.js +++ /dev/null @@ -1,80 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const ERC721BurnableMock = artifacts.require('ERC721BurnableMock'); - -contract('ERC721Burnable', function (accounts) { - const [owner, approved] = accounts; - - const firstTokenId = new BN(1); - const secondTokenId = new BN(2); - const unknownTokenId = new BN(3); - - const name = 'Non Fungible Token'; - const symbol = 'NFT'; - - beforeEach(async function () { - this.token = await ERC721BurnableMock.new(name, symbol); - }); - - describe('like a burnable ERC721', function () { - beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); - }); - - describe('burn', function () { - const tokenId = firstTokenId; - let logs = null; - - describe('when successful', function () { - beforeEach(async function () { - const result = await this.token.burn(tokenId, { from: owner }); - logs = result.logs; - }); - - it('burns the given token ID and adjusts the balance of the owner', async function () { - await expectRevert( - this.token.ownerOf(tokenId), - 'ERC721: owner query for nonexistent token', - ); - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('1'); - }); - - it('emits a burn event', async function () { - expectEvent.inLogs(logs, 'Transfer', { - from: owner, - to: ZERO_ADDRESS, - tokenId: tokenId, - }); - }); - }); - - describe('when there is a previous approval burned', function () { - beforeEach(async function () { - await this.token.approve(approved, tokenId, { from: owner }); - const result = await this.token.burn(tokenId, { from: owner }); - logs = result.logs; - }); - - context('getApproved', function () { - it('reverts', async function () { - await expectRevert( - this.token.getApproved(tokenId), 'ERC721: approved query for nonexistent token', - ); - }); - }); - }); - - describe('when the given token ID was not tracked by this contract', function () { - it('reverts', async function () { - await expectRevert( - this.token.burn(unknownTokenId, { from: owner }), 'ERC721: operator query for nonexistent token', - ); - }); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Pausable.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Pausable.test.js deleted file mode 100644 index 16847dc8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Pausable.test.js +++ /dev/null @@ -1,98 +0,0 @@ -const { BN, constants, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const ERC721PausableMock = artifacts.require('ERC721PausableMock'); - -contract('ERC721Pausable', function (accounts) { - const [ owner, receiver, operator ] = accounts; - - const name = 'Non Fungible Token'; - const symbol = 'NFT'; - - beforeEach(async function () { - this.token = await ERC721PausableMock.new(name, symbol); - }); - - context('when token is paused', function () { - const firstTokenId = new BN(1); - const secondTokenId = new BN(1337); - - const mockData = '0x42'; - - beforeEach(async function () { - await this.token.mint(owner, firstTokenId, { from: owner }); - await this.token.pause(); - }); - - it('reverts when trying to transferFrom', async function () { - await expectRevert( - this.token.transferFrom(owner, receiver, firstTokenId, { from: owner }), - 'ERC721Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to safeTransferFrom', async function () { - await expectRevert( - this.token.safeTransferFrom(owner, receiver, firstTokenId, { from: owner }), - 'ERC721Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to safeTransferFrom with data', async function () { - await expectRevert( - this.token.methods['safeTransferFrom(address,address,uint256,bytes)']( - owner, receiver, firstTokenId, mockData, { from: owner }, - ), 'ERC721Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to mint', async function () { - await expectRevert( - this.token.mint(receiver, secondTokenId), - 'ERC721Pausable: token transfer while paused', - ); - }); - - it('reverts when trying to burn', async function () { - await expectRevert( - this.token.burn(firstTokenId), - 'ERC721Pausable: token transfer while paused', - ); - }); - - describe('getApproved', function () { - it('returns approved address', async function () { - const approvedAccount = await this.token.getApproved(firstTokenId); - expect(approvedAccount).to.equal(ZERO_ADDRESS); - }); - }); - - describe('balanceOf', function () { - it('returns the amount of tokens owned by the given address', async function () { - const balance = await this.token.balanceOf(owner); - expect(balance).to.be.bignumber.equal('1'); - }); - }); - - describe('ownerOf', function () { - it('returns the amount of tokens owned by the given address', async function () { - const ownerOfToken = await this.token.ownerOf(firstTokenId); - expect(ownerOfToken).to.equal(owner); - }); - }); - - describe('exists', function () { - it('returns token existence', async function () { - expect(await this.token.exists(firstTokenId)).to.equal(true); - }); - }); - - describe('isApprovedForAll', function () { - it('returns the approval of the operator', async function () { - expect(await this.token.isApprovedForAll(owner, operator)).to.equal(false); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Royalty.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Royalty.test.js deleted file mode 100644 index 29b28dd0..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Royalty.test.js +++ /dev/null @@ -1,40 +0,0 @@ -const { BN, constants } = require('@openzeppelin/test-helpers'); -const ERC721RoyaltyMock = artifacts.require('ERC721RoyaltyMock'); -const { ZERO_ADDRESS } = constants; - -const { shouldBehaveLikeERC2981 } = require('../../common/ERC2981.behavior'); - -contract('ERC721Royalty', function (accounts) { - const [ account1, account2 ] = accounts; - const tokenId1 = new BN('1'); - const tokenId2 = new BN('2'); - const royalty = new BN('200'); - const salePrice = new BN('1000'); - - beforeEach(async function () { - this.token = await ERC721RoyaltyMock.new('My Token', 'TKN'); - - await this.token.mint(account1, tokenId1); - await this.token.mint(account1, tokenId2); - this.account1 = account1; - this.account2 = account2; - this.tokenId1 = tokenId1; - this.tokenId2 = tokenId2; - this.salePrice = salePrice; - }); - - describe('token specific functions', function () { - beforeEach(async function () { - await this.token.setTokenRoyalty(tokenId1, account1, royalty); - }); - - it('removes royalty information after burn', async function () { - await this.token.burn(tokenId1); - const tokenInfo = await this.token.royaltyInfo(tokenId1, salePrice); - - expect(tokenInfo[0]).to.be.equal(ZERO_ADDRESS); - expect(tokenInfo[1]).to.be.bignumber.equal(new BN('0')); - }); - }); - shouldBehaveLikeERC2981(); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721URIStorage.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721URIStorage.test.js deleted file mode 100644 index c476ad09..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721URIStorage.test.js +++ /dev/null @@ -1,96 +0,0 @@ -const { BN, expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC721URIStorageMock = artifacts.require('ERC721URIStorageMock'); - -contract('ERC721URIStorage', function (accounts) { - const [ owner ] = accounts; - - const name = 'Non Fungible Token'; - const symbol = 'NFT'; - - const firstTokenId = new BN('5042'); - const nonExistentTokenId = new BN('13'); - - beforeEach(async function () { - this.token = await ERC721URIStorageMock.new(name, symbol); - }); - - describe('token URI', function () { - beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - }); - - const baseURI = 'https://api.example.com/v1/'; - const sampleUri = 'mock://mytoken'; - - it('it is empty by default', async function () { - expect(await this.token.tokenURI(firstTokenId)).to.be.equal(''); - }); - - it('reverts when queried for non existent token id', async function () { - await expectRevert( - this.token.tokenURI(nonExistentTokenId), 'ERC721URIStorage: URI query for nonexistent token', - ); - }); - - it('can be set for a token id', async function () { - await this.token.setTokenURI(firstTokenId, sampleUri); - expect(await this.token.tokenURI(firstTokenId)).to.be.equal(sampleUri); - }); - - it('reverts when setting for non existent token id', async function () { - await expectRevert( - this.token.setTokenURI(nonExistentTokenId, sampleUri), 'ERC721URIStorage: URI set of nonexistent token', - ); - }); - - it('base URI can be set', async function () { - await this.token.setBaseURI(baseURI); - expect(await this.token.baseURI()).to.equal(baseURI); - }); - - it('base URI is added as a prefix to the token URI', async function () { - await this.token.setBaseURI(baseURI); - await this.token.setTokenURI(firstTokenId, sampleUri); - - expect(await this.token.tokenURI(firstTokenId)).to.be.equal(baseURI + sampleUri); - }); - - it('token URI can be changed by changing the base URI', async function () { - await this.token.setBaseURI(baseURI); - await this.token.setTokenURI(firstTokenId, sampleUri); - - const newBaseURI = 'https://api.example.com/v2/'; - await this.token.setBaseURI(newBaseURI); - expect(await this.token.tokenURI(firstTokenId)).to.be.equal(newBaseURI + sampleUri); - }); - - it('tokenId is appended to base URI for tokens with no URI', async function () { - await this.token.setBaseURI(baseURI); - - expect(await this.token.tokenURI(firstTokenId)).to.be.equal(baseURI + firstTokenId); - }); - - it('tokens without URI can be burnt ', async function () { - await this.token.burn(firstTokenId, { from: owner }); - - expect(await this.token.exists(firstTokenId)).to.equal(false); - await expectRevert( - this.token.tokenURI(firstTokenId), 'ERC721URIStorage: URI query for nonexistent token', - ); - }); - - it('tokens with URI can be burnt ', async function () { - await this.token.setTokenURI(firstTokenId, sampleUri); - - await this.token.burn(firstTokenId, { from: owner }); - - expect(await this.token.exists(firstTokenId)).to.equal(false); - await expectRevert( - this.token.tokenURI(firstTokenId), 'ERC721URIStorage: URI query for nonexistent token', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Votes.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Votes.test.js deleted file mode 100644 index 6f001f20..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/extensions/ERC721Votes.test.js +++ /dev/null @@ -1,174 +0,0 @@ -/* eslint-disable */ - -const { BN, expectEvent, time } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const { promisify } = require('util'); -const queue = promisify(setImmediate); - -const ERC721VotesMock = artifacts.require('ERC721VotesMock'); - -const { shouldBehaveLikeVotes } = require('../../../governance/utils/Votes.behavior'); - -contract('ERC721Votes', function (accounts) { - const [ account1, account2, account1Delegatee, other1, other2 ] = accounts; - this.name = 'My Vote'; - const symbol = 'MTKN'; - - beforeEach(async function () { - this.votes = await ERC721VotesMock.new(name, symbol); - - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.votes.getChainId(); - - this.NFT0 = new BN('10000000000000000000000000'); - this.NFT1 = new BN('10'); - this.NFT2 = new BN('20'); - this.NFT3 = new BN('30'); - }); - - describe('balanceOf', function () { - beforeEach(async function () { - await this.votes.mint(account1, this.NFT0); - await this.votes.mint(account1, this.NFT1); - await this.votes.mint(account1, this.NFT2); - await this.votes.mint(account1, this.NFT3); - }); - - it('grants to initial account', async function () { - expect(await this.votes.balanceOf(account1)).to.be.bignumber.equal('4'); - }); - }); - - describe('transfers', function () { - beforeEach(async function () { - await this.votes.mint(account1, this.NFT0); - }); - - it('no delegation', async function () { - const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); - expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); - expectEvent.notEmitted(receipt, 'DelegateVotesChanged'); - - this.account1Votes = '0'; - this.account2Votes = '0'; - }); - - it('sender delegation', async function () { - await this.votes.delegate(account1, { from: account1 }); - - const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); - expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: account1, previousBalance: '1', newBalance: '0' }); - - const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); - - this.account1Votes = '0'; - this.account2Votes = '0'; - }); - - it('receiver delegation', async function () { - await this.votes.delegate(account2, { from: account2 }); - - const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); - expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: account2, previousBalance: '0', newBalance: '1' }); - - const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); - - this.account1Votes = '0'; - this.account2Votes = '1'; - }); - - it('full delegation', async function () { - await this.votes.delegate(account1, { from: account1 }); - await this.votes.delegate(account2, { from: account2 }); - - const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); - expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: account1, previousBalance: '1', newBalance: '0'}); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: account2, previousBalance: '0', newBalance: '1' }); - - const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); - - this.account1Votes = '0'; - this.account2Votes = '1'; - }); - - it('returns the same total supply on transfers', async function () { - await this.votes.delegate(account1, { from: account1 }); - - const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); - - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.votes.getPastTotalSupply(receipt.blockNumber - 1)).to.be.bignumber.equal('1'); - expect(await this.votes.getPastTotalSupply(receipt.blockNumber + 1)).to.be.bignumber.equal('1'); - - this.account1Votes = '0'; - this.account2Votes = '0'; - }); - - it('generally returns the voting balance at the appropriate checkpoint', async function () { - await this.votes.mint(account1, this.NFT1); - await this.votes.mint(account1, this.NFT2); - await this.votes.mint(account1, this.NFT3); - - const total = await this.votes.balanceOf(account1); - - const t1 = await this.votes.delegate(other1, { from: account1 }); - await time.advanceBlock(); - await time.advanceBlock(); - const t2 = await this.votes.transferFrom(account1, other2, this.NFT0, { from: account1 }); - await time.advanceBlock(); - await time.advanceBlock(); - const t3 = await this.votes.transferFrom(account1, other2, this.NFT2, { from: account1 }); - await time.advanceBlock(); - await time.advanceBlock(); - const t4 = await this.votes.transferFrom(other2, account1, this.NFT2, { from: other2 }); - await time.advanceBlock(); - await time.advanceBlock(); - - expect(await this.votes.getPastVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.votes.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal(total); - expect(await this.votes.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal(total); - expect(await this.votes.getPastVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('3'); - expect(await this.votes.getPastVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('3'); - expect(await this.votes.getPastVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('2'); - expect(await this.votes.getPastVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('2'); - expect(await this.votes.getPastVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('3'); - expect(await this.votes.getPastVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('3'); - - this.account1Votes = '0'; - this.account2Votes = '0'; - }); - - afterEach(async function () { - expect(await this.votes.getVotes(account1)).to.be.bignumber.equal(this.account1Votes); - expect(await this.votes.getVotes(account2)).to.be.bignumber.equal(this.account2Votes); - - // need to advance 2 blocks to see the effect of a transfer on "getPastVotes" - const blockNumber = await time.latestBlock(); - await time.advanceBlock(); - expect(await this.votes.getPastVotes(account1, blockNumber)).to.be.bignumber.equal(this.account1Votes); - expect(await this.votes.getPastVotes(account2, blockNumber)).to.be.bignumber.equal(this.account2Votes); - }); - }); - - describe('Voting workflow', function () { - beforeEach(async function () { - this.account1 = account1; - this.account1Delegatee = account1Delegatee; - this.account2 = account2; - this.name = 'My Vote'; - }); - - shouldBehaveLikeVotes(); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/presets/ERC721PresetMinterPauserAutoId.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/presets/ERC721PresetMinterPauserAutoId.test.js deleted file mode 100644 index 4ad73552..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/presets/ERC721PresetMinterPauserAutoId.test.js +++ /dev/null @@ -1,125 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; -const { shouldSupportInterfaces } = require('../../../utils/introspection/SupportsInterface.behavior'); - -const { expect } = require('chai'); - -const ERC721PresetMinterPauserAutoId = artifacts.require('ERC721PresetMinterPauserAutoId'); - -contract('ERC721PresetMinterPauserAutoId', function (accounts) { - const [ deployer, other ] = accounts; - - const name = 'MinterAutoIDToken'; - const symbol = 'MAIT'; - const baseURI = 'my.app/'; - - const DEFAULT_ADMIN_ROLE = '0x0000000000000000000000000000000000000000000000000000000000000000'; - const MINTER_ROLE = web3.utils.soliditySha3('MINTER_ROLE'); - - beforeEach(async function () { - this.token = await ERC721PresetMinterPauserAutoId.new(name, symbol, baseURI, { from: deployer }); - }); - - shouldSupportInterfaces(['ERC721', 'ERC721Enumerable', 'AccessControl', 'AccessControlEnumerable']); - - it('token has correct name', async function () { - expect(await this.token.name()).to.equal(name); - }); - - it('token has correct symbol', async function () { - expect(await this.token.symbol()).to.equal(symbol); - }); - - it('deployer has the default admin role', async function () { - expect(await this.token.getRoleMemberCount(DEFAULT_ADMIN_ROLE)).to.be.bignumber.equal('1'); - expect(await this.token.getRoleMember(DEFAULT_ADMIN_ROLE, 0)).to.equal(deployer); - }); - - it('deployer has the minter role', async function () { - expect(await this.token.getRoleMemberCount(MINTER_ROLE)).to.be.bignumber.equal('1'); - expect(await this.token.getRoleMember(MINTER_ROLE, 0)).to.equal(deployer); - }); - - it('minter role admin is the default admin', async function () { - expect(await this.token.getRoleAdmin(MINTER_ROLE)).to.equal(DEFAULT_ADMIN_ROLE); - }); - - describe('minting', function () { - it('deployer can mint tokens', async function () { - const tokenId = new BN('0'); - - const receipt = await this.token.mint(other, { from: deployer }); - expectEvent(receipt, 'Transfer', { from: ZERO_ADDRESS, to: other, tokenId }); - - expect(await this.token.balanceOf(other)).to.be.bignumber.equal('1'); - expect(await this.token.ownerOf(tokenId)).to.equal(other); - - expect(await this.token.tokenURI(tokenId)).to.equal(baseURI + tokenId); - }); - - it('other accounts cannot mint tokens', async function () { - await expectRevert( - this.token.mint(other, { from: other }), - 'ERC721PresetMinterPauserAutoId: must have minter role to mint', - ); - }); - }); - - describe('pausing', function () { - it('deployer can pause', async function () { - const receipt = await this.token.pause({ from: deployer }); - expectEvent(receipt, 'Paused', { account: deployer }); - - expect(await this.token.paused()).to.equal(true); - }); - - it('deployer can unpause', async function () { - await this.token.pause({ from: deployer }); - - const receipt = await this.token.unpause({ from: deployer }); - expectEvent(receipt, 'Unpaused', { account: deployer }); - - expect(await this.token.paused()).to.equal(false); - }); - - it('cannot mint while paused', async function () { - await this.token.pause({ from: deployer }); - - await expectRevert( - this.token.mint(other, { from: deployer }), - 'ERC721Pausable: token transfer while paused', - ); - }); - - it('other accounts cannot pause', async function () { - await expectRevert( - this.token.pause({ from: other }), - 'ERC721PresetMinterPauserAutoId: must have pauser role to pause', - ); - }); - - it('other accounts cannot unpause', async function () { - await this.token.pause({ from: deployer }); - - await expectRevert( - this.token.unpause({ from: other }), - 'ERC721PresetMinterPauserAutoId: must have pauser role to unpause', - ); - }); - }); - - describe('burning', function () { - it('holders can burn their tokens', async function () { - const tokenId = new BN('0'); - - await this.token.mint(other, { from: deployer }); - - const receipt = await this.token.burn(tokenId, { from: other }); - - expectEvent(receipt, 'Transfer', { from: other, to: ZERO_ADDRESS, tokenId }); - - expect(await this.token.balanceOf(other)).to.be.bignumber.equal('0'); - expect(await this.token.totalSupply()).to.be.bignumber.equal('0'); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/utils/ERC721Holder.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/utils/ERC721Holder.test.js deleted file mode 100644 index 2431e667..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC721/utils/ERC721Holder.test.js +++ /dev/null @@ -1,24 +0,0 @@ -const { BN } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC721Holder = artifacts.require('ERC721Holder'); -const ERC721Mock = artifacts.require('ERC721Mock'); - -contract('ERC721Holder', function (accounts) { - const [ owner ] = accounts; - - const name = 'Non Fungible Token'; - const symbol = 'NFT'; - - it('receives an ERC721 token', async function () { - const token = await ERC721Mock.new(name, symbol); - const tokenId = new BN(1); - await token.mint(owner, tokenId); - - const receiver = await ERC721Holder.new(); - await token.safeTransferFrom(owner, receiver.address, tokenId, { from: owner }); - - expect(await token.ownerOf(tokenId)).to.be.equal(receiver.address); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/ERC777.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/ERC777.behavior.js deleted file mode 100644 index 9c96d0e6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/ERC777.behavior.js +++ /dev/null @@ -1,555 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const ERC777SenderRecipientMock = artifacts.require('ERC777SenderRecipientMock'); - -function shouldBehaveLikeERC777DirectSendBurn (holder, recipient, data) { - shouldBehaveLikeERC777DirectSend(holder, recipient, data); - shouldBehaveLikeERC777DirectBurn(holder, data); -} - -function shouldBehaveLikeERC777OperatorSendBurn (holder, recipient, operator, data, operatorData) { - shouldBehaveLikeERC777OperatorSend(holder, recipient, operator, data, operatorData); - shouldBehaveLikeERC777OperatorBurn(holder, operator, data, operatorData); -} - -function shouldBehaveLikeERC777UnauthorizedOperatorSendBurn (holder, recipient, operator, data, operatorData) { - shouldBehaveLikeERC777UnauthorizedOperatorSend(holder, recipient, operator, data, operatorData); - shouldBehaveLikeERC777UnauthorizedOperatorBurn(holder, operator, data, operatorData); -} - -function shouldBehaveLikeERC777DirectSend (holder, recipient, data) { - describe('direct send', function () { - context('when the sender has tokens', function () { - shouldDirectSendTokens(holder, recipient, new BN('0'), data); - shouldDirectSendTokens(holder, recipient, new BN('1'), data); - - it('reverts when sending more than the balance', async function () { - const balance = await this.token.balanceOf(holder); - await expectRevert.unspecified(this.token.send(recipient, balance.addn(1), data, { from: holder })); - }); - - it('reverts when sending to the zero address', async function () { - await expectRevert.unspecified(this.token.send(ZERO_ADDRESS, new BN('1'), data, { from: holder })); - }); - }); - - context('when the sender has no tokens', function () { - removeBalance(holder); - - shouldDirectSendTokens(holder, recipient, new BN('0'), data); - - it('reverts when sending a non-zero amount', async function () { - await expectRevert.unspecified(this.token.send(recipient, new BN('1'), data, { from: holder })); - }); - }); - }); -} - -function shouldBehaveLikeERC777OperatorSend (holder, recipient, operator, data, operatorData) { - describe('operator send', function () { - context('when the sender has tokens', async function () { - shouldOperatorSendTokens(holder, operator, recipient, new BN('0'), data, operatorData); - shouldOperatorSendTokens(holder, operator, recipient, new BN('1'), data, operatorData); - - it('reverts when sending more than the balance', async function () { - const balance = await this.token.balanceOf(holder); - await expectRevert.unspecified( - this.token.operatorSend(holder, recipient, balance.addn(1), data, operatorData, { from: operator }), - ); - }); - - it('reverts when sending to the zero address', async function () { - await expectRevert.unspecified( - this.token.operatorSend( - holder, ZERO_ADDRESS, new BN('1'), data, operatorData, { from: operator }, - ), - ); - }); - }); - - context('when the sender has no tokens', function () { - removeBalance(holder); - - shouldOperatorSendTokens(holder, operator, recipient, new BN('0'), data, operatorData); - - it('reverts when sending a non-zero amount', async function () { - await expectRevert.unspecified( - this.token.operatorSend(holder, recipient, new BN('1'), data, operatorData, { from: operator }), - ); - }); - - it('reverts when sending from the zero address', async function () { - // This is not yet reflected in the spec - await expectRevert.unspecified( - this.token.operatorSend( - ZERO_ADDRESS, recipient, new BN('0'), data, operatorData, { from: operator }, - ), - ); - }); - }); - }); -} - -function shouldBehaveLikeERC777UnauthorizedOperatorSend (holder, recipient, operator, data, operatorData) { - describe('operator send', function () { - it('reverts', async function () { - await expectRevert.unspecified(this.token.operatorSend(holder, recipient, new BN('0'), data, operatorData)); - }); - }); -} - -function shouldBehaveLikeERC777DirectBurn (holder, data) { - describe('direct burn', function () { - context('when the sender has tokens', function () { - shouldDirectBurnTokens(holder, new BN('0'), data); - shouldDirectBurnTokens(holder, new BN('1'), data); - - it('reverts when burning more than the balance', async function () { - const balance = await this.token.balanceOf(holder); - await expectRevert.unspecified(this.token.burn(balance.addn(1), data, { from: holder })); - }); - }); - - context('when the sender has no tokens', function () { - removeBalance(holder); - - shouldDirectBurnTokens(holder, new BN('0'), data); - - it('reverts when burning a non-zero amount', async function () { - await expectRevert.unspecified(this.token.burn(new BN('1'), data, { from: holder })); - }); - }); - }); -} - -function shouldBehaveLikeERC777OperatorBurn (holder, operator, data, operatorData) { - describe('operator burn', function () { - context('when the sender has tokens', async function () { - shouldOperatorBurnTokens(holder, operator, new BN('0'), data, operatorData); - shouldOperatorBurnTokens(holder, operator, new BN('1'), data, operatorData); - - it('reverts when burning more than the balance', async function () { - const balance = await this.token.balanceOf(holder); - await expectRevert.unspecified( - this.token.operatorBurn(holder, balance.addn(1), data, operatorData, { from: operator }), - ); - }); - }); - - context('when the sender has no tokens', function () { - removeBalance(holder); - - shouldOperatorBurnTokens(holder, operator, new BN('0'), data, operatorData); - - it('reverts when burning a non-zero amount', async function () { - await expectRevert.unspecified( - this.token.operatorBurn(holder, new BN('1'), data, operatorData, { from: operator }), - ); - }); - - it('reverts when burning from the zero address', async function () { - // This is not yet reflected in the spec - await expectRevert.unspecified( - this.token.operatorBurn( - ZERO_ADDRESS, new BN('0'), data, operatorData, { from: operator }, - ), - ); - }); - }); - }); -} - -function shouldBehaveLikeERC777UnauthorizedOperatorBurn (holder, operator, data, operatorData) { - describe('operator burn', function () { - it('reverts', async function () { - await expectRevert.unspecified(this.token.operatorBurn(holder, new BN('0'), data, operatorData)); - }); - }); -} - -function shouldDirectSendTokens (from, to, amount, data) { - shouldSendTokens(from, null, to, amount, data, null); -} - -function shouldOperatorSendTokens (from, operator, to, amount, data, operatorData) { - shouldSendTokens(from, operator, to, amount, data, operatorData); -} - -function shouldSendTokens (from, operator, to, amount, data, operatorData) { - const operatorCall = operator !== null; - - it(`${operatorCall ? 'operator ' : ''}can send an amount of ${amount}`, async function () { - const initialTotalSupply = await this.token.totalSupply(); - const initialFromBalance = await this.token.balanceOf(from); - const initialToBalance = await this.token.balanceOf(to); - - let logs; - if (!operatorCall) { - ({ logs } = await this.token.send(to, amount, data, { from })); - expectEvent.inLogs(logs, 'Sent', { - operator: from, - from, - to, - amount, - data, - operatorData: null, - }); - } else { - ({ logs } = await this.token.operatorSend(from, to, amount, data, operatorData, { from: operator })); - expectEvent.inLogs(logs, 'Sent', { - operator, - from, - to, - amount, - data, - operatorData, - }); - } - - expectEvent.inLogs(logs, 'Transfer', { - from, - to, - value: amount, - }); - - const finalTotalSupply = await this.token.totalSupply(); - const finalFromBalance = await this.token.balanceOf(from); - const finalToBalance = await this.token.balanceOf(to); - - expect(finalTotalSupply).to.be.bignumber.equal(initialTotalSupply); - expect(finalToBalance.sub(initialToBalance)).to.be.bignumber.equal(amount); - expect(finalFromBalance.sub(initialFromBalance)).to.be.bignumber.equal(amount.neg()); - }); -} - -function shouldDirectBurnTokens (from, amount, data) { - shouldBurnTokens(from, null, amount, data, null); -} - -function shouldOperatorBurnTokens (from, operator, amount, data, operatorData) { - shouldBurnTokens(from, operator, amount, data, operatorData); -} - -function shouldBurnTokens (from, operator, amount, data, operatorData) { - const operatorCall = operator !== null; - - it(`${operatorCall ? 'operator ' : ''}can burn an amount of ${amount}`, async function () { - const initialTotalSupply = await this.token.totalSupply(); - const initialFromBalance = await this.token.balanceOf(from); - - let logs; - if (!operatorCall) { - ({ logs } = await this.token.burn(amount, data, { from })); - expectEvent.inLogs(logs, 'Burned', { - operator: from, - from, - amount, - data, - operatorData: null, - }); - } else { - ({ logs } = await this.token.operatorBurn(from, amount, data, operatorData, { from: operator })); - expectEvent.inLogs(logs, 'Burned', { - operator, - from, - amount, - data, - operatorData, - }); - } - - expectEvent.inLogs(logs, 'Transfer', { - from, - to: ZERO_ADDRESS, - value: amount, - }); - - const finalTotalSupply = await this.token.totalSupply(); - const finalFromBalance = await this.token.balanceOf(from); - - expect(finalTotalSupply.sub(initialTotalSupply)).to.be.bignumber.equal(amount.neg()); - expect(finalFromBalance.sub(initialFromBalance)).to.be.bignumber.equal(amount.neg()); - }); -} - -function shouldBehaveLikeERC777InternalMint (recipient, operator, amount, data, operatorData) { - shouldInternalMintTokens(operator, recipient, new BN('0'), data, operatorData); - shouldInternalMintTokens(operator, recipient, amount, data, operatorData); - - it('reverts when minting tokens for the zero address', async function () { - await expectRevert.unspecified( - this.token.mintInternal(ZERO_ADDRESS, amount, data, operatorData, { from: operator }), - ); - }); -} - -function shouldInternalMintTokens (operator, to, amount, data, operatorData) { - it(`can (internal) mint an amount of ${amount}`, async function () { - const initialTotalSupply = await this.token.totalSupply(); - const initialToBalance = await this.token.balanceOf(to); - - const { logs } = await this.token.mintInternal(to, amount, data, operatorData, { from: operator }); - - expectEvent.inLogs(logs, 'Minted', { - operator, - to, - amount, - data, - operatorData, - }); - - expectEvent.inLogs(logs, 'Transfer', { - from: ZERO_ADDRESS, - to, - value: amount, - }); - - const finalTotalSupply = await this.token.totalSupply(); - const finalToBalance = await this.token.balanceOf(to); - - expect(finalTotalSupply.sub(initialTotalSupply)).to.be.bignumber.equal(amount); - expect(finalToBalance.sub(initialToBalance)).to.be.bignumber.equal(amount); - }); -} - -function shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook (operator, amount, data, operatorData) { - context('when TokensRecipient reverts', function () { - beforeEach(async function () { - await this.tokensRecipientImplementer.setShouldRevertReceive(true); - }); - - it('send reverts', async function () { - await expectRevert.unspecified(sendFromHolder(this.token, this.sender, this.recipient, amount, data)); - }); - - it('operatorSend reverts', async function () { - await expectRevert.unspecified( - this.token.operatorSend(this.sender, this.recipient, amount, data, operatorData, { from: operator }), - ); - }); - - it('mint (internal) reverts', async function () { - await expectRevert.unspecified( - this.token.mintInternal(this.recipient, amount, data, operatorData, { from: operator }), - ); - }); - }); - - context('when TokensRecipient does not revert', function () { - beforeEach(async function () { - await this.tokensRecipientImplementer.setShouldRevertSend(false); - }); - - it('TokensRecipient receives send data and is called after state mutation', async function () { - const { tx } = await sendFromHolder(this.token, this.sender, this.recipient, amount, data); - - const postSenderBalance = await this.token.balanceOf(this.sender); - const postRecipientBalance = await this.token.balanceOf(this.recipient); - - await assertTokensReceivedCalled( - this.token, - tx, - this.sender, - this.sender, - this.recipient, - amount, - data, - null, - postSenderBalance, - postRecipientBalance, - ); - }); - - it('TokensRecipient receives operatorSend data and is called after state mutation', async function () { - const { tx } = await this.token.operatorSend( - this.sender, this.recipient, amount, data, operatorData, - { from: operator }, - ); - - const postSenderBalance = await this.token.balanceOf(this.sender); - const postRecipientBalance = await this.token.balanceOf(this.recipient); - - await assertTokensReceivedCalled( - this.token, - tx, - operator, - this.sender, - this.recipient, - amount, - data, - operatorData, - postSenderBalance, - postRecipientBalance, - ); - }); - - it('TokensRecipient receives mint (internal) data and is called after state mutation', async function () { - const { tx } = await this.token.mintInternal( - this.recipient, amount, data, operatorData, { from: operator }, - ); - - const postRecipientBalance = await this.token.balanceOf(this.recipient); - - await assertTokensReceivedCalled( - this.token, - tx, - operator, - ZERO_ADDRESS, - this.recipient, - amount, - data, - operatorData, - new BN('0'), - postRecipientBalance, - ); - }); - }); -} - -function shouldBehaveLikeERC777SendBurnWithSendHook (operator, amount, data, operatorData) { - context('when TokensSender reverts', function () { - beforeEach(async function () { - await this.tokensSenderImplementer.setShouldRevertSend(true); - }); - - it('send reverts', async function () { - await expectRevert.unspecified(sendFromHolder(this.token, this.sender, this.recipient, amount, data)); - }); - - it('operatorSend reverts', async function () { - await expectRevert.unspecified( - this.token.operatorSend(this.sender, this.recipient, amount, data, operatorData, { from: operator }), - ); - }); - - it('burn reverts', async function () { - await expectRevert.unspecified(burnFromHolder(this.token, this.sender, amount, data)); - }); - - it('operatorBurn reverts', async function () { - await expectRevert.unspecified( - this.token.operatorBurn(this.sender, amount, data, operatorData, { from: operator }), - ); - }); - }); - - context('when TokensSender does not revert', function () { - beforeEach(async function () { - await this.tokensSenderImplementer.setShouldRevertSend(false); - }); - - it('TokensSender receives send data and is called before state mutation', async function () { - const preSenderBalance = await this.token.balanceOf(this.sender); - const preRecipientBalance = await this.token.balanceOf(this.recipient); - - const { tx } = await sendFromHolder(this.token, this.sender, this.recipient, amount, data); - - await assertTokensToSendCalled( - this.token, - tx, - this.sender, - this.sender, - this.recipient, - amount, - data, - null, - preSenderBalance, - preRecipientBalance, - ); - }); - - it('TokensSender receives operatorSend data and is called before state mutation', async function () { - const preSenderBalance = await this.token.balanceOf(this.sender); - const preRecipientBalance = await this.token.balanceOf(this.recipient); - - const { tx } = await this.token.operatorSend( - this.sender, this.recipient, amount, data, operatorData, - { from: operator }, - ); - - await assertTokensToSendCalled( - this.token, - tx, - operator, - this.sender, - this.recipient, - amount, - data, - operatorData, - preSenderBalance, - preRecipientBalance, - ); - }); - - it('TokensSender receives burn data and is called before state mutation', async function () { - const preSenderBalance = await this.token.balanceOf(this.sender); - - const { tx } = await burnFromHolder(this.token, this.sender, amount, data, { from: this.sender }); - - await assertTokensToSendCalled( - this.token, tx, this.sender, this.sender, ZERO_ADDRESS, amount, data, null, preSenderBalance, - ); - }); - - it('TokensSender receives operatorBurn data and is called before state mutation', async function () { - const preSenderBalance = await this.token.balanceOf(this.sender); - - const { tx } = await this.token.operatorBurn(this.sender, amount, data, operatorData, { from: operator }); - - await assertTokensToSendCalled( - this.token, tx, operator, this.sender, ZERO_ADDRESS, amount, data, operatorData, preSenderBalance, - ); - }); - }); -} - -function removeBalance (holder) { - beforeEach(async function () { - await this.token.burn(await this.token.balanceOf(holder), '0x', { from: holder }); - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal('0'); - }); -} - -async function assertTokensReceivedCalled (token, txHash, operator, from, to, amount, data, operatorData, fromBalance, - toBalance = '0') { - await expectEvent.inTransaction(txHash, ERC777SenderRecipientMock, 'TokensReceivedCalled', { - operator, from, to, amount, data, operatorData, token: token.address, fromBalance, toBalance, - }); -} - -async function assertTokensToSendCalled (token, txHash, operator, from, to, amount, data, operatorData, fromBalance, - toBalance = '0') { - await expectEvent.inTransaction(txHash, ERC777SenderRecipientMock, 'TokensToSendCalled', { - operator, from, to, amount, data, operatorData, token: token.address, fromBalance, toBalance, - }); -} - -async function sendFromHolder (token, holder, to, amount, data) { - if ((await web3.eth.getCode(holder)).length <= '0x'.length) { - return token.send(to, amount, data, { from: holder }); - } else { - // assume holder is ERC777SenderRecipientMock contract - return (await ERC777SenderRecipientMock.at(holder)).send(token.address, to, amount, data); - } -} - -async function burnFromHolder (token, holder, amount, data) { - if ((await web3.eth.getCode(holder)).length <= '0x'.length) { - return token.burn(amount, data, { from: holder }); - } else { - // assume holder is ERC777SenderRecipientMock contract - return (await ERC777SenderRecipientMock.at(holder)).burn(token.address, amount, data); - } -} - -module.exports = { - shouldBehaveLikeERC777DirectSendBurn, - shouldBehaveLikeERC777OperatorSendBurn, - shouldBehaveLikeERC777UnauthorizedOperatorSendBurn, - shouldBehaveLikeERC777InternalMint, - shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook, - shouldBehaveLikeERC777SendBurnWithSendHook, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/ERC777.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/ERC777.test.js deleted file mode 100644 index 40b840c7..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/ERC777.test.js +++ /dev/null @@ -1,610 +0,0 @@ -const { BN, constants, expectEvent, expectRevert, singletons } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const { - shouldBehaveLikeERC777DirectSendBurn, - shouldBehaveLikeERC777OperatorSendBurn, - shouldBehaveLikeERC777UnauthorizedOperatorSendBurn, - shouldBehaveLikeERC777InternalMint, - shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook, - shouldBehaveLikeERC777SendBurnWithSendHook, -} = require('./ERC777.behavior'); - -const { - shouldBehaveLikeERC20, - shouldBehaveLikeERC20Approve, -} = require('../ERC20/ERC20.behavior'); - -const ERC777 = artifacts.require('ERC777Mock'); -const ERC777SenderRecipientMock = artifacts.require('ERC777SenderRecipientMock'); - -contract('ERC777', function (accounts) { - const [ registryFunder, holder, defaultOperatorA, defaultOperatorB, newOperator, anyone ] = accounts; - - const initialSupply = new BN('10000'); - const name = 'ERC777Test'; - const symbol = '777T'; - const data = web3.utils.sha3('OZ777TestData'); - const operatorData = web3.utils.sha3('OZ777TestOperatorData'); - - const defaultOperators = [defaultOperatorA, defaultOperatorB]; - - beforeEach(async function () { - this.erc1820 = await singletons.ERC1820Registry(registryFunder); - }); - - context('with default operators', function () { - beforeEach(async function () { - this.token = await ERC777.new(holder, initialSupply, name, symbol, defaultOperators); - }); - - describe('as an ERC20 token', function () { - shouldBehaveLikeERC20('ERC777', initialSupply, holder, anyone, defaultOperatorA); - - describe('_approve', function () { - shouldBehaveLikeERC20Approve('ERC777', holder, anyone, initialSupply, function (owner, spender, amount) { - return this.token.approveInternal(owner, spender, amount); - }); - - describe('when the owner is the zero address', function () { - it('reverts', async function () { - await expectRevert(this.token.approveInternal(ZERO_ADDRESS, anyone, initialSupply), - 'ERC777: approve from the zero address', - ); - }); - }); - }); - }); - - it('does not emit AuthorizedOperator events for default operators', async function () { - await expectEvent.notEmitted.inConstruction(this.token, 'AuthorizedOperator'); - }); - - describe('basic information', function () { - it('returns the name', async function () { - expect(await this.token.name()).to.equal(name); - }); - - it('returns the symbol', async function () { - expect(await this.token.symbol()).to.equal(symbol); - }); - - it('returns a granularity of 1', async function () { - expect(await this.token.granularity()).to.be.bignumber.equal('1'); - }); - - it('returns the default operators', async function () { - expect(await this.token.defaultOperators()).to.deep.equal(defaultOperators); - }); - - it('default operators are operators for all accounts', async function () { - for (const operator of defaultOperators) { - expect(await this.token.isOperatorFor(operator, anyone)).to.equal(true); - } - }); - - it('returns the total supply', async function () { - expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply); - }); - - it('returns 18 when decimals is called', async function () { - expect(await this.token.decimals()).to.be.bignumber.equal('18'); - }); - - it('the ERC777Token interface is registered in the registry', async function () { - expect(await this.erc1820.getInterfaceImplementer(this.token.address, web3.utils.soliditySha3('ERC777Token'))) - .to.equal(this.token.address); - }); - - it('the ERC20Token interface is registered in the registry', async function () { - expect(await this.erc1820.getInterfaceImplementer(this.token.address, web3.utils.soliditySha3('ERC20Token'))) - .to.equal(this.token.address); - }); - }); - - describe('balanceOf', function () { - context('for an account with no tokens', function () { - it('returns zero', async function () { - expect(await this.token.balanceOf(anyone)).to.be.bignumber.equal('0'); - }); - }); - - context('for an account with tokens', function () { - it('returns their balance', async function () { - expect(await this.token.balanceOf(holder)).to.be.bignumber.equal(initialSupply); - }); - }); - }); - - context('with no ERC777TokensSender and no ERC777TokensRecipient implementers', function () { - describe('send/burn', function () { - shouldBehaveLikeERC777DirectSendBurn(holder, anyone, data); - - context('with self operator', function () { - shouldBehaveLikeERC777OperatorSendBurn(holder, anyone, holder, data, operatorData); - }); - - context('with first default operator', function () { - shouldBehaveLikeERC777OperatorSendBurn(holder, anyone, defaultOperatorA, data, operatorData); - }); - - context('with second default operator', function () { - shouldBehaveLikeERC777OperatorSendBurn(holder, anyone, defaultOperatorB, data, operatorData); - }); - - context('before authorizing a new operator', function () { - shouldBehaveLikeERC777UnauthorizedOperatorSendBurn(holder, anyone, newOperator, data, operatorData); - }); - - context('with new authorized operator', function () { - beforeEach(async function () { - await this.token.authorizeOperator(newOperator, { from: holder }); - }); - - shouldBehaveLikeERC777OperatorSendBurn(holder, anyone, newOperator, data, operatorData); - - context('with revoked operator', function () { - beforeEach(async function () { - await this.token.revokeOperator(newOperator, { from: holder }); - }); - - shouldBehaveLikeERC777UnauthorizedOperatorSendBurn(holder, anyone, newOperator, data, operatorData); - }); - }); - }); - - describe('mint (internal)', function () { - const to = anyone; - const amount = new BN('5'); - - context('with default operator', function () { - const operator = defaultOperatorA; - - shouldBehaveLikeERC777InternalMint(to, operator, amount, data, operatorData); - }); - - context('with non operator', function () { - const operator = newOperator; - - shouldBehaveLikeERC777InternalMint(to, operator, amount, data, operatorData); - }); - }); - - describe('mint (internal extended)', function () { - const amount = new BN('5'); - - context('to anyone', function () { - beforeEach(async function () { - this.recipient = anyone; - }); - - context('with default operator', function () { - const operator = defaultOperatorA; - - it('without requireReceptionAck', async function () { - await this.token.mintInternalExtended( - this.recipient, - amount, - data, - operatorData, - false, - { from: operator }, - ); - }); - - it('with requireReceptionAck', async function () { - await this.token.mintInternalExtended( - this.recipient, - amount, - data, - operatorData, - true, - { from: operator }, - ); - }); - }); - - context('with non operator', function () { - const operator = newOperator; - - it('without requireReceptionAck', async function () { - await this.token.mintInternalExtended( - this.recipient, - amount, - data, - operatorData, - false, - { from: operator }, - ); - }); - - it('with requireReceptionAck', async function () { - await this.token.mintInternalExtended( - this.recipient, - amount, - data, - operatorData, - true, - { from: operator }, - ); - }); - }); - }); - - context('to non ERC777TokensRecipient implementer', function () { - beforeEach(async function () { - this.tokensRecipientImplementer = await ERC777SenderRecipientMock.new(); - this.recipient = this.tokensRecipientImplementer.address; - }); - - context('with default operator', function () { - const operator = defaultOperatorA; - - it('without requireReceptionAck', async function () { - await this.token.mintInternalExtended( - this.recipient, - amount, - data, - operatorData, - false, - { from: operator }, - ); - }); - - it('with requireReceptionAck', async function () { - await expectRevert( - this.token.mintInternalExtended( - this.recipient, - amount, - data, - operatorData, - true, - { from: operator }, - ), - 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient', - ); - }); - }); - - context('with non operator', function () { - const operator = newOperator; - - it('without requireReceptionAck', async function () { - await this.token.mintInternalExtended( - this.recipient, - amount, - data, - operatorData, - false, - { from: operator }, - ); - }); - - it('with requireReceptionAck', async function () { - await expectRevert( - this.token.mintInternalExtended( - this.recipient, - amount, - data, - operatorData, - true, - { from: operator }, - ), - 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient', - ); - }); - }); - }); - }); - }); - - describe('operator management', function () { - it('accounts are their own operator', async function () { - expect(await this.token.isOperatorFor(holder, holder)).to.equal(true); - }); - - it('reverts when self-authorizing', async function () { - await expectRevert( - this.token.authorizeOperator(holder, { from: holder }), 'ERC777: authorizing self as operator', - ); - }); - - it('reverts when self-revoking', async function () { - await expectRevert( - this.token.revokeOperator(holder, { from: holder }), 'ERC777: revoking self as operator', - ); - }); - - it('non-operators can be revoked', async function () { - expect(await this.token.isOperatorFor(newOperator, holder)).to.equal(false); - - const { logs } = await this.token.revokeOperator(newOperator, { from: holder }); - expectEvent.inLogs(logs, 'RevokedOperator', { operator: newOperator, tokenHolder: holder }); - - expect(await this.token.isOperatorFor(newOperator, holder)).to.equal(false); - }); - - it('non-operators can be authorized', async function () { - expect(await this.token.isOperatorFor(newOperator, holder)).to.equal(false); - - const { logs } = await this.token.authorizeOperator(newOperator, { from: holder }); - expectEvent.inLogs(logs, 'AuthorizedOperator', { operator: newOperator, tokenHolder: holder }); - - expect(await this.token.isOperatorFor(newOperator, holder)).to.equal(true); - }); - - describe('new operators', function () { - beforeEach(async function () { - await this.token.authorizeOperator(newOperator, { from: holder }); - }); - - it('are not added to the default operators list', async function () { - expect(await this.token.defaultOperators()).to.deep.equal(defaultOperators); - }); - - it('can be re-authorized', async function () { - const { logs } = await this.token.authorizeOperator(newOperator, { from: holder }); - expectEvent.inLogs(logs, 'AuthorizedOperator', { operator: newOperator, tokenHolder: holder }); - - expect(await this.token.isOperatorFor(newOperator, holder)).to.equal(true); - }); - - it('can be revoked', async function () { - const { logs } = await this.token.revokeOperator(newOperator, { from: holder }); - expectEvent.inLogs(logs, 'RevokedOperator', { operator: newOperator, tokenHolder: holder }); - - expect(await this.token.isOperatorFor(newOperator, holder)).to.equal(false); - }); - }); - - describe('default operators', function () { - it('can be re-authorized', async function () { - const { logs } = await this.token.authorizeOperator(defaultOperatorA, { from: holder }); - expectEvent.inLogs(logs, 'AuthorizedOperator', { operator: defaultOperatorA, tokenHolder: holder }); - - expect(await this.token.isOperatorFor(defaultOperatorA, holder)).to.equal(true); - }); - - it('can be revoked', async function () { - const { logs } = await this.token.revokeOperator(defaultOperatorA, { from: holder }); - expectEvent.inLogs(logs, 'RevokedOperator', { operator: defaultOperatorA, tokenHolder: holder }); - - expect(await this.token.isOperatorFor(defaultOperatorA, holder)).to.equal(false); - }); - - it('cannot be revoked for themselves', async function () { - await expectRevert( - this.token.revokeOperator(defaultOperatorA, { from: defaultOperatorA }), - 'ERC777: revoking self as operator', - ); - }); - - context('with revoked default operator', function () { - beforeEach(async function () { - await this.token.revokeOperator(defaultOperatorA, { from: holder }); - }); - - it('default operator is not revoked for other holders', async function () { - expect(await this.token.isOperatorFor(defaultOperatorA, anyone)).to.equal(true); - }); - - it('other default operators are not revoked', async function () { - expect(await this.token.isOperatorFor(defaultOperatorB, holder)).to.equal(true); - }); - - it('default operators list is not modified', async function () { - expect(await this.token.defaultOperators()).to.deep.equal(defaultOperators); - }); - - it('revoked default operator can be re-authorized', async function () { - const { logs } = await this.token.authorizeOperator(defaultOperatorA, { from: holder }); - expectEvent.inLogs(logs, 'AuthorizedOperator', { operator: defaultOperatorA, tokenHolder: holder }); - - expect(await this.token.isOperatorFor(defaultOperatorA, holder)).to.equal(true); - }); - }); - }); - }); - - describe('send and receive hooks', function () { - const amount = new BN('1'); - const operator = defaultOperatorA; - // sender and recipient are stored inside 'this', since in some tests their addresses are determined dynamically - - describe('tokensReceived', function () { - beforeEach(function () { - this.sender = holder; - }); - - context('with no ERC777TokensRecipient implementer', function () { - context('with contract recipient', function () { - beforeEach(async function () { - this.tokensRecipientImplementer = await ERC777SenderRecipientMock.new(); - this.recipient = this.tokensRecipientImplementer.address; - - // Note that tokensRecipientImplementer doesn't implement the recipient interface for the recipient - }); - - it('send reverts', async function () { - await expectRevert( - this.token.send(this.recipient, amount, data, { from: holder }), - 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient', - ); - }); - - it('operatorSend reverts', async function () { - await expectRevert( - this.token.operatorSend(this.sender, this.recipient, amount, data, operatorData, { from: operator }), - 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient', - ); - }); - - it('mint (internal) reverts', async function () { - await expectRevert( - this.token.mintInternal(this.recipient, amount, data, operatorData, { from: operator }), - 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient', - ); - }); - - it('(ERC20) transfer succeeds', async function () { - await this.token.transfer(this.recipient, amount, { from: holder }); - }); - - it('(ERC20) transferFrom succeeds', async function () { - const approved = anyone; - await this.token.approve(approved, amount, { from: this.sender }); - await this.token.transferFrom(this.sender, this.recipient, amount, { from: approved }); - }); - }); - }); - - context('with ERC777TokensRecipient implementer', function () { - context('with contract as implementer for an externally owned account', function () { - beforeEach(async function () { - this.tokensRecipientImplementer = await ERC777SenderRecipientMock.new(); - this.recipient = anyone; - - await this.tokensRecipientImplementer.recipientFor(this.recipient); - - await this.erc1820.setInterfaceImplementer( - this.recipient, - web3.utils.soliditySha3('ERC777TokensRecipient'), this.tokensRecipientImplementer.address, - { from: this.recipient }, - ); - }); - - shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook(operator, amount, data, operatorData); - }); - - context('with contract as implementer for another contract', function () { - beforeEach(async function () { - this.recipientContract = await ERC777SenderRecipientMock.new(); - this.recipient = this.recipientContract.address; - - this.tokensRecipientImplementer = await ERC777SenderRecipientMock.new(); - await this.tokensRecipientImplementer.recipientFor(this.recipient); - await this.recipientContract.registerRecipient(this.tokensRecipientImplementer.address); - }); - - shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook(operator, amount, data, operatorData); - }); - - context('with contract as implementer for itself', function () { - beforeEach(async function () { - this.tokensRecipientImplementer = await ERC777SenderRecipientMock.new(); - this.recipient = this.tokensRecipientImplementer.address; - - await this.tokensRecipientImplementer.recipientFor(this.recipient); - }); - - shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook(operator, amount, data, operatorData); - }); - }); - }); - - describe('tokensToSend', function () { - beforeEach(function () { - this.recipient = anyone; - }); - - context('with a contract as implementer for an externally owned account', function () { - beforeEach(async function () { - this.tokensSenderImplementer = await ERC777SenderRecipientMock.new(); - this.sender = holder; - - await this.tokensSenderImplementer.senderFor(this.sender); - - await this.erc1820.setInterfaceImplementer( - this.sender, - web3.utils.soliditySha3('ERC777TokensSender'), this.tokensSenderImplementer.address, - { from: this.sender }, - ); - }); - - shouldBehaveLikeERC777SendBurnWithSendHook(operator, amount, data, operatorData); - }); - - context('with contract as implementer for another contract', function () { - beforeEach(async function () { - this.senderContract = await ERC777SenderRecipientMock.new(); - this.sender = this.senderContract.address; - - this.tokensSenderImplementer = await ERC777SenderRecipientMock.new(); - await this.tokensSenderImplementer.senderFor(this.sender); - await this.senderContract.registerSender(this.tokensSenderImplementer.address); - - // For the contract to be able to receive tokens (that it can later send), it must also implement the - // recipient interface. - - await this.senderContract.recipientFor(this.sender); - await this.token.send(this.sender, amount, data, { from: holder }); - }); - - shouldBehaveLikeERC777SendBurnWithSendHook(operator, amount, data, operatorData); - }); - - context('with a contract as implementer for itself', function () { - beforeEach(async function () { - this.tokensSenderImplementer = await ERC777SenderRecipientMock.new(); - this.sender = this.tokensSenderImplementer.address; - - await this.tokensSenderImplementer.senderFor(this.sender); - - // For the contract to be able to receive tokens (that it can later send), it must also implement the - // recipient interface. - - await this.tokensSenderImplementer.recipientFor(this.sender); - await this.token.send(this.sender, amount, data, { from: holder }); - }); - - shouldBehaveLikeERC777SendBurnWithSendHook(operator, amount, data, operatorData); - }); - }); - }); - }); - - context('with no default operators', function () { - beforeEach(async function () { - this.token = await ERC777.new(holder, initialSupply, name, symbol, []); - }); - - it('default operators list is empty', async function () { - expect(await this.token.defaultOperators()).to.deep.equal([]); - }); - }); - - describe('relative order of hooks', function () { - beforeEach(async function () { - await singletons.ERC1820Registry(registryFunder); - this.sender = await ERC777SenderRecipientMock.new(); - await this.sender.registerRecipient(this.sender.address); - await this.sender.registerSender(this.sender.address); - this.token = await ERC777.new(holder, initialSupply, name, symbol, []); - await this.token.send(this.sender.address, 1, '0x', { from: holder }); - }); - - it('send', async function () { - const { receipt } = await this.sender.send(this.token.address, anyone, 1, '0x'); - - const internalBeforeHook = receipt.logs.findIndex(l => l.event === 'BeforeTokenTransfer'); - expect(internalBeforeHook).to.be.gte(0); - const externalSendHook = receipt.logs.findIndex(l => l.event === 'TokensToSendCalled'); - expect(externalSendHook).to.be.gte(0); - - expect(externalSendHook).to.be.lt(internalBeforeHook); - }); - - it('burn', async function () { - const { receipt } = await this.sender.burn(this.token.address, 1, '0x'); - - const internalBeforeHook = receipt.logs.findIndex(l => l.event === 'BeforeTokenTransfer'); - expect(internalBeforeHook).to.be.gte(0); - const externalSendHook = receipt.logs.findIndex(l => l.event === 'TokensToSendCalled'); - expect(externalSendHook).to.be.gte(0); - - expect(externalSendHook).to.be.lt(internalBeforeHook); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/presets/ERC777PresetFixedSupply.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/presets/ERC777PresetFixedSupply.test.js deleted file mode 100644 index e6a842be..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/ERC777/presets/ERC777PresetFixedSupply.test.js +++ /dev/null @@ -1,49 +0,0 @@ -const { BN, singletons } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC777PresetFixedSupply = artifacts.require('ERC777PresetFixedSupply'); - -contract('ERC777PresetFixedSupply', function (accounts) { - const [registryFunder, owner, defaultOperatorA, defaultOperatorB, anyone] = accounts; - - const initialSupply = new BN('10000'); - const name = 'ERC777Preset'; - const symbol = '777P'; - - const defaultOperators = [defaultOperatorA, defaultOperatorB]; - - before(async function () { - await singletons.ERC1820Registry(registryFunder); - }); - - beforeEach(async function () { - this.token = await ERC777PresetFixedSupply.new(name, symbol, defaultOperators, initialSupply, owner); - }); - - it('returns the name', async function () { - expect(await this.token.name()).to.equal(name); - }); - - it('returns the symbol', async function () { - expect(await this.token.symbol()).to.equal(symbol); - }); - - it('returns the default operators', async function () { - expect(await this.token.defaultOperators()).to.deep.equal(defaultOperators); - }); - - it('default operators are operators for all accounts', async function () { - for (const operator of defaultOperators) { - expect(await this.token.isOperatorFor(operator, anyone)).to.equal(true); - } - }); - - it('returns the total supply equal to initial supply', async function () { - expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply); - }); - - it('returns the balance of owner equal to initial supply', async function () { - expect(await this.token.balanceOf(owner)).to.be.bignumber.equal(initialSupply); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/common/ERC2981.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/common/ERC2981.behavior.js deleted file mode 100644 index 0d906a91..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/token/common/ERC2981.behavior.js +++ /dev/null @@ -1,160 +0,0 @@ -const { BN, constants, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { ZERO_ADDRESS } = constants; - -const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsInterface.behavior'); - -function shouldBehaveLikeERC2981 () { - const royaltyFraction = new BN('10'); - - shouldSupportInterfaces(['ERC2981']); - - describe('default royalty', function () { - beforeEach(async function () { - await this.token.setDefaultRoyalty(this.account1, royaltyFraction); - }); - - it('checks royalty is set', async function () { - const royalty = new BN((this.salePrice * royaltyFraction) / 10000); - - const initInfo = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - - expect(initInfo[0]).to.be.equal(this.account1); - expect(initInfo[1]).to.be.bignumber.equal(royalty); - }); - - it('updates royalty amount', async function () { - const newPercentage = new BN('25'); - - // Updated royalty check - await this.token.setDefaultRoyalty(this.account1, newPercentage); - const royalty = new BN((this.salePrice * newPercentage) / 10000); - const newInfo = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - - expect(newInfo[0]).to.be.equal(this.account1); - expect(newInfo[1]).to.be.bignumber.equal(royalty); - }); - - it('holds same royalty value for different tokens', async function () { - const newPercentage = new BN('20'); - await this.token.setDefaultRoyalty(this.account1, newPercentage); - - const token1Info = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - const token2Info = await this.token.royaltyInfo(this.tokenId2, this.salePrice); - - expect(token1Info[1]).to.be.bignumber.equal(token2Info[1]); - }); - - it('Remove royalty information', async function () { - const newValue = new BN('0'); - await this.token.deleteDefaultRoyalty(); - - const token1Info = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - const token2Info = await this.token.royaltyInfo(this.tokenId2, this.salePrice); - // Test royalty info is still persistent across all tokens - expect(token1Info[0]).to.be.bignumber.equal(token2Info[0]); - expect(token1Info[1]).to.be.bignumber.equal(token2Info[1]); - // Test information was deleted - expect(token1Info[0]).to.be.equal(ZERO_ADDRESS); - expect(token1Info[1]).to.be.bignumber.equal(newValue); - }); - - it('reverts if invalid parameters', async function () { - await expectRevert( - this.token.setDefaultRoyalty(ZERO_ADDRESS, royaltyFraction), - 'ERC2981: invalid receiver', - ); - - await expectRevert( - this.token.setTokenRoyalty(this.tokenId1, this.account1, new BN('11000')), - 'ERC2981: royalty fee will exceed salePrice', - ); - }); - }); - - describe('token based royalty', function () { - beforeEach(async function () { - await this.token.setTokenRoyalty(this.tokenId1, this.account1, royaltyFraction); - }); - - it('updates royalty amount', async function () { - const newPercentage = new BN('25'); - let royalty = new BN((this.salePrice * royaltyFraction) / 10000); - // Initial royalty check - const initInfo = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - - expect(initInfo[0]).to.be.equal(this.account1); - expect(initInfo[1]).to.be.bignumber.equal(royalty); - - // Updated royalty check - await this.token.setTokenRoyalty(this.tokenId1, this.account1, newPercentage); - royalty = new BN((this.salePrice * newPercentage) / 10000); - const newInfo = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - - expect(newInfo[0]).to.be.equal(this.account1); - expect(newInfo[1]).to.be.bignumber.equal(royalty); - }); - - it('holds different values for different tokens', async function () { - const newPercentage = new BN('20'); - await this.token.setTokenRoyalty(this.tokenId2, this.account1, newPercentage); - - const token1Info = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - const token2Info = await this.token.royaltyInfo(this.tokenId2, this.salePrice); - - // must be different even at the same this.salePrice - expect(token1Info[1]).to.not.be.equal(token2Info.royaltyFraction); - }); - - it('reverts if invalid parameters', async function () { - await expectRevert( - this.token.setTokenRoyalty(this.tokenId1, ZERO_ADDRESS, royaltyFraction), - 'ERC2981: Invalid parameters', - ); - - await expectRevert( - this.token.setTokenRoyalty(this.tokenId1, this.account1, new BN('11000')), - 'ERC2981: royalty fee will exceed salePrice', - ); - }); - - it('can reset token after setting royalty', async function () { - const newPercentage = new BN('30'); - const royalty = new BN((this.salePrice * newPercentage) / 10000); - await this.token.setTokenRoyalty(this.tokenId1, this.account2, newPercentage); - - const tokenInfo = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - - // Tokens must have own information - expect(tokenInfo[1]).to.be.bignumber.equal(royalty); - expect(tokenInfo[0]).to.be.equal(this.account2); - - await this.token.setTokenRoyalty(this.tokenId2, this.account1, new BN('0')); - const result = await this.token.royaltyInfo(this.tokenId2, this.salePrice); - // Token must not share default information - expect(result[0]).to.be.equal(this.account1); - expect(result[1]).to.be.bignumber.equal(new BN('0')); - }); - - it('can hold default and token royalty information', async function () { - const newPercentage = new BN('30'); - const royalty = new BN((this.salePrice * newPercentage) / 10000); - - await this.token.setTokenRoyalty(this.tokenId2, this.account2, newPercentage); - - const token1Info = await this.token.royaltyInfo(this.tokenId1, this.salePrice); - const token2Info = await this.token.royaltyInfo(this.tokenId2, this.salePrice); - // Tokens must not have same values - expect(token1Info[1]).to.not.be.bignumber.equal(token2Info[1]); - expect(token1Info[0]).to.not.be.equal(token2Info[0]); - - // Updated token must have new values - expect(token2Info[0]).to.be.equal(this.account2); - expect(token2Info[1]).to.be.bignumber.equal(royalty); - }); - }); -} - -module.exports = { - shouldBehaveLikeERC2981, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Address.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Address.test.js deleted file mode 100644 index 6cd202c5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Address.test.js +++ /dev/null @@ -1,382 +0,0 @@ -const { balance, ether, expectRevert, send, expectEvent } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const AddressImpl = artifacts.require('AddressImpl'); -const EtherReceiver = artifacts.require('EtherReceiverMock'); -const CallReceiverMock = artifacts.require('CallReceiverMock'); - -contract('Address', function (accounts) { - const [ recipient, other ] = accounts; - - beforeEach(async function () { - this.mock = await AddressImpl.new(); - }); - - describe('isContract', function () { - it('returns false for account address', async function () { - expect(await this.mock.isContract(other)).to.equal(false); - }); - - it('returns true for contract address', async function () { - const contract = await AddressImpl.new(); - expect(await this.mock.isContract(contract.address)).to.equal(true); - }); - }); - - describe('sendValue', function () { - beforeEach(async function () { - this.recipientTracker = await balance.tracker(recipient); - }); - - context('when sender contract has no funds', function () { - it('sends 0 wei', async function () { - await this.mock.sendValue(other, 0); - - expect(await this.recipientTracker.delta()).to.be.bignumber.equal('0'); - }); - - it('reverts when sending non-zero amounts', async function () { - await expectRevert(this.mock.sendValue(other, 1), 'Address: insufficient balance'); - }); - }); - - context('when sender contract has funds', function () { - const funds = ether('1'); - beforeEach(async function () { - await send.ether(other, this.mock.address, funds); - }); - - it('sends 0 wei', async function () { - await this.mock.sendValue(recipient, 0); - expect(await this.recipientTracker.delta()).to.be.bignumber.equal('0'); - }); - - it('sends non-zero amounts', async function () { - await this.mock.sendValue(recipient, funds.subn(1)); - expect(await this.recipientTracker.delta()).to.be.bignumber.equal(funds.subn(1)); - }); - - it('sends the whole balance', async function () { - await this.mock.sendValue(recipient, funds); - expect(await this.recipientTracker.delta()).to.be.bignumber.equal(funds); - expect(await balance.current(this.mock.address)).to.be.bignumber.equal('0'); - }); - - it('reverts when sending more than the balance', async function () { - await expectRevert(this.mock.sendValue(recipient, funds.addn(1)), 'Address: insufficient balance'); - }); - - context('with contract recipient', function () { - beforeEach(async function () { - this.contractRecipient = await EtherReceiver.new(); - }); - - it('sends funds', async function () { - const tracker = await balance.tracker(this.contractRecipient.address); - - await this.contractRecipient.setAcceptEther(true); - await this.mock.sendValue(this.contractRecipient.address, funds); - expect(await tracker.delta()).to.be.bignumber.equal(funds); - }); - - it('reverts on recipient revert', async function () { - await this.contractRecipient.setAcceptEther(false); - await expectRevert( - this.mock.sendValue(this.contractRecipient.address, funds), - 'Address: unable to send value, recipient may have reverted', - ); - }); - }); - }); - }); - - describe('functionCall', function () { - beforeEach(async function () { - this.contractRecipient = await CallReceiverMock.new(); - }); - - context('with valid contract receiver', function () { - it('calls the requested function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - - const receipt = await this.mock.functionCall(this.contractRecipient.address, abiEncodedCall); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); - await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); - }); - - it('reverts when the called function reverts with no reason', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionRevertsNoReason', - type: 'function', - inputs: [], - }, []); - - await expectRevert( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall), - 'Address: low-level call failed', - ); - }); - - it('reverts when the called function reverts, bubbling up the revert reason', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionRevertsReason', - type: 'function', - inputs: [], - }, []); - - await expectRevert( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall), - 'CallReceiverMock: reverting', - ); - }); - - it('reverts when the called function runs out of gas', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionOutOfGas', - type: 'function', - inputs: [], - }, []); - - await expectRevert( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall, { gas: '100000' }), - 'Address: low-level call failed', - ); - }); - - it('reverts when the called function throws', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionThrows', - type: 'function', - inputs: [], - }, []); - - await expectRevert.unspecified( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall), - ); - }); - - it('reverts when function does not exist', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionDoesNotExist', - type: 'function', - inputs: [], - }, []); - - await expectRevert( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall), - 'Address: low-level call failed', - ); - }); - }); - - context('with non-contract receiver', function () { - it('reverts when address is not a contract', async function () { - const [ recipient ] = accounts; - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - await expectRevert(this.mock.functionCall(recipient, abiEncodedCall), 'Address: call to non-contract'); - }); - }); - }); - - describe('functionCallWithValue', function () { - beforeEach(async function () { - this.contractRecipient = await CallReceiverMock.new(); - }); - - context('with zero value', function () { - it('calls the requested function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - - const receipt = await this.mock.functionCallWithValue(this.contractRecipient.address, abiEncodedCall, 0); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); - await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); - }); - }); - - context('with non-zero value', function () { - const amount = ether('1.2'); - - it('reverts if insufficient sender balance', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - - await expectRevert( - this.mock.functionCallWithValue(this.contractRecipient.address, abiEncodedCall, amount), - 'Address: insufficient balance for call', - ); - }); - - it('calls the requested function with existing value', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - - const tracker = await balance.tracker(this.contractRecipient.address); - - await send.ether(other, this.mock.address, amount); - const receipt = await this.mock.functionCallWithValue(this.contractRecipient.address, abiEncodedCall, amount); - - expect(await tracker.delta()).to.be.bignumber.equal(amount); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); - await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); - }); - - it('calls the requested function with transaction funds', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - - const tracker = await balance.tracker(this.contractRecipient.address); - - expect(await balance.current(this.mock.address)).to.be.bignumber.equal('0'); - const receipt = await this.mock.functionCallWithValue( - this.contractRecipient.address, abiEncodedCall, amount, { from: other, value: amount }, - ); - - expect(await tracker.delta()).to.be.bignumber.equal(amount); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); - await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); - }); - - it('reverts when calling non-payable functions', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionNonPayable', - type: 'function', - inputs: [], - }, []); - - await send.ether(other, this.mock.address, amount); - await expectRevert( - this.mock.functionCallWithValue(this.contractRecipient.address, abiEncodedCall, amount), - 'Address: low-level call with value failed', - ); - }); - }); - }); - - describe('functionStaticCall', function () { - beforeEach(async function () { - this.contractRecipient = await CallReceiverMock.new(); - }); - - it('calls the requested function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockStaticFunction', - type: 'function', - inputs: [], - }, []); - - const receipt = await this.mock.functionStaticCall(this.contractRecipient.address, abiEncodedCall); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); - }); - - it('reverts on a non-static function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - - await expectRevert( - this.mock.functionStaticCall(this.contractRecipient.address, abiEncodedCall), - 'Address: low-level static call failed', - ); - }); - - it('bubbles up revert reason', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionRevertsReason', - type: 'function', - inputs: [], - }, []); - - await expectRevert( - this.mock.functionStaticCall(this.contractRecipient.address, abiEncodedCall), - 'CallReceiverMock: reverting', - ); - }); - - it('reverts when address is not a contract', async function () { - const [ recipient ] = accounts; - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - await expectRevert( - this.mock.functionStaticCall(recipient, abiEncodedCall), - 'Address: static call to non-contract', - ); - }); - }); - - describe('functionDelegateCall', function () { - beforeEach(async function () { - this.contractRecipient = await CallReceiverMock.new(); - }); - - it('delegate calls the requested function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionWritesStorage', - type: 'function', - inputs: [], - }, []); - - const receipt = await this.mock.functionDelegateCall(this.contractRecipient.address, abiEncodedCall); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); - - expect(await this.mock.sharedAnswer()).to.equal('42'); - }); - - it('bubbles up revert reason', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionRevertsReason', - type: 'function', - inputs: [], - }, []); - - await expectRevert( - this.mock.functionDelegateCall(this.contractRecipient.address, abiEncodedCall), - 'CallReceiverMock: reverting', - ); - }); - - it('reverts when address is not a contract', async function () { - const [ recipient ] = accounts; - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - await expectRevert( - this.mock.functionDelegateCall(recipient, abiEncodedCall), - 'Address: delegate call to non-contract', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Arrays.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Arrays.test.js deleted file mode 100644 index 67128fac..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Arrays.test.js +++ /dev/null @@ -1,87 +0,0 @@ -require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ArraysImpl = artifacts.require('ArraysImpl'); - -contract('Arrays', function (accounts) { - describe('findUpperBound', function () { - context('Even number of elements', function () { - const EVEN_ELEMENTS_ARRAY = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; - - beforeEach(async function () { - this.arrays = await ArraysImpl.new(EVEN_ELEMENTS_ARRAY); - }); - - it('returns correct index for the basic case', async function () { - expect(await this.arrays.findUpperBound(16)).to.be.bignumber.equal('5'); - }); - - it('returns 0 for the first element', async function () { - expect(await this.arrays.findUpperBound(11)).to.be.bignumber.equal('0'); - }); - - it('returns index of the last element', async function () { - expect(await this.arrays.findUpperBound(20)).to.be.bignumber.equal('9'); - }); - - it('returns first index after last element if searched value is over the upper boundary', async function () { - expect(await this.arrays.findUpperBound(32)).to.be.bignumber.equal('10'); - }); - - it('returns 0 for the element under the lower boundary', async function () { - expect(await this.arrays.findUpperBound(2)).to.be.bignumber.equal('0'); - }); - }); - - context('Odd number of elements', function () { - const ODD_ELEMENTS_ARRAY = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]; - - beforeEach(async function () { - this.arrays = await ArraysImpl.new(ODD_ELEMENTS_ARRAY); - }); - - it('returns correct index for the basic case', async function () { - expect(await this.arrays.findUpperBound(16)).to.be.bignumber.equal('5'); - }); - - it('returns 0 for the first element', async function () { - expect(await this.arrays.findUpperBound(11)).to.be.bignumber.equal('0'); - }); - - it('returns index of the last element', async function () { - expect(await this.arrays.findUpperBound(21)).to.be.bignumber.equal('10'); - }); - - it('returns first index after last element if searched value is over the upper boundary', async function () { - expect(await this.arrays.findUpperBound(32)).to.be.bignumber.equal('11'); - }); - - it('returns 0 for the element under the lower boundary', async function () { - expect(await this.arrays.findUpperBound(2)).to.be.bignumber.equal('0'); - }); - }); - - context('Array with gap', function () { - const WITH_GAP_ARRAY = [11, 12, 13, 14, 15, 20, 21, 22, 23, 24]; - - beforeEach(async function () { - this.arrays = await ArraysImpl.new(WITH_GAP_ARRAY); - }); - - it('returns index of first element in next filled range', async function () { - expect(await this.arrays.findUpperBound(17)).to.be.bignumber.equal('5'); - }); - }); - - context('Empty array', function () { - beforeEach(async function () { - this.arrays = await ArraysImpl.new([]); - }); - - it('always returns 0 for empty array', async function () { - expect(await this.arrays.findUpperBound(10)).to.be.bignumber.equal('0'); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Base64.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Base64.test.js deleted file mode 100644 index 5eb4f74b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Base64.test.js +++ /dev/null @@ -1,29 +0,0 @@ -const { expect } = require('chai'); - -const Base64Mock = artifacts.require('Base64Mock'); - -contract('Strings', function () { - beforeEach(async function () { - this.base64 = await Base64Mock.new(); - }); - - describe('from bytes - base64', function () { - it('converts to base64 encoded string with double padding', async function () { - const TEST_MESSAGE = 'test'; - const input = web3.utils.asciiToHex(TEST_MESSAGE); - expect(await this.base64.encode(input)).to.equal('dGVzdA=='); - }); - - it('converts to base64 encoded string with single padding', async function () { - const TEST_MESSAGE = 'test1'; - const input = web3.utils.asciiToHex(TEST_MESSAGE); - expect(await this.base64.encode(input)).to.equal('dGVzdDE='); - }); - - it('converts to base64 encoded string without padding', async function () { - const TEST_MESSAGE = 'test12'; - const input = web3.utils.asciiToHex(TEST_MESSAGE); - expect(await this.base64.encode(input)).to.equal('dGVzdDEy'); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Checkpoints.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Checkpoints.test.js deleted file mode 100644 index 37f9013e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Checkpoints.test.js +++ /dev/null @@ -1,59 +0,0 @@ -const { expectRevert, time } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const CheckpointsImpl = artifacts.require('CheckpointsImpl'); - -contract('Checkpoints', function (accounts) { - beforeEach(async function () { - this.checkpoint = await CheckpointsImpl.new(); - }); - - describe('without checkpoints', function () { - it('returns zero as latest value', async function () { - expect(await this.checkpoint.latest()).to.be.bignumber.equal('0'); - }); - - it('returns zero as past value', async function () { - await time.advanceBlock(); - expect(await this.checkpoint.getAtBlock(await web3.eth.getBlockNumber() - 1)).to.be.bignumber.equal('0'); - }); - }); - - describe('with checkpoints', function () { - beforeEach('pushing checkpoints', async function () { - this.tx1 = await this.checkpoint.push(1); - this.tx2 = await this.checkpoint.push(2); - await time.advanceBlock(); - this.tx3 = await this.checkpoint.push(3); - await time.advanceBlock(); - await time.advanceBlock(); - }); - - it('returns latest value', async function () { - expect(await this.checkpoint.latest()).to.be.bignumber.equal('3'); - }); - - it('returns past values', async function () { - expect(await this.checkpoint.getAtBlock(this.tx1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.checkpoint.getAtBlock(this.tx1.receipt.blockNumber)).to.be.bignumber.equal('1'); - expect(await this.checkpoint.getAtBlock(this.tx2.receipt.blockNumber)).to.be.bignumber.equal('2'); - // Block with no new checkpoints - expect(await this.checkpoint.getAtBlock(this.tx2.receipt.blockNumber + 1)).to.be.bignumber.equal('2'); - expect(await this.checkpoint.getAtBlock(this.tx3.receipt.blockNumber)).to.be.bignumber.equal('3'); - expect(await this.checkpoint.getAtBlock(this.tx3.receipt.blockNumber + 1)).to.be.bignumber.equal('3'); - }); - - it('reverts if block number >= current block', async function () { - await expectRevert( - this.checkpoint.getAtBlock(await web3.eth.getBlockNumber()), - 'Checkpoints: block not yet mined', - ); - - await expectRevert( - this.checkpoint.getAtBlock(await web3.eth.getBlockNumber() + 1), - 'Checkpoints: block not yet mined', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Context.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Context.behavior.js deleted file mode 100644 index 0f60945a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Context.behavior.js +++ /dev/null @@ -1,42 +0,0 @@ -const { BN, expectEvent } = require('@openzeppelin/test-helpers'); - -const ContextMock = artifacts.require('ContextMock'); - -function shouldBehaveLikeRegularContext (sender) { - describe('msgSender', function () { - it('returns the transaction sender when called from an EOA', async function () { - const { logs } = await this.context.msgSender({ from: sender }); - expectEvent.inLogs(logs, 'Sender', { sender }); - }); - - it('returns the transaction sender when from another contract', async function () { - const { tx } = await this.caller.callSender(this.context.address, { from: sender }); - await expectEvent.inTransaction(tx, ContextMock, 'Sender', { sender: this.caller.address }); - }); - }); - - describe('msgData', function () { - const integerValue = new BN('42'); - const stringValue = 'OpenZeppelin'; - - let callData; - - beforeEach(async function () { - callData = this.context.contract.methods.msgData(integerValue.toString(), stringValue).encodeABI(); - }); - - it('returns the transaction data when called from an EOA', async function () { - const { logs } = await this.context.msgData(integerValue, stringValue); - expectEvent.inLogs(logs, 'Data', { data: callData, integerValue, stringValue }); - }); - - it('returns the transaction sender when from another contract', async function () { - const { tx } = await this.caller.callData(this.context.address, integerValue, stringValue); - await expectEvent.inTransaction(tx, ContextMock, 'Data', { data: callData, integerValue, stringValue }); - }); - }); -} - -module.exports = { - shouldBehaveLikeRegularContext, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Context.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Context.test.js deleted file mode 100644 index 709aa87d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Context.test.js +++ /dev/null @@ -1,17 +0,0 @@ -require('@openzeppelin/test-helpers'); - -const ContextMock = artifacts.require('ContextMock'); -const ContextMockCaller = artifacts.require('ContextMockCaller'); - -const { shouldBehaveLikeRegularContext } = require('./Context.behavior'); - -contract('Context', function (accounts) { - const [ sender ] = accounts; - - beforeEach(async function () { - this.context = await ContextMock.new(); - this.caller = await ContextMockCaller.new(); - }); - - shouldBehaveLikeRegularContext(sender); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Counters.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Counters.test.js deleted file mode 100644 index 04be4c0c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Counters.test.js +++ /dev/null @@ -1,84 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const CountersImpl = artifacts.require('CountersImpl'); - -contract('Counters', function (accounts) { - beforeEach(async function () { - this.counter = await CountersImpl.new(); - }); - - it('starts at zero', async function () { - expect(await this.counter.current()).to.be.bignumber.equal('0'); - }); - - describe('increment', function () { - context('starting from 0', function () { - it('increments the current value by one', async function () { - await this.counter.increment(); - expect(await this.counter.current()).to.be.bignumber.equal('1'); - }); - - it('can be called multiple times', async function () { - await this.counter.increment(); - await this.counter.increment(); - await this.counter.increment(); - - expect(await this.counter.current()).to.be.bignumber.equal('3'); - }); - }); - }); - - describe('decrement', function () { - beforeEach(async function () { - await this.counter.increment(); - expect(await this.counter.current()).to.be.bignumber.equal('1'); - }); - context('starting from 1', function () { - it('decrements the current value by one', async function () { - await this.counter.decrement(); - expect(await this.counter.current()).to.be.bignumber.equal('0'); - }); - - it('reverts if the current value is 0', async function () { - await this.counter.decrement(); - await expectRevert(this.counter.decrement(), 'Counter: decrement overflow'); - }); - }); - context('after incremented to 3', function () { - it('can be called multiple times', async function () { - await this.counter.increment(); - await this.counter.increment(); - - expect(await this.counter.current()).to.be.bignumber.equal('3'); - - await this.counter.decrement(); - await this.counter.decrement(); - await this.counter.decrement(); - - expect(await this.counter.current()).to.be.bignumber.equal('0'); - }); - }); - }); - - describe('reset', function () { - context('null counter', function () { - it('does not throw', async function () { - await this.counter.reset(); - expect(await this.counter.current()).to.be.bignumber.equal('0'); - }); - }); - - context('non null counter', function () { - beforeEach(async function () { - await this.counter.increment(); - expect(await this.counter.current()).to.be.bignumber.equal('1'); - }); - it('reset to 0', async function () { - await this.counter.reset(); - expect(await this.counter.current()).to.be.bignumber.equal('0'); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Create2.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Create2.test.js deleted file mode 100644 index cfc88c0b..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Create2.test.js +++ /dev/null @@ -1,101 +0,0 @@ -const { balance, BN, ether, expectRevert, send } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const Create2Impl = artifacts.require('Create2Impl'); -const ERC20Mock = artifacts.require('ERC20Mock'); -const ERC1820Implementer = artifacts.require('ERC1820Implementer'); - -contract('Create2', function (accounts) { - const [deployerAccount] = accounts; - - const salt = 'salt message'; - const saltHex = web3.utils.soliditySha3(salt); - - const encodedParams = web3.eth.abi.encodeParameters( - ['string', 'string', 'address', 'uint256'], - ['MyToken', 'MTKN', deployerAccount, 100], - ).slice(2); - - const constructorByteCode = `${ERC20Mock.bytecode}${encodedParams}`; - - beforeEach(async function () { - this.factory = await Create2Impl.new(); - }); - describe('computeAddress', function () { - it('computes the correct contract address', async function () { - const onChainComputed = await this.factory - .computeAddress(saltHex, web3.utils.keccak256(constructorByteCode)); - const offChainComputed = - computeCreate2Address(saltHex, constructorByteCode, this.factory.address); - expect(onChainComputed).to.equal(offChainComputed); - }); - - it('computes the correct contract address with deployer', async function () { - const onChainComputed = await this.factory - .computeAddressWithDeployer(saltHex, web3.utils.keccak256(constructorByteCode), deployerAccount); - const offChainComputed = - computeCreate2Address(saltHex, constructorByteCode, deployerAccount); - expect(onChainComputed).to.equal(offChainComputed); - }); - }); - - describe('deploy', function () { - it('deploys a ERC1820Implementer from inline assembly code', async function () { - const offChainComputed = - computeCreate2Address(saltHex, ERC1820Implementer.bytecode, this.factory.address); - await this.factory.deployERC1820Implementer(0, saltHex); - expect(ERC1820Implementer.bytecode).to.include((await web3.eth.getCode(offChainComputed)).slice(2)); - }); - - it('deploys a ERC20Mock with correct balances', async function () { - const offChainComputed = computeCreate2Address(saltHex, constructorByteCode, this.factory.address); - - await this.factory.deploy(0, saltHex, constructorByteCode); - - const erc20 = await ERC20Mock.at(offChainComputed); - expect(await erc20.balanceOf(deployerAccount)).to.be.bignumber.equal(new BN(100)); - }); - - it('deploys a contract with funds deposited in the factory', async function () { - const deposit = ether('2'); - await send.ether(deployerAccount, this.factory.address, deposit); - expect(await balance.current(this.factory.address)).to.be.bignumber.equal(deposit); - - const onChainComputed = await this.factory - .computeAddressWithDeployer(saltHex, web3.utils.keccak256(constructorByteCode), this.factory.address); - - await this.factory.deploy(deposit, saltHex, constructorByteCode); - expect(await balance.current(onChainComputed)).to.be.bignumber.equal(deposit); - }); - - it('fails deploying a contract in an existent address', async function () { - await this.factory.deploy(0, saltHex, constructorByteCode, { from: deployerAccount }); - await expectRevert( - this.factory.deploy(0, saltHex, constructorByteCode, { from: deployerAccount }), 'Create2: Failed on deploy', - ); - }); - - it('fails deploying a contract if the bytecode length is zero', async function () { - await expectRevert( - this.factory.deploy(0, saltHex, '0x', { from: deployerAccount }), 'Create2: bytecode length is zero', - ); - }); - - it('fails deploying a contract if factory contract does not have sufficient balance', async function () { - await expectRevert( - this.factory.deploy(1, saltHex, constructorByteCode, { from: deployerAccount }), - 'Create2: insufficient balance', - ); - }); - }); -}); - -function computeCreate2Address (saltHex, bytecode, deployer) { - return web3.utils.toChecksumAddress(`0x${web3.utils.sha3(`0x${[ - 'ff', - deployer, - saltHex, - web3.utils.soliditySha3(bytecode), - ].map(x => x.replace(/0x/, '')).join('')}`).slice(-40)}`); -} diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Multicall.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Multicall.test.js deleted file mode 100644 index c6453bb6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Multicall.test.js +++ /dev/null @@ -1,57 +0,0 @@ -const { BN, expectRevert } = require('@openzeppelin/test-helpers'); -const MulticallTokenMock = artifacts.require('MulticallTokenMock'); - -contract('MulticallToken', function (accounts) { - const [deployer, alice, bob] = accounts; - const amount = 12000; - - beforeEach(async function () { - this.multicallToken = await MulticallTokenMock.new(new BN(amount), { from: deployer }); - }); - - it('batches function calls', async function () { - expect(await this.multicallToken.balanceOf(alice)).to.be.bignumber.equal(new BN('0')); - expect(await this.multicallToken.balanceOf(bob)).to.be.bignumber.equal(new BN('0')); - - await this.multicallToken.multicall([ - this.multicallToken.contract.methods.transfer(alice, amount / 2).encodeABI(), - this.multicallToken.contract.methods.transfer(bob, amount / 3).encodeABI(), - ], { from: deployer }); - - expect(await this.multicallToken.balanceOf(alice)).to.be.bignumber.equal(new BN(amount / 2)); - expect(await this.multicallToken.balanceOf(bob)).to.be.bignumber.equal(new BN(amount / 3)); - }); - - it('returns an array with the result of each call', async function () { - const MulticallTest = artifacts.require('MulticallTest'); - const multicallTest = await MulticallTest.new({ from: deployer }); - await this.multicallToken.transfer(multicallTest.address, amount, { from: deployer }); - expect(await this.multicallToken.balanceOf(multicallTest.address)).to.be.bignumber.equal(new BN(amount)); - - const recipients = [alice, bob]; - const amounts = [amount / 2, amount / 3].map(n => new BN(n)); - - await multicallTest.testReturnValues(this.multicallToken.address, recipients, amounts); - }); - - it('reverts previous calls', async function () { - expect(await this.multicallToken.balanceOf(alice)).to.be.bignumber.equal(new BN('0')); - - const call = this.multicallToken.multicall([ - this.multicallToken.contract.methods.transfer(alice, amount).encodeABI(), - this.multicallToken.contract.methods.transfer(bob, amount).encodeABI(), - ], { from: deployer }); - - await expectRevert(call, 'ERC20: transfer amount exceeds balance'); - expect(await this.multicallToken.balanceOf(alice)).to.be.bignumber.equal(new BN('0')); - }); - - it('bubbles up revert reasons', async function () { - const call = this.multicallToken.multicall([ - this.multicallToken.contract.methods.transfer(alice, amount).encodeABI(), - this.multicallToken.contract.methods.transfer(bob, amount).encodeABI(), - ], { from: deployer }); - - await expectRevert(call, 'ERC20: transfer amount exceeds balance'); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/StorageSlot.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/StorageSlot.test.js deleted file mode 100644 index 9d428875..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/StorageSlot.test.js +++ /dev/null @@ -1,110 +0,0 @@ -const { constants, BN } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const StorageSlotMock = artifacts.require('StorageSlotMock'); - -const slot = web3.utils.keccak256('some.storage.slot'); -const otherSlot = web3.utils.keccak256('some.other.storage.slot'); - -contract('StorageSlot', function (accounts) { - beforeEach(async function () { - this.store = await StorageSlotMock.new(); - }); - - describe('boolean storage slot', function () { - beforeEach(async function () { - this.value = true; - }); - - it('set', async function () { - await this.store.setBoolean(slot, this.value); - }); - - describe('get', function () { - beforeEach(async function () { - await this.store.setBoolean(slot, this.value); - }); - - it('from right slot', async function () { - expect(await this.store.getBoolean(slot)).to.be.equal(this.value); - }); - - it('from other slot', async function () { - expect(await this.store.getBoolean(otherSlot)).to.be.equal(false); - }); - }); - }); - - describe('address storage slot', function () { - beforeEach(async function () { - this.value = accounts[1]; - }); - - it('set', async function () { - await this.store.setAddress(slot, this.value); - }); - - describe('get', function () { - beforeEach(async function () { - await this.store.setAddress(slot, this.value); - }); - - it('from right slot', async function () { - expect(await this.store.getAddress(slot)).to.be.equal(this.value); - }); - - it('from other slot', async function () { - expect(await this.store.getAddress(otherSlot)).to.be.equal(constants.ZERO_ADDRESS); - }); - }); - }); - - describe('bytes32 storage slot', function () { - beforeEach(async function () { - this.value = web3.utils.keccak256('some byte32 value'); - }); - - it('set', async function () { - await this.store.setBytes32(slot, this.value); - }); - - describe('get', function () { - beforeEach(async function () { - await this.store.setBytes32(slot, this.value); - }); - - it('from right slot', async function () { - expect(await this.store.getBytes32(slot)).to.be.equal(this.value); - }); - - it('from other slot', async function () { - expect(await this.store.getBytes32(otherSlot)).to.be.equal(constants.ZERO_BYTES32); - }); - }); - }); - - describe('uint256 storage slot', function () { - beforeEach(async function () { - this.value = new BN(1742); - }); - - it('set', async function () { - await this.store.setUint256(slot, this.value); - }); - - describe('get', function () { - beforeEach(async function () { - await this.store.setUint256(slot, this.value); - }); - - it('from right slot', async function () { - expect(await this.store.getUint256(slot)).to.be.bignumber.equal(this.value); - }); - - it('from other slot', async function () { - expect(await this.store.getUint256(otherSlot)).to.be.bignumber.equal('0'); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Strings.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Strings.test.js deleted file mode 100644 index 5128ce57..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/Strings.test.js +++ /dev/null @@ -1,59 +0,0 @@ -const { constants, expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const StringsMock = artifacts.require('StringsMock'); - -contract('Strings', function (accounts) { - beforeEach(async function () { - this.strings = await StringsMock.new(); - }); - - describe('from uint256 - decimal format', function () { - it('converts 0', async function () { - expect(await this.strings.fromUint256(0)).to.equal('0'); - }); - - it('converts a positive number', async function () { - expect(await this.strings.fromUint256(4132)).to.equal('4132'); - }); - - it('converts MAX_UINT256', async function () { - expect(await this.strings.fromUint256(constants.MAX_UINT256)).to.equal(constants.MAX_UINT256.toString()); - }); - }); - - describe('from uint256 - hex format', function () { - it('converts 0', async function () { - expect(await this.strings.fromUint256Hex(0)).to.equal('0x00'); - }); - - it('converts a positive number', async function () { - expect(await this.strings.fromUint256Hex(0x4132)).to.equal('0x4132'); - }); - - it('converts MAX_UINT256', async function () { - expect(await this.strings.fromUint256Hex(constants.MAX_UINT256)) - .to.equal(web3.utils.toHex(constants.MAX_UINT256)); - }); - }); - - describe('from uint256 - fixed hex format', function () { - it('converts a positive number (long)', async function () { - expect(await this.strings.fromUint256HexFixed(0x4132, 32)) - .to.equal('0x0000000000000000000000000000000000000000000000000000000000004132'); - }); - - it('converts a positive number (short)', async function () { - await expectRevert( - this.strings.fromUint256HexFixed(0x4132, 1), - 'Strings: hex length insufficient', - ); - }); - - it('converts MAX_UINT256', async function () { - expect(await this.strings.fromUint256HexFixed(constants.MAX_UINT256, 32)) - .to.equal(web3.utils.toHex(constants.MAX_UINT256)); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/TimersBlockNumberImpl.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/TimersBlockNumberImpl.test.js deleted file mode 100644 index d9f83d93..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/TimersBlockNumberImpl.test.js +++ /dev/null @@ -1,55 +0,0 @@ -const { BN, time } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const TimersBlockNumberImpl = artifacts.require('TimersBlockNumberImpl'); - -contract('TimersBlockNumber', function (accounts) { - beforeEach(async function () { - this.instance = await TimersBlockNumberImpl.new(); - this.now = await web3.eth.getBlock('latest').then(({ number }) => number); - }); - - it('unset', async function () { - expect(await this.instance.getDeadline()).to.be.bignumber.equal('0'); - expect(await this.instance.isUnset()).to.be.equal(true); - expect(await this.instance.isStarted()).to.be.equal(false); - expect(await this.instance.isPending()).to.be.equal(false); - expect(await this.instance.isExpired()).to.be.equal(false); - }); - - it('pending', async function () { - await this.instance.setDeadline(this.now + 3); - expect(await this.instance.getDeadline()).to.be.bignumber.equal(new BN(this.now + 3)); - expect(await this.instance.isUnset()).to.be.equal(false); - expect(await this.instance.isStarted()).to.be.equal(true); - expect(await this.instance.isPending()).to.be.equal(true); - expect(await this.instance.isExpired()).to.be.equal(false); - }); - - it('expired', async function () { - await this.instance.setDeadline(this.now - 3); - expect(await this.instance.getDeadline()).to.be.bignumber.equal(new BN(this.now - 3)); - expect(await this.instance.isUnset()).to.be.equal(false); - expect(await this.instance.isStarted()).to.be.equal(true); - expect(await this.instance.isPending()).to.be.equal(false); - expect(await this.instance.isExpired()).to.be.equal(true); - }); - - it('reset', async function () { - await this.instance.reset(); - expect(await this.instance.getDeadline()).to.be.bignumber.equal(new BN(0)); - expect(await this.instance.isUnset()).to.be.equal(true); - expect(await this.instance.isStarted()).to.be.equal(false); - expect(await this.instance.isPending()).to.be.equal(false); - expect(await this.instance.isExpired()).to.be.equal(false); - }); - - it('fast forward', async function () { - await this.instance.setDeadline(this.now + 3); - expect(await this.instance.isPending()).to.be.equal(true); - expect(await this.instance.isExpired()).to.be.equal(false); - await time.advanceBlockTo(this.now + 3); - expect(await this.instance.isPending()).to.be.equal(false); - expect(await this.instance.isExpired()).to.be.equal(true); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/TimersTimestamp.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/TimersTimestamp.test.js deleted file mode 100644 index b08118d4..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/TimersTimestamp.test.js +++ /dev/null @@ -1,55 +0,0 @@ -const { BN, time } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const TimersTimestampImpl = artifacts.require('TimersTimestampImpl'); - -contract('TimersTimestamp', function (accounts) { - beforeEach(async function () { - this.instance = await TimersTimestampImpl.new(); - this.now = await web3.eth.getBlock('latest').then(({ timestamp }) => timestamp); - }); - - it('unset', async function () { - expect(await this.instance.getDeadline()).to.be.bignumber.equal('0'); - expect(await this.instance.isUnset()).to.be.equal(true); - expect(await this.instance.isStarted()).to.be.equal(false); - expect(await this.instance.isPending()).to.be.equal(false); - expect(await this.instance.isExpired()).to.be.equal(false); - }); - - it('pending', async function () { - await this.instance.setDeadline(this.now + 100); - expect(await this.instance.getDeadline()).to.be.bignumber.equal(new BN(this.now + 100)); - expect(await this.instance.isUnset()).to.be.equal(false); - expect(await this.instance.isStarted()).to.be.equal(true); - expect(await this.instance.isPending()).to.be.equal(true); - expect(await this.instance.isExpired()).to.be.equal(false); - }); - - it('expired', async function () { - await this.instance.setDeadline(this.now - 100); - expect(await this.instance.getDeadline()).to.be.bignumber.equal(new BN(this.now - 100)); - expect(await this.instance.isUnset()).to.be.equal(false); - expect(await this.instance.isStarted()).to.be.equal(true); - expect(await this.instance.isPending()).to.be.equal(false); - expect(await this.instance.isExpired()).to.be.equal(true); - }); - - it('reset', async function () { - await this.instance.reset(); - expect(await this.instance.getDeadline()).to.be.bignumber.equal(new BN(0)); - expect(await this.instance.isUnset()).to.be.equal(true); - expect(await this.instance.isStarted()).to.be.equal(false); - expect(await this.instance.isPending()).to.be.equal(false); - expect(await this.instance.isExpired()).to.be.equal(false); - }); - - it('fast forward', async function () { - await this.instance.setDeadline(this.now + 100); - expect(await this.instance.isPending()).to.be.equal(true); - expect(await this.instance.isExpired()).to.be.equal(false); - await time.increaseTo(this.now + 100); - expect(await this.instance.isPending()).to.be.equal(false); - expect(await this.instance.isExpired()).to.be.equal(true); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/ECDSA.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/ECDSA.test.js deleted file mode 100644 index d1539966..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/ECDSA.test.js +++ /dev/null @@ -1,222 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); -const { toEthSignedMessageHash } = require('../../helpers/sign'); - -const { expect } = require('chai'); - -const ECDSAMock = artifacts.require('ECDSAMock'); - -const TEST_MESSAGE = web3.utils.sha3('OpenZeppelin'); -const WRONG_MESSAGE = web3.utils.sha3('Nope'); -const NON_HASH_MESSAGE = '0x' + Buffer.from('abcd').toString('hex'); - -function to2098Format (signature) { - const long = web3.utils.hexToBytes(signature); - if (long.length !== 65) { - throw new Error('invalid signature length (expected long format)'); - } - if (long[32] >> 7 === 1) { - throw new Error('invalid signature \'s\' value'); - } - const short = long.slice(0, 64); - short[32] |= (long[64] % 27) << 7; // set the first bit of the 32nd byte to the v parity bit - return web3.utils.bytesToHex(short); -} - -function from2098Format (signature) { - const short = web3.utils.hexToBytes(signature); - if (short.length !== 64) { - throw new Error('invalid signature length (expected short format)'); - } - short.push((short[32] >> 7) + 27); - short[32] &= (1 << 7) - 1; // zero out the first bit of 1 the 32nd byte - return web3.utils.bytesToHex(short); -} - -function split (signature) { - const raw = web3.utils.hexToBytes(signature); - switch (raw.length) { - case 64: - return [ - web3.utils.bytesToHex(raw.slice(0, 32)), // r - web3.utils.bytesToHex(raw.slice(32, 64)), // vs - ]; - case 65: - return [ - raw[64], // v - web3.utils.bytesToHex(raw.slice(0, 32)), // r - web3.utils.bytesToHex(raw.slice(32, 64)), // s - ]; - default: - expect.fail('Invalid siganture length, cannot split'); - } -} - -contract('ECDSA', function (accounts) { - const [ other ] = accounts; - - beforeEach(async function () { - this.ecdsa = await ECDSAMock.new(); - }); - - context('recover with invalid signature', function () { - it('with short signature', async function () { - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, '0x1234'), 'ECDSA: invalid signature length'); - }); - - it('with long signature', async function () { - await expectRevert( - // eslint-disable-next-line max-len - this.ecdsa.recover(TEST_MESSAGE, '0x01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'), - 'ECDSA: invalid signature length', - ); - }); - }); - - context('recover with valid signature', function () { - context('using web3.eth.sign', function () { - it('returns signer address with correct signature', async function () { - // Create the signature - const signature = await web3.eth.sign(TEST_MESSAGE, other); - - // Recover the signer address from the generated message and signature. - expect(await this.ecdsa.recover( - toEthSignedMessageHash(TEST_MESSAGE), - signature, - )).to.equal(other); - }); - - it('returns signer address with correct signature for arbitrary length message', async function () { - // Create the signature - const signature = await web3.eth.sign(NON_HASH_MESSAGE, other); - - // Recover the signer address from the generated message and signature. - expect(await this.ecdsa.recover( - toEthSignedMessageHash(NON_HASH_MESSAGE), - signature, - )).to.equal(other); - }); - - it('returns a different address', async function () { - const signature = await web3.eth.sign(TEST_MESSAGE, other); - expect(await this.ecdsa.recover(WRONG_MESSAGE, signature)).to.not.equal(other); - }); - - it('reverts with invalid signature', async function () { - // eslint-disable-next-line max-len - const signature = '0x332ce75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e01c'; - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature'); - }); - }); - - context('with v0 signature', function () { - // Signature generated outside ganache with method web3.eth.sign(signer, message) - const signer = '0x2cc1166f6212628A0deEf2B33BEFB2187D35b86c'; - // eslint-disable-next-line max-len - const signatureWithoutVersion = '0x5d99b6f7f6d1f73d1a26497f2b1c89b24c0993913f86e9a2d02cd69887d9c94f3c880358579d811b21dd1b7fd9bb01c1d81d10e69f0384e675c32b39643be892'; - - it('reverts with 00 as version value', async function () { - const version = '00'; - const signature = signatureWithoutVersion + version; - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature \'v\' value'); - await expectRevert( - this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature)), - 'ECDSA: invalid signature \'v\' value', - ); - }); - - it('works with 27 as version value', async function () { - const version = '1b'; // 27 = 1b. - const signature = signatureWithoutVersion + version; - expect(await this.ecdsa.recover(TEST_MESSAGE, signature)).to.equal(signer); - expect(await this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature))).to.equal(signer); - expect(await this.ecdsa.recover_r_vs(TEST_MESSAGE, ...split(to2098Format(signature)))).to.equal(signer); - }); - - it('reverts with wrong version', async function () { - // The last two hex digits are the signature version. - // The only valid values are 0, 1, 27 and 28. - const version = '02'; - const signature = signatureWithoutVersion + version; - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature \'v\' value'); - await expectRevert( - this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature)), - 'ECDSA: invalid signature \'v\' value', - ); - }); - - it('works with short EIP2098 format', async function () { - const version = '1b'; // 27 = 1b. - const signature = signatureWithoutVersion + version; - expect(await this.ecdsa.recover(TEST_MESSAGE, to2098Format(signature))).to.equal(signer); - expect(await this.ecdsa.recover(TEST_MESSAGE, from2098Format(to2098Format(signature)))).to.equal(signer); - }); - }); - - context('with v1 signature', function () { - const signer = '0x1E318623aB09Fe6de3C9b8672098464Aeda9100E'; - // eslint-disable-next-line max-len - const signatureWithoutVersion = '0x331fe75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e0'; - - it('reverts with 01 as version value', async function () { - const version = '01'; - const signature = signatureWithoutVersion + version; - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature \'v\' value'); - await expectRevert( - this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature)), - 'ECDSA: invalid signature \'v\' value', - ); - }); - - it('works with 28 as version value', async function () { - const version = '1c'; // 28 = 1c. - const signature = signatureWithoutVersion + version; - expect(await this.ecdsa.recover(TEST_MESSAGE, signature)).to.equal(signer); - expect(await this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature))).to.equal(signer); - expect(await this.ecdsa.recover_r_vs(TEST_MESSAGE, ...split(to2098Format(signature)))).to.equal(signer); - }); - - it('reverts with wrong version', async function () { - // The last two hex digits are the signature version. - // The only valid values are 0, 1, 27 and 28. - const version = '02'; - const signature = signatureWithoutVersion + version; - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature \'v\' value'); - await expectRevert( - this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature)), - 'ECDSA: invalid signature \'v\' value', - ); - }); - - it('works with short EIP2098 format', async function () { - const version = '1c'; // 27 = 1b. - const signature = signatureWithoutVersion + version; - expect(await this.ecdsa.recover(TEST_MESSAGE, to2098Format(signature))).to.equal(signer); - expect(await this.ecdsa.recover(TEST_MESSAGE, from2098Format(to2098Format(signature)))).to.equal(signer); - }); - }); - - it('reverts with high-s value signature', async function () { - const message = '0xb94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'; - // eslint-disable-next-line max-len - const highSSignature = '0xe742ff452d41413616a5bf43fe15dd88294e983d3d36206c2712f39083d638bde0a0fc89be718fbc1033e1d30d78be1c68081562ed2e97af876f286f3453231d1b'; - await expectRevert(this.ecdsa.recover(message, highSSignature), 'ECDSA: invalid signature \'s\' value'); - await expectRevert( - this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(highSSignature)), - 'ECDSA: invalid signature \'s\' value', - ); - expect(() => to2098Format(highSSignature)).to.throw('invalid signature \'s\' value'); - }); - }); - - context('toEthSignedMessageHash', function () { - it('prefixes bytes32 data correctly', async function () { - expect(await this.ecdsa.methods['toEthSignedMessageHash(bytes32)'](TEST_MESSAGE)) - .to.equal(toEthSignedMessageHash(TEST_MESSAGE)); - }); - - it('prefixes dynamic length data correctly', async function () { - expect(await this.ecdsa.methods['toEthSignedMessageHash(bytes)'](NON_HASH_MESSAGE)) - .to.equal(toEthSignedMessageHash(NON_HASH_MESSAGE)); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/MerkleProof.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/MerkleProof.test.js deleted file mode 100644 index dab2062d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/MerkleProof.test.js +++ /dev/null @@ -1,59 +0,0 @@ -require('@openzeppelin/test-helpers'); - -const { MerkleTree } = require('merkletreejs'); -const keccak256 = require('keccak256'); - -const { expect } = require('chai'); - -const MerkleProofWrapper = artifacts.require('MerkleProofWrapper'); - -contract('MerkleProof', function (accounts) { - beforeEach(async function () { - this.merkleProof = await MerkleProofWrapper.new(); - }); - - describe('verify', function () { - it('returns true for a valid Merkle proof', async function () { - const elements = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''); - const merkleTree = new MerkleTree(elements, keccak256, { hashLeaves: true, sortPairs: true }); - - const root = merkleTree.getHexRoot(); - - const leaf = keccak256(elements[0]); - - const proof = merkleTree.getHexProof(leaf); - - expect(await this.merkleProof.verify(proof, root, leaf)).to.equal(true); - }); - - it('returns false for an invalid Merkle proof', async function () { - const correctElements = ['a', 'b', 'c']; - const correctMerkleTree = new MerkleTree(correctElements, keccak256, { hashLeaves: true, sortPairs: true }); - - const correctRoot = correctMerkleTree.getHexRoot(); - - const correctLeaf = keccak256(correctElements[0]); - - const badElements = ['d', 'e', 'f']; - const badMerkleTree = new MerkleTree(badElements); - - const badProof = badMerkleTree.getHexProof(badElements[0]); - - expect(await this.merkleProof.verify(badProof, correctRoot, correctLeaf)).to.equal(false); - }); - - it('returns false for a Merkle proof of invalid length', async function () { - const elements = ['a', 'b', 'c']; - const merkleTree = new MerkleTree(elements, keccak256, { hashLeaves: true, sortPairs: true }); - - const root = merkleTree.getHexRoot(); - - const leaf = keccak256(elements[0]); - - const proof = merkleTree.getHexProof(leaf); - const badProof = proof.slice(0, proof.length - 5); - - expect(await this.merkleProof.verify(badProof, root, leaf)).to.equal(false); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/SignatureChecker.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/SignatureChecker.test.js deleted file mode 100644 index 6c99e3cf..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/SignatureChecker.test.js +++ /dev/null @@ -1,71 +0,0 @@ -const { toEthSignedMessageHash } = require('../../helpers/sign'); - -const { expect } = require('chai'); - -const SignatureCheckerMock = artifacts.require('SignatureCheckerMock'); -const ERC1271WalletMock = artifacts.require('ERC1271WalletMock'); - -const TEST_MESSAGE = web3.utils.sha3('OpenZeppelin'); -const WRONG_MESSAGE = web3.utils.sha3('Nope'); - -contract('SignatureChecker (ERC1271)', function (accounts) { - const [signer, other] = accounts; - - before('deploying', async function () { - this.signaturechecker = await SignatureCheckerMock.new(); - this.wallet = await ERC1271WalletMock.new(signer); - this.signature = await web3.eth.sign(TEST_MESSAGE, signer); - }); - - context('EOA account', function () { - it('with matching signer and signature', async function () { - expect(await this.signaturechecker.isValidSignatureNow( - signer, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(true); - }); - - it('with invalid signer', async function () { - expect(await this.signaturechecker.isValidSignatureNow( - other, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(false); - }); - - it('with invalid signature', async function () { - expect(await this.signaturechecker.isValidSignatureNow( - signer, - toEthSignedMessageHash(WRONG_MESSAGE), - this.signature, - )).to.equal(false); - }); - }); - - context('ERC1271 wallet', function () { - it('with matching signer and signature', async function () { - expect(await this.signaturechecker.isValidSignatureNow( - this.wallet.address, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(true); - }); - - it('with invalid signer', async function () { - expect(await this.signaturechecker.isValidSignatureNow( - this.signaturechecker.address, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(false); - }); - - it('with invalid signature', async function () { - expect(await this.signaturechecker.isValidSignatureNow( - this.wallet.address, - toEthSignedMessageHash(WRONG_MESSAGE), - this.signature, - )).to.equal(false); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/draft-EIP712.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/draft-EIP712.test.js deleted file mode 100644 index 9e26a87c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/cryptography/draft-EIP712.test.js +++ /dev/null @@ -1,57 +0,0 @@ -const ethSigUtil = require('eth-sig-util'); -const Wallet = require('ethereumjs-wallet').default; - -const { EIP712Domain, domainSeparator } = require('../../helpers/eip712'); - -const EIP712 = artifacts.require('EIP712External'); - -contract('EIP712', function (accounts) { - const [mailTo] = accounts; - - const name = 'A Name'; - const version = '1'; - - beforeEach('deploying', async function () { - this.eip712 = await EIP712.new(name, version); - - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.eip712.getChainId(); - }); - - it('domain separator', async function () { - expect( - await this.eip712.domainSeparator(), - ).to.equal( - await domainSeparator(name, version, this.chainId, this.eip712.address), - ); - }); - - it('digest', async function () { - const chainId = this.chainId; - const verifyingContract = this.eip712.address; - const message = { - to: mailTo, - contents: 'very interesting', - }; - - const data = { - types: { - EIP712Domain, - Mail: [ - { name: 'to', type: 'address' }, - { name: 'contents', type: 'string' }, - ], - }, - domain: { name, version, chainId, verifyingContract }, - primaryType: 'Mail', - message, - }; - - const wallet = Wallet.generate(); - const signature = ethSigUtil.signTypedMessage(wallet.getPrivateKey(), { data }); - - await this.eip712.verify(signature, wallet.getAddressString(), message.to, message.contents); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/ConditionalEscrow.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/ConditionalEscrow.test.js deleted file mode 100644 index 3386ca55..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/ConditionalEscrow.test.js +++ /dev/null @@ -1,36 +0,0 @@ -const { ether, expectRevert } = require('@openzeppelin/test-helpers'); -const { shouldBehaveLikeEscrow } = require('./Escrow.behavior'); - -const ConditionalEscrowMock = artifacts.require('ConditionalEscrowMock'); - -contract('ConditionalEscrow', function (accounts) { - const [ owner, payee, ...otherAccounts ] = accounts; - - beforeEach(async function () { - this.escrow = await ConditionalEscrowMock.new({ from: owner }); - }); - - context('when withdrawal is allowed', function () { - beforeEach(async function () { - await Promise.all(otherAccounts.map(payee => this.escrow.setAllowed(payee, true))); - }); - - shouldBehaveLikeEscrow(owner, otherAccounts); - }); - - context('when withdrawal is disallowed', function () { - const amount = ether('23'); - - beforeEach(async function () { - await this.escrow.setAllowed(payee, false); - }); - - it('reverts on withdrawals', async function () { - await this.escrow.deposit(payee, { from: owner, value: amount }); - - await expectRevert(this.escrow.withdraw(payee, { from: owner }), - 'ConditionalEscrow: payee is not allowed to withdraw', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/Escrow.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/Escrow.behavior.js deleted file mode 100644 index b6d3a69c..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/Escrow.behavior.js +++ /dev/null @@ -1,94 +0,0 @@ -const { balance, ether, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -function shouldBehaveLikeEscrow (owner, [payee1, payee2]) { - const amount = ether('42'); - - describe('as an escrow', function () { - describe('deposits', function () { - it('can accept a single deposit', async function () { - await this.escrow.deposit(payee1, { from: owner, value: amount }); - - expect(await balance.current(this.escrow.address)).to.be.bignumber.equal(amount); - - expect(await this.escrow.depositsOf(payee1)).to.be.bignumber.equal(amount); - }); - - it('can accept an empty deposit', async function () { - await this.escrow.deposit(payee1, { from: owner, value: 0 }); - }); - - it('only the owner can deposit', async function () { - await expectRevert(this.escrow.deposit(payee1, { from: payee2 }), - 'Ownable: caller is not the owner', - ); - }); - - it('emits a deposited event', async function () { - const { logs } = await this.escrow.deposit(payee1, { from: owner, value: amount }); - expectEvent.inLogs(logs, 'Deposited', { - payee: payee1, - weiAmount: amount, - }); - }); - - it('can add multiple deposits on a single account', async function () { - await this.escrow.deposit(payee1, { from: owner, value: amount }); - await this.escrow.deposit(payee1, { from: owner, value: amount.muln(2) }); - - expect(await balance.current(this.escrow.address)).to.be.bignumber.equal(amount.muln(3)); - - expect(await this.escrow.depositsOf(payee1)).to.be.bignumber.equal(amount.muln(3)); - }); - - it('can track deposits to multiple accounts', async function () { - await this.escrow.deposit(payee1, { from: owner, value: amount }); - await this.escrow.deposit(payee2, { from: owner, value: amount.muln(2) }); - - expect(await balance.current(this.escrow.address)).to.be.bignumber.equal(amount.muln(3)); - - expect(await this.escrow.depositsOf(payee1)).to.be.bignumber.equal(amount); - - expect(await this.escrow.depositsOf(payee2)).to.be.bignumber.equal(amount.muln(2)); - }); - }); - - describe('withdrawals', async function () { - it('can withdraw payments', async function () { - const balanceTracker = await balance.tracker(payee1); - - await this.escrow.deposit(payee1, { from: owner, value: amount }); - await this.escrow.withdraw(payee1, { from: owner }); - - expect(await balanceTracker.delta()).to.be.bignumber.equal(amount); - - expect(await balance.current(this.escrow.address)).to.be.bignumber.equal('0'); - expect(await this.escrow.depositsOf(payee1)).to.be.bignumber.equal('0'); - }); - - it('can do an empty withdrawal', async function () { - await this.escrow.withdraw(payee1, { from: owner }); - }); - - it('only the owner can withdraw', async function () { - await expectRevert(this.escrow.withdraw(payee1, { from: payee1 }), - 'Ownable: caller is not the owner', - ); - }); - - it('emits a withdrawn event', async function () { - await this.escrow.deposit(payee1, { from: owner, value: amount }); - const { logs } = await this.escrow.withdraw(payee1, { from: owner }); - expectEvent.inLogs(logs, 'Withdrawn', { - payee: payee1, - weiAmount: amount, - }); - }); - }); - }); -} - -module.exports = { - shouldBehaveLikeEscrow, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/Escrow.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/Escrow.test.js deleted file mode 100644 index 025a2a93..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/Escrow.test.js +++ /dev/null @@ -1,14 +0,0 @@ -require('@openzeppelin/test-helpers'); -const { shouldBehaveLikeEscrow } = require('./Escrow.behavior'); - -const Escrow = artifacts.require('Escrow'); - -contract('Escrow', function (accounts) { - const [ owner, ...otherAccounts ] = accounts; - - beforeEach(async function () { - this.escrow = await Escrow.new({ from: owner }); - }); - - shouldBehaveLikeEscrow(owner, otherAccounts); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/RefundEscrow.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/RefundEscrow.test.js deleted file mode 100644 index 3ef28c68..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/escrow/RefundEscrow.test.js +++ /dev/null @@ -1,148 +0,0 @@ -const { balance, constants, ether, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; - -const { expect } = require('chai'); - -const RefundEscrow = artifacts.require('RefundEscrow'); - -contract('RefundEscrow', function (accounts) { - const [ owner, beneficiary, refundee1, refundee2 ] = accounts; - - const amount = ether('54'); - const refundees = [refundee1, refundee2]; - - it('requires a non-null beneficiary', async function () { - await expectRevert( - RefundEscrow.new(ZERO_ADDRESS, { from: owner }), 'RefundEscrow: beneficiary is the zero address', - ); - }); - - context('once deployed', function () { - beforeEach(async function () { - this.escrow = await RefundEscrow.new(beneficiary, { from: owner }); - }); - - context('active state', function () { - it('has beneficiary and state', async function () { - expect(await this.escrow.beneficiary()).to.equal(beneficiary); - expect(await this.escrow.state()).to.be.bignumber.equal('0'); - }); - - it('accepts deposits', async function () { - await this.escrow.deposit(refundee1, { from: owner, value: amount }); - - expect(await this.escrow.depositsOf(refundee1)).to.be.bignumber.equal(amount); - }); - - it('does not refund refundees', async function () { - await this.escrow.deposit(refundee1, { from: owner, value: amount }); - await expectRevert(this.escrow.withdraw(refundee1), - 'ConditionalEscrow: payee is not allowed to withdraw', - ); - }); - - it('does not allow beneficiary withdrawal', async function () { - await this.escrow.deposit(refundee1, { from: owner, value: amount }); - await expectRevert(this.escrow.beneficiaryWithdraw(), - 'RefundEscrow: beneficiary can only withdraw while closed', - ); - }); - }); - - it('only the owner can enter closed state', async function () { - await expectRevert(this.escrow.close({ from: beneficiary }), - 'Ownable: caller is not the owner', - ); - - const { logs } = await this.escrow.close({ from: owner }); - expectEvent.inLogs(logs, 'RefundsClosed'); - }); - - context('closed state', function () { - beforeEach(async function () { - await Promise.all(refundees.map(refundee => this.escrow.deposit(refundee, { from: owner, value: amount }))); - - await this.escrow.close({ from: owner }); - }); - - it('rejects deposits', async function () { - await expectRevert(this.escrow.deposit(refundee1, { from: owner, value: amount }), - 'RefundEscrow: can only deposit while active', - ); - }); - - it('does not refund refundees', async function () { - await expectRevert(this.escrow.withdraw(refundee1), - 'ConditionalEscrow: payee is not allowed to withdraw', - ); - }); - - it('allows beneficiary withdrawal', async function () { - const balanceTracker = await balance.tracker(beneficiary); - await this.escrow.beneficiaryWithdraw(); - expect(await balanceTracker.delta()).to.be.bignumber.equal(amount.muln(refundees.length)); - }); - - it('prevents entering the refund state', async function () { - await expectRevert(this.escrow.enableRefunds({ from: owner }), - 'RefundEscrow: can only enable refunds while active', - ); - }); - - it('prevents re-entering the closed state', async function () { - await expectRevert(this.escrow.close({ from: owner }), - 'RefundEscrow: can only close while active', - ); - }); - }); - - it('only the owner can enter refund state', async function () { - await expectRevert(this.escrow.enableRefunds({ from: beneficiary }), - 'Ownable: caller is not the owner', - ); - - const { logs } = await this.escrow.enableRefunds({ from: owner }); - expectEvent.inLogs(logs, 'RefundsEnabled'); - }); - - context('refund state', function () { - beforeEach(async function () { - await Promise.all(refundees.map(refundee => this.escrow.deposit(refundee, { from: owner, value: amount }))); - - await this.escrow.enableRefunds({ from: owner }); - }); - - it('rejects deposits', async function () { - await expectRevert(this.escrow.deposit(refundee1, { from: owner, value: amount }), - 'RefundEscrow: can only deposit while active', - ); - }); - - it('refunds refundees', async function () { - for (const refundee of [refundee1, refundee2]) { - const balanceTracker = await balance.tracker(refundee); - await this.escrow.withdraw(refundee, { from: owner }); - expect(await balanceTracker.delta()).to.be.bignumber.equal(amount); - } - }); - - it('does not allow beneficiary withdrawal', async function () { - await expectRevert(this.escrow.beneficiaryWithdraw(), - 'RefundEscrow: beneficiary can only withdraw while closed', - ); - }); - - it('prevents entering the closed state', async function () { - await expectRevert(this.escrow.close({ from: owner }), - 'RefundEscrow: can only close while active', - ); - }); - - it('prevents re-entering the refund state', async function () { - await expectRevert(this.escrow.enableRefunds({ from: owner }), - 'RefundEscrow: can only enable refunds while active', - ); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165.test.js deleted file mode 100644 index c891500e..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165.test.js +++ /dev/null @@ -1,13 +0,0 @@ -const { shouldSupportInterfaces } = require('./SupportsInterface.behavior'); - -const ERC165Mock = artifacts.require('ERC165Mock'); - -contract('ERC165', function (accounts) { - beforeEach(async function () { - this.mock = await ERC165Mock.new(); - }); - - shouldSupportInterfaces([ - 'ERC165', - ]); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165Checker.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165Checker.test.js deleted file mode 100644 index c3a6cdc6..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165Checker.test.js +++ /dev/null @@ -1,218 +0,0 @@ -require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const ERC165CheckerMock = artifacts.require('ERC165CheckerMock'); -const ERC165MissingData = artifacts.require('ERC165MissingData'); -const ERC165NotSupported = artifacts.require('ERC165NotSupported'); -const ERC165InterfacesSupported = artifacts.require('ERC165InterfacesSupported'); - -const DUMMY_ID = '0xdeadbeef'; -const DUMMY_ID_2 = '0xcafebabe'; -const DUMMY_ID_3 = '0xdecafbad'; -const DUMMY_UNSUPPORTED_ID = '0xbaddcafe'; -const DUMMY_UNSUPPORTED_ID_2 = '0xbaadcafe'; -const DUMMY_ACCOUNT = '0x1111111111111111111111111111111111111111'; - -contract('ERC165Checker', function (accounts) { - beforeEach(async function () { - this.mock = await ERC165CheckerMock.new(); - }); - - context('ERC165 missing return data', function () { - beforeEach(async function () { - this.target = await ERC165MissingData.new(); - }); - - it('does not support ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); - expect(supported.length).to.equal(1); - expect(supported[0]).to.equal(false); - }); - }); - - context('ERC165 not supported', function () { - beforeEach(async function () { - this.target = await ERC165NotSupported.new(); - }); - - it('does not support ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); - expect(supported.length).to.equal(1); - expect(supported[0]).to.equal(false); - }); - }); - - context('ERC165 supported', function () { - beforeEach(async function () { - this.target = await ERC165InterfacesSupported.new([]); - }); - - it('supports ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); - expect(supported).to.equal(true); - }); - - it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); - expect(supported.length).to.equal(1); - expect(supported[0]).to.equal(false); - }); - }); - - context('ERC165 and single interface supported', function () { - beforeEach(async function () { - this.target = await ERC165InterfacesSupported.new([DUMMY_ID]); - }); - - it('supports ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); - expect(supported).to.equal(true); - }); - - it('supports mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); - expect(supported).to.equal(true); - }); - - it('supports mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); - expect(supported).to.equal(true); - }); - - it('supports mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); - expect(supported.length).to.equal(1); - expect(supported[0]).to.equal(true); - }); - }); - - context('ERC165 and many interfaces supported', function () { - beforeEach(async function () { - this.supportedInterfaces = [DUMMY_ID, DUMMY_ID_2, DUMMY_ID_3]; - this.target = await ERC165InterfacesSupported.new(this.supportedInterfaces); - }); - - it('supports ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); - expect(supported).to.equal(true); - }); - - it('supports each interfaceId via supportsInterface', async function () { - for (const interfaceId of this.supportedInterfaces) { - const supported = await this.mock.supportsInterface(this.target.address, interfaceId); - expect(supported).to.equal(true); - }; - }); - - it('supports all interfaceIds via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, this.supportedInterfaces); - expect(supported).to.equal(true); - }); - - it('supports none of the interfaces queried via supportsAllInterfaces', async function () { - const interfaceIdsToTest = [DUMMY_UNSUPPORTED_ID, DUMMY_UNSUPPORTED_ID_2]; - - const supported = await this.mock.supportsAllInterfaces(this.target.address, interfaceIdsToTest); - expect(supported).to.equal(false); - }); - - it('supports not all of the interfaces queried via supportsAllInterfaces', async function () { - const interfaceIdsToTest = [...this.supportedInterfaces, DUMMY_UNSUPPORTED_ID]; - - const supported = await this.mock.supportsAllInterfaces(this.target.address, interfaceIdsToTest); - expect(supported).to.equal(false); - }); - - it('supports all interfaceIds via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, this.supportedInterfaces); - expect(supported.length).to.equal(3); - expect(supported[0]).to.equal(true); - expect(supported[1]).to.equal(true); - expect(supported[2]).to.equal(true); - }); - - it('supports none of the interfaces queried via getSupportedInterfaces', async function () { - const interfaceIdsToTest = [DUMMY_UNSUPPORTED_ID, DUMMY_UNSUPPORTED_ID_2]; - - const supported = await this.mock.getSupportedInterfaces(this.target.address, interfaceIdsToTest); - expect(supported.length).to.equal(2); - expect(supported[0]).to.equal(false); - expect(supported[1]).to.equal(false); - }); - - it('supports not all of the interfaces queried via getSupportedInterfaces', async function () { - const interfaceIdsToTest = [...this.supportedInterfaces, DUMMY_UNSUPPORTED_ID]; - - const supported = await this.mock.getSupportedInterfaces(this.target.address, interfaceIdsToTest); - expect(supported.length).to.equal(4); - expect(supported[0]).to.equal(true); - expect(supported[1]).to.equal(true); - expect(supported[2]).to.equal(true); - expect(supported[3]).to.equal(false); - }); - }); - - context('account address does not support ERC165', function () { - it('does not support ERC165', async function () { - const supported = await this.mock.supportsERC165(DUMMY_ACCOUNT); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(DUMMY_ACCOUNT, DUMMY_ID); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(DUMMY_ACCOUNT, [DUMMY_ID]); - expect(supported).to.equal(false); - }); - - it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(DUMMY_ACCOUNT, [DUMMY_ID]); - expect(supported.length).to.equal(1); - expect(supported[0]).to.equal(false); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165Storage.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165Storage.test.js deleted file mode 100644 index 568d6457..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC165Storage.test.js +++ /dev/null @@ -1,25 +0,0 @@ -const { expectRevert } = require('@openzeppelin/test-helpers'); - -const { shouldSupportInterfaces } = require('./SupportsInterface.behavior'); - -const ERC165Mock = artifacts.require('ERC165StorageMock'); - -contract('ERC165Storage', function (accounts) { - beforeEach(async function () { - this.mock = await ERC165Mock.new(); - }); - - it('register interface', async function () { - expect(await this.mock.supportsInterface('0x00000001')).to.be.equal(false); - await this.mock.registerInterface('0x00000001'); - expect(await this.mock.supportsInterface('0x00000001')).to.be.equal(true); - }); - - it('does not allow 0xffffffff', async function () { - await expectRevert(this.mock.registerInterface('0xffffffff'), 'ERC165: invalid interface id'); - }); - - shouldSupportInterfaces([ - 'ERC165', - ]); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC1820Implementer.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC1820Implementer.test.js deleted file mode 100644 index 8d9fe563..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/ERC1820Implementer.test.js +++ /dev/null @@ -1,66 +0,0 @@ -const { expectRevert, singletons } = require('@openzeppelin/test-helpers'); -const { bufferToHex, keccakFromString } = require('ethereumjs-util'); - -const { expect } = require('chai'); - -const ERC1820ImplementerMock = artifacts.require('ERC1820ImplementerMock'); - -contract('ERC1820Implementer', function (accounts) { - const [ registryFunder, implementee, other ] = accounts; - - const ERC1820_ACCEPT_MAGIC = bufferToHex(keccakFromString('ERC1820_ACCEPT_MAGIC')); - - beforeEach(async function () { - this.implementer = await ERC1820ImplementerMock.new(); - this.registry = await singletons.ERC1820Registry(registryFunder); - - this.interfaceA = bufferToHex(keccakFromString('interfaceA')); - this.interfaceB = bufferToHex(keccakFromString('interfaceB')); - }); - - context('with no registered interfaces', function () { - it('returns false when interface implementation is queried', async function () { - expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, implementee)) - .to.not.equal(ERC1820_ACCEPT_MAGIC); - }); - - it('reverts when attempting to set as implementer in the registry', async function () { - await expectRevert( - this.registry.setInterfaceImplementer( - implementee, this.interfaceA, this.implementer.address, { from: implementee }, - ), - 'Does not implement the interface', - ); - }); - }); - - context('with registered interfaces', function () { - beforeEach(async function () { - await this.implementer.registerInterfaceForAddress(this.interfaceA, implementee); - }); - - it('returns true when interface implementation is queried', async function () { - expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, implementee)) - .to.equal(ERC1820_ACCEPT_MAGIC); - }); - - it('returns false when interface implementation for non-supported interfaces is queried', async function () { - expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceB, implementee)) - .to.not.equal(ERC1820_ACCEPT_MAGIC); - }); - - it('returns false when interface implementation for non-supported addresses is queried', async function () { - expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, other)) - .to.not.equal(ERC1820_ACCEPT_MAGIC); - }); - - it('can be set as an implementer for supported interfaces in the registry', async function () { - await this.registry.setInterfaceImplementer( - implementee, this.interfaceA, this.implementer.address, { from: implementee }, - ); - - expect(await this.registry.getInterfaceImplementer(implementee, this.interfaceA)) - .to.equal(this.implementer.address); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/SupportsInterface.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/SupportsInterface.behavior.js deleted file mode 100644 index 3f6f5228..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/introspection/SupportsInterface.behavior.js +++ /dev/null @@ -1,126 +0,0 @@ -const { makeInterfaceId } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const INTERFACES = { - ERC165: [ - 'supportsInterface(bytes4)', - ], - ERC721: [ - 'balanceOf(address)', - 'ownerOf(uint256)', - 'approve(address,uint256)', - 'getApproved(uint256)', - 'setApprovalForAll(address,bool)', - 'isApprovedForAll(address,address)', - 'transferFrom(address,address,uint256)', - 'safeTransferFrom(address,address,uint256)', - 'safeTransferFrom(address,address,uint256,bytes)', - ], - ERC721Enumerable: [ - 'totalSupply()', - 'tokenOfOwnerByIndex(address,uint256)', - 'tokenByIndex(uint256)', - ], - ERC721Metadata: [ - 'name()', - 'symbol()', - 'tokenURI(uint256)', - ], - ERC1155: [ - 'balanceOf(address,uint256)', - 'balanceOfBatch(address[],uint256[])', - 'setApprovalForAll(address,bool)', - 'isApprovedForAll(address,address)', - 'safeTransferFrom(address,address,uint256,uint256,bytes)', - 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', - ], - ERC1155Receiver: [ - 'onERC1155Received(address,address,uint256,uint256,bytes)', - 'onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)', - ], - AccessControl: [ - 'hasRole(bytes32,address)', - 'getRoleAdmin(bytes32)', - 'grantRole(bytes32,address)', - 'revokeRole(bytes32,address)', - 'renounceRole(bytes32,address)', - ], - AccessControlEnumerable: [ - 'getRoleMember(bytes32,uint256)', - 'getRoleMemberCount(bytes32)', - ], - Governor: [ - 'name()', - 'version()', - 'COUNTING_MODE()', - 'hashProposal(address[],uint256[],bytes[],bytes32)', - 'state(uint256)', - 'proposalSnapshot(uint256)', - 'proposalDeadline(uint256)', - 'votingDelay()', - 'votingPeriod()', - 'quorum(uint256)', - 'getVotes(address,uint256)', - 'hasVoted(uint256,address)', - 'propose(address[],uint256[],bytes[],string)', - 'execute(address[],uint256[],bytes[],bytes32)', - 'castVote(uint256,uint8)', - 'castVoteWithReason(uint256,uint8,string)', - 'castVoteBySig(uint256,uint8,uint8,bytes32,bytes32)', - ], - GovernorTimelock: [ - 'timelock()', - 'proposalEta(uint256)', - 'queue(address[],uint256[],bytes[],bytes32)', - ], - ERC2981: [ - 'royaltyInfo(uint256,uint256)', - ], -}; - -const INTERFACE_IDS = {}; -const FN_SIGNATURES = {}; -for (const k of Object.getOwnPropertyNames(INTERFACES)) { - INTERFACE_IDS[k] = makeInterfaceId.ERC165(INTERFACES[k]); - for (const fnName of INTERFACES[k]) { - // the interface id of a single function is equivalent to its function signature - FN_SIGNATURES[fnName] = makeInterfaceId.ERC165([fnName]); - } -} - -function shouldSupportInterfaces (interfaces = []) { - describe('Contract interface', function () { - beforeEach(function () { - this.contractUnderTest = this.mock || this.token || this.holder || this.accessControl; - }); - - for (const k of interfaces) { - const interfaceId = INTERFACE_IDS[k]; - describe(k, function () { - describe('ERC165\'s supportsInterface(bytes4)', function () { - it('uses less than 30k gas [skip-on-coverage]', async function () { - expect(await this.contractUnderTest.supportsInterface.estimateGas(interfaceId)).to.be.lte(30000); - }); - - it('claims support [skip-on-coverage]', async function () { - expect(await this.contractUnderTest.supportsInterface(interfaceId)).to.equal(true); - }); - }); - - for (const fnName of INTERFACES[k]) { - const fnSig = FN_SIGNATURES[fnName]; - describe(fnName, function () { - it('has to be implemented', function () { - expect(this.contractUnderTest.abi.filter(fn => fn.signature === fnSig).length).to.equal(1); - }); - }); - } - }); - } - }); -} - -module.exports = { - shouldSupportInterfaces, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/Math.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/Math.test.js deleted file mode 100644 index 7e194dec..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/Math.test.js +++ /dev/null @@ -1,88 +0,0 @@ -const { BN, constants } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { MAX_UINT256 } = constants; - -const MathMock = artifacts.require('MathMock'); - -contract('Math', function (accounts) { - const min = new BN('1234'); - const max = new BN('5678'); - - beforeEach(async function () { - this.math = await MathMock.new(); - }); - - describe('max', function () { - it('is correctly detected in first argument position', async function () { - expect(await this.math.max(max, min)).to.be.bignumber.equal(max); - }); - - it('is correctly detected in second argument position', async function () { - expect(await this.math.max(min, max)).to.be.bignumber.equal(max); - }); - }); - - describe('min', function () { - it('is correctly detected in first argument position', async function () { - expect(await this.math.min(min, max)).to.be.bignumber.equal(min); - }); - - it('is correctly detected in second argument position', async function () { - expect(await this.math.min(max, min)).to.be.bignumber.equal(min); - }); - }); - - describe('average', function () { - function bnAverage (a, b) { - return a.add(b).divn(2); - } - - it('is correctly calculated with two odd numbers', async function () { - const a = new BN('57417'); - const b = new BN('95431'); - expect(await this.math.average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); - }); - - it('is correctly calculated with two even numbers', async function () { - const a = new BN('42304'); - const b = new BN('84346'); - expect(await this.math.average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); - }); - - it('is correctly calculated with one even and one odd number', async function () { - const a = new BN('57417'); - const b = new BN('84346'); - expect(await this.math.average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); - }); - - it('is correctly calculated with two max uint256 numbers', async function () { - const a = MAX_UINT256; - expect(await this.math.average(a, a)).to.be.bignumber.equal(bnAverage(a, a)); - }); - }); - - describe('ceilDiv', function () { - it('does not round up on exact division', async function () { - const a = new BN('10'); - const b = new BN('5'); - expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('2'); - }); - - it('rounds up on division with remainders', async function () { - const a = new BN('42'); - const b = new BN('13'); - expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('4'); - }); - - it('does not overflow', async function () { - const b = new BN('2'); - const result = new BN('1').shln(255); - expect(await this.math.ceilDiv(MAX_UINT256, b)).to.be.bignumber.equal(result); - }); - - it('correctly computes max uint256 divided by 1', async function () { - const b = new BN('1'); - expect(await this.math.ceilDiv(MAX_UINT256, b)).to.be.bignumber.equal(MAX_UINT256); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SafeCast.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SafeCast.test.js deleted file mode 100644 index 09c7a3f1..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SafeCast.test.js +++ /dev/null @@ -1,164 +0,0 @@ -const { BN, expectRevert } = require('@openzeppelin/test-helpers'); - -const { expect } = require('chai'); - -const SafeCastMock = artifacts.require('SafeCastMock'); - -contract('SafeCast', async (accounts) => { - beforeEach(async function () { - this.safeCast = await SafeCastMock.new(); - }); - - function testToUint (bits) { - describe(`toUint${bits}`, () => { - const maxValue = new BN('2').pow(new BN(bits)).subn(1); - - it('downcasts 0', async function () { - expect(await this.safeCast[`toUint${bits}`](0)).to.be.bignumber.equal('0'); - }); - - it('downcasts 1', async function () { - expect(await this.safeCast[`toUint${bits}`](1)).to.be.bignumber.equal('1'); - }); - - it(`downcasts 2^${bits} - 1 (${maxValue})`, async function () { - expect(await this.safeCast[`toUint${bits}`](maxValue)).to.be.bignumber.equal(maxValue); - }); - - it(`reverts when downcasting 2^${bits} (${maxValue.addn(1)})`, async function () { - await expectRevert( - this.safeCast[`toUint${bits}`](maxValue.addn(1)), - `SafeCast: value doesn't fit in ${bits} bits`, - ); - }); - - it(`reverts when downcasting 2^${bits} + 1 (${maxValue.addn(2)})`, async function () { - await expectRevert( - this.safeCast[`toUint${bits}`](maxValue.addn(2)), - `SafeCast: value doesn't fit in ${bits} bits`, - ); - }); - }); - } - - [8, 16, 32, 64, 96, 128, 224].forEach(bits => testToUint(bits)); - - describe('toUint256', () => { - const maxInt256 = new BN('2').pow(new BN(255)).subn(1); - const minInt256 = new BN('2').pow(new BN(255)).neg(); - - it('casts 0', async function () { - expect(await this.safeCast.toUint256(0)).to.be.bignumber.equal('0'); - }); - - it('casts 1', async function () { - expect(await this.safeCast.toUint256(1)).to.be.bignumber.equal('1'); - }); - - it(`casts INT256_MAX (${maxInt256})`, async function () { - expect(await this.safeCast.toUint256(maxInt256)).to.be.bignumber.equal(maxInt256); - }); - - it('reverts when casting -1', async function () { - await expectRevert( - this.safeCast.toUint256(-1), - 'SafeCast: value must be positive', - ); - }); - - it(`reverts when casting INT256_MIN (${minInt256})`, async function () { - await expectRevert( - this.safeCast.toUint256(minInt256), - 'SafeCast: value must be positive', - ); - }); - }); - - function testToInt (bits) { - describe(`toInt${bits}`, () => { - const minValue = new BN('-2').pow(new BN(bits - 1)); - const maxValue = new BN('2').pow(new BN(bits - 1)).subn(1); - - it('downcasts 0', async function () { - expect(await this.safeCast[`toInt${bits}`](0)).to.be.bignumber.equal('0'); - }); - - it('downcasts 1', async function () { - expect(await this.safeCast[`toInt${bits}`](1)).to.be.bignumber.equal('1'); - }); - - it('downcasts -1', async function () { - expect(await this.safeCast[`toInt${bits}`](-1)).to.be.bignumber.equal('-1'); - }); - - it(`downcasts -2^${bits - 1} (${minValue})`, async function () { - expect(await this.safeCast[`toInt${bits}`](minValue)).to.be.bignumber.equal(minValue); - }); - - it(`downcasts 2^${bits - 1} - 1 (${maxValue})`, async function () { - expect(await this.safeCast[`toInt${bits}`](maxValue)).to.be.bignumber.equal(maxValue); - }); - - it(`reverts when downcasting -2^${bits - 1} - 1 (${minValue.subn(1)})`, async function () { - await expectRevert( - this.safeCast[`toInt${bits}`](minValue.subn(1)), - `SafeCast: value doesn't fit in ${bits} bits`, - ); - }); - - it(`reverts when downcasting -2^${bits - 1} - 2 (${minValue.subn(2)})`, async function () { - await expectRevert( - this.safeCast[`toInt${bits}`](minValue.subn(2)), - `SafeCast: value doesn't fit in ${bits} bits`, - ); - }); - - it(`reverts when downcasting 2^${bits - 1} (${maxValue.addn(1)})`, async function () { - await expectRevert( - this.safeCast[`toInt${bits}`](maxValue.addn(1)), - `SafeCast: value doesn't fit in ${bits} bits`, - ); - }); - - it(`reverts when downcasting 2^${bits - 1} + 1 (${maxValue.addn(2)})`, async function () { - await expectRevert( - this.safeCast[`toInt${bits}`](maxValue.addn(2)), - `SafeCast: value doesn't fit in ${bits} bits`, - ); - }); - }); - } - - [8, 16, 32, 64, 128].forEach(bits => testToInt(bits)); - - describe('toInt256', () => { - const maxUint256 = new BN('2').pow(new BN(256)).subn(1); - const maxInt256 = new BN('2').pow(new BN(255)).subn(1); - - it('casts 0', async function () { - expect(await this.safeCast.toInt256(0)).to.be.bignumber.equal('0'); - }); - - it('casts 1', async function () { - expect(await this.safeCast.toInt256(1)).to.be.bignumber.equal('1'); - }); - - it(`casts INT256_MAX (${maxInt256})`, async function () { - expect(await this.safeCast.toInt256(maxInt256)).to.be.bignumber.equal(maxInt256); - }); - - it(`reverts when casting INT256_MAX + 1 (${maxInt256.addn(1)})`, async function () { - await expectRevert( - this.safeCast.toInt256(maxInt256.addn(1)), - 'SafeCast: value doesn\'t fit in an int256', - ); - }); - - it(`reverts when casting UINT256_MAX (${maxUint256})`, async function () { - await expectRevert( - this.safeCast.toInt256(maxUint256), - 'SafeCast: value doesn\'t fit in an int256', - ); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SafeMath.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SafeMath.test.js deleted file mode 100644 index 7c9b937a..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SafeMath.test.js +++ /dev/null @@ -1,403 +0,0 @@ -const { BN, constants, expectRevert } = require('@openzeppelin/test-helpers'); -const { MAX_UINT256 } = constants; - -const { expect } = require('chai'); - -const SafeMathMock = artifacts.require('SafeMathMock'); - -function expectStruct (value, expected) { - for (const key in expected) { - if (BN.isBN(value[key])) { - expect(value[key]).to.be.bignumber.equal(expected[key]); - } else { - expect(value[key]).to.be.equal(expected[key]); - } - } -} - -contract('SafeMath', function (accounts) { - beforeEach(async function () { - this.safeMath = await SafeMathMock.new(); - }); - - async function testCommutative (fn, lhs, rhs, expected, ...extra) { - expect(await fn(lhs, rhs, ...extra)).to.be.bignumber.equal(expected); - expect(await fn(rhs, lhs, ...extra)).to.be.bignumber.equal(expected); - } - - async function testFailsCommutative (fn, lhs, rhs, reason, ...extra) { - if (reason === undefined) { - await expectRevert.unspecified(fn(lhs, rhs, ...extra)); - await expectRevert.unspecified(fn(rhs, lhs, ...extra)); - } else { - await expectRevert(fn(lhs, rhs, ...extra), reason); - await expectRevert(fn(rhs, lhs, ...extra), reason); - } - } - - async function testCommutativeIterable (fn, lhs, rhs, expected, ...extra) { - expectStruct(await fn(lhs, rhs, ...extra), expected); - expectStruct(await fn(rhs, lhs, ...extra), expected); - } - - describe('with flag', function () { - describe('add', function () { - it('adds correctly', async function () { - const a = new BN('5678'); - const b = new BN('1234'); - - testCommutativeIterable(this.safeMath.tryAdd, a, b, { flag: true, value: a.add(b) }); - }); - - it('reverts on addition overflow', async function () { - const a = MAX_UINT256; - const b = new BN('1'); - - testCommutativeIterable(this.safeMath.tryAdd, a, b, { flag: false, value: '0' }); - }); - }); - - describe('sub', function () { - it('subtracts correctly', async function () { - const a = new BN('5678'); - const b = new BN('1234'); - - expectStruct(await this.safeMath.trySub(a, b), { flag: true, value: a.sub(b) }); - }); - - it('reverts if subtraction result would be negative', async function () { - const a = new BN('1234'); - const b = new BN('5678'); - - expectStruct(await this.safeMath.trySub(a, b), { flag: false, value: '0' }); - }); - }); - - describe('mul', function () { - it('multiplies correctly', async function () { - const a = new BN('1234'); - const b = new BN('5678'); - - testCommutativeIterable(this.safeMath.tryMul, a, b, { flag: true, value: a.mul(b) }); - }); - - it('multiplies by zero correctly', async function () { - const a = new BN('0'); - const b = new BN('5678'); - - testCommutativeIterable(this.safeMath.tryMul, a, b, { flag: true, value: a.mul(b) }); - }); - - it('reverts on multiplication overflow', async function () { - const a = MAX_UINT256; - const b = new BN('2'); - - testCommutativeIterable(this.safeMath.tryMul, a, b, { flag: false, value: '0' }); - }); - }); - - describe('div', function () { - it('divides correctly', async function () { - const a = new BN('5678'); - const b = new BN('5678'); - - expectStruct(await this.safeMath.tryDiv(a, b), { flag: true, value: a.div(b) }); - }); - - it('divides zero correctly', async function () { - const a = new BN('0'); - const b = new BN('5678'); - - expectStruct(await this.safeMath.tryDiv(a, b), { flag: true, value: a.div(b) }); - }); - - it('returns complete number result on non-even division', async function () { - const a = new BN('7000'); - const b = new BN('5678'); - - expectStruct(await this.safeMath.tryDiv(a, b), { flag: true, value: a.div(b) }); - }); - - it('reverts on division by zero', async function () { - const a = new BN('5678'); - const b = new BN('0'); - - expectStruct(await this.safeMath.tryDiv(a, b), { flag: false, value: '0' }); - }); - }); - - describe('mod', function () { - describe('modulos correctly', async function () { - it('when the dividend is smaller than the divisor', async function () { - const a = new BN('284'); - const b = new BN('5678'); - - expectStruct(await this.safeMath.tryMod(a, b), { flag: true, value: a.mod(b) }); - }); - - it('when the dividend is equal to the divisor', async function () { - const a = new BN('5678'); - const b = new BN('5678'); - - expectStruct(await this.safeMath.tryMod(a, b), { flag: true, value: a.mod(b) }); - }); - - it('when the dividend is larger than the divisor', async function () { - const a = new BN('7000'); - const b = new BN('5678'); - - expectStruct(await this.safeMath.tryMod(a, b), { flag: true, value: a.mod(b) }); - }); - - it('when the dividend is a multiple of the divisor', async function () { - const a = new BN('17034'); // 17034 == 5678 * 3 - const b = new BN('5678'); - - expectStruct(await this.safeMath.tryMod(a, b), { flag: true, value: a.mod(b) }); - }); - }); - - it('reverts with a 0 divisor', async function () { - const a = new BN('5678'); - const b = new BN('0'); - - expectStruct(await this.safeMath.tryMod(a, b), { flag: false, value: '0' }); - }); - }); - }); - - describe('with default revert message', function () { - describe('add', function () { - it('adds correctly', async function () { - const a = new BN('5678'); - const b = new BN('1234'); - - await testCommutative(this.safeMath.doAdd, a, b, a.add(b)); - }); - - it('reverts on addition overflow', async function () { - const a = MAX_UINT256; - const b = new BN('1'); - - await testFailsCommutative(this.safeMath.doAdd, a, b, undefined); - }); - }); - - describe('sub', function () { - it('subtracts correctly', async function () { - const a = new BN('5678'); - const b = new BN('1234'); - - expect(await this.safeMath.doSub(a, b)).to.be.bignumber.equal(a.sub(b)); - }); - - it('reverts if subtraction result would be negative', async function () { - const a = new BN('1234'); - const b = new BN('5678'); - - await expectRevert.unspecified(this.safeMath.doSub(a, b)); - }); - }); - - describe('mul', function () { - it('multiplies correctly', async function () { - const a = new BN('1234'); - const b = new BN('5678'); - - await testCommutative(this.safeMath.doMul, a, b, a.mul(b)); - }); - - it('multiplies by zero correctly', async function () { - const a = new BN('0'); - const b = new BN('5678'); - - await testCommutative(this.safeMath.doMul, a, b, '0'); - }); - - it('reverts on multiplication overflow', async function () { - const a = MAX_UINT256; - const b = new BN('2'); - - await testFailsCommutative(this.safeMath.doMul, a, b, undefined); - }); - }); - - describe('div', function () { - it('divides correctly', async function () { - const a = new BN('5678'); - const b = new BN('5678'); - - expect(await this.safeMath.doDiv(a, b)).to.be.bignumber.equal(a.div(b)); - }); - - it('divides zero correctly', async function () { - const a = new BN('0'); - const b = new BN('5678'); - - expect(await this.safeMath.doDiv(a, b)).to.be.bignumber.equal('0'); - }); - - it('returns complete number result on non-even division', async function () { - const a = new BN('7000'); - const b = new BN('5678'); - - expect(await this.safeMath.doDiv(a, b)).to.be.bignumber.equal('1'); - }); - - it('reverts on division by zero', async function () { - const a = new BN('5678'); - const b = new BN('0'); - - await expectRevert.unspecified(this.safeMath.doDiv(a, b)); - }); - }); - - describe('mod', function () { - describe('modulos correctly', async function () { - it('when the dividend is smaller than the divisor', async function () { - const a = new BN('284'); - const b = new BN('5678'); - - expect(await this.safeMath.doMod(a, b)).to.be.bignumber.equal(a.mod(b)); - }); - - it('when the dividend is equal to the divisor', async function () { - const a = new BN('5678'); - const b = new BN('5678'); - - expect(await this.safeMath.doMod(a, b)).to.be.bignumber.equal(a.mod(b)); - }); - - it('when the dividend is larger than the divisor', async function () { - const a = new BN('7000'); - const b = new BN('5678'); - - expect(await this.safeMath.doMod(a, b)).to.be.bignumber.equal(a.mod(b)); - }); - - it('when the dividend is a multiple of the divisor', async function () { - const a = new BN('17034'); // 17034 == 5678 * 3 - const b = new BN('5678'); - - expect(await this.safeMath.doMod(a, b)).to.be.bignumber.equal(a.mod(b)); - }); - }); - - it('reverts with a 0 divisor', async function () { - const a = new BN('5678'); - const b = new BN('0'); - - await expectRevert.unspecified(this.safeMath.doMod(a, b)); - }); - }); - }); - - describe('with custom revert message', function () { - describe('sub', function () { - it('subtracts correctly', async function () { - const a = new BN('5678'); - const b = new BN('1234'); - - expect(await this.safeMath.subWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.sub(b)); - }); - - it('reverts if subtraction result would be negative', async function () { - const a = new BN('1234'); - const b = new BN('5678'); - - await expectRevert(this.safeMath.subWithMessage(a, b, 'MyErrorMessage'), 'MyErrorMessage'); - }); - }); - - describe('div', function () { - it('divides correctly', async function () { - const a = new BN('5678'); - const b = new BN('5678'); - - expect(await this.safeMath.divWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.div(b)); - }); - - it('divides zero correctly', async function () { - const a = new BN('0'); - const b = new BN('5678'); - - expect(await this.safeMath.divWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal('0'); - }); - - it('returns complete number result on non-even division', async function () { - const a = new BN('7000'); - const b = new BN('5678'); - - expect(await this.safeMath.divWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal('1'); - }); - - it('reverts on division by zero', async function () { - const a = new BN('5678'); - const b = new BN('0'); - - await expectRevert(this.safeMath.divWithMessage(a, b, 'MyErrorMessage'), 'MyErrorMessage'); - }); - }); - - describe('mod', function () { - describe('modulos correctly', async function () { - it('when the dividend is smaller than the divisor', async function () { - const a = new BN('284'); - const b = new BN('5678'); - - expect(await this.safeMath.modWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.mod(b)); - }); - - it('when the dividend is equal to the divisor', async function () { - const a = new BN('5678'); - const b = new BN('5678'); - - expect(await this.safeMath.modWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.mod(b)); - }); - - it('when the dividend is larger than the divisor', async function () { - const a = new BN('7000'); - const b = new BN('5678'); - - expect(await this.safeMath.modWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.mod(b)); - }); - - it('when the dividend is a multiple of the divisor', async function () { - const a = new BN('17034'); // 17034 == 5678 * 3 - const b = new BN('5678'); - - expect(await this.safeMath.modWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.mod(b)); - }); - }); - - it('reverts with a 0 divisor', async function () { - const a = new BN('5678'); - const b = new BN('0'); - - await expectRevert(this.safeMath.modWithMessage(a, b, 'MyErrorMessage'), 'MyErrorMessage'); - }); - }); - }); - - describe('memory leakage', function () { - it('add', async function () { - expect(await this.safeMath.addMemoryCheck()).to.be.bignumber.equal('0'); - }); - - it('sub', async function () { - expect(await this.safeMath.subMemoryCheck()).to.be.bignumber.equal('0'); - }); - - it('mul', async function () { - expect(await this.safeMath.mulMemoryCheck()).to.be.bignumber.equal('0'); - }); - - it('div', async function () { - expect(await this.safeMath.divMemoryCheck()).to.be.bignumber.equal('0'); - }); - - it('mod', async function () { - expect(await this.safeMath.modMemoryCheck()).to.be.bignumber.equal('0'); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SignedMath.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SignedMath.test.js deleted file mode 100644 index 8e9826f0..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SignedMath.test.js +++ /dev/null @@ -1,93 +0,0 @@ -const { BN, constants } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); -const { MIN_INT256, MAX_INT256 } = constants; - -const SignedMathMock = artifacts.require('SignedMathMock'); - -contract('SignedMath', function (accounts) { - const min = new BN('-1234'); - const max = new BN('5678'); - - beforeEach(async function () { - this.math = await SignedMathMock.new(); - }); - - describe('max', function () { - it('is correctly detected in first argument position', async function () { - expect(await this.math.max(max, min)).to.be.bignumber.equal(max); - }); - - it('is correctly detected in second argument position', async function () { - expect(await this.math.max(min, max)).to.be.bignumber.equal(max); - }); - }); - - describe('min', function () { - it('is correctly detected in first argument position', async function () { - expect(await this.math.min(min, max)).to.be.bignumber.equal(min); - }); - - it('is correctly detected in second argument position', async function () { - expect(await this.math.min(max, min)).to.be.bignumber.equal(min); - }); - }); - - describe('average', function () { - function bnAverage (a, b) { - return a.add(b).divn(2); - } - - it('is correctly calculated with various input', async function () { - const valuesX = [ - new BN('0'), - new BN('3'), - new BN('-3'), - new BN('4'), - new BN('-4'), - new BN('57417'), - new BN('-57417'), - new BN('42304'), - new BN('-42304'), - MIN_INT256, - MAX_INT256, - ]; - - const valuesY = [ - new BN('0'), - new BN('5'), - new BN('-5'), - new BN('2'), - new BN('-2'), - new BN('57417'), - new BN('-57417'), - new BN('42304'), - new BN('-42304'), - MIN_INT256, - MAX_INT256, - ]; - - for (const x of valuesX) { - for (const y of valuesY) { - expect(await this.math.average(x, y)) - .to.be.bignumber.equal(bnAverage(x, y), `Bad result for average(${x}, ${y})`); - } - } - }); - }); - - describe('abs', function () { - for (const n of [ - MIN_INT256, - MIN_INT256.addn(1), - new BN('-1'), - new BN('0'), - new BN('1'), - MAX_INT256.subn(1), - MAX_INT256, - ]) { - it(`correctly computes the absolute value of ${n}`, async function () { - expect(await this.math.abs(n)).to.be.bignumber.equal(n.abs()); - }); - } - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SignedSafeMath.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SignedSafeMath.test.js deleted file mode 100644 index c6aa15ed..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/math/SignedSafeMath.test.js +++ /dev/null @@ -1,152 +0,0 @@ -const { BN, constants, expectRevert } = require('@openzeppelin/test-helpers'); -const { MAX_INT256, MIN_INT256 } = constants; - -const { expect } = require('chai'); - -const SignedSafeMathMock = artifacts.require('SignedSafeMathMock'); - -contract('SignedSafeMath', function (accounts) { - beforeEach(async function () { - this.safeMath = await SignedSafeMathMock.new(); - }); - - async function testCommutative (fn, lhs, rhs, expected) { - expect(await fn(lhs, rhs)).to.be.bignumber.equal(expected); - expect(await fn(rhs, lhs)).to.be.bignumber.equal(expected); - } - - async function testFailsCommutative (fn, lhs, rhs) { - await expectRevert.unspecified(fn(lhs, rhs)); - await expectRevert.unspecified(fn(rhs, lhs)); - } - - describe('add', function () { - it('adds correctly if it does not overflow and the result is positive', async function () { - const a = new BN('1234'); - const b = new BN('5678'); - - await testCommutative(this.safeMath.add, a, b, a.add(b)); - }); - - it('adds correctly if it does not overflow and the result is negative', async function () { - const a = MAX_INT256; - const b = MIN_INT256; - - await testCommutative(this.safeMath.add, a, b, a.add(b)); - }); - - it('reverts on positive addition overflow', async function () { - const a = MAX_INT256; - const b = new BN('1'); - - await testFailsCommutative(this.safeMath.add, a, b); - }); - - it('reverts on negative addition overflow', async function () { - const a = MIN_INT256; - const b = new BN('-1'); - - await testFailsCommutative(this.safeMath.add, a, b); - }); - }); - - describe('sub', function () { - it('subtracts correctly if it does not overflow and the result is positive', async function () { - const a = new BN('5678'); - const b = new BN('1234'); - - const result = await this.safeMath.sub(a, b); - expect(result).to.be.bignumber.equal(a.sub(b)); - }); - - it('subtracts correctly if it does not overflow and the result is negative', async function () { - const a = new BN('1234'); - const b = new BN('5678'); - - const result = await this.safeMath.sub(a, b); - expect(result).to.be.bignumber.equal(a.sub(b)); - }); - - it('reverts on positive subtraction overflow', async function () { - const a = MAX_INT256; - const b = new BN('-1'); - - await expectRevert.unspecified(this.safeMath.sub(a, b)); - }); - - it('reverts on negative subtraction overflow', async function () { - const a = MIN_INT256; - const b = new BN('1'); - - await expectRevert.unspecified(this.safeMath.sub(a, b)); - }); - }); - - describe('mul', function () { - it('multiplies correctly', async function () { - const a = new BN('5678'); - const b = new BN('-1234'); - - await testCommutative(this.safeMath.mul, a, b, a.mul(b)); - }); - - it('multiplies by zero correctly', async function () { - const a = new BN('0'); - const b = new BN('5678'); - - await testCommutative(this.safeMath.mul, a, b, '0'); - }); - - it('reverts on multiplication overflow, positive operands', async function () { - const a = MAX_INT256; - const b = new BN('2'); - - await testFailsCommutative(this.safeMath.mul, a, b); - }); - - it('reverts when minimum integer is multiplied by -1', async function () { - const a = MIN_INT256; - const b = new BN('-1'); - - await testFailsCommutative(this.safeMath.mul, a, b); - }); - }); - - describe('div', function () { - it('divides correctly', async function () { - const a = new BN('-5678'); - const b = new BN('5678'); - - const result = await this.safeMath.div(a, b); - expect(result).to.be.bignumber.equal(a.div(b)); - }); - - it('divides zero correctly', async function () { - const a = new BN('0'); - const b = new BN('5678'); - - expect(await this.safeMath.div(a, b)).to.be.bignumber.equal('0'); - }); - - it('returns complete number result on non-even division', async function () { - const a = new BN('7000'); - const b = new BN('5678'); - - expect(await this.safeMath.div(a, b)).to.be.bignumber.equal('1'); - }); - - it('reverts on division by zero', async function () { - const a = new BN('-5678'); - const b = new BN('0'); - - await expectRevert.unspecified(this.safeMath.div(a, b)); - }); - - it('reverts on overflow, negative second', async function () { - const a = new BN(MIN_INT256); - const b = new BN('-1'); - - await expectRevert.unspecified(this.safeMath.div(a, b)); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/BitMap.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/BitMap.test.js deleted file mode 100644 index 58d70ca8..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/BitMap.test.js +++ /dev/null @@ -1,145 +0,0 @@ -const { BN } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const BitMap = artifacts.require('BitMapMock'); - -contract('BitMap', function (accounts) { - const keyA = new BN('7891'); - const keyB = new BN('451'); - const keyC = new BN('9592328'); - - beforeEach(async function () { - this.bitmap = await BitMap.new(); - }); - - it('starts empty', async function () { - expect(await this.bitmap.get(keyA)).to.equal(false); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(false); - }); - - describe('setTo', function () { - it('set a key to true', async function () { - await this.bitmap.setTo(keyA, true); - expect(await this.bitmap.get(keyA)).to.equal(true); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(false); - }); - - it('set a key to false', async function () { - await this.bitmap.setTo(keyA, true); - await this.bitmap.setTo(keyA, false); - expect(await this.bitmap.get(keyA)).to.equal(false); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(false); - }); - - it('set several consecutive keys', async function () { - await this.bitmap.setTo(keyA.addn(0), true); - await this.bitmap.setTo(keyA.addn(1), true); - await this.bitmap.setTo(keyA.addn(2), true); - await this.bitmap.setTo(keyA.addn(3), true); - await this.bitmap.setTo(keyA.addn(4), true); - await this.bitmap.setTo(keyA.addn(2), false); - await this.bitmap.setTo(keyA.addn(4), false); - expect(await this.bitmap.get(keyA.addn(0))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(1))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(2))).to.equal(false); - expect(await this.bitmap.get(keyA.addn(3))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(4))).to.equal(false); - }); - }); - - describe('set', function () { - it('adds a key', async function () { - await this.bitmap.set(keyA); - expect(await this.bitmap.get(keyA)).to.equal(true); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(false); - }); - - it('adds several keys', async function () { - await this.bitmap.set(keyA); - await this.bitmap.set(keyB); - expect(await this.bitmap.get(keyA)).to.equal(true); - expect(await this.bitmap.get(keyB)).to.equal(true); - expect(await this.bitmap.get(keyC)).to.equal(false); - }); - - it('adds several consecutive keys', async function () { - await this.bitmap.set(keyA.addn(0)); - await this.bitmap.set(keyA.addn(1)); - await this.bitmap.set(keyA.addn(3)); - expect(await this.bitmap.get(keyA.addn(0))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(1))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(2))).to.equal(false); - expect(await this.bitmap.get(keyA.addn(3))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(4))).to.equal(false); - }); - }); - - describe('unset', function () { - it('removes added keys', async function () { - await this.bitmap.set(keyA); - await this.bitmap.set(keyB); - await this.bitmap.unset(keyA); - expect(await this.bitmap.get(keyA)).to.equal(false); - expect(await this.bitmap.get(keyB)).to.equal(true); - expect(await this.bitmap.get(keyC)).to.equal(false); - }); - - it('removes consecutive added keys', async function () { - await this.bitmap.set(keyA.addn(0)); - await this.bitmap.set(keyA.addn(1)); - await this.bitmap.set(keyA.addn(3)); - await this.bitmap.unset(keyA.addn(1)); - expect(await this.bitmap.get(keyA.addn(0))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(1))).to.equal(false); - expect(await this.bitmap.get(keyA.addn(2))).to.equal(false); - expect(await this.bitmap.get(keyA.addn(3))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(4))).to.equal(false); - }); - - it('adds and removes multiple keys', async function () { - // [] - - await this.bitmap.set(keyA); - await this.bitmap.set(keyC); - - // [A, C] - - await this.bitmap.unset(keyA); - await this.bitmap.unset(keyB); - - // [C] - - await this.bitmap.set(keyB); - - // [C, B] - - await this.bitmap.set(keyA); - await this.bitmap.unset(keyC); - - // [A, B] - - await this.bitmap.set(keyA); - await this.bitmap.set(keyB); - - // [A, B] - - await this.bitmap.set(keyC); - await this.bitmap.unset(keyA); - - // [B, C] - - await this.bitmap.set(keyA); - await this.bitmap.unset(keyB); - - // [A, C] - - expect(await this.bitmap.get(keyA)).to.equal(true); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(true); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableMap.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableMap.test.js deleted file mode 100644 index 9dc700b5..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableMap.test.js +++ /dev/null @@ -1,181 +0,0 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -const zip = require('lodash.zip'); - -const EnumerableMapMock = artifacts.require('EnumerableMapMock'); - -contract('EnumerableMap', function (accounts) { - const [ accountA, accountB, accountC ] = accounts; - - const keyA = new BN('7891'); - const keyB = new BN('451'); - const keyC = new BN('9592328'); - - beforeEach(async function () { - this.map = await EnumerableMapMock.new(); - }); - - async function expectMembersMatch (map, keys, values) { - expect(keys.length).to.equal(values.length); - - await Promise.all(keys.map(async key => - expect(await map.contains(key)).to.equal(true), - )); - - expect(await map.length()).to.bignumber.equal(keys.length.toString()); - - expect(await Promise.all(keys.map(key => - map.get(key), - ))).to.have.same.members(values); - - // To compare key-value pairs, we zip keys and values, and convert BNs to - // strings to workaround Chai limitations when dealing with nested arrays - expect(await Promise.all([...Array(keys.length).keys()].map(async (index) => { - const entry = await map.at(index); - return [entry.key.toString(), entry.value]; - }))).to.have.same.deep.members( - zip(keys.map(k => k.toString()), values), - ); - } - - it('starts empty', async function () { - expect(await this.map.contains(keyA)).to.equal(false); - - await expectMembersMatch(this.map, [], []); - }); - - describe('set', function () { - it('adds a key', async function () { - const receipt = await this.map.set(keyA, accountA); - expectEvent(receipt, 'OperationResult', { result: true }); - - await expectMembersMatch(this.map, [keyA], [accountA]); - }); - - it('adds several keys', async function () { - await this.map.set(keyA, accountA); - await this.map.set(keyB, accountB); - - await expectMembersMatch(this.map, [keyA, keyB], [accountA, accountB]); - expect(await this.map.contains(keyC)).to.equal(false); - }); - - it('returns false when adding keys already in the set', async function () { - await this.map.set(keyA, accountA); - - const receipt = (await this.map.set(keyA, accountA)); - expectEvent(receipt, 'OperationResult', { result: false }); - - await expectMembersMatch(this.map, [keyA], [accountA]); - }); - - it('updates values for keys already in the set', async function () { - await this.map.set(keyA, accountA); - - await this.map.set(keyA, accountB); - - await expectMembersMatch(this.map, [keyA], [accountB]); - }); - }); - - describe('remove', function () { - it('removes added keys', async function () { - await this.map.set(keyA, accountA); - - const receipt = await this.map.remove(keyA); - expectEvent(receipt, 'OperationResult', { result: true }); - - expect(await this.map.contains(keyA)).to.equal(false); - await expectMembersMatch(this.map, [], []); - }); - - it('returns false when removing keys not in the set', async function () { - const receipt = await this.map.remove(keyA); - expectEvent(receipt, 'OperationResult', { result: false }); - - expect(await this.map.contains(keyA)).to.equal(false); - }); - - it('adds and removes multiple keys', async function () { - // [] - - await this.map.set(keyA, accountA); - await this.map.set(keyC, accountC); - - // [A, C] - - await this.map.remove(keyA); - await this.map.remove(keyB); - - // [C] - - await this.map.set(keyB, accountB); - - // [C, B] - - await this.map.set(keyA, accountA); - await this.map.remove(keyC); - - // [A, B] - - await this.map.set(keyA, accountA); - await this.map.set(keyB, accountB); - - // [A, B] - - await this.map.set(keyC, accountC); - await this.map.remove(keyA); - - // [B, C] - - await this.map.set(keyA, accountA); - await this.map.remove(keyB); - - // [A, C] - - await expectMembersMatch(this.map, [keyA, keyC], [accountA, accountC]); - - expect(await this.map.contains(keyB)).to.equal(false); - }); - }); - - describe('read', function () { - beforeEach(async function () { - await this.map.set(keyA, accountA); - }); - - describe('get', function () { - it('existing value', async function () { - expect(await this.map.get(keyA)).to.be.equal(accountA); - }); - it('missing value', async function () { - await expectRevert(this.map.get(keyB), 'EnumerableMap: nonexistent key'); - }); - }); - - describe('get with message', function () { - it('existing value', async function () { - expect(await this.map.getWithMessage(keyA, 'custom error string')).to.be.equal(accountA); - }); - it('missing value', async function () { - await expectRevert(this.map.getWithMessage(keyB, 'custom error string'), 'custom error string'); - }); - }); - - describe('tryGet', function () { - it('existing value', async function () { - expect(await this.map.tryGet(keyA)).to.be.deep.equal({ - 0: true, - 1: accountA, - }); - }); - it('missing value', async function () { - expect(await this.map.tryGet(keyB)).to.be.deep.equal({ - 0: false, - 1: constants.ZERO_ADDRESS, - }); - }); - }); - }); -}); diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableSet.behavior.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableSet.behavior.js deleted file mode 100644 index 17e08667..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableSet.behavior.js +++ /dev/null @@ -1,131 +0,0 @@ -const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { expect } = require('chai'); - -function shouldBehaveLikeSet (valueA, valueB, valueC) { - async function expectMembersMatch (set, values) { - const contains = await Promise.all(values.map(value => set.contains(value))); - expect(contains.every(Boolean)).to.be.equal(true); - - const length = await set.length(); - expect(length).to.bignumber.equal(values.length.toString()); - - // To compare values we convert to strings to workaround Chai - // limitations when dealing with nested arrays (required for BNs) - const indexedValues = await Promise.all(Array(values.length).fill().map((_, index) => set.at(index))); - expect( - indexedValues.map(v => v.toString()), - ).to.have.same.members( - values.map(v => v.toString()), - ); - - const returnedValues = await set.values(); - expect( - returnedValues.map(v => v.toString()), - ).to.have.same.members( - values.map(v => v.toString()), - ); - } - - it('starts empty', async function () { - expect(await this.set.contains(valueA)).to.equal(false); - - await expectMembersMatch(this.set, []); - }); - - describe('add', function () { - it('adds a value', async function () { - const receipt = await this.set.add(valueA); - expectEvent(receipt, 'OperationResult', { result: true }); - - await expectMembersMatch(this.set, [valueA]); - }); - - it('adds several values', async function () { - await this.set.add(valueA); - await this.set.add(valueB); - - await expectMembersMatch(this.set, [valueA, valueB]); - expect(await this.set.contains(valueC)).to.equal(false); - }); - - it('returns false when adding values already in the set', async function () { - await this.set.add(valueA); - - const receipt = (await this.set.add(valueA)); - expectEvent(receipt, 'OperationResult', { result: false }); - - await expectMembersMatch(this.set, [valueA]); - }); - }); - - describe('at', function () { - it('reverts when retrieving non-existent elements', async function () { - await expectRevert.unspecified(this.set.at(0)); - }); - }); - - describe('remove', function () { - it('removes added values', async function () { - await this.set.add(valueA); - - const receipt = await this.set.remove(valueA); - expectEvent(receipt, 'OperationResult', { result: true }); - - expect(await this.set.contains(valueA)).to.equal(false); - await expectMembersMatch(this.set, []); - }); - - it('returns false when removing values not in the set', async function () { - const receipt = await this.set.remove(valueA); - expectEvent(receipt, 'OperationResult', { result: false }); - - expect(await this.set.contains(valueA)).to.equal(false); - }); - - it('adds and removes multiple values', async function () { - // [] - - await this.set.add(valueA); - await this.set.add(valueC); - - // [A, C] - - await this.set.remove(valueA); - await this.set.remove(valueB); - - // [C] - - await this.set.add(valueB); - - // [C, B] - - await this.set.add(valueA); - await this.set.remove(valueC); - - // [A, B] - - await this.set.add(valueA); - await this.set.add(valueB); - - // [A, B] - - await this.set.add(valueC); - await this.set.remove(valueA); - - // [B, C] - - await this.set.add(valueA); - await this.set.remove(valueB); - - // [A, C] - - await expectMembersMatch(this.set, [valueA, valueC]); - - expect(await this.set.contains(valueB)).to.equal(false); - }); - }); -} - -module.exports = { - shouldBehaveLikeSet, -}; diff --git a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableSet.test.js b/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableSet.test.js deleted file mode 100644 index 2b7d0a3d..00000000 --- a/CVLByExample/aave-token-v3/lib/openzeppelin-contracts/test/utils/structs/EnumerableSet.test.js +++ /dev/null @@ -1,46 +0,0 @@ -const { BN } = require('@openzeppelin/test-helpers'); - -const EnumerableBytes32SetMock = artifacts.require('EnumerableBytes32SetMock'); -const EnumerableAddressSetMock = artifacts.require('EnumerableAddressSetMock'); -const EnumerableUintSetMock = artifacts.require('EnumerableUintSetMock'); - -const { shouldBehaveLikeSet } = require('./EnumerableSet.behavior'); - -contract('EnumerableSet', function (accounts) { - // Bytes32Set - describe('EnumerableBytes32Set', function () { - const bytesA = '0xdeadbeef'.padEnd(66, '0'); - const bytesB = '0x0123456789'.padEnd(66, '0'); - const bytesC = '0x42424242'.padEnd(66, '0'); - - beforeEach(async function () { - this.set = await EnumerableBytes32SetMock.new(); - }); - - shouldBehaveLikeSet(bytesA, bytesB, bytesC); - }); - - // AddressSet - describe('EnumerableAddressSet', function () { - const [accountA, accountB, accountC] = accounts; - - beforeEach(async function () { - this.set = await EnumerableAddressSetMock.new(); - }); - - shouldBehaveLikeSet(accountA, accountB, accountC); - }); - - // UintSet - describe('EnumerableUintSet', function () { - const uintA = new BN('1234'); - const uintB = new BN('5678'); - const uintC = new BN('9101112'); - - beforeEach(async function () { - this.set = await EnumerableUintSetMock.new(); - }); - - shouldBehaveLikeSet(uintA, uintB, uintC); - }); -}); diff --git a/CVLByExample/aave-token-v3/package.json b/CVLByExample/aave-token-v3/package.json deleted file mode 100644 index a5424869..00000000 --- a/CVLByExample/aave-token-v3/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "devDependencies": { - "prettier": "^2.7.1", - "prettier-plugin-solidity": "^1.0.0-beta.19" - } -} diff --git a/CVLByExample/aave-token-v3/properties.md b/CVLByExample/aave-token-v3/properties.md deleted file mode 100644 index 0a485aec..00000000 --- a/CVLByExample/aave-token-v3/properties.md +++ /dev/null @@ -1,108 +0,0 @@ -# AAVE token V3. Specs - -## Summary of v2 → v3 - -AAVE is an ERC20 token deployed on Ethereum, which main utility is participating in the Aave governance system via voting on proposals or creating them. - -AAVE is a transparent proxy contract, and its current implementation ([here](https://etherscan.io/address/0xc13eac3b4f9eed480045113b7af00f7b5655ece8#code)) is version 2. - -Together will all the standard ERC20 functionalities, the current implementation includes extra logic mainly for the management and accounting of voting and proposition power. Due to the design/architecture of the Aave governance v2 system, of which AAVE is the main voting asset, the current AAVE implementation makes the token transfers quite gas-consuming, as multiple snapshots of data (voting and proposition power) need to be stored all the time. - -With a new iteration of the Aave governance in the Aave/BGD roadmap down the line, snapshots on the token will not be required anymore for its integration with the governance system. So this new version 3 of AAVE consists mainly of removing the snapshotting, together with adding extra minor meta-transactions capabilities. - -## Glossary - -$t_0$ → the state of the system before a transaction. - -$t_1$ → the state of the system after a transaction. - -**account** → Ethereum address involved in a transaction on the system. - -**power** → any and only one between proposition or voting powers. It can be delegated from one account to another. - -**proposition power** → measures the influence an account has regarding creating proposals on the Aave governance. - -**voting power** → measures the influence an account has regarding voting on proposals on the Aave governance. - -**delegation** → power that an account can use, not generate from his own AAVE balance. - -**balance** → the amount of AAVE tokens belonging to an account `balanceOf(account)` at any time $t$. - -## General rules - -- The total power (of one type) of all users in the system is less or equal than the sum of balances of all AAVE holders (totalSupply of AAVE token): $$\sum powerOfAccount_i <= \sum balanceOf(account_i)$$ -- If an account is delegating a power to itself or to `address(0)`, that means that account is not delegating that power to anybody: - - $$powerOfAccountX = (accountXDelegatingPower \ ? \ 0 : balanceOf(accountX)) + - \sum (balanceOf(accountDelegatingPowerToAccountX_i) \ / \ 10^{10} * 10^{10})$$ - -- If an account is not receiving delegation of power (one type) from anybody, and that account is not delegating that power to anybody, the power of that account must be equal to its AAVE balance. -- The power of all other accounts not described in cases should stay constant. -- Account1 ≠ account2 on the following cases. - -## Account1 and account2 are not delegating power - -- On transfer of $\forall z >= 0$ of AAVE tokens from **account1** to **account2** - - $$account1Power_{t1} = account1Power_{t0} - z$$ - - $$account2Power_{t1} = account2Power_{t0} + z$$ - -- After **account1** will delegate his **power** to **account2** - - $$account1Power_{t1} = account1Power_{t0} - account1Balance$$ - - $$account2Power_{t1} = account2Power_{t0} + account1Balance / 10^{10} * 10^{10}$$ - - $$account1PowerDelegatee_{t1} = account2$$ - - -## Account1 is delegating power to delegatee1, account2 is not delegating power to anybody - -- On transfer of $\forall z >= 0$ of AAVE tokens from **account1** to **account2** - - $$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance_{t0} / 10^{10} * 10^{10} + account1Balance_{t1} / 10^{10} * 10^{10}$$ - - $$account2Power_{t1} = account2Power_{t0} + z$$ - -- After **account1** will stop delegating his **power** to **delegatee1** - - $$account1Power_{t1} = account1Power_{t0} + account1Balance$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance / 10^{10} * 10^{10}$$$$ - -- After **account1** will delegate **power** to **delegatee2** - - $$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance / 10^{10} * 10^{10}$$ - - $$delegatee2Power_{t1} = delegatee2Power_{t0} + account1Balance / 10^{10} * 10^{10}$$ - - $$account1PowerDelegatee_{t1} = delegatee2$$ - - -## Account1 not delegating power to anybody, **account2** is delegating power to delegatee2 - -- On transfer of $\forall z >= 0$ of AAVE tokens from **account1** to **account2** - - $$account1Power_{t1} = account1Power_{t0} - z$$ - - $$account2Power_{t1} = account2Power_{t0} = 0$$ - - $$delegatee2Power_{t1}=delegatee2Power_{t0} - account2Balance_{t0} / 10^{10} * 10^{10} + account2Balance_{t1} / 10^{10} * 10^{10}$$ - - -## Account1 is delegating power to delegatee1, **account2** is delegating power to delegatee2 - -- On transfer of $\forall z >= 0$ of AAVE tokens from **account1** to **account2** - - $$account1Power_{t1} = account1Power_{t0} = 0$$ - - $$delegatee1Power_{t1} = delegatee1Power_{t0} - account1Balance_{t0} / 10^{10} * 10^{10} + account1Balance_{t1} / 10^{10} * 10^{10}$$ - - $$account2Power_{t1} = account2Power_{t0} = 0$$ - - $$delegatee2Power_{t1}=delegatee2Power_{t0} - account2Balance_{t0} / 10^{10} * 10^{10} + account2Balance_{t1} / 10^{10} * 10^{10}$$ diff --git a/CVLByExample/aave-token-v3/src/AaveTokenV3.sol b/CVLByExample/aave-token-v3/src/AaveTokenV3.sol deleted file mode 100644 index 6d793c5a..00000000 --- a/CVLByExample/aave-token-v3/src/AaveTokenV3.sol +++ /dev/null @@ -1,392 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {VersionedInitializable} from './utils/VersionedInitializable.sol'; -import {IGovernancePowerDelegationToken} from './interfaces/IGovernancePowerDelegationToken.sol'; -import {BaseAaveTokenV2} from './BaseAaveTokenV2.sol'; - -contract AaveTokenV3 is BaseAaveTokenV2, IGovernancePowerDelegationToken { - mapping(address => address) internal _votingDelegateeV2; - mapping(address => address) internal _propositionDelegateeV2; - - /// @dev we assume that for the governance system 18 decimals of precision is not needed, - // by this constant we reduce it by 10, to 8 decimals - uint256 public constant POWER_SCALE_FACTOR = 1e10; - - bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = - keccak256( - 'DelegateByType(address delegator,address delegatee,GovernancePowerType delegationType,uint256 nonce,uint256 deadline)' - ); - bytes32 public constant DELEGATE_TYPEHASH = - keccak256('Delegate(address delegator,address delegatee,uint256 nonce,uint256 deadline)'); - - /** - * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy - */ - function initialize() external virtual initializer {} - - /// @inheritdoc IGovernancePowerDelegationToken - function delegateByType(address delegatee, GovernancePowerType delegationType) - external - virtual - override - { - _delegateByType(msg.sender, delegatee, delegationType); - } - - /// @inheritdoc IGovernancePowerDelegationToken - function delegate(address delegatee) external override { - _delegateByType(msg.sender, delegatee, GovernancePowerType.VOTING); - _delegateByType(msg.sender, delegatee, GovernancePowerType.PROPOSITION); - } - - /// @inheritdoc IGovernancePowerDelegationToken - function getDelegateeByType(address delegator, GovernancePowerType delegationType) - external - view - override - returns (address) - { - return _getDelegateeByType(delegator, _balances[delegator], delegationType); - } - - /// @inheritdoc IGovernancePowerDelegationToken - function getDelegates(address delegator) external view override returns (address, address) { - DelegationAwareBalance memory delegatorBalance = _balances[delegator]; - return ( - _getDelegateeByType(delegator, delegatorBalance, GovernancePowerType.VOTING), - _getDelegateeByType(delegator, delegatorBalance, GovernancePowerType.PROPOSITION) - ); - } - - /// @inheritdoc IGovernancePowerDelegationToken - function getPowerCurrent(address user, GovernancePowerType delegationType) - public - view - override - returns (uint256) - { - DelegationAwareBalance memory userState = _balances[user]; - uint256 userOwnPower = uint8(userState.delegationState) & (uint8(delegationType) + 1) == 0 - ? _balances[user].balance - : 0; - uint256 userDelegatedPower = _getDelegatedPowerByType(userState, delegationType); - return userOwnPower + userDelegatedPower; - } - - /// @inheritdoc IGovernancePowerDelegationToken - function getPowersCurrent(address user) external view override returns (uint256, uint256) { - return ( - getPowerCurrent(user, GovernancePowerType.VOTING), - getPowerCurrent(user, GovernancePowerType.PROPOSITION) - ); - } - - /// @inheritdoc IGovernancePowerDelegationToken - function metaDelegateByType( - address delegator, - address delegatee, - GovernancePowerType delegationType, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external override { - require(delegator != address(0), 'INVALID_OWNER'); - //solium-disable-next-line - require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); - uint256 currentValidNonce = _nonces[delegator]; - bytes32 digest = keccak256( - abi.encodePacked( - '\x19\x01', - DOMAIN_SEPARATOR, - keccak256( - abi.encode( - DELEGATE_BY_TYPE_TYPEHASH, - delegator, - delegatee, - delegationType, - currentValidNonce, - deadline - ) - ) - ) - ); - - require(delegator == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); - unchecked { - // Does not make sense to check because it's not realistic to reach uint256.max in nonce - _nonces[delegator] = currentValidNonce + 1; - } - _delegateByType(delegator, delegatee, delegationType); - } - - /// @inheritdoc IGovernancePowerDelegationToken - function metaDelegate( - address delegator, - address delegatee, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external override { - require(delegator != address(0), 'INVALID_OWNER'); - //solium-disable-next-line - require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); - uint256 currentValidNonce = _nonces[delegator]; - bytes32 digest = keccak256( - abi.encodePacked( - '\x19\x01', - DOMAIN_SEPARATOR, - keccak256(abi.encode(DELEGATE_TYPEHASH, delegator, delegatee, currentValidNonce, deadline)) - ) - ); - - require(delegator == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); - unchecked { - // does not make sense to check because it's not realistic to reach uint256.max in nonce - _nonces[delegator] = currentValidNonce + 1; - } - _delegateByType(delegator, delegatee, GovernancePowerType.VOTING); - _delegateByType(delegator, delegatee, GovernancePowerType.PROPOSITION); - } - - /** - * @dev Modifies the delegated power of a `delegatee` account by type (VOTING, PROPOSITION). - * Passing the impact on the delegation of `delegatee` account before and after to reduce conditionals and not lose - * any precision. - * @param impactOnDelegationBefore how much impact a balance of another account had over the delegation of a `delegatee` - * before an action. - * For example, if the action is a delegation from one account to another, the impact before the action will be 0. - * @param impactOnDelegationAfter how much impact a balance of another account will have over the delegation of a `delegatee` - * after an action. - * For example, if the action is a delegation from one account to another, the impact after the action will be the whole balance - * of the account changing the delegatee. - * @param delegatee the user whom delegated governance power will be changed - * @param delegationType the type of governance power delegation (VOTING, PROPOSITION) - **/ - function _governancePowerTransferByType( - uint104 impactOnDelegationBefore, - uint104 impactOnDelegationAfter, - address delegatee, - GovernancePowerType delegationType - ) internal { - if (delegatee == address(0)) return; - if (impactOnDelegationBefore == impactOnDelegationAfter) return; - - // To make delegated balance fit into uint72 we're decreasing precision of delegated balance by POWER_SCALE_FACTOR - uint72 impactOnDelegationBefore72 = uint72(impactOnDelegationBefore / POWER_SCALE_FACTOR); - uint72 impactOnDelegationAfter72 = uint72(impactOnDelegationAfter / POWER_SCALE_FACTOR); - - if (delegationType == GovernancePowerType.VOTING) { - _balances[delegatee].delegatedVotingBalance = - _balances[delegatee].delegatedVotingBalance - - impactOnDelegationBefore72 + - impactOnDelegationAfter72; - } else { - _balances[delegatee].delegatedPropositionBalance = - _balances[delegatee].delegatedPropositionBalance - - impactOnDelegationBefore72 + - impactOnDelegationAfter72; - } - } - - /** - * @dev performs all state changes related to balance transfer and corresponding delegation changes - * @param from token sender - * @param to token recipient - * @param amount amount of tokens sent - **/ - function _transferWithDelegation( - address from, - address to, - uint256 amount - ) internal override { - if (from == to) { - return; - } - - if (from != address(0)) { - DelegationAwareBalance memory fromUserState = _balances[from]; - require(fromUserState.balance >= amount, 'ERC20: transfer amount exceeds balance'); - - uint104 fromBalanceAfter; - unchecked { - fromBalanceAfter = fromUserState.balance - uint104(amount); - } - _balances[from].balance = fromBalanceAfter; - if (fromUserState.delegationState != DelegationState.NO_DELEGATION) { - _governancePowerTransferByType( - fromUserState.balance, - fromBalanceAfter, - _getDelegateeByType(from, fromUserState, GovernancePowerType.VOTING), - GovernancePowerType.VOTING - ); - _governancePowerTransferByType( - fromUserState.balance, - fromBalanceAfter, - _getDelegateeByType(from, fromUserState, GovernancePowerType.PROPOSITION), - GovernancePowerType.PROPOSITION - ); - } - } - - if (to != address(0)) { - DelegationAwareBalance memory toUserState = _balances[to]; - uint104 toBalanceBefore = toUserState.balance; - toUserState.balance = toBalanceBefore + uint104(amount); - _balances[to] = toUserState; - - if (toUserState.delegationState != DelegationState.NO_DELEGATION) { - _governancePowerTransferByType( - toBalanceBefore, - toUserState.balance, - _getDelegateeByType(to, toUserState, GovernancePowerType.VOTING), - GovernancePowerType.VOTING - ); - _governancePowerTransferByType( - toBalanceBefore, - toUserState.balance, - _getDelegateeByType(to, toUserState, GovernancePowerType.PROPOSITION), - GovernancePowerType.PROPOSITION - ); - } - } - } - - /** - * @dev Extracts from state and returns delegated governance power (Voting, Proposition) - * @param userState the current state of a user - * @param delegationType the type of governance power delegation (VOTING, PROPOSITION) - **/ - function _getDelegatedPowerByType( - DelegationAwareBalance memory userState, - GovernancePowerType delegationType - ) internal pure returns (uint256) { - return - POWER_SCALE_FACTOR * - ( - delegationType == GovernancePowerType.VOTING - ? userState.delegatedVotingBalance - : userState.delegatedPropositionBalance - ); - } - - /** - * @dev Extracts from state and returns the delegatee of a delegator by type of governance power (Voting, Proposition) - * - If the delegator doesn't have any delegatee, returns address(0) - * @param delegator delegator - * @param userState the current state of a user - * @param delegationType the type of governance power delegation (VOTING, PROPOSITION) - **/ - function _getDelegateeByType( - address delegator, - DelegationAwareBalance memory userState, - GovernancePowerType delegationType - ) internal view returns (address) { - if (delegationType == GovernancePowerType.VOTING) { - return - /// With the & operation, we cover both VOTING_DELEGATED delegation and FULL_POWER_DELEGATED - /// as VOTING_DELEGATED is equivalent to 01 in binary and FULL_POWER_DELEGATED is equivalent to 11 - (uint8(userState.delegationState) & uint8(DelegationState.VOTING_DELEGATED)) != 0 - ? _votingDelegateeV2[delegator] - : address(0); - } - return - userState.delegationState >= DelegationState.PROPOSITION_DELEGATED - ? _propositionDelegateeV2[delegator] - : address(0); - } - - /** - * @dev Changes user's delegatee address by type of governance power (Voting, Proposition) - * @param delegator delegator - * @param delegationType the type of governance power delegation (VOTING, PROPOSITION) - * @param _newDelegatee the new delegatee - **/ - function _updateDelegateeByType( - address delegator, - GovernancePowerType delegationType, - address _newDelegatee - ) internal { - address newDelegatee = _newDelegatee == delegator ? address(0) : _newDelegatee; - if (delegationType == GovernancePowerType.VOTING) { - _votingDelegateeV2[delegator] = newDelegatee; - } else { - _propositionDelegateeV2[delegator] = newDelegatee; - } - } - - /** - * @dev Updates the specific flag which signaling about existence of delegation of governance power (Voting, Proposition) - * @param userState a user state to change - * @param delegationType the type of governance power delegation (VOTING, PROPOSITION) - * @param willDelegate next state of delegation - **/ - function _updateDelegationFlagByType( - DelegationAwareBalance memory userState, - GovernancePowerType delegationType, - bool willDelegate - ) internal pure returns (DelegationAwareBalance memory) { - if (willDelegate) { - // Because GovernancePowerType starts from 0, we should add 1 first, then we apply bitwise OR - userState.delegationState = DelegationState( - uint8(userState.delegationState) | (uint8(delegationType) + 1) - ); - } else { - // First bitwise NEGATION, ie was 01, after XOR with 11 will be 10, - // then bitwise AND, which means it will keep only another delegation type if it exists - userState.delegationState = DelegationState( - uint8(userState.delegationState) & - ((uint8(delegationType) + 1) ^ uint8(DelegationState.FULL_POWER_DELEGATED)) - ); - } - return userState; - } - - /** - * @dev This is the equivalent of an ERC20 transfer(), but for a power type: an atomic transfer of a balance (power). - * When needed, it decreases the power of the `delegator` and when needed, it increases the power of the `delegatee` - * @param delegator delegator - * @param _delegatee the user which delegated power will change - * @param delegationType the type of delegation (VOTING, PROPOSITION) - **/ - function _delegateByType( - address delegator, - address _delegatee, - GovernancePowerType delegationType - ) internal { - // Here we unify the property that delegating power to address(0) == delegating power to yourself == no delegation - // So from now on, not being delegating is (exclusively) that delegatee == address(0) - address delegatee = _delegatee == delegator ? address(0) : _delegatee; - - // We read the whole struct before validating delegatee, because in the optimistic case - // (_delegatee != currentDelegatee) we will reuse userState in the rest of the function - DelegationAwareBalance memory delegatorState = _balances[delegator]; - address currentDelegatee = _getDelegateeByType(delegator, delegatorState, delegationType); - if (delegatee == currentDelegatee) return; - - bool delegatingNow = currentDelegatee != address(0); - bool willDelegateAfter = delegatee != address(0); - - if (delegatingNow) { - _governancePowerTransferByType(delegatorState.balance, 0, currentDelegatee, delegationType); - } - - if (willDelegateAfter) { - _governancePowerTransferByType(0, delegatorState.balance, delegatee, delegationType); - } - - _updateDelegateeByType(delegator, delegationType, delegatee); - - if (willDelegateAfter != delegatingNow) { - _balances[delegator] = _updateDelegationFlagByType( - delegatorState, - delegationType, - willDelegateAfter - ); - } - - emit DelegateChanged(delegator, delegatee, delegationType); - } -} diff --git a/CVLByExample/aave-token-v3/src/BaseAaveToken.sol b/CVLByExample/aave-token-v3/src/BaseAaveToken.sol deleted file mode 100644 index 372e6708..00000000 --- a/CVLByExample/aave-token-v3/src/BaseAaveToken.sol +++ /dev/null @@ -1,161 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {Context} from '../lib/openzeppelin-contracts/contracts/utils/Context.sol'; -import {IERC20} from '../lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol'; -import {IERC20Metadata} from '../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol'; - -// Inspired by OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) -abstract contract BaseAaveToken is Context, IERC20Metadata { - enum DelegationState { - NO_DELEGATION, - VOTING_DELEGATED, - PROPOSITION_DELEGATED, - FULL_POWER_DELEGATED - } - - struct DelegationAwareBalance { - uint104 balance; - uint72 delegatedPropositionBalance; - uint72 delegatedVotingBalance; - DelegationState delegationState; - } - - mapping(address => DelegationAwareBalance) internal _balances; - - mapping(address => mapping(address => uint256)) internal _allowances; - - uint256 internal _totalSupply; - - string internal _name; - string internal _symbol; - - // @dev DEPRECATED - // kept for backwards compatibility with old storage layout - uint8 private ______DEPRECATED_OLD_ERC20_DECIMALS; - - /** - * @dev Returns the name of the token. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() public view virtual override returns (string memory) { - return _symbol; - } - - function decimals() public view virtual override returns (uint8) { - return 18; - } - - function totalSupply() public view virtual override returns (uint256) { - return _totalSupply; - } - - function balanceOf(address account) public view virtual override returns (uint256) { - return _balances[account].balance; - } - - function transfer(address to, uint256 amount) public virtual override returns (bool) { - address owner = _msgSender(); - _transfer(owner, to, amount); - return true; - } - - function allowance(address owner, address spender) - public - view - virtual - override - returns (uint256) - { - return _allowances[owner][spender]; - } - - function approve(address spender, uint256 amount) public virtual override returns (bool) { - address owner = _msgSender(); - _approve(owner, spender, amount); - return true; - } - - function transferFrom( - address from, - address to, - uint256 amount - ) public virtual override returns (bool) { - address spender = _msgSender(); - _spendAllowance(from, spender, amount); - _transfer(from, to, amount); - return true; - } - - function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { - address owner = _msgSender(); - _approve(owner, spender, _allowances[owner][spender] + addedValue); - return true; - } - - function decreaseAllowance(address spender, uint256 subtractedValue) - public - virtual - returns (bool) - { - address owner = _msgSender(); - uint256 currentAllowance = _allowances[owner][spender]; - require(currentAllowance >= subtractedValue, 'ERC20: decreased allowance below zero'); - unchecked { - _approve(owner, spender, currentAllowance - subtractedValue); - } - - return true; - } - - function _transfer( - address from, - address to, - uint256 amount - ) internal virtual { - require(from != address(0), 'ERC20: transfer from the zero address'); - require(to != address(0), 'ERC20: transfer to the zero address'); - - _transferWithDelegation(from, to, amount); - emit Transfer(from, to, amount); - } - - function _approve( - address owner, - address spender, - uint256 amount - ) internal virtual { - require(owner != address(0), 'ERC20: approve from the zero address'); - require(spender != address(0), 'ERC20: approve to the zero address'); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - function _spendAllowance( - address owner, - address spender, - uint256 amount - ) internal virtual { - uint256 currentAllowance = allowance(owner, spender); - if (currentAllowance != type(uint256).max) { - require(currentAllowance >= amount, 'ERC20: insufficient allowance'); - unchecked { - _approve(owner, spender, currentAllowance - amount); - } - } - } - - function _transferWithDelegation( - address from, - address to, - uint256 amount - ) internal virtual {} -} diff --git a/CVLByExample/aave-token-v3/src/BaseAaveTokenV2.sol b/CVLByExample/aave-token-v3/src/BaseAaveTokenV2.sol deleted file mode 100644 index 78939ef8..00000000 --- a/CVLByExample/aave-token-v3/src/BaseAaveTokenV2.sol +++ /dev/null @@ -1,77 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {VersionedInitializable} from './utils/VersionedInitializable.sol'; -import {BaseAaveToken} from './BaseAaveToken.sol'; - -abstract contract BaseAaveTokenV2 is BaseAaveToken, VersionedInitializable { - /// @dev owner => next valid nonce to submit with permit() - mapping(address => uint256) public _nonces; - - ///////// @dev DEPRECATED from AaveToken v1 ////////////////////////// - //////// kept for backwards compatibility with old storage layout //// - uint256[3] private ______DEPRECATED_FROM_AAVE_V1; - ///////// @dev END OF DEPRECATED from AaveToken v1 ////////////////////////// - - bytes32 public DOMAIN_SEPARATOR; - - ///////// @dev DEPRECATED from AaveToken v2 ////////////////////////// - //////// kept for backwards compatibility with old storage layout //// - uint256[4] private ______DEPRECATED_FROM_AAVE_V2; - ///////// @dev END OF DEPRECATED from AaveToken v2 ////////////////////////// - - bytes public constant EIP712_REVISION = bytes('1'); - bytes32 internal constant EIP712_DOMAIN = - keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); - bytes32 public constant PERMIT_TYPEHASH = - keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); - - uint256 public constant REVISION = 3; - - /** - * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md - * @param owner the owner of the funds - * @param spender the spender - * @param value the amount - * @param deadline the deadline timestamp, type(uint256).max for no deadline - * @param v signature param - * @param s signature param - * @param r signature param - */ - - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external { - require(owner != address(0), 'INVALID_OWNER'); - //solium-disable-next-line - require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); - uint256 currentValidNonce = _nonces[owner]; - bytes32 digest = keccak256( - abi.encodePacked( - '\x19\x01', - DOMAIN_SEPARATOR, - keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) - ) - ); - - require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); - unchecked { - // does not make sense to check because it's not realistic to reach uint256.max in nonce - _nonces[owner] = currentValidNonce + 1; - } - _approve(owner, spender, value); - } - - /** - * @dev returns the revision of the implementation contract - */ - function getRevision() internal pure override returns (uint256) { - return REVISION; - } -} diff --git a/CVLByExample/aave-token-v3/src/interfaces/IGovernancePowerDelegationToken.sol b/CVLByExample/aave-token-v3/src/interfaces/IGovernancePowerDelegationToken.sol deleted file mode 100644 index 968956bb..00000000 --- a/CVLByExample/aave-token-v3/src/interfaces/IGovernancePowerDelegationToken.sol +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -interface IGovernancePowerDelegationToken { - enum GovernancePowerType { - VOTING, - PROPOSITION - } - - /** - * @dev emitted when a user delegates to another - * @param delegator the user which delegated governance power - * @param delegatee the delegatee - * @param delegationType the type of delegation (VOTING, PROPOSITION) - **/ - event DelegateChanged( - address indexed delegator, - address indexed delegatee, - GovernancePowerType delegationType - ); - - // @dev we removed DelegatedPowerChanged event because to reconstruct the full state of the system, - // is enough to have Transfer and DelegateChanged TODO: document it - - /** - * @dev delegates the specific power to a delegatee - * @param delegatee the user which delegated power will change - * @param delegationType the type of delegation (VOTING, PROPOSITION) - **/ - function delegateByType(address delegatee, GovernancePowerType delegationType) external; - - /** - * @dev delegates all the governance powers to a specific user - * @param delegatee the user to which the powers will be delegated - **/ - function delegate(address delegatee) external; - - /** - * @dev returns the delegatee of an user - * @param delegator the address of the delegator - * @param delegationType the type of delegation (VOTING, PROPOSITION) - * @return address of the specified delegatee - **/ - function getDelegateeByType(address delegator, GovernancePowerType delegationType) - external - view - returns (address); - - /** - * @dev returns delegates of an user - * @param delegator the address of the delegator - * @return a tuple of addresses the VOTING and PROPOSITION delegatee - **/ - function getDelegates(address delegator) - external - view - returns (address, address); - - /** - * @dev returns the current voting or proposition power of a user. - * @param user the user - * @param delegationType the type of delegation (VOTING, PROPOSITION) - * @return the current voting or proposition power of a user - **/ - function getPowerCurrent(address user, GovernancePowerType delegationType) - external - view - returns (uint256); - - /** - * @dev returns the current voting or proposition power of a user. - * @param user the user - * @return the current voting and proposition power of a user - **/ - function getPowersCurrent(address user) - external - view - returns (uint256, uint256); - - /** - * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md - * @param delegator the owner of the funds - * @param delegatee the user to who owner delegates his governance power - * @param delegationType the type of governance power delegation (VOTING, PROPOSITION) - * @param deadline the deadline timestamp, type(uint256).max for no deadline - * @param v signature param - * @param s signature param - * @param r signature param - */ - function metaDelegateByType( - address delegator, - address delegatee, - GovernancePowerType delegationType, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external; - - /** - * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md - * @param delegator the owner of the funds - * @param delegatee the user to who delegator delegates his voting and proposition governance power - * @param deadline the deadline timestamp, type(uint256).max for no deadline - * @param v signature param - * @param s signature param - * @param r signature param - */ - function metaDelegate( - address delegator, - address delegatee, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external; -} diff --git a/CVLByExample/aave-token-v3/src/interfaces/ITransferHook.sol b/CVLByExample/aave-token-v3/src/interfaces/ITransferHook.sol deleted file mode 100644 index d0e37a9d..00000000 --- a/CVLByExample/aave-token-v3/src/interfaces/ITransferHook.sol +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -interface ITransferHook { - function onTransfer( - address from, - address to, - uint256 amount - ) external; -} diff --git a/CVLByExample/aave-token-v3/src/test/InternalDelegationFunctionsTest.t.sol b/CVLByExample/aave-token-v3/src/test/InternalDelegationFunctionsTest.t.sol deleted file mode 100644 index 2e54c28d..00000000 --- a/CVLByExample/aave-token-v3/src/test/InternalDelegationFunctionsTest.t.sol +++ /dev/null @@ -1,127 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {Strings} from '../../lib/openzeppelin-contracts/contracts/utils/Strings.sol'; -import {IERC20Metadata} from '../../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol'; -import {AaveTokenV3} from '../AaveTokenV3.sol'; - -import {AaveUtils, console} from './utils/AaveUtils.sol'; - -contract StorageTest is AaveTokenV3, AaveUtils { - function setUp() public {} - - function testFor_getDelegatedPowerByType() public { - DelegationAwareBalance memory userState; - userState.delegatedPropositionBalance = 100; - userState.delegatedVotingBalance = 200; - assertEq( - _getDelegatedPowerByType(userState, GovernancePowerType.VOTING), - userState.delegatedVotingBalance * POWER_SCALE_FACTOR - ); - assertEq( - _getDelegatedPowerByType(userState, GovernancePowerType.PROPOSITION), - userState.delegatedPropositionBalance * POWER_SCALE_FACTOR - ); - } - - function testFor_getDelegateeByType() public { - address user = address(0x1); - address user2 = address(0x2); - address user3 = address(0x3); - DelegationAwareBalance memory userState; - - _votingDelegateeV2[user] = address(user2); - _propositionDelegateeV2[user] = address(user3); - - userState.delegationState = DelegationState.VOTING_DELEGATED; - assertEq(_getDelegateeByType(user, userState, GovernancePowerType.VOTING), user2); - assertEq(_getDelegateeByType(user, userState, GovernancePowerType.PROPOSITION), address(0)); - - userState.delegationState = DelegationState.PROPOSITION_DELEGATED; - assertEq(_getDelegateeByType(user, userState, GovernancePowerType.VOTING), address(0)); - assertEq(_getDelegateeByType(user, userState, GovernancePowerType.PROPOSITION), user3); - - userState.delegationState = DelegationState.FULL_POWER_DELEGATED; - assertEq(_getDelegateeByType(user, userState, GovernancePowerType.VOTING), user2); - assertEq(_getDelegateeByType(user, userState, GovernancePowerType.PROPOSITION), user3); - } - - function _setDelegationStateAndTest( - DelegationState initialState, - GovernancePowerType governancePowerType, - bool willDelegate, - DelegationState expectedState - ) internal { - DelegationAwareBalance memory userState; - DelegationAwareBalance memory updatedUserState; - userState.delegationState = initialState; - updatedUserState = _updateDelegationFlagByType(userState, governancePowerType, willDelegate); - assertTrue( - updatedUserState.delegationState == expectedState, - Strings.toString(uint8(updatedUserState.delegationState)) - ); - } - - function testFor_updateDelegationFlagByType() public { - _setDelegationStateAndTest( - DelegationState.NO_DELEGATION, - GovernancePowerType.VOTING, - true, - DelegationState.VOTING_DELEGATED - ); - _setDelegationStateAndTest( - DelegationState.NO_DELEGATION, - GovernancePowerType.VOTING, - false, - DelegationState.NO_DELEGATION - ); - _setDelegationStateAndTest( - DelegationState.VOTING_DELEGATED, - GovernancePowerType.VOTING, - true, - DelegationState.VOTING_DELEGATED - ); - _setDelegationStateAndTest( - DelegationState.FULL_POWER_DELEGATED, - GovernancePowerType.VOTING, - false, - DelegationState.PROPOSITION_DELEGATED - ); - _setDelegationStateAndTest( - DelegationState.NO_DELEGATION, - GovernancePowerType.PROPOSITION, - true, - DelegationState.PROPOSITION_DELEGATED - ); - _setDelegationStateAndTest( - DelegationState.PROPOSITION_DELEGATED, - GovernancePowerType.PROPOSITION, - false, - DelegationState.NO_DELEGATION - ); - _setDelegationStateAndTest( - DelegationState.PROPOSITION_DELEGATED, - GovernancePowerType.VOTING, - true, - DelegationState.FULL_POWER_DELEGATED - ); - _setDelegationStateAndTest( - DelegationState.FULL_POWER_DELEGATED, - GovernancePowerType.VOTING, - true, - DelegationState.FULL_POWER_DELEGATED - ); - _setDelegationStateAndTest( - DelegationState.VOTING_DELEGATED, - GovernancePowerType.PROPOSITION, - true, - DelegationState.FULL_POWER_DELEGATED - ); - _setDelegationStateAndTest( - DelegationState.FULL_POWER_DELEGATED, - GovernancePowerType.PROPOSITION, - true, - DelegationState.FULL_POWER_DELEGATED - ); - } -} diff --git a/CVLByExample/aave-token-v3/src/test/StorageTest.t.sol b/CVLByExample/aave-token-v3/src/test/StorageTest.t.sol deleted file mode 100644 index b6cfcf4e..00000000 --- a/CVLByExample/aave-token-v3/src/test/StorageTest.t.sol +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {IERC20Metadata} from '../../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol'; -import {AaveTokenV3} from '../AaveTokenV3.sol'; - -import {AaveUtils, console} from './utils/AaveUtils.sol'; - -contract StorageTest is AaveUtils { - function setUp() public { - revertAaveImplementationUpdate(); - } - - function testForBaseMetadata() public { - string memory nameBefore = AAVE_TOKEN.name(); - string memory symbolBefore = AAVE_TOKEN.symbol(); - uint256 decimalsBefore = AAVE_TOKEN.decimals(); - - updateAaveImplementation(AAVE_IMPLEMENTATION_V3); - - assertEq(AAVE_TOKEN.name(), nameBefore); - assertEq(AAVE_TOKEN.symbol(), symbolBefore); - assertEq(AAVE_TOKEN.decimals(), decimalsBefore); - } - - function testForTotalSupply() public { - uint256 totalSupplyBefore = AAVE_TOKEN.totalSupply(); - - updateAaveImplementation(AAVE_IMPLEMENTATION_V3); - - assertEq(AAVE_TOKEN.totalSupply(), totalSupplyBefore); - } - - function testForBalances() public { - uint256[] memory balancesBefore = new uint256[](AAVE_HOLDERS.length); - for (uint256 i = 0; i < AAVE_HOLDERS.length; i += 1) { - balancesBefore[i] = AAVE_TOKEN.balanceOf(AAVE_HOLDERS[i]); - } - updateAaveImplementation(AAVE_IMPLEMENTATION_V3); - for (uint256 i = 0; i < AAVE_HOLDERS.length; i += 1) { - assertEq(AAVE_TOKEN.balanceOf(AAVE_HOLDERS[i]), balancesBefore[i]); - } - } -} diff --git a/CVLByExample/aave-token-v3/src/test/utils/AaveUtils.sol b/CVLByExample/aave-token-v3/src/test/utils/AaveUtils.sol deleted file mode 100644 index 07b2b310..00000000 --- a/CVLByExample/aave-token-v3/src/test/utils/AaveUtils.sol +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import 'forge-std/Test.sol'; - -import {IERC20Metadata} from '../../../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol'; - -import {AaveTokenV3} from '../../AaveTokenV3.sol'; - -import {IBaseAdminUpgradeabilityProxy} from './IBaseAdminUpgradeabilityProxy.sol'; - -abstract contract AaveUtils is Test { - address[] public AAVE_HOLDERS; - IERC20Metadata public constant AAVE_TOKEN = - IERC20Metadata(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); - - address public constant AAVE_V2_IMPLEMENTATION = 0xC13eac3B4F9EED480045113B7af00F7B5655Ece8; - - address public constant AAVE_TOKEN_PROXY_ADMIN = 0x61910EcD7e8e942136CE7Fe7943f956cea1CC2f7; - address public AAVE_IMPLEMENTATION_V3; - - constructor() { - AAVE_IMPLEMENTATION_V3 = address(new AaveTokenV3()); - AAVE_HOLDERS = new address[](10); - AAVE_HOLDERS = [ - 0x4da27a545c0c5B758a6BA100e3a049001de870f5, - 0xFFC97d72E13E01096502Cb8Eb52dEe56f74DAD7B, - 0x25F2226B597E8F9514B3F68F00f494cF4f286491, - 0xC697051d1C6296C24aE3bceF39acA743861D9A81, - 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8, - 0x317625234562B1526Ea2FaC4030Ea499C5291de4, - 0x47ac0Fb4F2D84898e4D9E7b4DaB3C24507a6D503, - 0xF977814e90dA44bFA03b6295A0616a897441aceC, - 0x26a78D5b6d7a7acEEDD1e6eE3229b372A624d8b7, - 0x28C6c06298d514Db089934071355E5743bf21d60 - ]; - } - - function updateAaveImplementation(address newImplementation) public { - vm.prank(AAVE_TOKEN_PROXY_ADMIN); - IBaseAdminUpgradeabilityProxy(address(AAVE_TOKEN)).upgradeTo(newImplementation); - } - - function revertAaveImplementationUpdate() public { - updateAaveImplementation(AAVE_V2_IMPLEMENTATION); - } -} diff --git a/CVLByExample/aave-token-v3/src/test/utils/IBaseAdminUpgradeabilityProxy.sol b/CVLByExample/aave-token-v3/src/test/utils/IBaseAdminUpgradeabilityProxy.sol deleted file mode 100644 index 453fdfec..00000000 --- a/CVLByExample/aave-token-v3/src/test/utils/IBaseAdminUpgradeabilityProxy.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -interface IBaseAdminUpgradeabilityProxy { - function upgradeTo(address newImplementation) external; -} diff --git a/CVLByExample/aave-token-v3/src/utils/VersionedInitializable.sol b/CVLByExample/aave-token-v3/src/utils/VersionedInitializable.sol deleted file mode 100644 index d7c07743..00000000 --- a/CVLByExample/aave-token-v3/src/utils/VersionedInitializable.sol +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity ^0.8.0; - -/** - * @title VersionedInitializable - * - * @dev Helper contract to support initializer functions. To use it, replace - * the constructor with a function that has the `initializer` modifier. - * WARNING: Unlike constructors, initializer functions must be manually - * invoked. This applies both to deploying an Initializable contract, as well - * as extending an Initializable contract via inheritance. - * WARNING: When used with inheritance, manual care must be taken to not invoke - * a parent initializer twice, or ensure that all initializers are idempotent, - * because this is not dealt with automatically as with constructors. - * - * @author Aave, inspired by the OpenZeppelin Initializable contract - */ -abstract contract VersionedInitializable { - /** - * @dev Indicates that the contract has been initialized. - */ - uint256 internal lastInitializedRevision = 0; - - /** - * @dev Modifier to use in the initializer function of a contract. - */ - modifier initializer() { - uint256 revision = getRevision(); - require(revision > lastInitializedRevision, 'Contract instance has already been initialized'); - - lastInitializedRevision = revision; - - _; - } - - /// @dev returns the revision number of the contract. - /// Needs to be defined in the inherited class as a constant. - function getRevision() internal pure virtual returns (uint256); - - // Reserved storage space to allow for layout changes in the future. - uint256[50] private ______gap; -}